// Games 4-6: Privacy Defender, Link Inspector, Two-Factor Hero
const { useState: useS2, useEffect: useE2, useRef: useR2, useMemo: useM2 } = React;

// ─────────────────────────────────────────────────────────────────────
// GAME 4: PRIVACY DEFENDER
// ─────────────────────────────────────────────────────────────────────
const POST_THEMES = [
  { app: 'PHOTOGRAM', user: '@lily.j', tint: 'linear-gradient(135deg,#ff4ec3,#a06bff,#34e6ff)' },
  { app: 'TAKTAK',    user: '@m4xpower',tint: 'linear-gradient(135deg,#0a141a,#ff4d6d)' },
  { app: 'SNAPCAM',   user: '@b3ans',   tint: 'linear-gradient(135deg,#ffd84d,#ff8a3d)' },
  { app: 'PHOTOGRAM', user: '@noah.x',  tint: 'linear-gradient(135deg,#7dff5a,#34e6ff)' },
];

function PrivacyDefender({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'priv');
  const [rounds] = useS2(() => pickRandom(PRIVACY_BANK, 10));
  const [idx, setIdx] = useS2(0);
  const [score, setScore] = useS2(0);
  const [feedback, setFeedback] = useS2(null);
  const [done, setDone] = useS2(false);
  const [flash, setFlash] = useS2(null);
  const post = rounds[idx];
  const theme = POST_THEMES[idx % POST_THEMES.length];

  function answer(choice) {
    if (feedback) return;
    const ok = (choice === 'post' && post.type === 'safe') || (choice === 'dont' && post.type === 'dont');
    if (ok) { SFX.correct(); setScore(s => s + 10); setFlash('ok'); }
    else    { SFX.wrong();   setScore(s => Math.max(0, s - 5)); setFlash('bad'); }
    setFeedback({ ok });
    setTimeout(() => setFlash(null), 350);
  }
  function next() {
    setFeedback(null);
    if (idx + 1 >= rounds.length) {
      setDone(true);
      onScore(score);
      setTimeout(() => SFX.win(), 200);
    } else setIdx(i => i + 1);
  }

  if (done) {
    const rank = getRank(score, game.maxScore, game.ranks);
    return <ResultScreen game={game} score={score} rank={rank} onExit={onExit} onReplay={() => location.reload()} />;
  }

  return (
    <GameShell game={game} onExit={onExit} flash={flash}>
      <div className="pd-stage">
        <div className="ph-meta">
          <span className="ph-counter">POST <b>{idx + 1}</b> / {rounds.length}</span>
          <span className="ph-score">SCORE <b>{score}</b></span>
        </div>

        <div className="pd-phone">
          <div className="pd-phone__notch" />
          <div className="pd-post">
            <div className="pd-post__head">
              <div className="pd-post__avatar" style={{ background: theme.tint }} />
              <div>
                <div className="pd-post__user">{theme.user}</div>
                <div className="pd-post__app">{theme.app}</div>
              </div>
              <div className="pd-post__more">···</div>
            </div>
            <div className="pd-post__photo" style={{ background: theme.tint }}>
              <div className="pd-post__placeholder">PHOTO</div>
              <div className="pd-post__overlay">
                {post.tags.map(t => <span key={t}>● {t}</span>)}
              </div>
            </div>
            <div className="pd-post__caption">{post.caption}</div>
            <div className="pd-post__actions"><span>♡  💬  ↗</span><span>save</span></div>
          </div>
        </div>

        {feedback ? (
          <div className={`pd-fb pd-fb--${feedback.ok ? 'ok' : 'bad'}`}>
            <Scanner mood={feedback.ok ? 'cheering' : 'facepalm'} size={64} />
            <div className="pd-fb__text">
              <b>{feedback.ok ? 'GOOD CALL' : 'OOF'}</b>
              <span>{post.why}</span>
            </div>
            <ArcadeButton onClick={next} color={game.color} size="md">{idx + 1 >= rounds.length ? 'SEE RESULT' : 'NEXT POST ▸'}</ArcadeButton>
          </div>
        ) : (
          <div className="pd-actions">
            <ArcadeButton onClick={() => answer('dont')} color="#ff4d6d" textColor="#fff" size="lg">⛔ DON'T POST</ArcadeButton>
            <ArcadeButton onClick={() => answer('post')} color="#7dff5a" size="lg">✓ POST IT</ArcadeButton>
          </div>
        )}
      </div>
    </GameShell>
  );
}
window.PrivacyDefender = PrivacyDefender;

