// Games 1-3: Phish or Legit, Password Smash, Red Flag Rush
const { useState: useS1, useEffect: useE1, useRef: useR1, useMemo: useM1, useCallback: useCb1 } = React;

function pickRandom(arr, n) {
  const a = [...arr];
  for (let i = a.length - 1; i > 0; i--) {
    const j = Math.floor(Math.random() * (i + 1));
    [a[i], a[j]] = [a[j], a[i]];
  }
  return a.slice(0, n);
}

// ─────────────────────────────────────────────────────────────────────
// GAME 1: PHISH OR LEGIT
// ─────────────────────────────────────────────────────────────────────
function GamePhish({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'phish');
  const [rounds] = useS1(() => pickRandom(PHISH_BANK, 10));
  const [idx, setIdx] = useS1(0);
  const [score, setScore] = useS1(0);
  const [feedback, setFeedback] = useS1(null);  // { ok, why }
  const [flash, setFlash] = useS1(null);
  const [done, setDone] = useS1(false);

  const current = rounds[idx];

  function answer(choice) {
    if (feedback) return;
    const ok = current.type === choice;
    if (ok) { SFX.correct(); setScore(s => s + 10); setFlash('ok'); }
    else    { SFX.wrong();   setScore(s => Math.max(0, s - 5)); setFlash('bad'); }
    setFeedback({ ok, why: current.why });
    setTimeout(() => setFlash(null), 350);
  }
  function next() {
    setFeedback(null);
    if (idx + 1 >= rounds.length) {
      setDone(true);
      const final = score; // already updated
      setTimeout(() => SFX.win(), 200);
      onScore(final);
    } 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="ph-stage">
        <div className="ph-meta">
          <span className="ph-counter">ROUND <b>{idx + 1}</b> / {rounds.length}</span>
          <span className="ph-score">SCORE <b>{score}</b></span>
        </div>
        <div className={`ph-msg ph-msg--${current.kind.toLowerCase().includes('email') ? 'email' : current.kind.toLowerCase().includes('pop') ? 'popup' : current.kind.toLowerCase().includes('notif') ? 'notif' : 'text'}`}>
          <div className="ph-msg__head">
            <span className="ph-msg__kind">{current.kind.toUpperCase()}</span>
            <span className="ph-msg__time">{['09:14','12:03','17:48','21:22'][idx % 4]}</span>
          </div>
          <div className="ph-msg__body">{current.body}</div>
        </div>

        {feedback ? (
          <div className={`ph-feedback ph-feedback--${feedback.ok ? 'ok' : 'bad'}`}>
            <div className="ph-feedback__top">
              <Scanner mood={feedback.ok ? 'cheering' : 'facepalm'} size={64} />
              <div>
                <div className="ph-feedback__verdict">{feedback.ok ? 'CORRECT' : 'GOTCHA'}</div>
                <div className="ph-feedback__why">{feedback.why}</div>
              </div>
            </div>
            <ArcadeButton onClick={next} color={game.color} size="md">{idx + 1 >= rounds.length ? 'SEE RESULT' : 'NEXT MESSAGE ▸'}</ArcadeButton>
          </div>
        ) : (
          <div className="ph-actions">
            <ArcadeButton onClick={() => answer('phish')} color="#ff4d6d" textColor="#fff" size="lg">⚠ PHISH</ArcadeButton>
            <ArcadeButton onClick={() => answer('legit')} color="#7dff5a" size="lg">✓ LEGIT</ArcadeButton>
          </div>
        )}
      </div>
    </GameShell>
  );
}
window.GamePhish = GamePhish;

// ─────────────────────────────────────────────────────────────────────
// GAME 2: PASSWORD SMASH
// ─────────────────────────────────────────────────────────────────────
const COMMON_BAD = ['password','123456','12345','qwerty','letmein','admin','iloveyou','welcome','abc123','pokemon','minecraft','football','dragon'];
const TARGETS = [30, 50, 65, 80, 95];

