// hero3d.jsx — Draggable 3D pastry turntable for the hero
const { useState: uSh3, useEffect: uEh3, useRef: uRh3 } = React;

const PASTRIES = [
  { name: "Butter Croissant", tone: "#E8B96A", deep: "#8A5A2A", glow: "#FFE9B8", price: "$6.00", tag: "Daily", img: "brand/photos/croissant-single.jpg" },
  { name: "Cinnamon Roll", tone: "#D89466", deep: "#6E3E1F", glow: "#F4D2A8", price: "$7.00", tag: "Daily favorite", img: "brand/photos/cinnamon-roll-branded.jpg" },
  { name: "Chocolate Croissant", tone: "#A06A3A", deep: "#3A1E10", glow: "#D49B65", price: "$6.75", tag: "Daily", img: "brand/photos/croissant-almond.jpg" },
  { name: "Morning Bun", tone: "#E4A56A", deep: "#7C4820", glow: "#FFD9A0", price: "$7.50", tag: "Crunchy top", img: "brand/photos/morning-bun-new.jpg" },
  { name: "Glazed Donut", tone: "#F4D69A", deep: "#A07640", glow: "#FFF1C8", price: "$4.50", tag: "Bestseller", img: "brand/photos/donuts-new.jpg" },
  { name: "Bear Claw", tone: "#C99060", deep: "#6A3D1A", glow: "#EFC596", price: "$6.75", tag: "Almond", img: "brand/photos/bear-claw.jpg" },
];

function Pastry3D({ p, large }) {
  const size = large ? 240 : 180;
  return (
    <div style={{
      width: size, height: size, borderRadius: "50%",
      background: `radial-gradient(circle at 35% 28%, ${p.glow} 0%, ${p.tone} 35%, ${p.deep} 100%)`,
      boxShadow: `0 30px 60px rgba(0,0,0,0.45), inset -20px -30px 60px rgba(0,0,0,0.35), inset 18px 22px 40px rgba(255,255,255,0.25)`,
      position: "relative", overflow: "hidden"
    }}>
      {p.img && (
        <img src={p.img} alt={p.name}
          style={{ position: "absolute", inset: 0, width: "100%", height: "100%", objectFit: "cover", display: "block" }}/>
      )}
      <div style={{
        position: "absolute", inset: "10%", borderRadius: "50%",
        background: `radial-gradient(ellipse at 38% 30%, rgba(255,250,230,0.55), transparent 45%)`,
        mixBlendMode: "screen"
      }}/>
      {!p.img && (
        <React.Fragment>
          <div style={{ position: "absolute", inset: "20%", borderRadius: "50%", border: `2px solid ${p.deep}`, opacity: 0.18 }}/>
          <div style={{ position: "absolute", inset: "32%", borderRadius: "50%", border: `1.5px solid ${p.deep}`, opacity: 0.22 }}/>
          <div style={{ position: "absolute", inset: "45%", borderRadius: "50%", background: p.deep, opacity: 0.3 }}/>
        </React.Fragment>
      )}
    </div>
  );
}

