// Main app — wires everything together with a tweaks panel
function App() {
  const defaults = TWEAK_DEFAULTS;
  const [tweaks, setTweak] = useTweaks(defaults);

  const [profile, updateProfile] = useProfile();
  const stickers = profile.stickers;
  const [openGame, setOpenGame] = React.useState(null); // {game, kind}
  const [reward, setReward] = React.useState(null);
  const [redeemMsg, setRedeemMsg] = React.useState(null);

  const giveSticker = React.useCallback((s) => {
    updateProfile(prev => addSticker(prev, s));
  }, [updateProfile]);

  // First-visit gate: show AgePrompt before letting the kid open math games.
  const [pendingMathGame, setPendingMathGame] = React.useState(null);
  const needsAge = profile.age == null;

  const setAge = React.useCallback((age) => {
    updateProfile(prev => {
      const perGame = { ...prev.perGame };
      MATH_GAMES.forEach(g => {
        const existing = perGame[g.id];
        const seeded = seedDifficulty(age, g.id);
        perGame[g.id] = existing
          ? { ...existing, difficulty: existing.difficulty ?? seeded }
          : { difficulty: seeded, recentResults: [] };
      });
      return { ...prev, age, perGame };
    });
    if (pendingMathGame) {
      setOpenGame({ game: pendingMathGame, kind: 'math' });
      setPendingMathGame(null);
    }
  }, [updateProfile, pendingMathGame]);

  const handleOpen = (game, kind) => {
    if (kind === 'math' && needsAge) {
      setPendingMathGame(game);
      return;
    }
    setOpenGame({ game, kind });
  };

  const handleRedeem = (rawCode) => {
    const entry = findCode(rawCode);
    if (!entry) {
      setRedeemMsg({ type: 'error', text: 'Hmm, det ser ikke ut som en gyldig kode. Prøv igjen!' });
      return;
    }
    setReward({
      code: entry.code,
      sticker: entry.sticker,
      mediaType: entry.media?.type || 'Bilde',
      mediaLabel: entry.media?.label || 'Overraskelse',
      mediaUrl: entry.media?.url || null,
    });
    updateProfile(prev => addRedeemedCode(addSticker(prev, entry.sticker), entry.code));
    setRedeemMsg({ type: 'success', text: 'Yay! Koden er gyldig — sjekk overraskelsen!' });
    setTimeout(() => setRedeemMsg(null), 4000);
  };

  // Called by GameRunner when the kid finishes a round.
  // Persists results, runs the lottery for math games that award codes,
  // and either opens the reward modal (on a win) or returns to the home page.
  const handleGameFinish = (result) => {
    const game = openGame?.game;
    if (!game) return;
    const gameId = game.id;

    // 1. Persist round results and bump difficulty for next time.
    updateProfile(prev => {
      const slot = prev.perGame[gameId] || { difficulty: seedDifficulty(prev.age, gameId), recentResults: [] };
      const recentResults = [...slot.recentResults, ...(result.rounds || [])].slice(-5);
      const difficulty = nextDifficulty(slot.difficulty, recentResults);
      return {
        ...prev,
        perGame: { ...prev.perGame, [gameId]: { difficulty, recentResults } },
      };
    });

    setOpenGame(null);

    // 2. Only games marked reward=true run the lottery. The rest just close.
    if (!result.passed || !game.reward) return;

    const perf = performanceScore(result.rounds || []);
    const forceWin = !!tweaks.devForceWin;
    const lot = runLottery(profile, perf, { forceWin });
    if (!lot.won || !lot.entry) return;

    // 3. Win: persist the code + sticker, show the reward modal.
    const entry = lot.entry;
    updateProfile(prev => addWonCode(addSticker(prev, entry.sticker), entry.code));
    setReward({
      code: entry.code,
      sticker: entry.sticker,
      mediaType: entry.media?.type || 'Bilde',
      mediaLabel: entry.media?.label || 'Overraskelse',
      mediaUrl: entry.media?.url || null,
    });
  };

  return (
    <>
      <BgDecor />
      <div className="app">
        <Header />
        <Hero />
        <MathSection onOpen={handleOpen} />
        <RandomSection onOpen={handleOpen} />
        <RedeemSection onRedeem={handleRedeem} message={redeemMsg} />
        <StickerCollection stickers={stickers} total={tweaks.stickerSlots} />
        <Footer />
      </div>
      {openGame && openGame.kind === 'math' && (
        <MathGameModal
          game={openGame.game}
          profile={profile}
          onClose={() => setOpenGame(null)}
          onFinish={handleGameFinish}
        />
      )}
      {openGame && openGame.kind === 'random' && (
        <RandomGameModal
          game={openGame.game}
          onClose={() => setOpenGame(null)}
        />
      )}
      {reward && <RewardModal reward={reward} onClose={() => setReward(null)} />}
      {pendingMathGame && (
        <AgePrompt
          gameTitle={pendingMathGame.title}
          onPick={setAge}
          onClose={() => setPendingMathGame(null)}
        />
      )}

      <TweaksPanel title="Tweaks">
        <TweakSection title="Klistremerker">
          <TweakSlider label="Antall plasser" value={tweaks.stickerSlots} min={12} max={48} step={4} onChange={v => setTweak('stickerSlots', v)} />
          <TweakButton label="Tøm samlingen" onClick={() => updateProfile(prev => ({ ...prev, stickers: [] }))} />
          <TweakButton label="Legg til et tilfeldig" onClick={() => giveSticker(STICKER_POOL[Math.floor(Math.random()*STICKER_POOL.length)])} />
        </TweakSection>
        <TweakSection title="Profil">
          <div style={{ fontSize: 11, color: 'rgba(41,38,27,.6)' }}>
            Alder: {profile.age ?? 'ikke satt'}
          </div>
          <TweakButton label="Endre alder" onClick={() => updateProfile(prev => ({ ...prev, age: null, perGame: {} }))} />
          <TweakButton label="Nullstill profil" onClick={() => updateProfile(_ => defaultProfile())} />
        </TweakSection>
        <TweakSection title="Lotteri (utvikler)">
          <TweakToggle label="Tving alltid gevinst" value={tweaks.devForceWin} onChange={v => setTweak('devForceWin', v)} />
        </TweakSection>
        <TweakSection title="Demo">
          <TweakButton label="Vis premie-popup" onClick={() => {
            const s = STICKER_POOL[Math.floor(Math.random()*STICKER_POOL.length)];
            setReward({ code: '🌈 🦄 ⭐ 🚀', sticker: s, mediaType: 'YouTube', mediaLabel: 'Demo-video' });
            giveSticker(s);
          }} />
        </TweakSection>
      </TweaksPanel>
    </>
  );
}

