/* ============================================================
   LIVE DEMO — play a round directly on the site
   ============================================================ */
const { useState: useS3, useRef: useR3, useEffect: useE3, useMemo: useM3 } = React;

// Preview cap: how many rounds the web demo allows before gating.
// Persisted in localStorage so refreshes/returns don't reset it.
const DEMO_LIMIT = 10;
const DEMO_STORAGE_KEY = 'vero_demo_rounds_played';

const readPlayed = () => {
  try {
    const n = parseInt(window.localStorage.getItem(DEMO_STORAGE_KEY) || '0', 10);
    return Number.isFinite(n) && n >= 0 ? n : 0;
  } catch { return 0; }
};

const writePlayed = (n) => {
  try { window.localStorage.setItem(DEMO_STORAGE_KEY, String(n)); } catch {}
};

// Generate a "chart" with a concealed future
const makeRound = (seed) => {
  const rng = (s => () => (s = (s * 9301 + 49297) % 233280) / 233280)(seed);
  const bias = rng() - 0.48; // slight drift bias; positive → uptrend likely
  const candles = [];
  let p = 100;
  for (let i = 0; i < 40; i++) {
    const o = p;
    const c = o + (rng() - 0.5 + bias * 0.3) * 1.8;
    const hi = Math.max(o, c) + rng() * 0.8;
    const lo = Math.min(o, c) - rng() * 0.8;
    candles.push({ o, c, hi, lo });
    p = c;
  }
  // future: 6 more candles
  const future = [];
  let fp = p;
  for (let i = 0; i < 6; i++) {
    const o = fp;
    const c = o + (rng() - 0.5 + bias * 0.7) * 1.8;
    const hi = Math.max(o, c) + rng() * 0.8;
    const lo = Math.min(o, c) - rng() * 0.8;
    future.push({ o, c, hi, lo });
    fp = c;
  }
  const correct = future[future.length - 1].c > p ? 'UP' : 'DOWN';
  return { candles, future, correct, lastPrice: p };
};

