// ─────────────────────────────────────────────────────────────────────────────
// /gallery — "Version B" of the home: a curved gallery corridor.
//
// Geometry (CSS 3D, no WebGL):
//   The camera sits inside a ring (cylinder) of radius R, pushed toward the
//   front of the ring, looking at the far wall. The wall + floor + ceiling are
//   static; only the ring of hung pieces rotates as you walk (scroll / drag /
//   arrows). The piece straight ahead is the "active" one and drives the
//   caption at the bottom of the screen.
// ─────────────────────────────────────────────────────────────────────────────

const { useState: gUseState, useEffect: gUseEffect, useRef: gUseRef, useMemo: gUseMemo, useCallback: gUseCallback } = React;

const G_WALL_SEGMENTS = 96;

function gMeasure() {
  const vw = window.innerWidth;
  const vh = window.innerHeight;
  const H = Math.round(Math.min(vh * 0.40, vw * 0.62));   // piece height (world px)
  const W = Math.round(H * 0.74);                        // piece width
  return { vw, vh, H, W };
}

function gNumParam(k, d) {
  const q = new URLSearchParams(window.location.search);
  const v = q.has(k) ? parseFloat(q.get(k)) : NaN;
  return Number.isFinite(v) ? v : d;
}

function gNorm(deg) {
  // normalise to (-180, 180]
  let d = ((deg + 180) % 360 + 360) % 360 - 180;
  return d === -180 ? 180 : d;
}

function GalleryPiece({ item, slot, index, step, geo, onPick, active }) {
  const theta = -slot * step;
  const style = {
    width: `${geo.W}px`,
    marginLeft: `${-geo.W / 2}px`,
    marginTop: `${-geo.H / 2}px`,
    transform: `rotateY(${theta}deg) translateZ(${-(geo.R - geo.inset)}px) translateY(${-geo.H * 0.08}px)`,
  };

  if (item.kind === 'title') {
    return (
      <div className="gx-piece gx-piece--title" style={style} data-i={index}>
        <button className="gx-card gx-card--title" style={{ height: `${geo.H}px` }} onClick={() => onPick(index)} aria-label="Index of Taste — introduction">
          <span className="gx-title-eyebrow">Vol. 01</span>
          <img src="index-of-taste.svg?v=2" alt="Index of Taste" className="gx-title-logo" />
          <span className="gx-title-meta">Spring / Summer 2026<br />{item.count} entries</span>
        </button>
      </div>
    );
  }

  const p = item.person;
  const Fig = window.Figure;
  const isTba = !!p.tba;
  return (
    <div className={`gx-piece${active ? ' is-active' : ''}${isTba ? ' gx-piece--tba' : ''}`} style={style} data-i={index}>
      <button
        className="gx-card"
        style={{ height: `${geo.H}px`, '--gx-paper': item.paper }}
        onClick={() => { if (!isTba) onPick(index); }}
        aria-label={isTba ? 'To be announced' : `${p.name}, ${p.role}`}
        aria-disabled={isTba || undefined}
      >
        <span className="gx-card__num">No. {String(item.no).padStart(2, '0')}</span>
        <span className="gx-card__fig">{Fig ? <Fig person={p} bare /> : null}</span>
      </button>
      <div className="gx-label">
        {isTba ? (
          <span className="gx-label__name gx-label__name--tba">To be announced</span>
        ) : (
          <>
            <span className="gx-label__name">{p.name}</span>
            <span className="gx-label__role">{p.role}</span>
          </>
        )}
      </div>
    </div>
  );
}

function GalleryListView({ people, onOpen }) {
  return (
    <div className="gx-list">
      <ol className="gx-list__items">
        {people.map((p, i) => {
          const isTba = !!p.tba;
          return (
            <li key={p.id}>
              <button
                className={`gx-list__row${isTba ? ' gx-list__row--tba' : ''}`}
                onClick={() => { if (!isTba) onOpen(p.id); }}
                aria-disabled={isTba || undefined}
              >
                <span className="gx-list__no">{String(i + 1).padStart(2, '0')}</span>
                {isTba ? (
                  <span className="gx-list__name gx-list__name--tba">To be announced</span>
                ) : (
                  <>
                    <span className="gx-list__name">{p.name}</span>
                    <span className="gx-list__role">{p.role}</span>
                    <span className="gx-list__arrow" aria-hidden="true">→</span>
                  </>
                )}
              </button>
            </li>
          );
        })}
      </ol>
    </div>
  );
}

