/* ─── Gallery: tabbed image gallery ───────────────────────────
   Content comes from window.HOOPOE_GALLERY (defined in index.html).
   Click a tab → its images show in a grid. Click an image → lightbox.
   ───────────────────────────────────────────────────────────── */

function Gallery() {
  const TABS = window.HOOPOE_GALLERY || [];
  const [active, setActive] = React.useState(0);
  const [lightbox, setLightbox] = React.useState(null); // { images, index }

  if (TABS.length === 0) return null;

  const activeTab = TABS[active] || TABS[0];
  const images = activeTab.images || [];

  const openLightbox = (i) => setLightbox({ images, index: i });
  const closeLightbox = () => setLightbox(null);
  const nav = (dir) => setLightbox(lb => {
    if (!lb) return lb;
    const n = lb.images.length;
    return { ...lb, index: (lb.index + dir + n) % n };
  });

  React.useEffect(() => {
    if (!lightbox) return;
    const onKey = (e) => {
      if (e.key === 'Escape') closeLightbox();
      if (e.key === 'ArrowRight') nav(1);
      if (e.key === 'ArrowLeft') nav(-1);
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [lightbox]);

  return (
    <section className="section" id="gallery" data-screen-label="Gallery">
      <div className="container">
        <div className="section-head">
          <div>
            <div className="eyebrow">03 / Gallery</div>
            <h2>See the work, capability by capability.</h2>
          </div>
          <p className="head-aside">
            Select a capability to browse finished parts, prototypes and production runs from our workshop floor.
          </p>
        </div>

        {/* Tabs */}
        <div className="gallery-tabs" role="tablist">
          {TABS.map((t, i) => (
            <button
              key={t.id}
              role="tab"
              aria-selected={i === active}
              className={`gallery-tab ${i === active ? 'active' : ''}`}
              onClick={() => setActive(i)}
            >
              <span className="gallery-tab-num">{String(i + 1).padStart(2, '0')}</span>
              {t.label}
            </button>
          ))}
        </div>

        {/* Image grid */}
        <div className="gallery-grid">
          {images.map((src, i) => (
            <button key={src + i} className="gallery-cell" onClick={() => openLightbox(i)}>
              <img src={src} alt={`${activeTab.label} — ${i + 1}`} loading="lazy"/>
              <span className="gallery-cell-zoom" aria-hidden="true">
                <svg viewBox="0 0 24 24" width="20" height="20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
                  <circle cx="11" cy="11" r="7"/>
                  <line x1="16" y1="16" x2="21" y2="21"/>
                  <line x1="11" y1="8" x2="11" y2="14"/>
                  <line x1="8" y1="11" x2="14" y2="11"/>
                </svg>
              </span>
            </button>
          ))}
          {images.length === 0 && (
            <div className="gallery-empty">No images yet for this capability.</div>
          )}
        </div>
      </div>

      {/* Lightbox */}
      {lightbox && (
        <div className="lightbox" onClick={(e) => e.target === e.currentTarget && closeLightbox()}>
          <button className="lightbox-close" onClick={closeLightbox} aria-label="Close">×</button>
          {lightbox.images.length > 1 && (
            <button className="lightbox-nav prev" onClick={() => nav(-1)} aria-label="Previous">‹</button>
          )}
          <figure className="lightbox-figure">
            <img src={lightbox.images[lightbox.index]} alt=""/>
            <figcaption>
              {activeTab.label} · {lightbox.index + 1} / {lightbox.images.length}
            </figcaption>
          </figure>
          {lightbox.images.length > 1 && (
            <button className="lightbox-nav next" onClick={() => nav(1)} aria-label="Next">›</button>
          )}
        </div>
      )}
    </section>
  );
}

Object.assign(window, { Gallery });