// ─────────────────────────────────────────────────────────────────────
// GAME 5: LINK INSPECTOR
// ─────────────────────────────────────────────────────────────────────
function LinkInspector({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'link');
  const [rounds] = useS2(() => pickRandom(LINK_BANK, 10));
  const [idx, setIdx] = useS2(0);
  const [score, setScore] = useS2(0);
  const [hovered, setHovered] = useS2(false);
  const [feedback, setFeedback] = useS2(null);
  const [done, setDone] = useS2(false);
  const [flash, setFlash] = useS2(null);
  const cur = rounds[idx];

  const subjects = [
    'Account verification needed',
    'Your invoice is ready',
    'Action required: confirm sign-in',
    'Reward: claim your bonus',
    'Subscription update',
    'Security alert',
    'New device sign-in',
    'Refund waiting',
    'Important: account locked',
    'Your order summary',
  ];

  function answer(choice) {
    if (feedback) return;
    const ok = (choice === 'safe' && cur.type === 'safe') || (choice === 'dodgy' && cur.type === 'dodgy');
    if (ok) { SFX.correct(); setScore(s => s + 10); setFlash('ok'); }
    else    { SFX.wrong();   setScore(s => Math.max(0, s - 5)); setFlash('bad'); }
    setFeedback({ ok });
    setTimeout(() => setFlash(null), 350);
  }
  function next() {
    setFeedback(null);
    setHovered(false);
    if (idx + 1 >= rounds.length) {
      setDone(true);
      onScore(score);
      setTimeout(() => SFX.win(), 200);
    } else setIdx(i => i + 1);
  }

  if (done) {
    const rank = getRank(score, game.maxScore, game.ranks);
    return <ResultScreen game={game} score={score} rank={rank} onExit={onExit} onReplay={() => location.reload()} />;
  }

  return (
    <GameShell game={game} onExit={onExit} flash={flash}>
      <div className="li-stage">
        <div className="ph-meta">
          <span className="ph-counter">EMAIL <b>{idx + 1}</b> / {rounds.length}</span>
          <span className="ph-score">SCORE <b>{score}</b></span>
          {!hovered && !feedback && <span className="ph-counter li-hint">⤷ HOVER THE LINK FIRST</span>}
        </div>

        <div className="li-mail">
          <div className="li-mail__head">
            <span className="li-mail__from">no-reply@<b>{cur.display.split('/')[0]}</b></span>
            <span className="li-mail__time">today · 09:14</span>
          </div>
          <div className="li-mail__subject">{subjects[idx % subjects.length]}</div>
          <div className="li-mail__body">
            <p>Hey,</p>
            <p>We need you to confirm your account before we can keep things running. Tap the secure link below to continue:</p>
            <div className="li-link-wrap">
              <a
                className="li-link"
                onMouseEnter={() => { setHovered(true); SFX.tick(); }}
                onClick={(e) => e.preventDefault()}
                href="#"
              >
                ▸ {cur.display}
              </a>
              {hovered && (
                <div className="li-tooltip">
                  <span className="li-tooltip__label">REAL DESTINATION</span>
                  <span className="li-tooltip__url">{cur.real}</span>
                </div>
              )}
            </div>
            <p>Thanks,<br/>The Team.</p>
          </div>
        </div>

        {feedback ? (
          <div className="pd-fb">
            <Scanner mood={feedback.ok ? 'cheering' : 'facepalm'} size={64} />
            <div className="pd-fb__text">
              <b>{feedback.ok ? 'NAILED IT' : 'WATCH FOR THIS'}</b>
              <span>{cur.why}</span>
            </div>
            <ArcadeButton onClick={next} color={game.color} textColor="#04101a" size="md">{idx + 1 >= rounds.length ? 'SEE RESULT' : 'NEXT EMAIL ▸'}</ArcadeButton>
          </div>
        ) : (
          <div className="pd-actions">
            <ArcadeButton onClick={() => answer('dodgy')} color="#ff4d6d" textColor="#fff" size="lg" disabled={!hovered}>🚨 DODGY</ArcadeButton>
            <ArcadeButton onClick={() => answer('safe')} color="#7dff5a" size="lg" disabled={!hovered}>✓ SAFE</ArcadeButton>
          </div>
        )}
      </div>
    </GameShell>
  );
}
window.LinkInspector = LinkInspector;

// ─────────────────────────────────────────────────────────────────────
// GAME 6: TWO-FACTOR HERO
// Endless: timer = max(4, 12 - correctStreak). Show window = max(3, 5 - 0.5*correct).
// 3 lives. Wrong/timeout = lose life, retry same level. End at 0 lives or 15 rounds.
// ─────────────────────────────────────────────────────────────────────
function genCode() {
  let c = '';
  for (let i = 0; i < 6; i++) c += Math.floor(Math.random() * 10);
  return c;
}

