<h1>Apps</h1>

<div id="search-container">
  <input type="text" id="search-bar" placeholder="Search apps..." />
</div>

<div id="apps-container" class="apps-container"></div>
<script>
  const server = "/cdn/";

  document.addEventListener("DOMContentLoaded", () => {
    const appsContainer = document.getElementById("apps-container");
    const searchBar = document.getElementById("search-bar");

    fetch("/json/apps.json")
      .then((response) => response.json())
      .then((apps) => {
        const renderApps = (filter = "") => {
          appsContainer.innerHTML = "";

          apps.forEach((app) => {
            if (app.name.toLowerCase().includes(filter.toLowerCase())) {
              const appDiv = document.createElement("div");
              appDiv.classList.add("app");

              const appTitle = document.createElement("h2");
              appTitle.textContent = app.name;

              const appImage = document.createElement("img");
              appImage.src = `${app.image}`;
              appImage.alt = app.name;
              appImage.title = app.name;
              appImage.setAttribute("data-url", app.url);
              appImage.setAttribute("data-name", app.name);

              appImage.addEventListener("click", (e) => {
                const appUrl = e.target.getAttribute("data-url");
                const appName = e.target.getAttribute("data-name");
                const lpUrl =
                  window.__uv$config.prefix +
                  window.__uv$config.encodeUrl(appUrl);
                sessionStorage.setItem("lpurl", lpUrl);
                sessionStorage.setItem("rawurl", `starlight://${appName}`);
                window.location.href = "/./go/";
              });

              appDiv.appendChild(appImage);
              appDiv.appendChild(appTitle);
              appsContainer.appendChild(appDiv);
            }
          });

          if (appsContainer.children.length === 0) {
            const noResultsMessage = document.createElement("p");
            noResultsMessage.textContent = "No apps found.";
            appsContainer.appendChild(noResultsMessage);
          }
        };

        renderApps();

        searchBar.addEventListener("input", () => {
          renderApps(searchBar.value.trim());
        });
      })
      .catch((error) => console.error("Error loading apps:", error));
  });
</script>
