/* ══════════════════════════════════════════════════════
   STACKED PANELS — 3D fanned project chooser
   Plain-React reimplementation of a Framer-Motion component.
   Uses a single rAF spring loop (no external deps).
   window.StackedPanels({ projects, onSelect })
   ══════════════════════════════════════════════════════ */
const SP_Z_SPREAD = 46;
const SP_SIGMA = 2.6;

function StackedPanels({ projects, onSelect }) {
  const total = projects.length;
  const containerRef = React.useRef(null);
  const stageRef = React.useRef(null);
  const panelRefs = React.useRef([]);
  const [hovered, setHovered] = React.useState(-1);

  // per-panel base geometry (stable) — uniform size for a clean coverflow
  const geo = React.useMemo(() => projects.map((_, i) => {
    const w = 194, h = 268;
    const baseZ = i * 3;
    return { w, h, baseZ, opacity: 1, ml: -w / 2, mt: -h / 2, t: total > 1 ? i / (total - 1) : 0 };
  }), [projects, total]);

  React.useEffect(() => {
    const container = containerRef.current;
    const stage = stageRef.current;
    if (!container || !stage) return;

    // animated state
    const cur = { rotX: 18, rotY: -42, y: new Array(total).fill(0), sy: new Array(total).fill(1), x: new Array(total).fill(0), z: new Array(total).fill(0), op: new Array(total).fill(1) };
    const tgt = { rotX: 18, rotY: -42, y: new Array(total).fill(0), sy: new Array(total).fill(1), x: new Array(total).fill(0), z: new Array(total).fill(0), op: new Array(total).fill(1) };
    let raf;
    let lastFocus = -1;

    const applyStage = () => {
      stage.style.transform = `rotateX(${cur.rotX}deg) rotateY(${cur.rotY}deg)`;
    };
    const applyPanel = (i) => {
      const el = panelRefs.current[i];
      if (!el) return;
      const g = geo[i];
      el.style.transform = `translateZ(${g.baseZ + cur.z[i]}px) translateX(${cur.x[i]}px) translateY(${cur.y[i]}px) scaleY(${cur.sy[i]})`;
      el.style.opacity = cur.op[i];
    };

    const tick = () => {
      const kScene = 0.1, kWave = 0.18;
      cur.rotX += (tgt.rotX - cur.rotX) * kScene;
      cur.rotY += (tgt.rotY - cur.rotY) * kScene;
      applyStage();
      for (let i = 0; i < total; i++) {
        cur.y[i] += (tgt.y[i] - cur.y[i]) * kWave;
        cur.sy[i] += (tgt.sy[i] - cur.sy[i]) * kWave;
        cur.x[i] += (tgt.x[i] - cur.x[i]) * kWave;
        cur.z[i] += (tgt.z[i] - cur.z[i]) * kWave;
        cur.op[i] += (tgt.op[i] - cur.op[i]) * kWave;
        applyPanel(i);
      }
      raf = requestAnimationFrame(tick);
    };

    const SPREAD = 132;   // gap between neighbours in the opened coverflow
    const onMove = (e) => {
      const rect = container.getBoundingClientRect();
      const cx = Math.max(0, Math.min(1, (e.clientX - rect.left) / rect.width));
      const cy = (e.clientY - rect.top) / rect.height;
      tgt.rotY = -14 + (cx - 0.5) * 8;
      tgt.rotX = 12 + (cy - 0.5) * -8;
      const cursorPos = cx * (total - 1);
      const focus = Math.round(cursorPos);
      if (focus !== lastFocus) { lastFocus = focus; setHovered(focus); }
      for (let i = 0; i < total; i++) {
        const signed = i - cursorPos;
        const dist = Math.abs(signed);
        const influence = Math.exp(-(dist * dist) / (2 * 1.0 * 1.0));
        // coverflow: focused panel slides to centre, others spread out around it
        tgt.x[i] = signed * SPREAD;
        tgt.y[i] = -influence * 42;
        tgt.sy[i] = 0.85 + influence * 0.15;
        tgt.z[i] = influence * 130 - dist * 10;
        tgt.op[i] = 0.42 + influence * 0.58;
      }
    };
    const onLeave = () => {
      tgt.rotY = -42; tgt.rotX = 18;
      lastFocus = -1; setHovered(-1);
      for (let i = 0; i < total; i++) { tgt.y[i] = 0; tgt.sy[i] = 1; tgt.x[i] = 0; tgt.z[i] = 0; tgt.op[i] = 1; }
    };

    container.addEventListener('mousemove', onMove);
    container.addEventListener('mouseleave', onLeave);
    raf = requestAnimationFrame(tick);
    return () => {
      cancelAnimationFrame(raf);
      container.removeEventListener('mousemove', onMove);
      container.removeEventListener('mouseleave', onLeave);
    };
  }, [geo, total]);

  return (
    <div ref={containerRef} className="sp-container"
      style={{ position:'relative', width:'100%', height:'520px', display:'flex',
               alignItems:'center', justifyContent:'center', userSelect:'none', perspective:'950px' }}>
      <div ref={stageRef} style={{ position:'relative', left:'0px', width:0, height:0, transformStyle:'preserve-3d' }}>
        {projects.map((p, i) => {
          const g = geo[i];
          return (
            <div key={i}
              ref={el => panelRefs.current[i] = el}
              onMouseEnter={() => setHovered(i)}
              onClick={() => onSelect && onSelect(p)}
              style={{
                position:'absolute', width:g.w, height:g.h, marginLeft:g.ml, marginTop:g.mt,
                borderRadius:'10px', overflow:'hidden', cursor:'pointer',
                transformOrigin:'bottom center', opacity:1,
                boxShadow: hovered === i ? '0 24px 60px rgba(0,0,0,0.5)' : '0 10px 30px rgba(0,0,0,0.28)',
              }}>
              {/* thumbnail */}
              <div style={{ position:'absolute', inset:0, backgroundImage:`url(${p.thumb})`,
                            backgroundSize:'cover', backgroundPosition:'center' }} />
              {/* dark grade for legibility */}
              <div style={{ position:'absolute', inset:0,
                            background:'linear-gradient(to bottom, rgba(0,0,0,0.05) 0%, rgba(0,0,0,0.15) 45%, rgba(0,0,0,0.82) 100%)' }} />
              {/* hover accent tint */}
              <div style={{ position:'absolute', inset:0, background:'#fff',
                            mixBlendMode:'overlay', opacity: hovered === i ? 0.12 : 0,
                            transition:'opacity 0.25s' }} />
              {/* border */}
              <div style={{ position:'absolute', inset:0, borderRadius:'inherit', boxSizing:'border-box',
                            border:'1px solid rgba(255,255,255,0.16)' }} />
              {/* label */}
              <div style={{ position:'absolute', left:0, right:0, bottom:0, padding:'14px 14px 16px', textAlign:'left' }}>
                <div style={{ fontSize:'8px', letterSpacing:'0.18em', textTransform:'uppercase',
                              color:'rgba(255,255,255,0.65)', marginBottom:'5px' }}>{p.category} · {p.year}</div>
                <div style={{ fontFamily:"'Cormorant Garamond', serif", fontSize:'19px', fontWeight:400,
                              color:'#fff', lineHeight:1.05 }}>{p.title}</div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

window.StackedPanels = StackedPanels;
