// HyperspaceMathAnimations.jsx — Brendan's game animation grammar.
// 4 stacked states all looping live, using Hyperspace Math as the reference
// scene. Cockpit-view of a starship with HUD console, holographic equation,
// distant ringed planets, parallax starfield, nebula shimmer.

const { useMemo } = React;

/* ============================================================
   STARFIELD — 2 parallax layers (HTML overlay for clean infinite scroll)
   ============================================================ */

const makeStars = (n, seed) => {
  const arr = [];
  for (let i = 0; i < n; i++) {
    const x = Math.sin((i + seed) * 9301) * 10000;
    const y = Math.sin((i + seed) * 7919) * 10000;
    const z = Math.sin((i + seed) * 3571) * 10000;
    arr.push({
      i,
      left: (x - Math.floor(x)) * 100,
      top: (y - Math.floor(y)) * 100,
      size: 0.6 + (z - Math.floor(z)) * 2.4,
      bright: 0.4 + ((x - Math.floor(x)) + (y - Math.floor(y))) / 2 * 0.6,
    });
  }
  return arr;
};

const Starfield = ({ count, seed, anim, sizeBoost = 1, sparkle = false }) => {
  const stars = useMemo(() => makeStars(count, seed), [count, seed]);
  return (
    <div className={`absolute top-0 left-0 h-full ${anim}`} style={{ width: "200%" }} aria-hidden>
      {/* render stars twice (across 0–50% and 50–100% of 200%-wide container) for seamless loop */}
      {[0, 50].map((offset) =>
        stars.map((s) => (
          <div
            key={`${offset}-${s.i}`}
            className="absolute"
            style={{
              left: `${(s.left / 2) + offset}%`,
              top: `${s.top}%`,
              width: s.size * sizeBoost,
              height: s.size * sizeBoost,
              opacity: s.bright,
            }}
          >
            {sparkle && s.size > 2 ? (
              <svg viewBox="0 0 10 10" className="w-full h-full" fill="#FFEB80">
                <path d="M5 0 L6 4 L10 5 L6 6 L5 10 L4 6 L0 5 L4 4 Z" />
              </svg>
            ) : (
              <div className="w-full h-full rounded-full bg-white" />
            )}
          </div>
        ))
      )}
    </div>
  );
};

/* ============================================================
   SPACE BACKDROP — nebula, planets, moon (SVG)
   ============================================================ */

const SpaceBackdrop = () => (
  <svg viewBox="0 0 800 360" preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full block">
    <defs>
      <linearGradient id="hs-sky" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" stopColor="#06091F" />
        <stop offset="60%" stopColor="#1F2F52" />
        <stop offset="100%" stopColor="#0A1024" />
      </linearGradient>
      <radialGradient id="hs-neb1" cx="50%" cy="50%">
        <stop offset="0%" stopColor="#E8B651" stopOpacity="0.42" />
        <stop offset="100%" stopColor="#E8B651" stopOpacity="0" />
      </radialGradient>
      <radialGradient id="hs-neb2" cx="50%" cy="50%">
        <stop offset="0%" stopColor="#7E5BA0" stopOpacity="0.55" />
        <stop offset="100%" stopColor="#7E5BA0" stopOpacity="0" />
      </radialGradient>
      <radialGradient id="hs-neb3" cx="50%" cy="50%">
        <stop offset="0%" stopColor="#3D5A8C" stopOpacity="0.5" />
        <stop offset="100%" stopColor="#3D5A8C" stopOpacity="0" />
      </radialGradient>
      <radialGradient id="hs-planet" cx="34%" cy="32%">
        <stop offset="0%" stopColor="#FBEACA" />
        <stop offset="50%" stopColor="#E8B651" />
        <stop offset="100%" stopColor="#3F2C0A" />
      </radialGradient>
      <radialGradient id="hs-moon" cx="40%" cy="40%">
        <stop offset="0%" stopColor="#C9DCFF" />
        <stop offset="100%" stopColor="#3D5A8C" />
      </radialGradient>
    </defs>
    <rect width="800" height="360" fill="url(#hs-sky)" />
    {/* nebula clouds (animated) */}
    <g className="anim-nebula-shimmer" style={{ transformOrigin: "30% 40%" }}>
      <ellipse cx="180" cy="140" rx="220" ry="120" fill="url(#hs-neb1)" />
      <ellipse cx="220" cy="100" rx="140" ry="70" fill="url(#hs-neb2)" />
    </g>
    <g className="anim-nebula-shimmer" style={{ transformOrigin: "70% 60%", animationDelay: "-2.5s" }}>
      <ellipse cx="560" cy="220" rx="200" ry="100" fill="url(#hs-neb3)" />
      <ellipse cx="600" cy="200" rx="120" ry="60" fill="url(#hs-neb2)" opacity="0.65" />
    </g>

    {/* distant ringed planet (upper right) */}
    <g transform="translate(670 76)">
      <ellipse cx="0" cy="2" rx="58" ry="10" fill="#E8B651" opacity="0.5" />
      <circle cx="0" cy="0" r="32" fill="url(#hs-planet)" />
      <ellipse cx="0" cy="2" rx="58" ry="10" fill="none" stroke="#E8B651" strokeWidth="2" />
      <ellipse cx="0" cy="2" rx="48" ry="7" fill="none" stroke="#FBEACA" strokeWidth="0.8" opacity="0.6" />
      <path d="M-26 -10 Q0 -14 26 -10" stroke="#7A5318" strokeWidth="1.5" fill="none" opacity="0.7" />
      <path d="M-28 8 Q0 6 28 8" stroke="#7A5318" strokeWidth="1.2" fill="none" opacity="0.6" />
      <ellipse cx="-10" cy="-12" rx="12" ry="7" fill="#FFFFFF" opacity="0.28" />
    </g>
    {/* small distant moon */}
    <g transform="translate(110 70)">
      <circle cx="0" cy="0" r="14" fill="url(#hs-moon)" />
      <circle cx="-4" cy="-3" r="3" fill="#1F2F52" opacity="0.4" />
      <circle cx="4" cy="4" r="2" fill="#1F2F52" opacity="0.4" />
      <circle cx="-5" cy="5" r="1.5" fill="#1F2F52" opacity="0.4" />
    </g>
  </svg>
);

