/* ============================================================
   ГАЛЕРЕЯ + LIGHTBOX
   ============================================================ */

/* lazy reveal on scroll */
function useReveal() {
  const ref = useRef(null);
  useEffect(() => {
    const els = ref.current ? ref.current.querySelectorAll(".reveal") : [];
    const animReady = document.documentElement.classList.contains("anim-ready");
    if (!animReady || !("IntersectionObserver" in window)) {
      els.forEach((el) => el.classList.add("in"));
      return;
    }
    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((e) => {
          if (e.isIntersecting) { e.target.classList.add("in"); io.unobserve(e.target); }
        });
      },
      { rootMargin: "0px 0px -8% 0px", threshold: 0.05 }
    );
    els.forEach((el, i) => { el.style.transitionDelay = (Math.min(i, 6) * 45) + "ms"; io.observe(el); });
    return () => io.disconnect();
  });
  return ref;
}

/* ---- сетка (masonry) ---- */
function GridView({ items, onOpen }) {
  const ref = useReveal();
  return (
    <div className="grid" ref={ref}>
      {items.map((w, i) => (
        <figure
          className="grid__item reveal"
          key={w.id}
          onClick={() => onOpen(i)}
          role="button"
          tabIndex={0}
          onKeyDown={(e) => { if (e.key === "Enter") onOpen(i); }}
        >
          <Placeholder ratio={w.ratio} src={w.src} pos={w.pos} tone={w.tone} label={w.label} alt={w.title} no={String(i + 1).padStart(2, "0")} />
          <figcaption className="tile-cap">
            <span className="t">{w.title}</span>
            <span className="m">{w.meta}</span>
          </figcaption>
        </figure>
      ))}
    </div>
  );
}

/* ---- список (крупные строки) ---- */
function ListView({ items, onOpen }) {
  const ref = useReveal();
  return (
    <div className="list" ref={ref}>
      {items.map((w, i) => (
        <div
          className="list__row reveal"
          key={w.id}
          onClick={() => onOpen(i)}
          role="button"
          tabIndex={0}
          onKeyDown={(e) => { if (e.key === "Enter") onOpen(i); }}
        >
          <span className="list__num">{String(i + 1).padStart(2, "0")}</span>
          <div className="list__thumb">
            <Placeholder ratio="1:1" src={w.src} pos={w.pos} tone={w.tone} label={w.label} alt={w.title} />
          </div>
          <div>
            <div className="list__title">{w.title}</div>
          </div>
          <div style={{ display: "flex", alignItems: "center", gap: 22 }}>
            <span className="list__meta">{w.meta}</span>
            <span className="arrow"><Icon.arrow /></span>
          </div>
        </div>
      ))}
    </div>
  );
}

/* ---- галерея ---- */
function Gallery({ id, kicker, title, lead, items, view, onView }) {
  const [lb, setLb] = useState(-1);
  return (
    <section className="gallery wrap page" key={id}>
      <div className="gallery__head">
        <div>
          <div className="eyebrow" style={{ marginBottom: 16 }}>{kicker}</div>
          <h1 className="gallery__title">{title}</h1>
        </div>
        <p className="gallery__lead">{lead}</p>
      </div>

      <div className="gallery__bar">
        <span className="gallery__count">{String(items.length).padStart(2, "0")} работ</span>
        <div className="viewtoggle" role="group" aria-label="Вид галереи">
          <button className={view === "grid" ? "is-active" : ""} onClick={() => onView("grid")} aria-pressed={view === "grid"}>
            <Icon.grid /> Сетка
          </button>
          <button className={view === "list" ? "is-active" : ""} onClick={() => onView("list")} aria-pressed={view === "list"}>
            <Icon.list /> Список
          </button>
        </div>
      </div>

      {view === "grid"
        ? <GridView items={items} onOpen={setLb} />
        : <ListView items={items} onOpen={setLb} />}

      <Lightbox items={items} index={lb} onClose={() => setLb(-1)} onIndex={setLb} />
    </section>
  );
}

/* ---- LIGHTBOX ---- */
function Lightbox({ items, index, onClose, onIndex }) {
  const open = index >= 0;
  const touch = useRef({ x: 0, y: 0 });

  const prev = useCallback(() => onIndex((index - 1 + items.length) % items.length), [index, items.length, onIndex]);
  const next = useCallback(() => onIndex((index + 1) % items.length), [index, items.length, onIndex]);

  useEffect(() => {
    if (!open) return;
    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 = ""; };
  }, [open, prev, next, onClose]);

  const w = open ? items[index] : null;

  return (
    <div
      className={"lightbox" + (open ? " is-open" : "")}
      aria-hidden={!open}
      onTouchStart={(e) => { touch.current = { x: e.touches[0].clientX, y: e.touches[0].clientY }; }}
      onTouchEnd={(e) => {
        const dx = e.changedTouches[0].clientX - touch.current.x;
        const dy = e.changedTouches[0].clientY - touch.current.y;
        if (Math.abs(dx) > 50 && Math.abs(dx) > Math.abs(dy)) { dx > 0 ? prev() : next(); }
      }}
    >
      <div className="lightbox__top">
        <span className="lightbox__counter">
          {open ? String(index + 1).padStart(2, "0") : "00"} <span style={{ opacity: 0.5 }}>/ {String(items.length).padStart(2, "0")}</span>
        </span>
        <button className="lightbox__close" onClick={onClose}>Закрыть <Icon.close /></button>
      </div>

      <div className="lightbox__stage">
        <button className="lightbox__nav lightbox__nav--prev" onClick={prev} aria-label="Предыдущая"><Icon.left /></button>
        <div className="lightbox__img">
          {w && <Placeholder key={w.id} ratio={w.ratio} src={w.src} pos={w.pos} tone={w.tone} label={w.label} alt={w.title} no={String(index + 1).padStart(2, "0")} />}
        </div>
        <button className="lightbox__nav lightbox__nav--next" onClick={next} aria-label="Следующая"><Icon.right /></button>
      </div>

      <div className="lightbox__cap">
        <div>
          <h3>{w ? w.title : ""}</h3>
          <p>{w ? w.desc : ""}</p>
        </div>
        <span className="meta">{w ? w.meta : ""}</span>
      </div>
    </div>
  );
}

Object.assign(window, { Gallery, GridView, ListView, Lightbox, useReveal });
