/* ============================================================
   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 DemoPaywall = ({ totalPlayed }) => (
  <div
    role="dialog"
    aria-modal="true"
    aria-label="Preview complete — download the app to keep playing"
    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: 24,
    }}
  >
    <div style={{
      maxWidth: 460,
      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: 20,
      padding: '36px 28px',
      boxShadow: '0 20px 60px rgba(0,0,0,0.55)',
    }}>
      <div style={{
        fontFamily: 'var(--font-mono)',
        fontSize: 10.5,
        letterSpacing: 3,
        color: '#8BA4EE',
        marginBottom: 16,
      }}>PREVIEW COMPLETE</div>
      <h3 style={{
        fontFamily: 'var(--font-heading)',
        fontSize: 26,
        fontWeight: 700,
        lineHeight: 1.2,
        color: 'var(--vero-fg)',
        margin: '0 0 12px',
      }}>
        You've played your {DEMO_LIMIT} preview rounds.
      </h3>
      <p style={{
        fontSize: 14.5,
        lineHeight: 1.55,
        color: 'var(--vero-fg-2)',
        margin: '0 0 24px',
      }}>
        The full game lives in the app — unlimited rounds, every mode, real historical charts, and the full learning library. Free to download.
      </p>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap', marginBottom: 4 }}>
        <a href="#" aria-label="Download on the App Store" style={{ display: 'inline-block', lineHeight: 0 }}>
          <svg viewBox="0 0 120 40" xmlns="http://www.w3.org/2000/svg" style={{ height: 44, width: 'auto', display: 'block' }} role="img">
            <rect width="120" height="40" rx="6" fill="#000"/>
            <rect x="0.5" y="0.5" width="119" height="39" rx="5.5" fill="none" stroke="#A6A6A6" strokeWidth="0.5"/>
            <g fill="#fff">
              <path d="M24.77 20.3a4.34 4.34 0 0 1 2.07-3.65 4.45 4.45 0 0 0-3.5-1.89c-1.47-.15-2.9.88-3.65.88-.76 0-1.92-.86-3.16-.84a4.66 4.66 0 0 0-3.92 2.39c-1.69 2.93-.43 7.24 1.2 9.61.81 1.16 1.76 2.46 3 2.41 1.21-.05 1.67-.77 3.13-.77 1.45 0 1.87.77 3.13.75 1.3-.02 2.12-1.17 2.91-2.34a9.6 9.6 0 0 0 1.33-2.71 4.2 4.2 0 0 1-2.56-3.86Zm-2.4-7.1a4.28 4.28 0 0 0 .98-3.06 4.35 4.35 0 0 0-2.82 1.46 4.07 4.07 0 0 0-1 2.94 3.6 3.6 0 0 0 2.84-1.34Z"/>
              <text x="42" y="16" fontFamily="-apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" fontSize="7" fill="#fff">Download on the</text>
              <text x="42" y="29" fontFamily="-apple-system, BlinkMacSystemFont, 'Helvetica Neue', Helvetica, Arial, sans-serif" fontSize="15" fontWeight="600" fill="#fff">App Store</text>
            </g>
          </svg>
        </a>
        <a href="#" aria-label="Get it on Google Play" style={{ display: 'inline-block', lineHeight: 0 }}>
          <svg viewBox="0 0 135 40" xmlns="http://www.w3.org/2000/svg" style={{ height: 44, width: 'auto', display: 'block' }} role="img">
            <rect width="135" height="40" rx="6" fill="#000"/>
            <rect x="0.5" y="0.5" width="134" height="39" rx="5.5" fill="none" stroke="#A6A6A6" strokeWidth="0.5"/>
            <g transform="translate(10 9)">
              <defs>
                <linearGradient id="gp-pw-a" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#00A0FF"/><stop offset="1" stopColor="#00E2FF"/></linearGradient>
                <linearGradient id="gp-pw-b" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#FFE000"/><stop offset="1" stopColor="#FFBD00"/></linearGradient>
                <linearGradient id="gp-pw-c" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#FF3A44"/><stop offset="1" stopColor="#C31162"/></linearGradient>
                <linearGradient id="gp-pw-d" x1="0" y1="0" x2="1" y2="-1"><stop offset="0" stopColor="#32A071"/><stop offset="1" stopColor="#2DA771"/></linearGradient>
              </defs>
              <path d="M.3.7A1.63 1.63 0 0 0 0 1.9v19.2c0 .44.12.83.3 1.13l10.4-10.3L.3.7Z" fill="url(#gp-pw-a)"/>
              <path d="M14.13 14.93 10.7 11.5.3 22.2c.35.4.93.43 1.6.05l12.23-7.32Z" fill="url(#gp-pw-c)"/>
              <path d="m14.13 14.93 3.5-1.98c1.1-.63 1.1-1.65 0-2.27l-3.55-2.01-3.38 3.33 3.43 3.43Z" fill="url(#gp-pw-b)"/>
              <path d="M1.9.66C1.23.28.65.31.3.7L10.7 11.5l3.4-3.38L1.9.66Z" fill="url(#gp-pw-d)"/>
            </g>
            <g fill="#fff">
              <text x="40" y="16" fontFamily="'Roboto', -apple-system, sans-serif" fontSize="7" fill="#fff">GET IT ON</text>
              <text x="40" y="29" fontFamily="'Roboto', -apple-system, sans-serif" fontSize="15" fontWeight="600" fill="#fff">Google Play</text>
            </g>
          </svg>
        </a>
      </div>
      <div style={{ fontSize: 11.5, color: 'var(--vero-fg-3)', marginTop: 16, lineHeight: 1.5 }}>
        You played {totalPlayed} {totalPlayed === 1 ? 'round' : 'rounds'} of the web preview. The app is free to download.
      </div>
    </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;