/* ============================================================
   BRENDAN ROCKETSHIP — single SVG, face varies via prop
   ============================================================ */

const BrendanDefs = ({ id }) => (
  <defs>
    <linearGradient id={`${id}-body`} x1="0%" y1="0%" x2="100%" y2="0%">
      <stop offset="0%" stopColor="#5A75AD" />
      <stop offset="30%" stopColor="#7E92BD" />
      <stop offset="60%" stopColor="#3D5A8C" />
      <stop offset="100%" stopColor="#15203F" />
    </linearGradient>
    <linearGradient id={`${id}-nose`} x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stopColor="#FBEACA" />
      <stop offset="40%" stopColor="#E8B651" />
      <stop offset="100%" stopColor="#8E6722" />
    </linearGradient>
    <linearGradient id={`${id}-fin`} x1="0%" y1="0%" x2="100%" y2="100%">
      <stop offset="0%" stopColor="#F2DBA6" />
      <stop offset="50%" stopColor="#E8B651" />
      <stop offset="100%" stopColor="#7A5318" />
    </linearGradient>
    <radialGradient id={`${id}-window`} cx="35%" cy="30%" r="80%">
      <stop offset="0%" stopColor="#FFFFFF" />
      <stop offset="40%" stopColor="#C9DCFF" />
      <stop offset="100%" stopColor="#1F2F52" />
    </radialGradient>
    <radialGradient id={`${id}-flame1`} cx="50%" cy="10%" r="100%">
      <stop offset="0%" stopColor="#FFFFFF" />
      <stop offset="25%" stopColor="#FFEB80" />
      <stop offset="60%" stopColor="#E8B651" stopOpacity="0.95" />
      <stop offset="100%" stopColor="#E07A5F" stopOpacity="0" />
    </radialGradient>
    <radialGradient id={`${id}-flame2`} cx="50%" cy="10%" r="100%">
      <stop offset="0%" stopColor="#FFFFFF" />
      <stop offset="50%" stopColor="#FFD96B" />
      <stop offset="100%" stopColor="#E07A5F" stopOpacity="0" />
    </radialGradient>
    <filter id={`${id}-glow`} x="-50%" y="-50%" width="200%" height="200%">
      <feGaussianBlur stdDeviation="5" />
    </filter>
  </defs>
);

const RocketFace = ({ mood = "determined" }) => {
  if (mood === "joy") {
    return (
      <g>
        {/* squinted joy eyes */}
        <path d="M86 134 Q92 128 98 134" stroke="#15203F" strokeWidth="2.4" fill="none" strokeLinecap="round" />
        <path d="M114 134 Q108 128 102 134" stroke="#15203F" strokeWidth="2.4" fill="none" strokeLinecap="round" />
        <path d="M92 146 Q100 154 108 146 Q104 148 100 148 Q96 148 92 146 Z" fill="#15203F" />
      </g>
    );
  }
  if (mood === "concerned") {
    return (
      <g>
        <circle cx="92" cy="138" r="2" fill="#15203F" />
        <circle cx="108" cy="138" r="2" fill="#15203F" />
        {/* drooped brow */}
        <path d="M86 132 Q92 134 96 134" stroke="#15203F" strokeWidth="2" fill="none" strokeLinecap="round" />
        <path d="M114 132 Q108 134 104 134" stroke="#15203F" strokeWidth="2" fill="none" strokeLinecap="round" />
        {/* small worried mouth */}
        <path d="M94 148 Q100 145 106 148" stroke="#15203F" strokeWidth="1.8" fill="none" strokeLinecap="round" />
      </g>
    );
  }
  if (mood === "proud") {
    return (
      <g>
        {/* smug eyes */}
        <path d="M86 134 Q90 132 96 134" stroke="#15203F" strokeWidth="2.2" fill="none" strokeLinecap="round" />
        <path d="M114 134 Q110 132 104 134" stroke="#15203F" strokeWidth="2.2" fill="none" strokeLinecap="round" />
        <circle cx="91" cy="137" r="1.4" fill="#15203F" />
        <circle cx="109" cy="137" r="1.4" fill="#15203F" />
        <path d="M92 146 Q100 152 108 146" stroke="#15203F" strokeWidth="2.2" fill="none" strokeLinecap="round" />
      </g>
    );
  }
  // determined (default)
  return (
    <g>
      <path d="M86 136 L97 140 L86 142 Z" fill="#15203F" />
      <path d="M114 136 L103 140 L114 142 Z" fill="#15203F" />
      <circle cx="90" cy="139" r="1.4" fill="#FFFFFF" />
      <circle cx="110" cy="139" r="1.4" fill="#FFFFFF" />
      <path d="M84 132 L96 134" stroke="#15203F" strokeWidth="2.2" strokeLinecap="round" />
      <path d="M116 132 L104 134" stroke="#15203F" strokeWidth="2.2" strokeLinecap="round" />
      <path d="M92 149 Q100 153 110 148" stroke="#15203F" strokeWidth="2.2" fill="none" strokeLinecap="round" />
    </g>
  );
};