// Modal that mounts a GameRunner for the chosen math game. The hero is the
// same colored card we use everywhere; below it sits the live runner. When
// the runner finishes it calls onFinish, which closes the modal and (on a
// win) opens the reward modal.
function MathGameModal({ game, profile, onClose, onFinish }) {
  if (!game) return null;
  const [phase, setPhase] = React.useState('intro'); // intro | playing
  const playing = phase === 'playing';
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className={`modal-hero ${playing ? 'modal-hero-slim' : ''}`} style={{ background: game.bg }}>
          <button className="modal-close" onClick={onClose}>✕</button>
          {playing ? (
            <div className="modal-hero-slim-title" style={{ color: game.symbolDark ? '#6B4A00' : '#fff' }}>
              <span className="modal-hero-slim-symbol">{game.symbol}</span>
              <span>{game.title}</span>
            </div>
          ) : (
            <span className="modal-hero-symbol" style={{ color: game.symbolDark ? '#6B4A00' : '#fff', fontSize: game.isEmoji ? 100 : 120 }}>
              {game.symbol}
            </span>
          )}
        </div>
        {playing ? (
          <GameRunner gameId={game.id} profile={profile} onFinish={onFinish} />
        ) : (
          <div className="modal-body">
            <h3>{game.title}</h3>
            <p>{game.desc} Klar til å spille?</p>
            <div className="modal-meta">
              <span className={`chip ${game.diffClass}`}>{game.difficulty}</span>
              {game.reward && <span className="chip reward">🎁 Gir kode etter fullført</span>}
              <span className="chip">⏱ Ca. 1 min</span>
            </div>
            <div className="modal-actions">
              <button className="btn-primary" onClick={() => setPhase('playing')}>▶ Start spillet</button>
              <button className="btn-secondary" onClick={onClose}>Avbryt</button>
            </div>
          </div>
        )}
      </div>
    </div>
  );
}

// Asks the kid for their age once. Used to seed initial difficulty for every
// math game; nothing else uses age, and nothing leaves the device.
function AgePrompt({ gameTitle, onPick, onClose }) {
  const ages = [5, 6, 7, 8, 9, 10, 11, 12];
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <div className="modal-hero" style={{ background: 'linear-gradient(135deg,#FFE066,#FF7AB8)' }}>
          <button className="modal-close" onClick={onClose}>✕</button>
          <span className="modal-hero-symbol" style={{ color: '#fff', fontSize: 96 }}>🎂</span>
        </div>
        <div className="modal-body">
          <h3>Hvor gammel er du?</h3>
          <p>Vi bruker alderen din til å gjøre {gameTitle ? <strong>{gameTitle}</strong> : 'mattespillene'} akkurat passe vanskelig. Alderen lagres bare på denne enheten.</p>
          <div className="age-grid">
            {ages.map(a => (
              <button key={a} className="age-btn" onClick={() => onPick(a)}>{a}</button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// Modal that hosts a standalone HTML game inside an iframe so kids stay in Math4Kids.
// Sandbox lets the game run scripts and audio but blocks top navigation and popups.
function RandomGameModal({ game, onClose }) {
  React.useEffect(() => {
    const onKey = (e) => { if (e.key === 'Escape') onClose(); };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [onClose]);
  return (
    <div className="modal-backdrop" onClick={onClose}>
      <div className="modal modal-iframe" onClick={e => e.stopPropagation()}>
        <div className="modal-iframe-bar" style={{ background: game.bg }}>
          <div className="modal-iframe-title">{game.title}</div>
          <button className="modal-close" onClick={onClose} aria-label="Lukk spillet">✕</button>
        </div>
        <iframe
          className="modal-iframe-frame"
          src={encodeURI(game.url)}
          title={game.title}
          sandbox="allow-scripts allow-same-origin allow-pointer-lock"
          allow="autoplay"
        />
      </div>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<App />);