function strengthOf(pw) {
  if (!pw) return { score: 0, label: 'EMPTY', color: '#3a4a55', tip: 'Type a password to start.' };
  let s = Math.min(40, pw.length * 4);
  if (/[a-z]/.test(pw)) s += 8;
  if (/[A-Z]/.test(pw)) s += 8;
  if (/[0-9]/.test(pw)) s += 10;
  if (/[^A-Za-z0-9]/.test(pw)) s += 18;
  if (pw.length >= 12) s += 8;
  if (pw.length >= 16) s += 6;
  // variety bonus
  const unique = new Set(pw).size;
  s += Math.min(8, unique - 4);
  // penalties
  const lower = pw.toLowerCase();
  if (COMMON_BAD.some(b => lower.includes(b))) s -= 35;
  if (/^[a-z]+$/i.test(pw)) s -= 8;
  if (/^[0-9]+$/.test(pw)) s -= 12;
  if (/(.)\1\1/.test(pw)) s -= 10;
  s = Math.max(0, Math.min(100, Math.round(s)));

  let label, color, tip;
  if (s < 25)      { label = 'WEAK';      color = '#ff4d6d'; tip = 'Way too short. Add more characters.'; }
  else if (s < 50) { label = 'MEH';       color = '#ff8a3d'; tip = 'Mix in upper-case + a number.'; }
  else if (s < 70) { label = 'OK';        color = '#ffd84d'; tip = 'Add a symbol like !, @ or #.'; }
  else if (s < 88) { label = 'STRONG';    color = '#7dff5a'; tip = 'Nice. Make it longer for legendary.'; }
  else             { label = 'LEGENDARY'; color = '#ff4ec3'; tip = 'Lock it in!'; }

  if (COMMON_BAD.some(b => lower.includes(b))) tip = 'Common word detected — swap it out!';
  return { score: s, label, color, tip };
}

function PasswordSmash({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'pass');
  const [level, setLevel] = useS1(0);
  const [pw, setPw] = useS1('');
  const [totals, setTotals] = useS1([]);
  const [done, setDone] = useS1(false);
  const inputRef = useR1(null);
  const lastTip = useR1('');

  useE1(() => {
    setPw('');
    setTimeout(() => inputRef.current && inputRef.current.focus(), 50);
  }, [level]);

  const target = TARGETS[level];
  const st = useM1(() => strengthOf(pw), [pw]);
  const reached = st.score >= target;

  function submit() {
    if (!reached) { SFX.wrong(); return; }
    SFX.correct();
    // Bonus for hitting target with fewer characters: target/length
    const efficiency = Math.max(1, Math.round((target / Math.max(8, pw.length)) * 30));
    const bonus = reached && st.score >= target + 15 ? 20 : 0;
    const round = 60 + efficiency + bonus;
    const next = [...totals, round];
    setTotals(next);
    if (level + 1 >= TARGETS.length) {
      setDone(true);
      const final = next.reduce((a, b) => a + b, 0);
      onScore(final);
      setTimeout(() => SFX.win(), 200);
    } else {
      setLevel(l => l + 1);
    }
  }

  function onKey(e) {
    if (e.key === 'Enter') submit();
    else SFX.type();
  }

  if (done) {
    const final = totals.reduce((a, b) => a + b, 0);
    const rank = getRank(final, game.maxScore, game.ranks);
    const stickers = ['like a wet noodle 🍜','like an old shoelace 🪢','like a solid padlock 🔒','like a vault door 🛡','like a cosmic firewall ✨'];
    const sticker = stickers[Math.min(stickers.length - 1, Math.floor((final / game.maxScore) * stickers.length))];
    return (
      <ResultScreen game={game} score={final} rank={rank} onExit={onExit} onReplay={() => location.reload()}>
        <div className="result__sticker">YOUR PASSWORD IS<br/><b>{sticker}</b></div>
      </ResultScreen>
    );
  }

  return (
    <GameShell game={game} onExit={onExit}>
      <div className="ps-stage">
        <div className="ps-meta">
          <span className="ph-counter">LEVEL <b>{level + 1}</b> / {TARGETS.length}</span>
          <span className="ph-score">TARGET <b>{target}%</b></span>
        </div>
        <div className="ps-input-wrap">
          <label className="ps-label">TYPE A PASSWORD</label>
          <input
            ref={inputRef}
            className="ps-input"
            value={pw}
            onChange={e => setPw(e.target.value)}
            onKeyDown={onKey}
            spellCheck={false}
            autoComplete="off"
            placeholder="start typing…"
            style={{ caretColor: st.color }}
          />
          <div className="ps-meter">
            <div className="ps-meter__bar" style={{ width: `${st.score}%`, background: st.color, boxShadow: `0 0 18px ${st.color}` }} />
            <div className="ps-meter__target" style={{ left: `${target}%` }}>
              <span>TARGET {target}</span>
            </div>
          </div>
          <div className="ps-stats">
            <span>STRENGTH <b style={{color: st.color}}>{st.label}</b></span>
            <span>SCORE <b style={{color: st.color}}>{st.score}</b></span>
            <span>LEN <b>{pw.length}</b></span>
          </div>
        </div>

        <div className="ps-mascot">
          <Scanner mood={reached ? 'cheering' : (st.score < 25 ? 'worried' : 'happy')} size={64} />
          <div className="mascot-bubble">{reached ? `Locked in! Press ENTER to submit.` : st.tip}</div>
        </div>

        <div className="ps-actions">
          <ArcadeButton onClick={() => setPw('')} color="#1a2530" textColor="#9bb3c2" size="md">CLEAR</ArcadeButton>
          <ArcadeButton onClick={submit} color={reached ? game.color : '#1a2530'} textColor={reached ? '#04101a' : '#3a4a55'} size="lg" disabled={!reached}>
            {reached ? 'SUBMIT ▸ ENTER' : `NEED ${Math.max(0, target - st.score)} MORE`}
          </ArcadeButton>
        </div>
      </div>
    </GameShell>
  );
}
window.PasswordSmash = PasswordSmash;