const BrendanRocket = ({ id, mood = "determined", thrust = "pulse" }) => (
  <svg viewBox="0 0 200 220" className="w-full h-full block">
    <BrendanDefs id={id} />
    {/* outer flame glow */}
    <g style={{ transformOrigin: "100px 180px" }} className={thrust === "flare" ? "anim-thruster-flare" : thrust === "sputter" ? "anim-thruster-sputter" : "anim-thruster-pulse"}>
      <ellipse cx="100" cy="204" rx="30" ry="18" fill="#E07A5F" opacity="0.45" filter={`url(#${id}-glow)`} />
      <path d="M78 176 Q82 206 100 218 Q118 206 122 176 Z" fill={`url(#${id}-flame1)`} />
      <path d="M86 176 Q90 200 100 210 Q110 200 114 176 Z" fill={`url(#${id}-flame2)`} />
      <path d="M94 176 Q96 194 100 202 Q104 194 106 176 Z" fill="#FFFFFF" opacity="0.9" />
    </g>

    {/* side fins */}
    <path d="M60 152 L74 130 L74 178 L52 184 Z" fill={`url(#${id}-fin)`} />
    <path d="M140 152 L126 130 L126 178 L148 184 Z" fill={`url(#${id}-fin)`} />
    <path d="M64 154 L72 134 L72 174 Z" fill="#FBEACA" opacity="0.55" />
    <path d="M136 154 L128 134 L128 174 Z" fill="#FBEACA" opacity="0.55" />

    {/* fuselage */}
    <path d="M74 80 L74 174 Q74 184 80 186 L120 186 Q126 184 126 174 L126 80 Z" fill={`url(#${id}-body)`} />
    <path d="M84 82 L84 178 Q84 184 88 184 L92 184 Q88 184 88 178 L88 82 Z" fill="#FFFFFF" opacity="0.22" />

    {/* nose cone */}
    <path d="M74 80 Q74 56 100 36 Q126 56 126 80 Z" fill={`url(#${id}-nose)`} />
    <path d="M86 74 Q92 56 100 44" stroke="#FFEB80" strokeWidth="3.5" strokeLinecap="round" fill="none" opacity="0.7" />
    <path d="M74 80 L126 80" stroke="#7A5318" strokeWidth="1.5" opacity="0.6" />

    {/* racing stripes */}
    <rect x="74" y="108" width="52" height="3.5" fill="#E8B651" />
    <rect x="74" y="114" width="52" height="1.5" fill="#E8B651" opacity="0.55" />

    {/* porthole with face */}
    <circle cx="100" cy="140" r="23" fill="#15203F" />
    <circle cx="100" cy="140" r="20" fill={`url(#${id}-window)`} />
    <circle cx="100" cy="140" r="20" fill="none" stroke="#E8B651" strokeWidth="2.5" />
    <path d="M88 128 Q94 124 102 124" stroke="#FFFFFF" strokeWidth="2" fill="none" opacity="0.7" strokeLinecap="round" />
    <g fill="#E8B651">
      <circle cx="78" cy="100" r="1.6" />
      <circle cx="122" cy="100" r="1.6" />
      <circle cx="78" cy="170" r="1.6" />
      <circle cx="122" cy="170" r="1.6" />
    </g>

    <RocketFace mood={mood} />

    {/* booster vents */}
    <rect x="76" y="178" width="48" height="5" fill="#15203F" rx="1" />
    <rect x="82" y="183" width="36" height="3" fill="#15203F" rx="1" />
  </svg>
);

/* ============================================================
   COCKPIT CHROME + HUD CONSOLE
   ============================================================ */

const CockpitChrome = () => (
  <svg viewBox="0 0 800 360" preserveAspectRatio="xMidYMid slice" className="absolute inset-0 w-full h-full block pointer-events-none">
    <defs>
      <linearGradient id="cock-frame" x1="0%" y1="0%" x2="0%" y2="100%">
        <stop offset="0%" stopColor="#152042" />
        <stop offset="100%" stopColor="#06091F" />
      </linearGradient>
    </defs>
    {/* top frame */}
    <path d="M0 0 L800 0 L800 28 Q740 38 600 36 Q400 30 200 36 Q60 38 0 28 Z" fill="url(#cock-frame)" />
    <path d="M0 28 Q60 38 200 36 Q400 30 600 36 Q740 38 800 28" stroke="#E8B651" strokeWidth="1" opacity="0.4" fill="none" />
    {/* top indicators */}
    <g>
      <circle cx="40" cy="14" r="3" fill="#7DD3A8" />
      <circle cx="56" cy="14" r="3" fill="#E8B651" />
      <circle cx="72" cy="14" r="3" fill="#3D5A8C" />
      <rect x="100" y="10" width="40" height="8" rx="2" fill="#1F2F52" stroke="#E8B651" strokeWidth="0.5" />
      <rect x="102" y="12" width="28" height="4" fill="#E8B651" opacity="0.7" />
      <text x="760" y="18" textAnchor="end" fontFamily="JetBrains Mono, monospace" fontWeight="700" fontSize="11" fill="#E8B651">SECTOR · 7G</text>
    </g>

    {/* left side frame */}
    <path d="M0 28 L0 360 L36 360 Q40 200 36 28 Z" fill="url(#cock-frame)" />
    {/* right side frame */}
    <path d="M800 28 L800 360 L764 360 Q760 200 764 28 Z" fill="url(#cock-frame)" />

    {/* bottom console */}
    <path d="M0 360 L800 360 L800 280 Q740 270 600 274 Q400 272 200 274 Q60 270 0 280 Z" fill="url(#cock-frame)" />
    {/* console rim */}
    <path d="M0 280 Q60 270 200 274 Q400 272 600 274 Q740 270 800 280" stroke="#E8B651" strokeWidth="1.5" fill="none" />

    {/* corner glints */}
    <circle cx="20" cy="20" r="2" fill="#E8B651" />
    <circle cx="780" cy="20" r="2" fill="#E8B651" />
    <circle cx="20" cy="340" r="2" fill="#E8B651" />
    <circle cx="780" cy="340" r="2" fill="#E8B651" />
  </svg>
);

