"use client";

import { useState } from "react";

import { useBodyClass } from "@/lib/useBodyClass";

/**
 * The project listing's filter panel.
 *
 * Every href here was built by the backend's UrlBuilder — chips, sort options,
 * clear links, all of them. This component renders labels, counts and flags. It
 * does not know how a listing URL is spelled, which is the point: with Arabic
 * slugs and four dimensions there would otherwise be forty chances per page to
 * encode one differently from the canonical tag it leads to.
 *
 * Structure follows the Blade component:
 *
 *  - a quick bar of presets, then the advanced panel behind a trigger. The panel
 *    used to be the whole filter, forty chips deep, which is what the client was
 *    reacting to.
 *  - `<details>` for the sort menu, because it opens, closes and is keyboard
 *    operable with no JavaScript, and every option inside is a real link.
 *  - the advanced panel is a button plus a sibling panel rather than another
 *    `<details>`: `<details>` keeps its content inside itself, so the trigger had
 *    to become a full-width row for the panel to have any width, which threw the
 *    word out of the line it belongs at the end of.
 *  - the panel ships open and collapses on mount, so with scripting off every
 *    filter is present rather than behind a control that cannot be pressed.
 */
export default function ProjectFilters({ panel }: { panel: any }) {
  const [open, setOpen] = useState<boolean>(Boolean(panel?.advancedOpen));

  /*
   * The panel is collapsed by `body.filters-collapsed`, not by an attribute on
   * the panel itself — the panel element is replaced on every filter change and
   * a class on <body> survives that.
   *
   * It ships open and is collapsed here, so a reader without scripting gets all
   * the filters rather than a control they cannot press.
   */
  useBodyClass("filters-collapsed", !open);

  if (!panel) {
    return null;
  }

  /*
   * Labels arrive resolved from the API.
   *
   * This is a Client Component — it owns the advanced panel's open state — and a
   * translator function cannot be passed across the server/client boundary in
   * the App Router. Resolving them on the server is also where they belong: they
   * come from lang/{ar,en}/, the same files the Blade component read.
   */
  const L = panel.labels;

  return (
    <section className="project-filters" id={panel.anchor} aria-label={L.filters}>
      <div className="project-filters__bar">
        <p className="project-filters__count">
          {L.resultsCount}
        </p>

        <details className="sort-menu">
          <summary className="sort-menu__trigger">
            <span className="sort-menu__label">{L.sortBy}</span>
            <span className="sort-menu__current">{panel.sortLabel}</span>
          </summary>

          <ul className="sort-menu__list">
            {panel.sortOptions.map((option: any) => (
              <li key={option.key}>
                <a
                  className={`sort-menu__option${option.active ? " is-active" : ""}`}
                  href={option.url}
                  aria-current={option.active ? "true" : undefined}
                >
                  {option.label}
                </a>
              </li>
            ))}
          </ul>
        </details>
      </div>

      {/* The tabs are direct children rather than wrapped in a <nav>, so the
          trigger can share the row without `display: contents` taking the nav's
          role out of the accessibility tree. */}
      <div className="filters-head" role="group" aria-label={L.filters}>
        {panel.quick.map((preset: any) => (
          <a
            key={preset.key}
            className={`filters-head__tab${preset.active ? " is-active" : ""}`}
            href={preset.url}
            aria-current={preset.active ? "true" : undefined}
          >
            {preset.label}
          </a>
        ))}

        <button
          className="filters-head__tab filters-head__tab--advanced"
          type="button"
          data-filter-panel-toggle
          aria-expanded={open}
          aria-controls={`${panel.anchor}-advanced`}
          onClick={() => setOpen((value) => !value)}
        >
          {L.advancedFilter}
          {panel.activeCount > 0 ? (
            <span className="filters-head__count">{panel.activeCount}</span>
          ) : null}
        </button>
      </div>

      <div
        className="filters-head__panel"
        id={`${panel.anchor}-advanced`}
        data-filter-panel
        {...(open ? { "data-open": "" } : {})}
      >
        {panel.dimensions.map((dimension: any) => (
          <div
            className="filter-group"
            role="group"
            aria-label={dimension.label}
            key={dimension.key}
          >
            <span className="filter-group__label">{dimension.label}</span>

            <div className="filter-group__options">
              <a
                className={`filter-chip${dimension.cleared ? " is-active" : ""}`}
                href={dimension.clearUrl}
                aria-current={dimension.cleared ? "true" : undefined}
              >
                {L.all}
              </a>

              {dimension.options.map((option: any) => (
                <a
                  key={option.key}
                  className={`filter-chip${option.active ? " is-active" : ""}`}
                  href={option.url}
                  aria-current={option.active ? "true" : undefined}
                >
                  {option.label}
                  {typeof option.count === "number" ? (
                    <span className="filter-chip__count">{option.count}</span>
                  ) : null}
                </a>
              ))}
            </div>
          </div>
        ))}

        {panel.activeCount > 0 ? (
          <div className="project-filters__active">
            <span className="project-filters__active-label">{L.activeFilters}</span>

            {panel.active.map((chip: any, index: number) => (
              <a className="active-chip" href={chip.url} key={index}>
                {chip.label}
                <span className="active-chip__remove" aria-hidden="true">
                  ×
                </span>
              </a>
            ))}

            <a className="active-chip active-chip--clear" href={panel.clearAllUrl}>
              {L.clearFilters}
            </a>
          </div>
        ) : null}
      </div>
    </section>
  );
}