function GalleryView({ onOpen, onHome }) {
  const people = window.PEOPLE || [];
  const papers = ['#eddbbf', '#F4F0E8', '#e8dfd0', '#efe6d6'];

  const items = gUseMemo(() => [
    { kind: 'title', count: people.length },
    ...people.map((person, i) => ({ kind: 'person', person, no: i + 1, paper: papers[i % papers.length] })),
  ], [people]);

  const N = items.length;
  // The ring only has S physical slots; each slot shows whichever item of the
  // (infinite, looping) sequence is nearest to it, so content swaps silently
  // behind the camera and ~7 pieces are in view at once.
  const S = gNumParam('gn', 13);
  const step = 360 / S;

  const [m, setM] = gUseState(gMeasure);
  const [mode, setMode] = gUseState('gallery');   // 'gallery' | 'list'
  const [pos, setPos] = gUseState(0);              // unbounded integer position along the sequence
  const activeIdx = ((pos % N) + N) % N;
  const [entering, setEntering] = gUseState(false);

  // Ring radius: pieces spaced ~1.5 widths apart along the arc.
  const geo = gUseMemo(() => {
    const num = gNumParam;
    const spacing = m.W * num('gs', 1.3);
    const R = (S * spacing) / (2 * Math.PI);
    return {
      ...m,
      R,
      c: R * num('gc', 0.75),                      // camera distance from ring centre
      persp: Math.round(m.vh * num('gp', 0.5)),   // CSS perspective (smaller = wider lens)
      inset: (m.W * m.W) / (8 * R) + 6,          // keep flat prints in front of the faceted wall
      floorY: m.H * 0.72,                      // floor & ceiling are a 2D gradient behind the wall (see .gx-stage)
      ceilY: -m.H * 1.9,
    };
  }, [m, S]);

  const ringRef = gUseRef(null);
  const rot = gUseRef(0);       // current rotation (deg)
  const target = gUseRef(0);    // target rotation (deg)
  const snapTimer = gUseRef(0);
  const drag = gUseRef(null);

  // ── resize ──
  gUseEffect(() => {
    const onR = () => setM(gMeasure());
    window.addEventListener('resize', onR);
    return () => window.removeEventListener('resize', onR);
  }, []);

  const snap = gUseCallback(() => {
    target.current = Math.round(target.current / step) * step;
  }, [step]);

  const go = gUseCallback((delta) => {
    target.current = (Math.round(target.current / step) + delta) * step;
  }, [step]);


  // ── animation loop ──
  gUseEffect(() => {
    let raf;
    let lastPos = null;
    const reduce = window.matchMedia && window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    const tick = () => {
      const k = reduce ? 0.35 : 0.085;
      rot.current += (target.current - rot.current) * k;
      if (Math.abs(target.current - rot.current) < 0.001) rot.current = target.current;
      const ring = ringRef.current;
      if (ring) {
        ring.style.transform = `rotateY(${rot.current}deg)`;
        // hide pieces that are behind / beside the camera
        const kids = ring.children;
        for (let j = 0; j < kids.length; j++) {
          const phi = gNorm(-j * step + rot.current);
          const a = Math.abs(phi);
          const el = kids[j];
          const vis = a < 112;
          if (el._vis !== vis) { el.style.visibility = vis ? 'visible' : 'hidden'; el._vis = vis; }
        }
      }
      const p = Math.round(rot.current / step);
      if (p !== lastPos) { lastPos = p; setPos(p); }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, [step]);

  // ── input: wheel, keys ──
  gUseEffect(() => {
    if (mode !== 'gallery') return;
    const onWheel = (e) => {
      e.preventDefault();
      const d = Math.abs(e.deltaX) > Math.abs(e.deltaY) ? e.deltaX : e.deltaY;
      target.current += d * 0.06;
      clearTimeout(snapTimer.current);
      snapTimer.current = setTimeout(snap, 160);
    };
    const onKey = (e) => {
      if (e.key === 'ArrowRight' || e.key === 'ArrowDown') { e.preventDefault(); go(1); }
      else if (e.key === 'ArrowLeft' || e.key === 'ArrowUp') { e.preventDefault(); go(-1); }
      else if (e.key === 'Enter') {
        const it = items[activeIdxRef.current];
        if (it && it.kind === 'person' && !it.person.tba) enter(it.person.id);
      }
    };
    window.addEventListener('wheel', onWheel, { passive: false });
    window.addEventListener('keydown', onKey);
    return () => {
      window.removeEventListener('wheel', onWheel);
      window.removeEventListener('keydown', onKey);
      clearTimeout(snapTimer.current);
    };
  }, [mode, snap, go, items]);

  const activeIdxRef = gUseRef(0);
  activeIdxRef.current = activeIdx;

  // ── input: drag (mouse + touch) ──
  const onPointerDown = (e) => {
    if (e.button !== undefined && e.button !== 0) return;
    drag.current = { x: e.clientX, start: target.current, moved: 0 };
  };
  gUseEffect(() => {
    const move = (e) => {
      const d = drag.current;
      if (!d || d.justDragged) return;
      const dx = e.clientX - d.x;
      d.moved = Math.max(d.moved, Math.abs(dx));
      // drag left → walk forward
      target.current = d.start - dx * (step / (geo.W * 0.9));
    };
    const up = () => {
      const d = drag.current;
      if (!d || d.justDragged) return;
      if (d.moved > 4) snap();
      drag.current = d.moved > 4 ? { ...d, justDragged: true } : null;
      setTimeout(() => { if (drag.current && drag.current.justDragged) drag.current = null; }, 0);
    };
    window.addEventListener('pointermove', move);
    window.addEventListener('pointerup', up);
    window.addEventListener('pointercancel', up);
    return () => {
      window.removeEventListener('pointermove', move);
      window.removeEventListener('pointerup', up);
      window.removeEventListener('pointercancel', up);
    };
  }, [step, geo.W, snap]);

  const enter = (id) => {
    setEntering(true);
    setTimeout(() => onOpen(id), 520);
  };

  // i: unbounded sequence index of the clicked piece
  const onPick = (i) => {
    if (drag.current && drag.current.justDragged) return;
    const it = items[((i % N) + N) % N];
    if (i === pos && it.kind === 'person' && !it.person.tba) enter(it.person.id);
    else target.current = i * step;
  };

  // ── static wall, floor & ceiling ──
  const wall = gUseMemo(() => {
    const segs = [];
    const segW = 2 * geo.R * Math.tan(Math.PI / G_WALL_SEGMENTS) + 1.5;
    const h = geo.floorY - geo.ceilY;
    for (let s = 0; s < G_WALL_SEGMENTS; s++) {
      const th = (s / G_WALL_SEGMENTS) * 360;
      const phi = Math.abs(gNorm(th));
      if (phi > 104) continue;
      // view-relative shading: far wall brightest, near walls fall into soft grey
      const shade = Math.round(250 - Math.pow(phi / 104, 1.6) * 22);
      segs.push(
        <div key={s} className="gx-wall__seg" style={{
          width: `${segW}px`,
          height: `${h}px`,
          marginLeft: `${-segW / 2}px`,
          marginTop: `${geo.ceilY}px`,
          background: `linear-gradient(180deg, rgb(${shade - 6},${shade - 6},${shade - 7}) 0%, rgb(${shade},${shade},${shade - 1}) 38%, rgb(${shade - 3},${shade - 3},${shade - 4}) 100%)`,
          transform: `rotateY(${th}deg) translateZ(${-geo.R}px)`,
        }} />
      );
    }
    return segs;
  }, [geo]);

  const active = items[activeIdx];
  const sceneTransform = `translateZ(${geo.persp - geo.c}px)`;

  return (
    <div className={`gx${entering ? ' is-entering' : ''}`} data-mode={mode}>
      <header className="gx-top">
        <button className="gx-top__brand" onClick={onHome} aria-label="Index of Taste home">
          <img src="index-of-taste.svg?v=2" alt="Index of Taste" />
        </button>
        <div className="gx-toggle" role="tablist" aria-label="View">
          <button role="tab" aria-selected={mode === 'gallery'} className={mode === 'gallery' ? 'is-on' : ''} onClick={() => setMode('gallery')}>Gallery</button>
          <button role="tab" aria-selected={mode === 'list'} className={mode === 'list' ? 'is-on' : ''} onClick={() => setMode('list')}>List</button>
        </div>
      </header>

      {mode === 'list' ? (
        <GalleryListView people={people} onOpen={onOpen} />
      ) : (
        <>
          <div
            className="gx-stage"
            style={{ perspective: `${geo.persp}px` }}
            onPointerDown={onPointerDown}
          >
            <div className="gx-scene" style={{ transform: sceneTransform }}>
              <div className="gx-wall">{wall}</div>
              <div className="gx-ring" ref={ringRef}>
                {Array.from({ length: S }, (_, slot) => {
                  const i = slot + S * Math.round((pos - slot) / S);
                  return (
                    <GalleryPiece
                      key={slot}
                      slot={slot}
                      item={items[((i % N) + N) % N]}
                      index={i}
                      step={step}
                      geo={geo}
                      onPick={onPick}
                      active={i === pos}
                    />
                  );
                })}
              </div>
            </div>
          </div>

          <footer className="gx-caption" aria-live="polite">
            {active && active.kind === 'person' ? (
              active.person.tba ? (
                <div className="gx-caption__inner" key={activeIdx}>
                  <span className="gx-caption__eyebrow">No. {String(active.no).padStart(2, '0')} — Vol. 01</span>
                  <h2 className="gx-caption__title">To be announced</h2>
                </div>
              ) : (
                <div className="gx-caption__inner" key={activeIdx}>
                  <span className="gx-caption__eyebrow">No. {String(active.no).padStart(2, '0')} — {active.person.role}</span>
                  <h2 className="gx-caption__title">{active.person.name}</h2>
                  <button className="gx-caption__cta" onClick={() => enter(active.person.id)}>Enter the profile →</button>
                </div>
              )
            ) : (
              <div className="gx-caption__inner" key="intro">
                <span className="gx-caption__eyebrow">Vol. 01 — Spring / Summer 2026</span>
                <h2 className="gx-caption__title">An Index of Taste</h2>
                <button className="gx-caption__cta" onClick={() => go(1)}>Walk the index →</button>
              </div>
            )}
          </footer>

          <div className="gx-nav">
            <span className="gx-nav__hint">Scroll or drag to walk<br />Click a portrait to enter</span>
            <div className="gx-nav__btns">
              <button onClick={() => go(-1)} aria-label="Previous">‹</button>
              <button onClick={() => go(1)} aria-label="Next">›</button>
            </div>
          </div>
        </>
      )}
    </div>
  );
}

window.GalleryView = GalleryView;