function HeroTurntable() {
  // Only two pieces of React state: drag cursor + label display (~10fps)
  const [dragging, setDragging] = uSh3(false);
  const [frontIdx, setFrontIdx] = uSh3(0);

  // All animation state in refs — zero React re-renders from the RAF loop
  const containerRef = uRh3(null); // CSS variable injection point
  const angleRef = uRh3(0);        // current rotation angle
  const draggingRef = uRh3(false); // mirror of dragging state for RAF closure
  const startRef = uRh3({ x: 0, a: 0 });
  const velRef = uRh3(0);
  const lastRef = uRh3({ t: 0, x: 0 });
  const autoplay = uRh3(true);
  const frameRef = uRh3(0);

  const count = PASTRIES.length;
  const radius = 260;

  // Write angle to CSS variable — no React involved
  function applyAngle(a) {
    angleRef.current = a;
    if (containerRef.current) {
      containerRef.current.style.setProperty("--rot-y", a + "deg");
    }
  }

  // RAF loop: runs once on mount, never re-runs (empty deps)
  uEh3(() => {
    let raf;
    const tick = () => {
      if (!draggingRef.current) {
        if (autoplay.current && Math.abs(velRef.current) < 0.02) {
          applyAngle(angleRef.current + 0.12);
        } else {
          applyAngle(angleRef.current + velRef.current);
          velRef.current *= 0.95;
          if (Math.abs(velRef.current) < 0.005) velRef.current = 0;
        }
      }
      // Label update throttled to ~10fps
      frameRef.current++;
      if (frameRef.current % 6 === 0) {
        const norm = ((angleRef.current % 360) + 360) % 360;
        const slot = 360 / count;
        const idx = Math.round(norm / slot) % count;
        setFrontIdx(idx);
      }
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  function onDown(e) {
    setDragging(true);
    draggingRef.current = true;
    autoplay.current = false;
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    startRef.current = { x, a: angleRef.current };
    lastRef.current = { t: performance.now(), x };
    velRef.current = 0;
  }
  function onMove(e) {
    if (!draggingRef.current) return;
    const x = e.touches ? e.touches[0].clientX : e.clientX;
    applyAngle(startRef.current.a + (x - startRef.current.x) * 0.5);
    const now = performance.now();
    const dt = now - lastRef.current.t || 16;
    velRef.current = ((x - lastRef.current.x) * 0.5) / (dt / 16);
    lastRef.current = { t: now, x };
  }
  function onUp() {
    setDragging(false);
    draggingRef.current = false;
    setTimeout(() => { autoplay.current = true; }, 4000);
  }

  uEh3(() => {
    if (!dragging) return;
    const move = (e) => onMove(e);
    const up = () => onUp();
    window.addEventListener("mousemove", move);
    window.addEventListener("mouseup", up);
    window.addEventListener("touchmove", move, { passive: true });
    window.addEventListener("touchend", up);
    return () => {
      window.removeEventListener("mousemove", move);
      window.removeEventListener("mouseup", up);
      window.removeEventListener("touchmove", move);
      window.removeEventListener("touchend", up);
    };
  }, [dragging]);

  const front = PASTRIES[(count - frontIdx) % count];

  return (
    <div
      ref={containerRef}
      onMouseDown={onDown}
      onTouchStart={onDown}
      style={{
        position: "relative",
        width: "100%", maxWidth: 720, aspectRatio: "1 / 0.92",
        perspective: 1400,
        margin: "0 auto",
        cursor: dragging ? "grabbing" : "grab",
        userSelect: "none", touchAction: "none"
      }}
    >
      {/* turntable base */}
      <div style={{
        position: "absolute", left: "50%", bottom: "8%", transform: "translateX(-50%)",
        width: "82%", aspectRatio: "1 / 0.22", borderRadius: "50%",
        background: "radial-gradient(ellipse at center, rgba(0,0,0,0.55) 0%, rgba(0,0,0,0.15) 50%, transparent 80%)",
        filter: "blur(8px)"
      }}/>

      {/* 3D ring — transform driven by CSS var(--rot-y), bypasses React entirely */}
      <div style={{
        position: "absolute", inset: 0,
        transformStyle: "preserve-3d",
        transform: "rotateX(18deg) rotateY(var(--rot-y, 0deg))",
      }}>
        {PASTRIES.map((p, i) => {
          const a = (i / count) * 360;
          return (
            <div key={i} style={{
              position: "absolute", left: "50%", top: "50%",
              width: 180, height: 180, marginLeft: -90, marginTop: -90,
              transform: `rotateY(${a}deg) translateZ(${radius}px) rotateY(calc(-1 * var(--rot-y, 0deg))) rotateX(-18deg)`,
              transformStyle: "preserve-3d"
            }}>
              <Pastry3D p={p}/>
            </div>
          );
        })}
      </div>

      {/* Hint */}
      <div style={{
        position: "absolute", bottom: -8, left: "50%", transform: "translateX(-50%)",
        color: "rgba(253,248,240,0.65)", fontSize: 11, letterSpacing: "0.2em",
        textTransform: "uppercase", display: "flex", alignItems: "center", gap: 10
      }}>
        <svg width="18" height="12" viewBox="0 0 18 12" fill="none" stroke="currentColor" strokeWidth="1.4">
          <path d="M2 6 L6 2 M2 6 L6 10 M2 6h14"/>
          <path d="M16 6 L12 2 M16 6 L12 10" transform="translate(-14)"/>
          <path d="M16 6 L12 2 M16 6 L12 10"/>
        </svg>
        <span>Drag to spin</span>
      </div>

      {/* Label — React state, throttled to ~10fps */}
      <div style={{
        position: "absolute", top: "8%", left: "50%", transform: "translateX(-50%)",
        background: "rgba(11,90,102,0.55)", backdropFilter: "blur(20px)",
        border: "1px solid rgba(253,248,240,0.18)",
        padding: "10px 18px", borderRadius: 9999,
        color: "var(--color-cream)", display: "inline-flex", gap: 14, alignItems: "center",
        fontSize: 14, fontWeight: 600, whiteSpace: "nowrap",
        transition: "opacity 250ms"
      }}>
        <span style={{ fontFamily: "var(--display)", fontSize: 17, fontWeight: 600 }}>{front.name}</span>
        <span style={{ width: 4, height: 4, borderRadius: 999, background: "var(--color-honey)" }}/>
        <span style={{ color: "var(--color-honey)", fontWeight: 700 }}>{front.price}</span>
      </div>
    </div>
  );
}

Object.assign(window, { HeroTurntable });
