"use client";

import Image from "next/image";
import { useEffect, useMemo, useRef, useState } from "react";
import type { ArchiveEvent } from "@/content/archive";

type Props = {
  events: (ArchiveEvent & { images: string[]; full: string[] })[];
};

const CATEGORIES = ["All", "Exhibitions", "Private Events", "The Collection", "Acquisitions"] as const;

export default function GalleryExplorer({ events }: Props) {
  const [cat, setCat] = useState<(typeof CATEGORIES)[number]>("All");
  const [open, setOpen] = useState<string | null>(events[0]?.key ?? null);
  const [lightbox, setLightbox] = useState<{ src: string; alt: string } | null>(null);
  const closeRef = useRef<HTMLButtonElement>(null);
  const returnFocusRef = useRef<HTMLElement | null>(null);

  const visible = useMemo(
    () => (cat === "All" ? events : events.filter((e) => e.category === cat)),
    [cat, events]
  );

  useEffect(() => {
    if (!lightbox) return;
    closeRef.current?.focus();
    const onKey = (e: KeyboardEvent) => {
      if (e.key === "Escape") setLightbox(null);
      if (e.key === "Tab") {
        // the dialog has a single focusable control; keep focus on it
        e.preventDefault();
        closeRef.current?.focus();
      }
    };
    document.addEventListener("keydown", onKey);
    return () => {
      document.removeEventListener("keydown", onKey);
      returnFocusRef.current?.focus();
    };
  }, [lightbox]);

  return (
    <div>
      {/* Filter, typographic, no chrome */}
      <div
        role="group"
        aria-label="Archive categories"
        style={{ display: "flex", gap: "clamp(18px, 3vw, 40px)", flexWrap: "wrap", borderBottom: "1px solid var(--hairline)", paddingBottom: 18 }}
      >
        {CATEGORIES.map((c) => (
          <button
            key={c}
            aria-pressed={cat === c}
            onClick={() => setCat(c)}
            style={{
              background: "none",
              border: 0,
              padding: "6px 0",
              cursor: "pointer",
              fontFamily: "var(--font-sans)",
              fontSize: 11.5,
              fontWeight: 500,
              letterSpacing: "0.2em",
              textTransform: "uppercase",
              color: cat === c ? "var(--ivory)" : "var(--stone)",
              borderBottom: cat === c ? "1px solid var(--sapphire)" : "1px solid transparent",
              transition: "color 0.3s var(--ease), border-color 0.3s var(--ease)",
            }}
          >
            {c}
          </button>
        ))}
      </div>

      {/* Events */}
      <div style={{ display: "grid", gap: "clamp(10px, 1.5vw, 18px)", marginTop: "clamp(32px, 4vw, 56px)" }}>
        {visible.map((e) => {
          const isOpen = open === e.key;
          return (
            <section key={e.key} aria-label={e.title} style={{ border: "1px solid var(--hairline)", background: "var(--night-850)" }}>
              <button
                onClick={() => setOpen(isOpen ? null : e.key)}
                aria-expanded={isOpen}
                style={{
                  display: "grid",
                  gridTemplateColumns: "minmax(90px, 140px) 1fr auto auto",
                  gap: "clamp(12px, 2.5vw, 32px)",
                  alignItems: "baseline",
                  width: "100%",
                  textAlign: "left",
                  background: "none",
                  border: 0,
                  cursor: "pointer",
                  padding: "clamp(18px, 2.5vw, 30px) clamp(16px, 2.5vw, 32px)",
                  color: "inherit",
                }}
              >
                <span className="caption" style={{ letterSpacing: "0.14em", textTransform: "uppercase" }}>{e.when}</span>
                <span className="serif" style={{ fontSize: "clamp(1.15rem, 1.8vw, 1.5rem)", color: "var(--ivory)" }}>
                  {e.title}
                </span>
                <span className="caption tabular">{e.images.length}</span>
                <span className="caption" aria-hidden="true" style={{ color: "var(--sapphire)", transform: isOpen ? "rotate(90deg)" : "none", transition: "transform 0.35s var(--ease)", display: "inline-block" }}>
                  →
                </span>
              </button>
              {isOpen && (
                <div style={{ padding: "0 clamp(16px, 2.5vw, 32px) clamp(18px, 2.5vw, 30px)" }}>
                  <p className="caption" style={{ maxWidth: "60ch", marginBottom: 20 }}>{e.note}</p>
                  <div
                    style={{
                      display: "grid",
                      gridTemplateColumns: "repeat(auto-fill, minmax(150px, 1fr))",
                      gap: 3,
                    }}
                  >
                    {e.images.map((src, i) => (
                      <button
                        key={src}
                        onClick={(ev) => {
                          returnFocusRef.current = ev.currentTarget;
                          setLightbox({ src: e.full[i], alt: `${e.title}, photograph ${i + 1}` });
                        }}
                        style={{ background: "none", border: 0, padding: 0, cursor: "zoom-in" }}
                        aria-label={`View photograph ${i + 1} of ${e.title}`}
                      >
                        <span className="archive-img" style={{ display: "block", aspectRatio: "1/1", border: 0 }}>
                          {/* thumbs are small; plain img keeps the archive light */}
                          {/* eslint-disable-next-line @next/next/no-img-element */}
                          <img src={src} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover" }} />
                        </span>
                      </button>
                    ))}
                  </div>
                </div>
              )}
            </section>
          );
        })}
      </div>

      {/* Lightbox */}
      {lightbox && (
        <div
          role="dialog"
          aria-modal="true"
          aria-label="Photograph"
          onClick={() => setLightbox(null)}
          style={{
            position: "fixed",
            inset: 0,
            zIndex: 200,
            background: "rgba(4, 9, 15, 0.94)",
            display: "grid",
            placeItems: "center",
            padding: "clamp(16px, 4vw, 64px)",
            cursor: "zoom-out",
          }}
        >
          <Image
            src={lightbox.src}
            alt={lightbox.alt}
            width={1600}
            height={1200}
            style={{ maxWidth: "100%", maxHeight: "88vh", width: "auto", height: "auto", objectFit: "contain" }}
          />
          <button
            ref={closeRef}
            onClick={() => setLightbox(null)}
            aria-label="Close"
            style={{
              position: "absolute",
              top: 20,
              right: 26,
              background: "none",
              border: 0,
              color: "var(--ivory)",
              fontSize: 28,
              cursor: "pointer",
              fontFamily: "var(--font-serif)",
            }}
          >
            ×
          </button>
        </div>
      )}
    </div>
  );
}
