/* Onboarding — 4-step swipeable intro + Splash */
const { useState, useEffect, useRef } = React;

function SplashScreen({ palette, onDone }) {
  const [opacity, setOpacity] = useState(1);
  useEffect(() => {
    const t1 = setTimeout(() => setOpacity(0), 1200);
    const t2 = setTimeout(onDone, 1800);
    return () => { clearTimeout(t1); clearTimeout(t2); };
  }, []);
  return (
    <div style={{
      position: 'absolute', inset: 0, zIndex: 300,
      background: palette.bg1,
      display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center',
      opacity, transition: 'opacity 0.6s ease',
      pointerEvents: opacity > 0 ? 'auto' : 'none',
    }}>
      <div style={{ animation: 'tessera-float 3s ease-in-out infinite' }}>
        {window.DynamicLogo && <window.DynamicLogo palette={palette} />}
      </div>
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 11, letterSpacing: '0.44em',
        color: palette.dim, marginTop: 18,
        textTransform: 'uppercase',
      }}>APERIODIC MOSAIC</div>
      <div style={{
        fontFamily: "'JetBrains Mono', monospace",
        fontSize: 38, fontWeight: 700,
        letterSpacing: '0.22em', color: palette.ink,
        textShadow: `0 0 48px ${palette.glow}66`,
        marginTop: 4,
      }}>TESSERA</div>
    </div>
  );
}