// ─────────────────────────────────────────────────────────────────────
// GAME 3: RED FLAG RUSH
// ─────────────────────────────────────────────────────────────────────
function RedFlagRush({ onExit, onScore }) {
  const game = GAMES.find(g => g.id === 'flag');
  const [time, setTime] = useS1(60);
  const [items, setItems] = useS1([]);   // array of {id, msg, born}
  const [score, setScore] = useS1(0);
  const [correct, setCorrect] = useS1(0);
  const [wrong, setWrong] = useS1(0);
  const [done, setDone] = useS1(false);
  const [drag, setDrag] = useS1(null);
  const [hoverBin, setHoverBin] = useS1(null);
  const [splash, setSplash] = useS1(null);
  const idRef = useR1(0);

  // timer
  useE1(() => {
    if (done) return;
    const i = setInterval(() => {
      setTime(t => {
        if (t <= 1) { clearInterval(i); finish(); return 0; }
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(i);
  }, [done]);

  // spawn
  useE1(() => {
    if (done) return;
    let alive = true;
    const spawn = () => {
      if (!alive || done) return;
      setItems(curr => {
        if (curr.length >= 4) return curr;
        const msg = pickRandom(RED_FLAG_BANK, 1)[0];
        return [...curr, { id: ++idRef.current, msg, born: Date.now() }];
      });
      setTimeout(spawn, 1500 + Math.random() * 1500);
    };
    const t = setTimeout(spawn, 600);
    return () => { alive = false; clearTimeout(t); };
  }, [done]);

  function finish() {
    setDone(true);
    const final = score;
    onScore(final);
    setTimeout(() => SFX.win(), 200);
  }

  function handleDrop(bin) {
    if (!drag) return;
    const item = items.find(i => i.id === drag);
    if (!item) return;
    const ok = (bin === 'safe' && item.msg.type === 'safe') || (bin === 'flag' && item.msg.type === 'flag');
    if (ok) { SFX.correct(); setScore(s => s + 1); setCorrect(c => c + 1); }
    else    { SFX.wrong();   setScore(s => Math.max(0, s - 2)); setWrong(w => w + 1); }
    setSplash({ bin, ok, ts: Date.now() });
    setItems(curr => curr.filter(i => i.id !== drag));
    setDrag(null); setHoverBin(null);
    setTimeout(() => setSplash(null), 350);
  }

  // Click-to-sort fallback when not dragging
  function tap(item, bin) {
    if (drag) return;
    setDrag(item.id);
    setTimeout(() => handleDrop(bin), 0);
  }

  if (done) {
    const total = correct + wrong;
    const acc = total ? Math.round((correct / total) * 100) : 0;
    const rank = getRank(score, game.maxScore, game.ranks);
    return (
      <ResultScreen game={game} score={score} rank={rank} onExit={onExit} onReplay={() => location.reload()}>
        <div className="result__metrics">
          <div><span>SORTED</span><b>{total}</b></div>
          <div><span>ACCURACY</span><b>{acc}%</b></div>
          <div><span>WRONG</span><b>{wrong}</b></div>
        </div>
      </ResultScreen>
    );
  }

  return (
    <GameShell game={game} onExit={onExit}>
      <div className="rf-stage">
        <div className="rf-meta">
          <span className="ph-counter">TIME <b style={{color: time < 10 ? '#ff4d6d' : '#fff'}}>{time}s</b></span>
          <span className="ph-score">SCORE <b>{score}</b></span>
          <span className="ph-counter">✓ {correct}  ✗ {wrong}</span>
        </div>

        <div className="rf-bins">
          <div
            className={`rf-bin rf-bin--safe ${hoverBin === 'safe' ? 'is-hover' : ''} ${splash && splash.bin === 'safe' ? (splash.ok ? 'is-ok' : 'is-bad') : ''}`}
            onDragOver={e => { e.preventDefault(); setHoverBin('safe'); }}
            onDragLeave={() => setHoverBin(null)}
            onDrop={() => handleDrop('safe')}
          >
            <div className="rf-bin__label">✓ SAFE</div>
            <div className="rf-bin__hint">drag here</div>
          </div>

          <div className="rf-arena">
            {items.map(item => (
              <div
                key={item.id}
                className={`rf-msg ${drag === item.id ? 'is-drag' : ''}`}
                draggable
                onDragStart={() => { setDrag(item.id); SFX.click(); }}
                onDragEnd={() => { setDrag(null); setHoverBin(null); }}
                style={{ '--delay': `${(item.id % 5) * 0.05}s` }}
              >
                <span className="rf-msg__handle">⋮⋮</span>
                <span className="rf-msg__body">"{item.msg.body}"</span>
                <div className="rf-msg__quick">
                  <button onClick={() => tap(item, 'safe')} title="safe">✓</button>
                  <button onClick={() => tap(item, 'flag')} title="flag">⚠</button>
                </div>
              </div>
            ))}
            {items.length === 0 && (
              <div className="rf-arena__empty"><Scanner mood="alert" size={56} /><span>incoming…</span></div>
            )}
          </div>

          <div
            className={`rf-bin rf-bin--flag ${hoverBin === 'flag' ? 'is-hover' : ''} ${splash && splash.bin === 'flag' ? (splash.ok ? 'is-ok' : 'is-bad') : ''}`}
            onDragOver={e => { e.preventDefault(); setHoverBin('flag'); }}
            onDragLeave={() => setHoverBin(null)}
            onDrop={() => handleDrop('flag')}
          >
            <div className="rf-bin__label">⚠ RED FLAG</div>
            <div className="rf-bin__hint">drag here</div>
          </div>
        </div>

        <div className="rf-foot">
          <Scanner mood="alert" size={48} />
          <span>Drag chats to a bin — or tap ✓ / ⚠ on the message itself.</span>
        </div>
      </div>
    </GameShell>
  );
}
window.RedFlagRush = RedFlagRush;

// ─────────────────────────────────────────────────────────────────────
// Shared Game Shell + Result Screen
// ─────────────────────────────────────────────────────────────────────
function GameShell({ game, onExit, flash, children }) {
  return (
    <div className={`gshell flash-${flash || 'none'}`} data-screen-label={`Game · ${game.title}`} style={{ '--g': game.color, '--ga': game.accent }}>
      <header className="gshell__bar">
        <button className="gshell__back" onClick={() => { SFX.powerOff(); onExit(); }}>◂ BACK TO HUB</button>
        <div className="gshell__title">
          <PixIcon name={game.icon} size={28} color={game.color} />
          <span>{game.title}</span>
        </div>
        <div className="gshell__chip" style={{ borderColor: game.color, color: game.color }}>CAB-0{GAMES.indexOf(game)+1}</div>
      </header>
      <div className="gshell__inner">{children}</div>
    </div>
  );
}
window.GameShell = GameShell;

function ResultScreen({ game, score, rank, onExit, onReplay, children }) {
  return (
    <div className="result" style={{ '--g': game.color }} data-screen-label="Result">
      <div className="result__inner">
        <Scanner mood="cheering" size={140} />
        <div className="result__head">RESULTS</div>
        <div className="result__game">{game.title}</div>
        <div className="result__score">{score}</div>
        <div className="result__rank">RANK · <b>{rank}</b></div>
        {children}
        <div className="result__actions">
          <ArcadeButton onClick={() => { SFX.click(); onReplay(); }} color={game.color} size="lg">PLAY AGAIN</ArcadeButton>
          <ArcadeButton onClick={() => { SFX.click(); onExit(); }} color="#1a2530" textColor="#eafcff" size="lg">BACK TO HUB</ArcadeButton>
        </div>
      </div>
    </div>
  );
}
window.ResultScreen = ResultScreen;
window.pickRandom = pickRandom;
