---
import EventCard from "../components/EventCard.astro";
import SiteLayout from "../layouts/SiteLayout.astro";
import { getEventPath, organizedEvents } from "../data/events";

const featured = organizedEvents.find((event) => event.highlight);
const primaryEvents = organizedEvents.filter((event) => event !== featured);
const featuredPath = featured ? getEventPath(featured) : undefined;
---

<SiteLayout title="Events" description="Events organized by Neeldhara Misra." brandSubtitle="">
  {featured && (
    <section class="featured-band" aria-labelledby="featured-title">
      <div>
        <p class="eyebrow">Up next</p>
        <h2 id="featured-title">{featured.title}</h2>
        <p>{featured.summary}</p>
      </div>
      <a class="icon-link" href={featuredPath} aria-label={`Open ${featured.title} page`}>
        <svg aria-hidden="true" focusable="false" viewBox="0 0 24 24">
          <path d="M10.5 13.5a3.2 3.2 0 0 0 4.5 0l3.4-3.4a3.2 3.2 0 0 0-4.5-4.5l-1.1 1.1" />
          <path d="M13.5 10.5a3.2 3.2 0 0 0-4.5 0l-3.4 3.4a3.2 3.2 0 0 0 4.5 4.5l1.1-1.1" />
          <path d="m9.5 14.5 5-5" />
        </svg>
      </a>
    </section>
  )}

  <section class="event-list-section" id="events" data-event-filters>
    <div class="filter-panel" aria-label="Filter event catalog">
      <div class="filter-status">
        <p class="filter-summary" aria-live="polite" data-filter-summary>Showing all {primaryEvents.length} events</p>
        <button class="filter-reset" type="button" data-filter-reset hidden>Reset filters</button>
      </div>
    </div>

    <div class="event-grid">
      {primaryEvents.map((event) => <EventCard event={event} />)}
    </div>
    <p class="filter-empty" data-filter-empty hidden>No events match these filters.</p>
  </section>

  <script>
    const filterRoot = document.querySelector<HTMLElement>("[data-event-filters]");

    if (filterRoot) {
      const cards = Array.from(filterRoot.querySelectorAll<HTMLElement>("[data-event-card]"));
      const kindButtons = Array.from(filterRoot.querySelectorAll<HTMLButtonElement>("[data-filter-kind]"));
      const yearButtons = Array.from(filterRoot.querySelectorAll<HTMLButtonElement>("[data-filter-year]"));
      const summary = filterRoot.querySelector<HTMLElement>("[data-filter-summary]");
      const empty = filterRoot.querySelector<HTMLElement>("[data-filter-empty]");
      const resetButton = filterRoot.querySelector<HTMLButtonElement>("[data-filter-reset]");
      const validKinds = new Set(["all", ...kindButtons.map((button) => button.dataset.filterKind).filter(Boolean)]);
      const validYears = new Set(["all", ...yearButtons.map((button) => button.dataset.filterYear).filter(Boolean)]);
      const params = new URLSearchParams(window.location.search);

      let activeKind = "all";
      let activeYear = "all";
      const requestedKind = params.get("type");
      const requestedYear = params.get("year");

      if (requestedKind && validKinds.has(requestedKind)) activeKind = requestedKind;
      if (requestedYear && validYears.has(requestedYear)) activeYear = requestedYear;

      function syncButtons(
        buttons: HTMLButtonElement[],
        key: "filterKind" | "filterYear",
        value: string,
      ) {
        buttons.forEach((button) => {
          button.setAttribute("aria-pressed", button.dataset[key] === value ? "true" : "false");
        });
      }

      function syncUrl() {
        const url = new URL(window.location.href);
        if (activeKind === "all") url.searchParams.delete("type");
        else url.searchParams.set("type", activeKind);

        if (activeYear === "all") url.searchParams.delete("year");
        else url.searchParams.set("year", activeYear);

        window.history.replaceState(null, "", `${url.pathname}${url.search}${url.hash}`);
      }

      function getActiveFilterLabel() {
        const filters = [];
        if (activeKind !== "all") filters.push(activeKind);
        if (activeYear !== "all") filters.push(activeYear);
        return filters.length ? ` for ${filters.join(" / ")}` : "";
      }

      function applyFilters(updateUrl = false) {
        let visibleCount = 0;

        cards.forEach((card) => {
          const matchesKind = activeKind === "all" || card.dataset.eventKind === activeKind;
          const matchesYear = activeYear === "all" || card.dataset.eventYear === activeYear;
          const visible = matchesKind && matchesYear;

          card.hidden = !visible;
          if (visible) visibleCount += 1;
        });

        syncButtons(kindButtons, "filterKind", activeKind);
        syncButtons(yearButtons, "filterYear", activeYear);

        if (summary) {
          summary.textContent =
            activeKind === "all" && activeYear === "all"
              ? `Showing all ${cards.length} events`
              : `Showing ${visibleCount} of ${cards.length} events${getActiveFilterLabel()}`;
        }

        if (resetButton) resetButton.hidden = activeKind === "all" && activeYear === "all";
        if (empty) empty.hidden = visibleCount !== 0;
        if (updateUrl) syncUrl();
      }

      kindButtons.forEach((button) => {
        button.addEventListener("click", () => {
          activeKind = button.dataset.filterKind ?? "all";
          applyFilters(true);
        });
      });

      yearButtons.forEach((button) => {
        button.addEventListener("click", () => {
          activeYear = button.dataset.filterYear ?? "all";
          applyFilters(true);
        });
      });

      resetButton?.addEventListener("click", () => {
        activeKind = "all";
        activeYear = "all";
        applyFilters(true);
      });

      applyFilters();
    }
  </script>
</SiteLayout>