function TwoFactorHero({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'twofa');
  const MAX_ROUNDS = 15;
  const [round, setRound] = useS2(1);
  const [correctStreak, setCorrectStreak] = useS2(0); // # successes (drives difficulty)
  const [phase, setPhase] = useS2('show'); // show | type | result
  const [code, setCode] = useS2(() => genCode());
  const [typed, setTyped] = useS2('');
  const [score, setScore] = useS2(0);
  const [lives, setLives] = useS2(3);
  const [results, setResults] = useS2([]);
  const [done, setDone] = useS2(false);
  const [tenths, setTenths] = useS2(0); // remaining time in 0.1s units
  const [showLeftMs, setShowLeftMs] = useS2(0);
  const inputRef = useR2(null);
  const resolvedRef = useR2(false);

  // current limits (function of correct count)
  const limitSec = Math.max(4, 12 - correctStreak);
  const showSec = Math.max(3, 5 - 0.5 * correctStreak);
  const danger = tenths <= limitSec * 10 * 0.4;
  const critical = tenths <= limitSec * 10 * 0.2;

  // SHOW phase
  useE2(() => {
    if (phase !== 'show') return;
    resolvedRef.current = false;
    setTyped('');
    setTenths(Math.round(limitSec * 10));
    setShowLeftMs(Math.round(showSec * 1000));
    const start = Date.now();
    const dur = showSec * 1000;
    const id = setInterval(() => {
      const left = Math.max(0, dur - (Date.now() - start));
      setShowLeftMs(left);
      if (left <= 0) {
        clearInterval(id);
        SFX.boot();
        setPhase('type');
        setTimeout(() => inputRef.current && inputRef.current.focus(), 60);
      }
    }, 100);
    return () => clearInterval(id);
  }, [phase, round]);

  // TYPE phase: 100ms tick countdown
  useE2(() => {
    if (phase !== 'type') return;
    const id = setInterval(() => {
      setTenths(t => {
        if (t <= 1) {
          clearInterval(id);
          if (!resolvedRef.current) { resolvedRef.current = true; resolve(false, 0); }
          return 0;
        }
        // urgent ticks
        const next = t - 1;
        if (next % 10 === 0) {
          if (next <= limitSec * 10 * 0.2) SFX.wrong();
          else SFX.tick();
        }
        return next;
      });
    }, 100);
    return () => clearInterval(id);
  }, [phase]);

  function resolve(ok, leftoverTenths) {
    if (resolvedRef.current && !ok) {} // already flagged
    resolvedRef.current = true;
    setPhase('result');
    const leftoverSec = leftoverTenths / 10;
    let points = 0;
    if (ok) {
      // 5 + leftoverSec * 5  → up to ~50ish, scaled by current limit
      points = Math.round(5 + leftoverSec * 5);
      SFX.correct();
    } else {
      SFX.lose();
    }
    setScore(s => s + points);
    setResults(r => [...r, { ok, leftoverSec, points, round }]);
    if (!ok) setLives(l => l - 1);

    setTimeout(() => {
      const newLives = ok ? lives : lives - 1;
      const nextRound = round + 1;
      if (newLives <= 0 || nextRound > MAX_ROUNDS) {
        setDone(true);
        onScore(score + points);
        setTimeout(() => SFX.win(), 200);
      } else {
        if (ok) setCorrectStreak(c => c + 1);
        setRound(nextRound);
        setCode(genCode());
        setPhase('show');
      }
    }, 1600);
  }

  function onChange(e) {
    if (phase !== 'type') return;
    const v = e.target.value.replace(/\D/g, '').slice(0, 6);
    setTyped(v);
    if (v.length > 0) SFX.type();
    if (v.length === 6) {
      const ok = v === code;
      const leftover = tenths;
      setTimeout(() => { if (!resolvedRef.current) resolve(ok, leftover); }, 60);
    }
  }

  if (done) {
    const final = score;
    const rank = getRank(final, game.maxScore, game.ranks);
    const blocked = results.filter(r => r.ok).length;
    const fastest = results.filter(r => r.ok).reduce((m,r) => Math.max(m, r.leftoverSec), 0);
    return (
      <ResultScreen game={game} score={final} rank={rank} onExit={onExit} onReplay={() => location.reload()}>
        <div className="result__metrics">
          <div><span>ROUNDS</span><b>{results.length}</b></div>
          <div><span>BLOCKED</span><b>{blocked}</b></div>
          <div><span>FASTEST</span><b>{fastest.toFixed(1)}s</b></div>
        </div>
      </ResultScreen>
    );
  }

  const lastResult = results[results.length - 1];
  const hackerProgress = Math.max(0, Math.min(1, 1 - tenths / (limitSec * 10)));
  const showSecLeft = (showLeftMs / 1000).toFixed(1);

  return (
    <GameShell game={game} onExit={onExit} flash={phase === 'result' ? (lastResult && lastResult.ok ? 'ok' : 'bad') : null}>
      <div className={`tf-stage ${critical ? 'is-critical' : ''} ${danger ? 'is-danger' : ''}`}>
        <div className="ph-meta">
          <span className="ph-counter">ROUND <b>{round}</b> / {MAX_ROUNDS}</span>
          <span className="ph-score">SCORE <b>{score}</b></span>
          <span className="ph-counter">LIMIT <b>{limitSec}s</b></span>
          <span className="ph-counter tf-lives">LIVES {[0,1,2].map(i => <b key={i} className={i < lives ? 'on' : ''}>♥</b>)}</span>
        </div>

        {/* Hacker advance bar */}
        <div className="tf-hacker">
          <div className="tf-hacker__track">
            <div className="tf-hacker__bar" style={{ width: `${hackerProgress * 100}%` }} />
            <div className="tf-hacker__hacker" style={{ left: `${hackerProgress * 100}%` }}>
              <span>{critical ? '😈' : danger ? '👤' : '🥷'}</span>
              <i>HACKER</i>
            </div>
            <div className="tf-hacker__door">🔒 YOU</div>
          </div>
        </div>

        <div className="tf-grid">
          {/* Phone showing the code */}
          <div className={`tf-phone ${phase === 'show' ? 'is-live' : ''}`}>
            <div className="tf-phone__top">
              <span>9:41</span>
              <span>● ● ● ●</span>
            </div>
            <div className="tf-phone__app">
              <div className="tf-phone__brand">★ AUTH</div>
              <div className="tf-phone__label">YOUR CODE</div>
              <div className={`tf-phone__code ${phase !== 'show' ? 'is-hidden' : ''}`}>
                {phase === 'show' ? code : '— — — — — —'}
              </div>
              <div className="tf-phone__sub">
                {phase === 'show' ? `memorise · ${showSecLeft}s` : 'code expired'}
              </div>
              {phase === 'show' && (
                <div className="tf-phone__bar"><div style={{ width: `${(showLeftMs / (showSec * 1000)) * 100}%` }} /></div>
              )}
            </div>
          </div>

          {/* Login screen */}
          <div className="tf-login">
            <div className="tf-login__head">
              <Scanner mood={phase === 'result' ? (lastResult && lastResult.ok ? 'cheering' : 'facepalm') : (critical ? 'alert' : danger ? 'worried' : 'alert')} size={48} />
              <div>
                <div className="tf-login__title">LOG IN · STEP 2</div>
                <div className="tf-login__sub">
                  {phase === 'result'
                    ? (lastResult && lastResult.ok ? 'You blocked the hacker!' : 'TOO SLOW — they\'re inside!')
                    : critical ? 'FASTER, they\'re getting in!'
                    : danger ? 'They\'re close — type it!'
                    : 'enter the 6-digit code'}
                </div>
              </div>
            </div>

            <div className={`tf-timer ${critical ? 'is-low' : ''} ${danger && !critical ? 'is-warn' : ''}`}>
              <div className="tf-timer__bar"><div style={{ width: `${(tenths / (limitSec * 10)) * 100}%` }} /></div>
              <div className="tf-timer__num">{(tenths / 10).toFixed(1)}s</div>
            </div>

            <div className="tf-input-row">
              {[0,1,2,3,4,5].map(i => (
                <div key={i} className={`tf-cell ${typed[i] ? 'on' : ''}`}>{typed[i] || '_'}</div>
              ))}
            </div>
            <input
              ref={inputRef}
              className="tf-input"
              value={typed}
              onChange={onChange}
              disabled={phase !== 'type'}
              inputMode="numeric"
              autoComplete="one-time-code"
              placeholder={phase === 'show' ? 'wait…' : 'type the code'}
            />

            {phase === 'result' && lastResult && (
              <div className={`tf-verdict ${lastResult.ok ? 'ok' : 'bad'}`}>
                {lastResult.ok
                  ? `BLOCKED · +${lastResult.points}`
                  : `THEY GOT IN! −1 LIFE`}
              </div>
            )}
          </div>
        </div>
      </div>
    </GameShell>
  );
}
window.TwoFactorHero = TwoFactorHero;
// Endless mode tweaks
GAMES.find(g => g.id === 'twofa').ranks = ['Slow Defender','Code Cadet','Quick Fingers','Lockdown Pro','Lightning Hero','Untouchable'];
GAMES.find(g => g.id === 'twofa').maxScore = 800;