const LiveDemo = () => {
  const [round, setRound] = useS3(1);
  const [seed, setSeed] = useS3(7);
  const [phase, setPhase] = useS3('guess'); // guess | reveal
  const [answer, setAnswer] = useS3(null);
  const [score, setScore] = useS3(0);
  const [streak, setStreak] = useS3(0);
  const [time, setTime] = useS3(30);
  const [reveal, setReveal] = useS3(0); // 0..1 for animated reveal
  const [totalPlayed, setTotalPlayed] = useS3(readPlayed);
  const paywalled = totalPlayed >= DEMO_LIMIT;

  const data = useM3(() => makeRound(seed), [seed]);
  const allCandles = phase === 'reveal'
    ? [...data.candles, ...data.future.slice(0, Math.floor(reveal * data.future.length))]
    : data.candles;

  // timer
  useE3(() => {
    if (phase !== 'guess') return;
    if (paywalled) return;
    setTime(30);
    const start = Date.now();
    const iv = setInterval(() => {
      const rem = Math.max(0, 30 - Math.floor((Date.now() - start) / 1000));
      setTime(rem);
      if (rem === 0) {
        clearInterval(iv);
        // auto-reveal with no answer
        if (phase === 'guess') handleAnswer(null);
      }
    }, 200);
    return () => clearInterval(iv);
  }, [phase, seed, paywalled]);

  // reveal animation
  useE3(() => {
    if (phase !== 'reveal') return;
    setReveal(0);
    const start = Date.now();
    const iv = setInterval(() => {
      const r = Math.min(1, (Date.now() - start) / 1200);
      setReveal(r);
      if (r >= 1) clearInterval(iv);
    }, 30);
    return () => clearInterval(iv);
  }, [phase, seed]);

  const handleAnswer = (dir) => {
    if (phase !== 'guess') return;
    if (paywalled) return;
    setAnswer(dir);
    setPhase('reveal');
    if (dir === data.correct) {
      setScore(s => s + 10);
      setStreak(s => s + 1);
    } else {
      setStreak(0);
    }
    const next = totalPlayed + 1;
    setTotalPlayed(next);
    writePlayed(next);
  };

  const nextRound = () => {
    if (paywalled) return;
    setRound(r => r + 1);
    setSeed(s => s + 1);
    setAnswer(null);
    setPhase('guess');
    setReveal(0);
  };

  const reset = () => {
    setRound(1);
    setSeed(7);
    setAnswer(null);
    setScore(0);
    setStreak(0);
    setPhase('guess');
    setReveal(0);
  };

  // chart dimensions
  const W = 800, H = 360;
  const PADL = 20, PADR = 56;
  const all = [...data.candles, ...data.future];
  const min = Math.min(...all.map(c => c.lo)) - 0.3;
  const max = Math.max(...all.map(c => c.hi)) + 0.3;
  const yOf = v => 20 + (max - v) / (max - min) * (H - 40);
  const totalW = 46; // total candles shown (40 history + 6 future slots reserved)
  const cw = (W - PADL - PADR) / totalW;

  const correct = answer === data.correct;
  const lastVisible = allCandles[allCandles.length - 1];

  return (
    <div style={{ position: 'relative' }}>
      {/* HUD */}
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 20, position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', gap: 32 }}>
          <Metric label="Score" value={score}/>
          <Metric label="Streak" value={streak}/>
          <Metric label="Round" value={round}/>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
          <div style={{
            fontFamily: 'var(--font-mono)',
            fontSize: 13, fontWeight: 600,
            color: time <= 5 ? '#EF4444' : 'var(--vero-fg-2)',
            minWidth: 42,
          }}>
            {phase === 'guess' ? `0:${String(time).padStart(2, '0')}` : '—'}
          </div>
          {!paywalled && (
            <button onClick={reset} style={{
              background: 'transparent',
              border: '1px solid rgba(255,255,255,0.1)',
              color: 'var(--vero-fg-2)',
              fontSize: 12, fontWeight: 500,
              padding: '6px 12px', borderRadius: 9999,
              cursor: 'pointer',
              fontFamily: 'inherit',
            }}>Reset</button>
          )}
        </div>
      </div>

      {/* timer bar */}
      <div style={{ height: 3, background: 'rgba(255,255,255,0.05)', borderRadius: 2, marginBottom: 16, overflow: 'hidden', position: 'relative', zIndex: 2 }}>
        <div style={{
          height: '100%',
          width: phase === 'guess' ? `${(time / 30) * 100}%` : '0%',
          background: time <= 5 ? '#EF4444' : 'var(--vero-accent)',
          transition: 'width .3s linear, background .3s',
        }}/>
      </div>

      {/* chart */}
      <div style={{
        background: 'var(--vero-bg)',
        border: '1px solid rgba(255,255,255,0.06)',
        borderRadius: 16,
        padding: 20,
        position: 'relative',
        zIndex: 2,
      }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 10, fontSize: 11, fontFamily: 'var(--font-mono)', color: 'var(--vero-fg-3)' }}>
          <span>● VERO-DEMO &nbsp;·&nbsp; <span style={{color:'#8BA4EE',background:'rgba(107,138,228,0.15)',padding:'2px 8px',borderRadius:4,fontWeight:600}}>5m</span> &nbsp;·&nbsp; reveals the upcoming candles</span>
          <span style={{ color: 'var(--vero-fg)' }}>
            ${lastVisible?.c?.toFixed(2)}
            {phase === 'reveal' && (
              <span style={{ marginLeft: 10, color: data.future[Math.floor(reveal * data.future.length) - 1]?.c > data.lastPrice ? '#10B981' : '#EF4444' }}>
                {((lastVisible?.c - data.lastPrice) >= 0 ? '+' : '')}{((lastVisible?.c - data.lastPrice) || 0).toFixed(2)}
              </span>
            )}
          </span>
        </div>

        <svg viewBox={`0 0 ${W} ${H}`} style={{ width: '100%', height: 'auto', display: 'block' }}>
          {/* grid */}
          <g stroke="rgba(255,255,255,0.04)" strokeDasharray="3 5">
            {[0, 1, 2, 3].map(i => (
              <line key={i} x1={PADL} x2={W - PADR} y1={20 + i * (H - 40) / 3} y2={20 + i * (H - 40) / 3}/>
            ))}
          </g>
          {/* price labels */}
          <g fill="#52525B" fontSize="10" fontFamily="JetBrains Mono, monospace">
            <text x={W - PADR + 8} y="23">{max.toFixed(2)}</text>
            <text x={W - PADR + 8} y={H / 2}>{((max + min) / 2).toFixed(2)}</text>
            <text x={W - PADR + 8} y={H - 20}>{min.toFixed(2)}</text>
          </g>
          {/* divider between history and future */}
          {phase === 'reveal' && (
            <line
              x1={PADL + 40 * cw} x2={PADL + 40 * cw}
              y1={20} y2={H - 20}
              stroke="rgba(107,138,228,0.35)"
              strokeDasharray="4 4"
            />
          )}
          {/* candles */}
          {allCandles.map((c, i) => {
            const x = PADL + i * cw;
            const up = c.c >= c.o;
            const col = up ? '#10B981' : '#EF4444';
            const isFuture = i >= 40;
            return (
              <g key={i} opacity={isFuture ? 1 : 1}>
                <line x1={x + cw / 2} x2={x + cw / 2} y1={yOf(c.hi)} y2={yOf(c.lo)} stroke={col} strokeWidth="1"/>
                <rect x={x + 1} y={yOf(Math.max(c.o, c.c))} width={cw - 2} height={Math.max(1, Math.abs(yOf(c.c) - yOf(c.o)))} fill={col}/>
              </g>
            );
          })}
          {/* reveal banner */}
          {phase === 'reveal' && reveal >= 1 && (
            <g>
              <rect x={W / 2 - 90} y={20} width="180" height="36" rx="18" fill={correct ? 'rgba(16,185,129,0.15)' : 'rgba(239,68,68,0.15)'} stroke={correct ? 'rgba(16,185,129,0.5)' : 'rgba(239,68,68,0.5)'}/>
              <text x={W / 2} y={43} textAnchor="middle" fill={correct ? '#10B981' : '#EF4444'} fontSize="15" fontWeight="700" fontFamily="Space Grotesk, sans-serif">
                {answer === null ? 'Time out' : correct ? '✓ Correct!' : '✕ Answer: ' + data.correct}
              </text>
            </g>
          )}
        </svg>
      </div>

      {/* actions */}
      <div style={{ marginTop: 20, position: 'relative', zIndex: 2 }}>
        {phase === 'guess' ? (
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
            <button
              onClick={() => handleAnswer('UP')}
              style={{
                background: 'rgba(16,185,129,0.1)',
                border: '1.5px solid rgba(16,185,129,0.45)',
                borderRadius: 14,
                padding: '22px 0',
                color: '#10B981',
                fontWeight: 700,
                fontSize: 18,
                letterSpacing: '.5px',
                cursor: 'pointer',
                fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                transition: 'all .15s',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(16,185,129,0.18)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(16,185,129,0.1)'}
            >
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M12 19V5M5 12l7-7 7 7"/></svg>
              UP
            </button>
            <button
              onClick={() => handleAnswer('DOWN')}
              style={{
                background: 'rgba(239,68,68,0.1)',
                border: '1.5px solid rgba(239,68,68,0.45)',
                borderRadius: 14,
                padding: '22px 0',
                color: '#EF4444',
                fontWeight: 700,
                fontSize: 18,
                letterSpacing: '.5px',
                cursor: 'pointer',
                fontFamily: 'inherit',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                transition: 'all .15s',
              }}
              onMouseEnter={e => e.currentTarget.style.background = 'rgba(239,68,68,0.18)'}
              onMouseLeave={e => e.currentTarget.style.background = 'rgba(239,68,68,0.1)'}
            >
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round"><path d="M12 5v14M19 12l-7 7-7-7"/></svg>
              DOWN
            </button>
          </div>
        ) : (
          <button
            onClick={nextRound}
            style={{
              width: '100%',
              background: 'var(--vero-accent)',
              border: 'none',
              borderRadius: 14,
              padding: '18px 0',
              color: '#fff',
              fontWeight: 700,
              fontSize: 17,
              letterSpacing: '.3px',
              cursor: 'pointer',
              fontFamily: 'inherit',
              boxShadow: '0 8px 24px rgba(107,138,228,0.3)',
              transition: 'background .15s',
            }}
            onMouseEnter={e => e.currentTarget.style.background = '#5A7BD4'}
            onMouseLeave={e => e.currentTarget.style.background = '#6B8AE4'}
          >
            Next round →
          </button>
        )}
      </div>

      <div style={{ marginTop: 16, fontSize: 12, color: 'var(--vero-fg-3)', textAlign: 'center', position: 'relative', zIndex: 2 }}>
        Call the direction — Vero reveals the upcoming candles. Shorter timeframes reveal more; longer timeframes reveal fewer.
      </div>

      {paywalled && <DemoPaywall totalPlayed={totalPlayed} />}
    </div>
  );
};

const WAITLIST_ENDPOINT = 'https://vero-api-production-c742.up.railway.app/v1/waitlist';

const DemoPaywall = ({ totalPlayed }) => {
  const [email, setEmail] = useS3('');
  const [status, setStatus] = useS3('idle'); // idle | loading | success | error
  const [message, setMessage] = useS3('');

  const submit = (e) => {
    e.preventDefault();
    if (status === 'loading') return;
    setStatus('loading');
    setMessage('');

    fetch(WAITLIST_ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({ email, source: 'demo_gate' }),
    })
      .then((res) => {
        if (res.status === 429) {
          setStatus('error');
          setMessage('Too many attempts, try again in a minute.');
          return;
        }
        if (!res.ok) {
          setStatus('error');
          setMessage('Something went wrong — try again.');
          return;
        }
        return res.json().then((data) => {
          setStatus('success');
          setMessage((data && data.already_subscribed)
            ? "You're already on the list."
            : "You're on the list — we'll email you when Vero launches.");
        });
      })
      .catch(() => {
        setStatus('error');
        setMessage('Something went wrong — try again.');
      });
  };

  return (
    <div
      role="dialog"
      aria-modal="true"
      aria-label="Preview complete — get notified when the full app launches"
      style={{
        position: 'absolute',
        inset: 0,
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        background: 'rgba(9,9,11,0.82)',
        backdropFilter: 'blur(14px)',
        WebkitBackdropFilter: 'blur(14px)',
        borderRadius: 16,
        zIndex: 20,
        padding: 16,
        overflowY: 'auto',
      }}
    >
      <div style={{
        maxWidth: 420,
        width: '100%',
        textAlign: 'center',
        background: 'linear-gradient(180deg, rgba(107,138,228,0.14), rgba(9,9,11,0.6))',
        border: '1px solid rgba(107,138,228,0.3)',
        borderRadius: 16,
        padding: '22px 18px',
        boxShadow: '0 20px 60px rgba(0,0,0,0.55)',
      }}>
        <div style={{
          fontFamily: 'var(--font-mono)',
          fontSize: 10,
          letterSpacing: 2.5,
          color: '#8BA4EE',
          marginBottom: 10,
        }}>PREVIEW COMPLETE</div>
        <h3 style={{
          fontFamily: 'var(--font-heading)',
          fontSize: 'clamp(18px, 5.2vw, 24px)',
          fontWeight: 700,
          lineHeight: 1.2,
          color: 'var(--vero-fg)',
          margin: '0 0 10px',
        }}>
          That's your {DEMO_LIMIT} preview rounds.
        </h3>
        <p style={{
          fontSize: 'clamp(12.5px, 3.6vw, 14px)',
          lineHeight: 1.5,
          color: 'var(--vero-fg-2)',
          margin: '0 0 6px',
        }}>
          The full game is launching soon on iOS and Android — unlimited rounds, every mode, the full learning library.
        </p>
        <p style={{
          fontSize: 12,
          lineHeight: 1.5,
          color: 'var(--vero-fg-3)',
          margin: '0 0 16px',
        }}>
          Get an email when Vero launches. Nothing else, ever.
        </p>
        <form
          onSubmit={submit}
          style={{ display: 'flex', flexWrap: 'wrap', gap: 8, justifyContent: 'center' }}
        >
          <input
            type="email"
            required
            value={email}
            onChange={(e) => setEmail(e.target.value)}
            placeholder="you@email.com"
            aria-label="Email address"
            style={{
              flex: '1 1 180px',
              minWidth: 0,
              padding: '12px 16px',
              borderRadius: 9999,
              border: '1px solid rgba(255,255,255,0.1)',
              background: 'rgba(255,255,255,0.06)',
              color: 'var(--vero-fg)',
              fontFamily: 'var(--font-body)',
              fontSize: 'max(16px, 1rem)',
            }}
          />
          <button
            type="submit"
            disabled={status === 'loading'}
            style={{
              display: 'inline-flex',
              alignItems: 'center',
              justifyContent: 'center',
              gap: 8,
              flex: '1 1 140px',
              minWidth: 0,
              background: 'var(--vero-accent)',
              border: 'none',
              borderRadius: 12,
              padding: '12px 20px',
              color: '#fff',
              fontWeight: 700,
              fontSize: 15,
              fontFamily: 'inherit',
              cursor: status === 'loading' ? 'not-allowed' : 'pointer',
              opacity: status === 'loading' ? 0.6 : 1,
              boxShadow: '0 8px 24px rgba(107,138,228,0.3)',
            }}
          >
            {status === 'loading' ? 'Joining…' : 'Join the waitlist'}
          </button>
        </form>
        <p
          role="status"
          aria-live="polite"
          style={{
            minHeight: 16,
            margin: '10px 0 0',
            fontSize: 12.5,
            color: status === 'error' ? 'var(--vero-bear)' : status === 'success' ? 'var(--vero-bull)' : 'var(--vero-fg-3)',
          }}
        >
          {message}
        </p>
      </div>
    </div>
  );
};

const Metric = ({ label, value }) => (
  <div>
    <div style={{ fontSize: 10.5, color: 'var(--vero-fg-3)', fontWeight: 500, letterSpacing: '.3px' }}>{label}</div>
    <div style={{ fontFamily: 'var(--font-heading)', fontWeight: 700, fontSize: 22, color: 'var(--vero-fg)', lineHeight: 1 }}>{value}</div>
  </div>
);

window.LiveDemo = LiveDemo;
