/* global React */
const { useState: useStateSV, useEffect: useEffectSV, useMemo: useMemoSV, useRef: useRefSV } = React;

// ============ Slide 1: Stadium panorama with phone lights ============
function StadiumPanorama({ accent = '#FFB300' }) {
  // Curved tribune tiers with phone lights on them
  const tiers = useMemoSV(() => {
    const arr = [];
    // 5 curved tiers
    for (let t = 0; t < 5; t++) {
      const lights = [];
      const count = 28 + t * 4;
      for (let i = 0; i < count; i++) {
        lights.push({
          i,
          t,
          // distribute along the arc
          x: i / (count - 1),
          // jitter for natural feel
          jitter: (Math.sin(i * 17.31 + t * 3.7) + 1) / 2,
          on: Math.sin(i * 11.7 + t * 5.3) > 0.2,
        });
      }
      arr.push(lights);
    }
    return arr;
  }, []);

  const [twinkle, setTwinkle] = useStateSV(0);
  useEffectSV(() => {
    const t = setInterval(() => setTwinkle((x) => x + 1), 300);
    return () => clearInterval(t);
  }, []);

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      background: 'radial-gradient(ellipse at 50% 100%, #222a35 0%, transparent 70%)',
      overflow: 'hidden',
    }}>
      {/* Field — bottom curve */}
      <svg viewBox="0 0 390 280" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
      }}>
        <defs>
          <linearGradient id="field" x1="0" y1="0" x2="0" y2="1">
            <stop offset="0" stopColor="#3d6a45" />
            <stop offset="1" stopColor="#162a1c" />
          </linearGradient>
          <radialGradient id="fieldLight" cx="50%" cy="100%" r="60%">
            <stop offset="0" stopColor="rgba(218,195,137,0.35)" />
            <stop offset="1" stopColor="transparent" />
          </radialGradient>
        </defs>
        {/* Distant horizon — pitch */}
        <path d="M -20 240 Q 195 215 410 240 L 410 290 L -20 290 Z" fill="url(#field)" />
        <path d="M -20 240 Q 195 215 410 240 L 410 290 L -20 290 Z" fill="url(#fieldLight)" />
        {/* Center spot */}
        <ellipse cx="195" cy="258" rx="3" ry="1" fill="rgba(255,255,255,.4)" />

        {/* Tribune arcs (back to front) */}
        {tiers.map((tier, ti) => {
          const tn = tiers.length;
          const yTop = 30 + ti * 14;   // higher tiers are further back
          const yBot = yTop + 18;
          const curveDepth = 18 + ti * 4;
          const path = `M -10 ${yTop} Q 195 ${yTop - curveDepth} 400 ${yTop}
                        L 400 ${yBot} Q 195 ${yBot - curveDepth} -10 ${yBot} Z`;
          return (
            <g key={ti}>
              <path d={path}
                fill={`hsl(220 8% ${14 + ti * 2}%)`}
                stroke={`hsl(220 8% ${22 + ti * 2}%)`}
                strokeWidth="0.5"
              />
            </g>
          );
        })}
      </svg>

      {/* Phone lights — overlaid as positioned dots */}
      {tiers.map((tier, ti) => {
        const yTop = 30 + ti * 14;
        const curveDepth = 18 + ti * 4;
        return tier.map((light) => {
          // bezier point at parameter x ∈ [0,1] for arc from (-10, yTop) → ctrl(195, yTop-curveDepth) → (400, yTop)
          const u = light.x;
          const px = (1 - u) * (1 - u) * -10 + 2 * (1 - u) * u * 195 + u * u * 400;
          const py = (1 - u) * (1 - u) * yTop + 2 * (1 - u) * u * (yTop - curveDepth) + u * u * yTop;
          // Random vertical placement within tier
          const yOff = 4 + light.jitter * 10;
          // Brightness varies + occasional twinkle
          const twinkleOn = ((light.i * 7 + ti * 11 + twinkle) % 13) > 8;
          const lit = light.on && twinkleOn;
          const isAccent = light.jitter > 0.85;
          const color = isAccent ? accent : (light.jitter > 0.55 ? '#fff' : '#b59a72');
          const size = 1.5 + light.jitter * 1.3;
          return (
            <div key={`${ti}-${light.i}`} style={{
              position: 'absolute',
              left: `${(px / 390) * 100}%`,
              top: `${((py + yOff) / 280) * 100}%`,
              width: size, height: size,
              borderRadius: '50%',
              background: color,
              opacity: lit ? 1 : 0.25,
              boxShadow: lit ? `0 0 ${4 + light.jitter * 5}px ${color}` : 'none',
              transition: 'opacity 300ms ease, box-shadow 300ms ease',
              transform: 'translate(-50%, -50%)',
            }} />
          );
        });
      })}

      {/* Foreground silhouette of nearest crowd / barrier */}
      <svg viewBox="0 0 390 280" preserveAspectRatio="none" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
        pointerEvents: 'none',
      }}>
        <path d="M 0 250
                 L 0 280 L 390 280 L 390 250
                 Q 380 248 360 252 Q 340 247 320 251 Q 300 246 280 251
                 Q 260 247 240 251 Q 220 246 200 250 Q 180 246 160 251
                 Q 140 247 120 251 Q 100 246 80 250 Q 60 247 40 251 Q 20 246 0 250 Z"
              fill="#000" opacity="0.85" />
      </svg>
    </div>
  );
}