const HudConsole = ({ state = "idle" }) => (
  <div className="absolute inset-x-0 bottom-0 h-[18%] sm:h-[20%] z-10 pointer-events-none px-6 sm:px-10 pb-2 sm:pb-3 flex items-end gap-3 sm:gap-5 hud-scanlines">
    {/* left HUD */}
    <div className="flex-1 flex flex-col gap-1 min-w-0">
      <div className="font-mono text-[9px] sm:text-[10px] text-brendan-amber/80 tracking-wider uppercase">FUEL</div>
      <div className="h-2 bg-brendan-deep/60 rounded-full overflow-hidden ring-1 ring-brendan-amber/30">
        <div className="h-full bg-gradient-to-r from-brendan-amber to-[#FBEACA] anim-hud-pulse" style={{ width: "82%" }} />
      </div>
      <div className="font-mono text-[9px] sm:text-[10px] text-white/70 tracking-wider">82% · ON LINE</div>
    </div>
    {/* center status pill */}
    <div className="flex-shrink-0 flex flex-col items-center gap-1">
      {state === "correct" && (
        <div className="anim-lock-pop">
          <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-[#7DD3A8] text-brendan-bg font-mono font-bold text-[11px] sm:text-[12px] tracking-wider shadow-glow">
            <svg viewBox="0 0 12 12" className="w-3 h-3" fill="currentColor"><path d="M2 6 L5 9 L10 3" stroke="currentColor" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
            LOCKED IN
          </div>
        </div>
      )}
      {state === "wrong" && (
        <div className="anim-recalc-blink">
          <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-brendan-amber/90 text-brendan-bg font-mono font-bold text-[11px] sm:text-[12px] tracking-wider">
            <span className="inline-block w-1.5 h-1.5 rounded-full bg-brendan-bg anim-console-blink" />
            RECALCULATE
          </div>
        </div>
      )}
      {state === "end" && (
        <div className="anim-badge-glow inline-flex items-center justify-center w-9 h-9 sm:w-11 sm:h-11 rounded-full bg-brendan-amber text-brendan-deep font-mono font-bold text-[10px]">
          <svg viewBox="0 0 24 24" className="w-5 h-5" fill="currentColor">
            <path d="M12 1 L15 8 L22 8 L17 13 L19 21 L12 17 L5 21 L7 13 L2 8 L9 8 Z" />
          </svg>
        </div>
      )}
      {state === "idle" && (
        <div className="inline-flex items-center gap-1.5 px-3 py-1 rounded-full bg-brendan-deep/80 text-brendan-amber font-mono font-bold text-[11px] tracking-wider ring-1 ring-brendan-amber/40">
          <span className="inline-block w-1.5 h-1.5 rounded-full bg-brendan-amber anim-console-blink" />
          AWAIT INPUT
        </div>
      )}
    </div>
    {/* right HUD */}
    <div className="flex-1 flex flex-col gap-1 items-end min-w-0">
      <div className="font-mono text-[9px] sm:text-[10px] text-brendan-amber/80 tracking-wider uppercase">VELOCITY</div>
      <div className="font-mono font-bold text-white/90 text-[12px] sm:text-[14px] tabular-nums">
        {state === "correct" ? "C × 1.0" : state === "wrong" ? "0.0 km/s" : "0.4 km/s"}
      </div>
      <div className="font-mono text-[9px] sm:text-[10px] text-white/60 tracking-wider">HEADING 042°</div>
    </div>
  </div>
);

/* ============================================================
   HOLOGRAPHIC EQUATION PANEL
   ============================================================ */

const Hologram = ({ children, big = false }) => (
  <div className={`absolute z-20 pointer-events-none left-[14%] sm:left-[10%] top-[18%] sm:top-[14%]`}>
    <div className="anim-holo-flicker relative">
      {/* glow halo */}
      <div className="absolute -inset-3 rounded-2xl bg-brendan-amber/15 blur-2xl" />
      <div className="relative bg-brendan-amber/8 rounded-2xl px-4 sm:px-6 py-3 sm:py-4 ring-1 ring-brendan-amber/60 shadow-glow backdrop-blur-sm" style={{ background: "rgba(232,182,81,0.08)" }}>
        <div className="font-mono text-[9px] sm:text-[10px] text-brendan-amber/80 tracking-[0.22em] uppercase mb-1">EQUATION · DECODE</div>
        <p className={`font-display ${big ? "text-[28px] sm:text-[44px]" : "text-[24px] sm:text-[36px]"} font-semibold text-brendan-amber leading-none tracking-tight`} style={{ textShadow: "0 0 12px rgba(232,182,81,0.6)" }}>
          {children}
        </p>
        {/* corner brackets */}
        <svg className="absolute top-0 left-0 w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="#E8B651" strokeWidth="1.5"><path d="M0 4 L0 0 L4 0" /></svg>
        <svg className="absolute top-0 right-0 w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="#E8B651" strokeWidth="1.5"><path d="M8 0 L12 0 L12 4" /></svg>
        <svg className="absolute bottom-0 left-0 w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="#E8B651" strokeWidth="1.5"><path d="M0 8 L0 12 L4 12" /></svg>
        <svg className="absolute bottom-0 right-0 w-3 h-3" viewBox="0 0 12 12" fill="none" stroke="#E8B651" strokeWidth="1.5"><path d="M8 12 L12 12 L12 8" /></svg>
      </div>
    </div>
  </div>
);

/* ============================================================
   HYPERSPACE STREAKS — radial lines pulling past
   ============================================================ */

const HyperspaceStreaks = ({ count = 36, seed = 9 }) => {
  const ps = useMemo(() => {
    const rnd = (i) => { const x = Math.sin((i + seed) * 9301) * 10000; return x - Math.floor(x); };
    const arr = [];
    for (let i = 0; i < count; i++) {
      const r = (k) => rnd(i * 7 + k);
      const angle = r(1) * Math.PI * 2;
      const dist = 80 + r(2) * 280;
      const x = Math.cos(angle) * dist;
      const y = Math.sin(angle) * dist;
      arr.push({
        i,
        rot: angle * 180 / Math.PI,
        sx: x,
        sy: y,
        len: 30 + r(3) * 80,
        delay: -r(4) * 5,
        op: 0.5 + r(5) * 0.5,
      });
    }
    return arr;
  }, [count, seed]);
  return (
    <div className="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden>
      {ps.map((p) => (
        <div
          key={p.i}
          className="absolute anim-streak"
          style={{
            left: "50%",
            top: "44%",
            width: p.len,
            height: 2,
            transformOrigin: "0 50%",
            transform: `rotate(${p.rot}deg)`,
            background: "linear-gradient(to right, transparent, #FFEB80, #FFFFFF)",
            ["--sx"]: `${p.sx}px`,
            ["--sy"]: `${p.sy}px`,
            opacity: p.op,
            animationDelay: `${p.delay}s`,
            borderRadius: "2px",
          }}
        />
      ))}
    </div>
  );
};

/* ============================================================
   AMBER PARTICLES (light orbs drifting around correct state)
   ============================================================ */

const AmberParticles = ({ count = 30, seed = 11 }) => {
  const ps = useMemo(() => {
    const rnd = (i) => { const x = Math.sin((i + seed) * 9301) * 10000; return x - Math.floor(x); };
    const arr = [];
    for (let i = 0; i < count; i++) {
      const r = (k) => rnd(i * 7 + k);
      const angle = r(1) * Math.PI * 2;
      const dist = 30 + r(2) * 180;
      arr.push({
        i,
        cx: Math.cos(angle) * dist,
        cy: Math.sin(angle) * dist - 30,
        size: 4 + r(3) * 6,
        delay: -r(4) * 5,
      });
    }
    return arr;
  }, [count, seed]);
  return (
    <div className="absolute inset-0 pointer-events-none overflow-hidden" aria-hidden>
      {ps.map((p) => (
        <div
          key={p.i}
          className="absolute anim-amber-particle"
          style={{
            left: "50%",
            top: "50%",
            width: p.size,
            height: p.size,
            ["--cx"]: `${p.cx}px`,
            ["--cy"]: `${p.cy}px`,
            animationDelay: `${p.delay}s`,
          }}
        >
          <div className="w-full h-full rounded-full bg-brendan-amber shadow-glow" />
        </div>
      ))}
    </div>
  );
};

/* ============================================================
   WAYPOINT PLANET (end-of-round)
   ============================================================ */

const Waypoint = () => (
  <svg viewBox="0 0 200 200" className="absolute w-[20%] sm:w-[18%]" style={{ right: "12%", top: "30%", maxWidth: 160 }}>
    <defs>
      <radialGradient id="wp-glow" cx="50%" cy="50%">
        <stop offset="0%" stopColor="#FBEACA" stopOpacity="0.85" />
        <stop offset="40%" stopColor="#E8B651" stopOpacity="0.5" />
        <stop offset="100%" stopColor="#E8B651" stopOpacity="0" />
      </radialGradient>
      <radialGradient id="wp-planet" cx="34%" cy="34%">
        <stop offset="0%" stopColor="#C5DCB6" />
        <stop offset="55%" stopColor="#7AA66F" />
        <stop offset="100%" stopColor="#2A4A22" />
      </radialGradient>
    </defs>
    <g className="anim-waypoint-glow" style={{ transformOrigin: "100px 100px" }}>
      <circle cx="100" cy="100" r="90" fill="url(#wp-glow)" />
    </g>
    <circle cx="100" cy="100" r="46" fill="url(#wp-planet)" />
    {/* continents */}
    <ellipse cx="84" cy="86" rx="14" ry="10" fill="#3F6A38" opacity="0.85" />
    <ellipse cx="110" cy="108" rx="18" ry="12" fill="#3F6A38" opacity="0.85" />
    <ellipse cx="92" cy="118" rx="10" ry="6" fill="#3F6A38" opacity="0.85" />
    {/* highlight */}
    <ellipse cx="86" cy="84" rx="14" ry="8" fill="#FFFFFF" opacity="0.25" />
    {/* atmosphere ring */}
    <circle cx="100" cy="100" r="48" fill="none" stroke="#7DD3A8" strokeWidth="2" opacity="0.65" />
    {/* waypoint marker pin above */}
    <g transform="translate(100 30)">
      <path d="M0 0 L-7 -16 L7 -16 Z" fill="#E8B651" />
      <circle cx="0" cy="-22" r="6" fill="#E8B651" />
      <text x="0" y="-19" textAnchor="middle" fontFamily="JetBrains Mono, monospace" fontWeight="700" fontSize="7" fill="#15203F">7G</text>
    </g>
  </svg>
);

/* ============================================================
   UI ATOMS
   ============================================================ */

const StateLabel = ({ num, title, kind, desc }) => (
  <div className="flex items-baseline gap-3 mb-3 sm:mb-4">
    <div className="font-kid text-[12px] tracking-[0.2em] font-semibold text-walnut-3">{String(num).padStart(2, "0")}</div>
    <div className="flex-1 min-w-0">
      <h2 className="font-display italic text-walnut text-[24px] sm:text-[30px] leading-tight">
        <span className="font-semibold not-italic mr-2">{title}</span>
        <span className="font-display italic text-walnut-2">({kind})</span>
      </h2>
      <p className="font-kid text-walnut-3 text-[12px] sm:text-[13px] mt-1 max-w-[64ch]">{desc}</p>
    </div>
  </div>
);

const AnswerBtn = ({ label, kind = "default", className = "" }) => {
  const base = "min-h-[56px] sm:min-h-[64px] px-4 sm:px-6 rounded-2xl font-mono font-bold text-[18px] sm:text-[22px] shadow-btn select-none transition-all flex items-center justify-center gap-2 tracking-wider";
  if (kind === "correct") return <div className={`${base} bg-brendan-amber text-brendan-deep shadow-glow ${className}`}>{label}</div>;
  if (kind === "ghost")   return <div className={`${base} bg-brendan-deep/80 text-brendan-amber ring-1 ring-brendan-amber/40 ${className}`}>{label}</div>;
  if (kind === "primary") return <div className={`${base} bg-brendan-amber text-brendan-deep ${className}`}>{label}</div>;
  if (kind === "dim")     return <div className={`${base} bg-brendan-deep/60 text-white/40 ring-1 ring-brendan-amber/20 ${className}`}>{label}</div>;
  return <div className={`${base} bg-brendan-deep/80 text-white/90 ring-1 ring-brendan-amber/30 ${className}`}>{label}</div>;
};

const PraiseWord = ({ word = "On target!" }) => (
  <div className="absolute inset-x-0 top-[8%] sm:top-[6%] flex justify-center pointer-events-none z-30">
    <div className="anim-praise-pop">
      <h3 className="font-display italic font-bold text-[40px] sm:text-[60px] leading-none tracking-tight"
          style={{ color: "#E8B651", textShadow: "0 4px 0 #15203F, 0 0 24px rgba(232,182,81,0.7), 0 0 60px rgba(232,182,81,0.45)" }}>
        {word}
      </h3>
    </div>
  </div>
);

const HintCard = ({ children }) => (
  <div className="absolute right-[6%] top-[14%] max-w-[40%] z-20 pointer-events-none anim-hint-pop">
    <div className="bg-brendan-deep/95 text-white rounded-2xl px-4 py-3 shadow-lift ring-1 ring-brendan-amber/40 backdrop-blur-sm">
      <div className="flex items-start gap-2.5">
        <div className="mt-0.5 w-5 h-5 rounded-full bg-brendan-amber text-brendan-deep flex items-center justify-center font-mono font-bold text-[10px] flex-shrink-0">i</div>
        <div>
          <div className="font-mono text-[9px] uppercase tracking-[0.22em] text-brendan-amber mb-0.5">FLIGHT ASSIST</div>
          <p className="font-kid text-white text-[13px] sm:text-[14px] leading-snug">{children}</p>
        </div>
      </div>
    </div>
  </div>
);

const XpTag = () => (
  <div className="absolute right-[26%] bottom-[3%] z-30 anim-coin-float pointer-events-none">
    <div className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-full bg-brendan-amber text-brendan-deep shadow-glow font-mono font-bold text-[12px] sm:text-[13px] tracking-wider">
      <svg viewBox="0 0 12 12" className="w-3 h-3" fill="currentColor"><path d="M6 1 L7 4 L10 5 L7 6 L6 9 L5 6 L2 5 L5 4 Z" /></svg>
      +25 XP
    </div>
  </div>
);

const GoldStar = ({ delay = 0, size = 40 }) => (
  <div className="inline-block star-stamp" style={{ animationDelay: `${delay}s`, width: size, height: size }}>
    <svg viewBox="0 0 40 40" className="w-full h-full">
      <defs>
        <radialGradient id={`hs-gs-${delay}`} cx="35%" cy="30%">
          <stop offset="0%" stopColor="#FBEACA" />
          <stop offset="50%" stopColor="#E8B651" />
          <stop offset="100%" stopColor="#8E6722" />
        </radialGradient>
      </defs>
      <path d="M20 3 L25 15 L38 17 L28 26 L31 39 L20 32 L9 39 L12 26 L2 17 L15 15 Z" fill={`url(#hs-gs-${delay})`} stroke="#7A5318" strokeWidth="1.2" strokeLinejoin="round" />
      <ellipse cx="15" cy="12" rx="4" ry="2.4" fill="#FFFFFF" opacity="0.55" />
    </svg>
  </div>
);

const RibbonBanner = ({ text }) => (
  <div className="relative inline-block">
    <svg viewBox="0 0 320 56" className="absolute inset-0 w-full h-full" preserveAspectRatio="none">
      <defs>
        <linearGradient id="hs-ribbon" x1="0%" y1="0%" x2="0%" y2="100%">
          <stop offset="0%" stopColor="#7E92BD" />
          <stop offset="100%" stopColor="#15203F" />
        </linearGradient>
      </defs>
      <path d="M0 28 L12 8 L308 8 L320 28 L308 48 L12 48 Z" fill="url(#hs-ribbon)" />
      <path d="M0 28 L12 8 L308 8 L320 28" stroke="#E8B651" strokeWidth="1.5" fill="none" opacity="0.6" />
    </svg>
    <div className="relative px-8 sm:px-10 py-2 sm:py-3 font-mono font-bold text-brendan-amber text-[14px] sm:text-[16px] tracking-[0.18em] z-10">{text}</div>
  </div>
);

/* ============================================================
   COMMON SCENE WRAPPER
   ============================================================ */

const SceneFrame = ({ children, shake = false }) => (
  <div className={`relative aspect-[16/7.4] sm:aspect-[16/7.2] overflow-hidden bg-brendan-bg ${shake ? "anim-cam-shake" : ""}`}>
    <SpaceBackdrop />
    {/* parallax starfields */}
    <Starfield count={70} seed={1} anim="anim-star-far" sizeBoost={0.8} />
    <Starfield count={40} seed={2} anim="anim-star-near" sizeBoost={1.2} sparkle />
    {children}
    <CockpitChrome />
  </div>
);

/* ============================================================
   STATES
   ============================================================ */

const StateIdle = () => (
  <section>
    <StateLabel
      num={1}
      title="Idle"
      kind="the prompt"
      desc="Rocket hovers (4s hover-bob). Thrusters pulse softly (1.5s ease-in-out). Starfield drifts in 2 parallax layers (far 60s, near 30s). Nebula shimmers (8s, opacity 0.7→1). Holographic equation flickers subtly. HUD readouts pulse."
    />
    <article className="rounded-[24px] bg-cream paper-grain ring-1 ring-walnut/15 shadow-lift overflow-hidden">
      <SceneFrame>
        <Hologram>12 × 8 = <span className="opacity-60">?</span></Hologram>
        <div className="absolute anim-hover-bob" style={{ left: "47%", top: "26%", width: "20%", maxWidth: 200 }}>
          <BrendanRocket id="brendan-idle" mood="determined" thrust="pulse" />
        </div>
        <HudConsole state="idle" />
      </SceneFrame>
      <div className="bg-brendan-bg px-4 sm:px-6 py-4 sm:py-5">
        <div className="grid grid-cols-4 gap-2 sm:gap-3 max-w-[640px] mx-auto">
          <AnswerBtn label="84" />
          <AnswerBtn label="96" />
          <AnswerBtn label="108" />
          <AnswerBtn label="112" />
        </div>
      </div>
    </article>
  </section>
);

const StateCorrect = () => (
  <section>
    <StateLabel
      num={2}
      title="Correct"
      kind="hyperspace jump"
      desc="Rocket leans + scales 1.1× into hyperspace. Thrusters flare amber-gold (0.6s). 36 star-streaks pull radially past the camera. 30 amber-gold light particles drift outward. Console flips to '✓ LOCKED IN'. Italic 'On target!' praise pop. Camera shakes ±2px."
    />
    <article className="rounded-[24px] bg-cream paper-grain ring-1 ring-walnut/15 shadow-lift overflow-hidden">
      <SceneFrame shake>
        <HyperspaceStreaks count={36} seed={9} />
        <AmberParticles count={30} seed={11} />
        <Hologram>12 × <span className="text-[#7DD3A8]">8</span> = <span className="text-[#7DD3A8]">96</span></Hologram>
        <PraiseWord word="On target!" />
        <div className="absolute anim-hyperjump-rocket" style={{ left: "47%", top: "26%", width: "20%", maxWidth: 200 }}>
          <BrendanRocket id="brendan-jump" mood="joy" thrust="flare" />
        </div>
        <HudConsole state="correct" />
      </SceneFrame>
      <div className="bg-brendan-bg px-4 sm:px-6 py-4 sm:py-5 relative">
        <div className="grid grid-cols-4 gap-2 sm:gap-3 max-w-[640px] mx-auto relative">
          <AnswerBtn label="84" />
          <div className="relative">
            <AnswerBtn label="96" kind="correct" />
            <XpTag />
          </div>
          <AnswerBtn label="108" />
          <AnswerBtn label="112" />
        </div>
      </div>
    </article>
  </section>
);

const StateWrong = () => (
  <section>
    <StateLabel
      num={3}
      title="Wrong"
      kind="recalculate, pilot"
      desc="Rocket dips 8px + tilts -3° once. Thrusters sputter (opacity blink, scale dip). Console flashes amber 'RECALCULATE'. Warm amber vignette pulses (1.5s × 2). Hint card slides in from right. No alarm sound, no red — supportive instead."
    />
    <article className="rounded-[24px] bg-cream paper-grain ring-1 ring-walnut/15 shadow-lift overflow-hidden">
      <SceneFrame>
        <Hologram>12 × 8 = <span className="opacity-60">?</span></Hologram>
        {/* amber vignette */}
        <div className="absolute inset-0 anim-vignette-pulse pointer-events-none" style={{ background: "radial-gradient(ellipse at center, transparent 38%, rgba(232,182,81,0.32) 100%)" }} />
        <HintCard>
          Check the multiplication &mdash; try again, <span className="text-brendan-amber font-semibold">pilot</span>.
        </HintCard>
        <div className="absolute anim-rocket-dip" style={{ left: "47%", top: "26%", width: "20%", maxWidth: 200 }}>
          <BrendanRocket id="brendan-dip" mood="concerned" thrust="sputter" />
        </div>
        <HudConsole state="wrong" />
      </SceneFrame>
      <div className="bg-brendan-bg px-4 sm:px-6 py-4 sm:py-5">
        <div className="grid grid-cols-4 gap-2 sm:gap-3 max-w-[640px] mx-auto">
          <AnswerBtn label="84" />
          <AnswerBtn label="96" />
          <AnswerBtn label="108" kind="dim" />
          <AnswerBtn label="112" />
        </div>
      </div>
    </article>
  </section>
);

const StateEnd = () => (
  <section>
    <StateLabel
      num={4}
      title="End-of-round"
      kind="mission complete"
      desc="Rocket parks beside a glowing waypoint planet (atmosphere glow 3s pulse). 'Mission complete!' italic banner + '7/7 calculations locked' ribbon. 5 amber star-rank icons stamp in (0.2s stagger). Pilot's badge glows on the console (2.4s pulse). 'Next mission' + 'Return to base' CTAs."
    />
    <article className="rounded-[24px] bg-cream paper-grain ring-1 ring-walnut/15 shadow-lift overflow-hidden">
      <SceneFrame>
        <Waypoint />
        <div className="absolute inset-x-0 top-[6%] flex flex-col items-center gap-2 z-20 pointer-events-none anim-banner-pop">
          <h3 className="font-display italic font-bold text-brendan-amber text-[28px] sm:text-[42px] leading-none" style={{ textShadow: "0 0 24px rgba(232,182,81,0.6)" }}>
            Mission complete!
          </h3>
          <RibbonBanner text="7 / 7 LOCKED" />
          <div className="flex gap-1.5 sm:gap-2 mt-1">
            <GoldStar delay={0} />
            <GoldStar delay={0.2} />
            <GoldStar delay={0.4} />
            <GoldStar delay={0.6} />
            <GoldStar delay={0.8} />
          </div>
        </div>
        <div className="absolute anim-hover-bob" style={{ left: "30%", top: "30%", width: "18%", maxWidth: 180 }}>
          <BrendanRocket id="brendan-park" mood="proud" thrust="pulse" />
        </div>
        <HudConsole state="end" />
      </SceneFrame>
      <div className="bg-brendan-bg px-4 sm:px-6 py-4 sm:py-5">
        <div className="grid grid-cols-1 sm:grid-cols-2 gap-3 sm:gap-4 max-w-[640px] mx-auto">
          <AnswerBtn label="NEXT MISSION ▶" kind="primary" />
          <AnswerBtn label="RETURN TO BASE" kind="ghost" />
        </div>
      </div>
    </article>
  </section>
);

/* ============================================================
   RULES CARD
   ============================================================ */

const RULES = [
  ["Rocket hover",     "4s ease-in-out",                    "translate-y -6px"],
  ["Thruster pulse",   "1.5s ease-in-out",                  "scale 1 → 1.25y/1.1x, opacity 0.85 → 1"],
  ["Thruster flare",   "0.6s ease-in-out",                  "scale 1.6→2y, 1.2→1.3x (on correct)"],
  ["Starfield drift",  "60s far · 30s near · linear ∞",     "translate-x 100% (2 parallax layers)"],
  ["Nebula shimmer",   "8s ease-in-out",                    "opacity 0.7 → 1, scale 1 → 1.04"],
  ["Hologram flicker", "5s ease-in-out · random",           "opacity 1 → 0.65 → 1 → 0.75"],
  ["HUD pulse",        "2.4s ease-in-out",                  "opacity 0.8 → 1"],
  ["Hyperspace jump",  "0.6s ease-in",                      "rocket scale 1 → 1.1, translate-y -8px"],
  ["Star streaks",     "0.4s ease-out · ∞ loop, 30+ lines", "scale-x 0.2 → 2.4 + translate radial"],
  ["Camera shake",     "0.3s once",                         "translate ±2px (low amplitude)"],
  ["Praise word",      "0.65s cubic-bezier(.34,1.56,.64,1)", "scale 0.4 → 1.12 → 1, rotate -8° → 0°"],
  ["Wrong vignette",   "1.5s × 2 cycles",                   "amber radial pulse"],
  ["Rocket dip",       "0.4s once",                         "translate-y +8px, rotate -3°"],
  ["Waypoint glow",    "3s ease-in-out",                    "scale 1 → 1.08, opacity 0.65 → 1"],
  ["Star stamp",       "0.4s pop · 0.2s stagger",           "scale 0 → 1.25 → 1, rotate -30° → 0°"],
];

const RulesCard = () => (
  <article className="rounded-[24px] bg-brendan-bg text-cream p-5 sm:p-7 shadow-lift ring-1 ring-brendan-amber/30">
    <div className="flex items-baseline justify-between mb-4">
      <h3 className="font-display italic font-semibold text-[22px] sm:text-[26px] text-brendan-amber">Animation grammar</h3>
      <span className="font-mono text-[10px] uppercase tracking-[0.22em] text-cream/60">applies to all 5 Brendan games</span>
    </div>
    <div className="grid grid-cols-1 sm:grid-cols-2 gap-y-3 gap-x-6">
      {RULES.map(([name, timing, transform]) => (
        <div key={name} className="flex flex-col gap-0.5 border-l-2 border-brendan-amber/70 pl-3">
          <div className="font-mono font-bold text-cream text-[13px] leading-tight uppercase tracking-wider">{name}</div>
          <div className="font-mono text-[11px] text-cream/70 leading-tight">{timing}</div>
          <div className="font-mono text-[11px] text-brendan-amber leading-tight">{transform}</div>
        </div>
      ))}
    </div>
    <div className="mt-5 pt-4 border-t border-cream/15">
      <p className="font-mono text-[11px] text-cream/70">
        Default pop easing: <span className="text-brendan-amber">cubic-bezier(0.34, 1.56, 0.64, 1)</span> &middot;
        Flutter easing: <span className="text-brendan-amber">cubic-bezier(0.45, 0.05, 0.55, 0.95)</span>
      </p>
    </div>
  </article>
);

/* ============================================================
   MAIN COMPONENT
   ============================================================ */

function HyperspaceMathAnimations() {
  return (
    <div className="min-h-screen px-4 sm:px-8 lg:px-12 py-8 sm:py-12 max-w-[1100px] mx-auto">
      <header className="mb-8 sm:mb-12">
        <div className="flex items-start gap-2 text-[11px] uppercase tracking-[0.22em] font-semibold text-copper">
          <span className="inline-block w-6 h-px bg-copper mt-2" />
          <span>Game animation system &middot; Brendan</span>
        </div>
        <h1 className="font-display text-walnut mt-3 leading-[0.95] text-[40px] sm:text-[60px] lg:text-[68px] tracking-tight max-w-[20ch]">
          <span className="italic font-medium">Hyperspace Math,</span>{" "}
          <span className="font-semibold">in motion.</span>
        </h1>
        <p className="font-display italic text-walnut-2 text-[15px] sm:text-[18px] mt-4 max-w-[64ch] leading-snug">
          The visual + motion grammar for all five of Brendan&rsquo;s games &mdash; Galactic Comms,
          Hyperspace Math, Cargo Split, Fuel Cells, Mission Briefs. Cockpit-view starship + sci-fi
          glow + parallax starfield. Every state below loops live.
        </p>
        <div className="flex flex-wrap gap-2 mt-5">
          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full text-[11px] font-semibold" style={{ background: "#E1E8F4", color: "#1F2F52", boxShadow: "inset 0 0 0 1px rgba(61,90,140,0.3)" }}>
            <span className="w-1.5 h-1.5 rounded-full" style={{ background: "#3D5A8C" }} />
            5th&ndash;6th Grade &middot; 4 states
          </span>
          <span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-cream ring-1 ring-walnut/15 text-[11px] font-semibold text-walnut-2">
            Reference scene: Hyperspace Math
          </span>
        </div>
      </header>

      <div className="flex flex-col gap-8 sm:gap-12">
        <StateIdle />
        <StateCorrect />
        <StateWrong />
        <StateEnd />
        <RulesCard />
      </div>

      <footer className="mt-12 pt-6 border-t border-walnut/10 flex flex-wrap items-baseline justify-between gap-4 text-[12px] font-medium text-walnut-3">
        <p className="font-display italic text-walnut-2 text-[14px]">
          &ldquo;Pilots calculate. Then they fly.&rdquo;
        </p>
        <span>Cammy &amp; Caris Learning Club &middot; Brendan animation system</span>
      </footer>
    </div>
  );
}

window.HyperspaceMathAnimations = HyperspaceMathAnimations;

window.HMAStates = { StateIdle, StateCorrect, StateWrong, StateEnd };
