---
const options = {
  nextauth: "NextAuth.js",
  prisma: "Prisma",
  drizzle: "Drizzle",
  tailwind: "Tailwind CSS",
  trpc: "tRPC",
};
---

<script>
  const inputs = document
    .getElementById("componentForm")
    ?.querySelectorAll("input") as NodeListOf<HTMLInputElement>;

  const updatePackagesQueryParam = (selected: string[]) => {
    const packagesQueryParam = selected.join(",");

    const url = new URL(window.location.href);
    url.searchParams.set("packages", packagesQueryParam);
    window.history.pushState({}, "", url);
  };

  const getSelectedFromPackagesQueryParam = () => {
    const selectedParam = new URLSearchParams(window.location.search).get(
      "packages",
    );

    if (selectedParam === null) {
      return ["nextauth", "drizzle", "tailwind", "trpc"];
    }

    return selectedParam.split(",");
  };

  inputs.forEach((input) =>
    input.addEventListener("change", (aaa) => {
      console.log({ inputs, aaa, input });
      const initialSelected = Array.from(inputs).flatMap(
        ({ value, checked }) => {
          return checked ? [value] : [];
        },
      );

      if (
        input.value === "drizzle" &&
        initialSelected.includes("drizzle") &&
        initialSelected.includes("prisma")
      ) {
        document.getElementById("prisma")?.click();
      } else if (
        input.value === "prisma" &&
        initialSelected.includes("prisma") &&
        initialSelected.includes("drizzle")
      ) {
        document.getElementById("drizzle")?.click();
      }

      const selected = Array.from(inputs).flatMap(({ value, checked }) => {
        return checked ? [value] : [];
      });

      updatePackagesQueryParam(selected);

      // Rerender the diagram
      document.dispatchEvent(
        new CustomEvent("fileStructureComponentsChange", {
          detail: { selected },
        }),
      );

      hideUnselectedDocs(selected);
    }),
  );

  const hideUnselectedDocs = (selected: string[]) => {
    document
      .querySelectorAll<HTMLElement>("*[data-components]")
      .forEach((el) => {
        el.style.display = !el.dataset.components
          ?.split(" ")
          .some((components) =>
            components.split("+").every((option) => selected.includes(option)),
          )
          ? "none"
          : "";
      });
  };

  // Set initial state based on query param
  const initialSelected = getSelectedFromPackagesQueryParam();

  inputs.forEach((input) => {
    input.checked = initialSelected.includes(input.value);
  });

  hideUnselectedDocs(initialSelected);
</script>

<form
  method="get"
  id="componentForm"
  class="mb-4 w-full rounded border border-t3-purple-300 p-4 text-lg"
>
  {
    Object.entries(options).map(([code, name]) => (
      <div>
        <input
          id={code}
          type="checkbox"
          name="conf"
          checked={code !== "prisma"}
          value={code}
          class="h-4 w-4"
        />
        <label for={code}>{name}</label>
      </div>
    ))
  }
</form>