// ============ Slide 2: Synchronization wave ============
function SyncWave({ accent = '#22D3EE' }) {
  const [t, setT] = useStateSV(0);
  useEffectSV(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  // Grid of phone "screens" pulsing in unison
  const cols = 9, rows = 7;
  const cells = useMemoSV(() => {
    const arr = [];
    for (let r = 0; r < rows; r++) {
      for (let c = 0; c < cols; c++) arr.push({ r, c });
    }
    return arr;
  }, []);

  // Pulse all in unison (every 1.4s), but with slight perspective fade for back rows
  const phase = (t * 1.6) % 2;
  const on = phase < 1;

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      perspective: 800,
      perspectiveOrigin: '50% 30%',
      background: 'radial-gradient(ellipse at 50% 50%, #252a30 0%, transparent 65%)',
      overflow: 'hidden',
    }}>
      <div style={{
        position: 'absolute', inset: '20% 8% 8% 8%',
        transformStyle: 'preserve-3d',
        transform: 'rotateX(58deg) translateZ(-20px)',
        display: 'grid',
        gridTemplateColumns: `repeat(${cols}, 1fr)`,
        gridTemplateRows: `repeat(${rows}, 1fr)`,
        gap: 6,
      }}>
        {cells.map((cell, i) => {
          const distFromCenter = Math.abs(cell.c - (cols - 1) / 2) / ((cols - 1) / 2);
          const rowFade = 1 - cell.r / rows * 0.4;
          return (
            <div key={i} style={{
              borderRadius: 3,
              background: on ? accent : '#383b40',
              opacity: on ? (0.6 + 0.4 * rowFade) : 0.4,
              boxShadow: on ? `0 0 ${6 * rowFade}px ${accent}` : 'none',
              transition: 'all 400ms cubic-bezier(.5,0,.3,1)',
              transform: `scale(${0.8 + 0.2 * rowFade})`,
            }} />
          );
        })}
      </div>

      {/* Sync indicator — radial wave ring */}
      <div style={{
        position: 'absolute', left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)',
        pointerEvents: 'none',
      }}>
        <div style={{
          width: 80 + (phase % 1) * 120,
          height: 80 + (phase % 1) * 120,
          border: `2px solid ${accent}`,
          borderRadius: '50%',
          opacity: 1 - (phase % 1),
          transition: 'none',
        }} />
      </div>

      {/* Server time badge */}
      <div style={{
        position: 'absolute', top: 16, left: '50%', transform: 'translateX(-50%)',
        padding: '6px 12px',
        background: 'rgba(0,0,0,.45)',
        borderRadius: 999,
        border: `1px solid ${accent}55`,
        display: 'flex', alignItems: 'center', gap: 6,
      }}>
        <div style={{
          width: 6, height: 6, borderRadius: '50%',
          background: accent,
          boxShadow: `0 0 6px ${accent}`,
          animation: 'pulseDot 1s infinite',
        }} />
        <span className="mono" style={{
          fontSize: 10, letterSpacing: '0.2em', color: '#fff',
          fontWeight: 600,
        }}>
          NTP · {Math.floor((t * 100) % 1000).toString().padStart(3, '0')}MS
        </span>
      </div>
    </div>
  );
}