function OnboardingFlow({ palette, onComplete }) {
  const [step, setStep] = useState(0);
  const touchStartX = useRef(0);
  const STEPS = 4;

  function next() { step < STEPS - 1 ? setStep(step + 1) : onComplete(); }
  function prev() { step > 0 && setStep(step - 1); }

  function handleTouchStart(e) { touchStartX.current = e.touches[0].clientX; }
  function handleTouchEnd(e) {
    const dx = e.changedTouches[0].clientX - touchStartX.current;
    if (dx < -50) next();
    else if (dx > 50) prev();
  }

  const thickAngle = 72;
  const thinAngle = 36;
  const R = 40;

  const thickPoints = (() => {
    const a1 = (-thickAngle / 2) * Math.PI / 180;
    const a2 = (thickAngle / 2) * Math.PI / 180;
    return `0,0 ${Math.cos(a1) * R},${Math.sin(a1) * R} ${(Math.cos(a1) + Math.cos(a2)) * R * 0.62},${(Math.sin(a1) + Math.sin(a2)) * R * 0.62} ${Math.cos(a2) * R},${Math.sin(a2) * R}`;
  })();

  const thinPoints = (() => {
    const a1 = (-thinAngle / 2) * Math.PI / 180;
    const a2 = (thinAngle / 2) * Math.PI / 180;
    return `0,0 ${Math.cos(a1) * R},${Math.sin(a1) * R} ${(Math.cos(a1) + Math.cos(a2)) * R * 0.62},${(Math.sin(a1) + Math.sin(a2)) * R * 0.62} ${Math.cos(a2) * R},${Math.sin(a2) * R}`;
  })();

  const steps = [
    {
      title: 'Reveal',
      subtitle: 'Tap to reveal the mosaic',
      body: 'Each tile you touch blooms into existence. The pattern grows outward from a single seed.',
      visual: (
        <div style={{ position: 'relative', width: 200, height: 200 }}>
          <svg viewBox="-60 -60 120 120" width="200" height="200">
            <polygon points={thickPoints}
              fill={palette.thick} stroke={palette.thickEdge} strokeWidth="1.2"
              opacity="0.9" />
            {[0, 72, 144, 216, 288].map((a, i) => (
              <g key={i} transform={`rotate(${a})`} style={{ animation: `tessera-pulse 2s ease-in-out ${i * 0.3}s infinite` }}>
                <polygon points={thickPoints}
                  fill="none" stroke={palette.tappableEdge} strokeWidth="1.5"
                  opacity="0.5" transform="translate(28, 0)" />
              </g>
            ))}
          </svg>
        </div>
      ),
    },
    {
      title: 'Two Shapes',
      subtitle: 'Two rhombi. One never-repeating pattern.',
      body: 'The thick rhombus (72°) and thin rhombus (36°) — just two tiles create infinite complexity.',
      visual: (
        <div style={{ display: 'flex', gap: 32, alignItems: 'center' }}>
          <div style={{ textAlign: 'center' }}>
            <svg viewBox="-50 -50 100 100" width="120" height="120"
              style={{ filter: `drop-shadow(0 0 12px ${palette.thick}88)` }}>
              <polygon points={thickPoints}
                fill={palette.thick} stroke={palette.thickEdge} strokeWidth="1.5" />
            </svg>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: palette.thick, marginTop: 4 }}>72° / 108°</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: palette.dim, letterSpacing: '0.14em', marginTop: 2 }}>THICK</div>
          </div>
          <div style={{ textAlign: 'center' }}>
            <svg viewBox="-50 -50 100 100" width="120" height="120"
              style={{ filter: `drop-shadow(0 0 12px ${palette.thin}88)` }}>
              <polygon points={thinPoints}
                fill={palette.thin} stroke={palette.thinEdge} strokeWidth="1.5" />
            </svg>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 11, color: palette.thin, marginTop: 4 }}>36° / 144°</div>
            <div style={{ fontFamily: "'JetBrains Mono', monospace", fontSize: 9, color: palette.dim, letterSpacing: '0.14em', marginTop: 2 }}>THIN</div>
          </div>
        </div>
      ),
    },
    {
      title: 'Penrose',
      subtitle: 'A pattern that never repeats',
      body: 'Discovered by Sir Roger Penrose in 1974. The same fivefold symmetry found in starfish, apple blossoms, and Nobel Prize–winning quasicrystals.',
      visual: (
        <div style={{ position: 'relative', width: 180, height: 180 }}>
          <svg viewBox="-50 -50 100 100" width="180" height="180"
            style={{ filter: `drop-shadow(0 0 24px ${palette.glow}66)` }}>
            {[0, 72, 144, 216, 288].map((a, i) => (
              <g key={i} transform={`rotate(${a})`}>
                <polygon points={thickPoints}
                  fill={palette.thick} stroke={palette.thickEdge} strokeWidth="0.8"
                  opacity="0.85" transform="scale(0.7)" />
              </g>
            ))}
            {[36, 108, 180, 252, 324].map((a, i) => (
              <g key={i} transform={`rotate(${a})`}>
                <polygon points={thinPoints}
                  fill={palette.thin} stroke={palette.thinEdge} strokeWidth="0.8"
                  opacity="0.85" transform="scale(0.7) translate(20, 0)" />
              </g>
            ))}
          </svg>
          <div style={{
            position: 'absolute', bottom: -8, left: '50%', transform: 'translateX(-50%)',
            fontFamily: "'JetBrains Mono', monospace", fontSize: 10,
            letterSpacing: '0.2em', color: palette.dim, whiteSpace: 'nowrap',
          }}>1974 · NOBEL 2020</div>
        </div>
      ),
    },
    {
      title: 'Your Mosaic',
      subtitle: 'Every pattern is unique',
      body: 'No two mosaics are ever the same. This one will be yours — a living, growing work of mathematical art.',
      visual: (
        <div style={{ animation: 'tessera-float 3.2s ease-in-out infinite' }}>
          {window.DynamicLogo && <window.DynamicLogo palette={palette} />}
        </div>
      ),
      isFinal: true,
    },
  ];

  const s = steps[step];

  return (
    <div
      onTouchStart={handleTouchStart}
      onTouchEnd={handleTouchEnd}
      style={{
        position: 'absolute', inset: 0, zIndex: 200,
        background: palette.bg1,
        display: 'flex', flexDirection: 'column',
        color: palette.ink,
        fontFamily: "'Manrope', system-ui, sans-serif",
        WebkitTapHighlightColor: 'transparent',
        touchAction: 'pan-y',
      }}
    >
      {/* Background mosaic */}
      <div style={{
        position: 'absolute', inset: 0, opacity: 0.12, pointerEvents: 'none',
      }}>
        {window.BackgroundCanvas && <window.BackgroundCanvas palette={palette} />}
      </div>

      {/* Skip */}
      {step < STEPS - 1 && (
        <div onClick={onComplete} style={{
          position: 'absolute', top: 60, right: 20, zIndex: 10,
          fontFamily: "'JetBrains Mono', monospace", fontSize: 11,
          letterSpacing: '0.16em', color: palette.dim, cursor: 'pointer',
          padding: '6px 10px',
        }}>SKIP</div>
      )}

      {/* Content */}
      <div style={{
        flex: 1, display: 'flex', flexDirection: 'column',
        alignItems: 'center', justifyContent: 'center',
        gap: 28, padding: '80px 32px 40px',
        position: 'relative',
      }}>
        {/* Visual */}
        <div style={{
          minHeight: 200, display: 'flex', alignItems: 'center', justifyContent: 'center',
          filter: `drop-shadow(0 0 20px ${palette.glow}44)`,
        }}>
          {s.visual}
        </div>

        {/* Text */}
        <div style={{ textAlign: 'center', maxWidth: 300 }}>
          <div style={{
            fontFamily: "'JetBrains Mono', monospace",
            fontSize: 9, letterSpacing: '0.32em', color: palette.dim,
            marginBottom: 6, textTransform: 'uppercase',
          }}>{s.title}</div>
          <div style={{
            fontSize: 22, fontWeight: 700, lineHeight: 1.3,
            marginBottom: 10,
          }}>{s.subtitle}</div>
          <div style={{
            fontSize: 14, lineHeight: 1.6, color: palette.dim,
          }}>{s.body}</div>
        </div>
      </div>

      {/* Bottom: dots + button */}
      <div style={{
        padding: '0 28px 40px', display: 'flex', flexDirection: 'column',
        alignItems: 'center', gap: 20, position: 'relative',
      }}>
        {/* Dots */}
        <div style={{ display: 'flex', gap: 8 }}>
          {Array.from({ length: STEPS }, (_, i) => (
            <div key={i} style={{
              width: i === step ? 20 : 6, height: 6, borderRadius: 3,
              background: i === step ? palette.thick : `${palette.dim}66`,
              transition: 'all 0.3s ease',
            }} />
          ))}
        </div>

        {/* Button */}
        <button onClick={next} style={{
          width: '100%', height: 52, borderRadius: 16,
          background: s.isFinal ? palette.thick : 'transparent',
          color: s.isFinal ? palette.bg1 : palette.ink,
          border: s.isFinal ? 'none' : `1px solid ${palette.dim}66`,
          fontFamily: "'JetBrains Mono', monospace",
          fontSize: 13, fontWeight: 700, letterSpacing: '0.22em',
          cursor: 'pointer',
          boxShadow: s.isFinal ? `0 8px 28px ${palette.thick}44` : 'none',
          WebkitTapHighlightColor: 'transparent',
          touchAction: 'manipulation',
        }}>
          {s.isFinal ? 'BEGIN' : 'NEXT'}
        </button>
      </div>
    </div>
  );
}

window.SplashScreen = SplashScreen;
window.OnboardingFlow = OnboardingFlow;
