/* ============================================================
   GALLERY COMPONENTS — Nav, grid, lightbox
   ============================================================ */
const { useState, useEffect, useCallback, useRef } = React;

/* ---------- Top navigation (inner pages) ---------- */
function Nav({ dir, route, go }) {
  const cols = window.SITE.collections;
  const onWork = route.page === "gallery" || route.page === "work";
  return (
    <header className={"nav nav--" + dir}>
      <button className="nav__brand" onClick={() => go({ page: "home" })}>
        {window.SITE.name}
      </button>
      <nav className="nav__links">
        {cols.map((c) => (
          <button
            key={c.id}
            className={
              "nav__link" +
              (route.page === "gallery" && route.id === c.id ? " is-active" : "")
            }
            onClick={() => go({ page: "gallery", id: c.id })}
          >
            {c.title}
          </button>
        ))}
        <span className="nav__sep" aria-hidden="true" />
        <button
          className={"nav__link" + (route.page === "about" ? " is-active" : "")}
          onClick={() => go({ page: "about" })}
        >
          About
        </button>
      </nav>
    </header>
  );
}

/* ---------- Uniform grid of one collection ---------- */
function GalleryGrid({ collection, t, onOpen }) {
  const [loaded, setLoaded] = useState({});
  return (
    <section className="gallery">
      <div className="gallery__head">
        <h1 className="gallery__title">{collection.title}</h1>
        <p className="gallery__blurb">{collection.blurb}</p>
        <span className="gallery__count">
          {String(collection.photos.length).padStart(2, "0")} frames
        </span>
      </div>

      <div
        className="grid"
        style={{ "--cols": t.columns, "--gap": t.gap + "px" }}
      >
        {collection.photos.map((p, i) => (
          <figure
            key={p.src}
            className={"cell" + (loaded[i] ? " is-loaded" : "")}
            onClick={() => onOpen(i)}
            tabIndex={0}
            onKeyDown={(e) => (e.key === "Enter" ? onOpen(i) : null)}
          >
            <img
              src={p.src}
              alt={collection.title + " " + (i + 1)}
              style={{ aspectRatio: p.w + " / " + p.h }}
              ref={(el) => {
                if (el && el.complete && !loaded[i])
                  setLoaded((s) => (s[i] ? s : { ...s, [i]: true }));
              }}
              onLoad={() => setLoaded((s) => (s[i] ? s : { ...s, [i]: true }))}
            />
            <span className="cell__plus" aria-hidden="true">+</span>
            {t.showCaptions && (
              <figcaption className="cell__cap">
                {collection.title} · {String(i + 1).padStart(2, "0")}
              </figcaption>
            )}
          </figure>
        ))}
      </div>
    </section>
  );
}

/* ---------- Fullscreen lightbox ---------- */
function Lightbox({ collection, index, setIndex, onClose }) {
  const photos = collection.photos;
  const prev = useCallback(
    () => setIndex((i) => (i - 1 + photos.length) % photos.length),
    [photos.length, setIndex]
  );
  const next = useCallback(
    () => setIndex((i) => (i + 1) % photos.length),
    [photos.length, setIndex]
  );

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      else if (e.key === "ArrowLeft") prev();
      else if (e.key === "ArrowRight") next();
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = "hidden";
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [prev, next, onClose]);

  if (index == null) return null;
  const p = photos[index];

  return (
    <div className="lb" onClick={onClose}>
      <button className="lb__close" onClick={onClose} aria-label="Close">
        Close
      </button>
      <button
        className="lb__nav lb__nav--prev"
        onClick={(e) => { e.stopPropagation(); prev(); }}
        aria-label="Previous"
      >
        <span>←</span>
      </button>
      <figure className="lb__stage" onClick={(e) => e.stopPropagation()}>
        <img key={p.src} src={p.src} alt="" className="lb__img" />
        <figcaption className="lb__cap">
          <span>{collection.title}</span>
          <span className="lb__num">
            {String(index + 1).padStart(2, "0")} / {String(photos.length).padStart(2, "0")}
          </span>
        </figcaption>
      </figure>
      <button
        className="lb__nav lb__nav--next"
        onClick={(e) => { e.stopPropagation(); next(); }}
        aria-label="Next"
      >
        <span>→</span>
      </button>
    </div>
  );
}

Object.assign(window, { Nav, GalleryGrid, Lightbox });