// ============ Slide 3: Brightness & battery ============
function BrightnessBattery({ accent = '#FB7185' }) {
  const [t, setT] = useStateSV(0);
  useEffectSV(() => {
    let raf;
    const start = performance.now();
    const tick = (now) => {
      setT((now - start) / 1000);
      raf = requestAnimationFrame(tick);
    };
    raf = requestAnimationFrame(tick);
    return () => cancelAnimationFrame(raf);
  }, []);

  const sunRays = 12;
  const rotation = t * 20;

  return (
    <div style={{
      position: 'relative', width: '100%', height: '100%',
      overflow: 'hidden',
      background: `radial-gradient(circle at 50% 50%, ${accent}25 0%, transparent 55%)`,
    }}>
      {/* Sun rays (brightness) */}
      <svg viewBox="0 0 390 280" preserveAspectRatio="xMidYMid meet" style={{
        position: 'absolute', inset: 0, width: '100%', height: '100%',
      }}>
        <g transform={`translate(195 140) rotate(${rotation})`}>
          {Array.from({ length: sunRays }).map((_, i) => {
            const a = (i / sunRays) * Math.PI * 2;
            const x1 = Math.cos(a) * 75;
            const y1 = Math.sin(a) * 75;
            const x2 = Math.cos(a) * 130;
            const y2 = Math.sin(a) * 130;
            return (
              <line key={i} x1={x1} y1={y1} x2={x2} y2={y2}
                    stroke={accent} strokeWidth="3" strokeLinecap="round" opacity="0.55" />
            );
          })}
        </g>
      </svg>

      {/* Phone silhouette */}
      <div style={{
        position: 'absolute',
        left: '50%', top: '50%',
        transform: 'translate(-50%, -50%)',
      }}>
        <div style={{
          width: 112, height: 168,
          background: '#0d0e12',
          borderRadius: 18,
          border: '2px solid #42464c',
          padding: 8,
          boxShadow: `0 0 60px ${accent}66, 0 20px 40px rgba(0,0,0,.5)`,
          position: 'relative',
        }}>
          {/* Phone "screen" at max brightness */}
          <div style={{
            width: '100%', height: '100%',
            background: `linear-gradient(135deg, #fff 0%, ${accent} 100%)`,
            borderRadius: 11,
            display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center',
            gap: 8,
            boxShadow: `0 0 40px #fff inset, 0 0 24px ${accent}`,
          }}>
            {/* Battery glyph */}
            <svg width="44" height="22" viewBox="0 0 44 22" fill="none">
              <rect x="1" y="1" width="38" height="20" rx="3" stroke="#111" strokeWidth="1.5" />
              <rect x="40" y="7" width="3" height="8" rx="1" fill="#111" />
              <rect x="3" y="3" width={Math.min(34, 8 + ((t * 8) % 30))} height="16" rx="1.5" fill="#111" />
            </svg>
            <div className="mono" style={{
              fontSize: 9, letterSpacing: '0.15em', color: '#111',
              fontWeight: 700,
            }}>
              MAX · 100%
            </div>
          </div>
        </div>
      </div>

      {/* Brightness scale labels */}
      <div style={{
        position: 'absolute', left: 30, bottom: 28,
        display: 'flex', flexDirection: 'column', gap: 4,
      }}>
        <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '0.2em' }}>
          BRIGHTNESS
        </div>
        <div style={{
          width: 80, height: 4, borderRadius: 2,
          background: '#42464c',
          position: 'relative',
          overflow: 'hidden',
        }}>
          <div style={{
            position: 'absolute', left: 0, top: 0, bottom: 0,
            width: '100%',
            background: `linear-gradient(90deg, #737a82, ${accent})`,
          }} />
        </div>
      </div>

      <div style={{
        position: 'absolute', right: 30, bottom: 28,
        display: 'flex', flexDirection: 'column', gap: 4, alignItems: 'flex-end',
      }}>
        <div className="mono" style={{ fontSize: 9, color: 'var(--ink-3)', letterSpacing: '0.2em' }}>
          ALWAYS-ON
        </div>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <div style={{
            width: 8, height: 8, borderRadius: '50%',
            background: accent, boxShadow: `0 0 6px ${accent}`,
            animation: 'pulseDot 1.4s infinite',
          }} />
          <span style={{ fontSize: 11, color: 'var(--ink-2)', fontWeight: 600 }}>
            ACTIVE
          </span>
        </div>
      </div>
    </div>
  );
}

// ============ Dispatcher ============
function OnboardVisual({ variant, accent }) {
  if (variant === 0) return <StadiumPanorama accent={accent} />;
  if (variant === 1) return <SyncWave accent={accent} />;
  return <BrightnessBattery accent={accent} />;
}

window.OnboardVisual = OnboardVisual;
