/* Main app: hub + router */
const { useState: useSA, useEffect: useEA, useMemo: useMA } = React;

function LanguageSwitcher() {
  const [locale, setLoc] = useLocale();
  return (
    <div className="lang-switch" role="group" aria-label={t('hub.lang.label')}>
      {LOCALES.map(loc => (
        <button key={loc}
          className={`lang-btn${locale === loc ? ' active' : ''}`}
          onClick={() => { setLoc(loc); window.rebuildGames && window.rebuildGames(); }}
          aria-pressed={locale === loc}>
          {loc.toUpperCase()}
        </button>
      ))}
    </div>
  );
}

function Hub({ progress, onSelect, profile, onEditProfile }) {
  const [locale] = useLocale();
  const games = useMA(() => buildGames(), [locale]);
  const completed = games.filter(g => progress[g.id]?.best != null).length;
  const total = games.length;
  const pct = Math.round(completed / total * 100);

  // All levels are unlocked
  const isUnlocked = (i) => true;

  const [lb, setLb] = useSA([]);
  useEA(() => {
    let cancelled = false;
    fetchLeaderboard().then(entries => { if (!cancelled) setLb(Array.isArray(entries) ? entries : []); });
    return () => { cancelled = true; };
  }, []);

  // Best overall = sum of bests across all categories for current player
  const myBestTotal = Object.values(progress).reduce((sum, p) => sum + (p.best || 0), 0);
  const myEntry = myBestTotal > 0 ? [{ who: profile.name, score: myBestTotal, isYou: true }] : [];
  const allEntries = [...lb, ...myEntry].sort((a, b) => b.score - a.score).slice(0, 8);

  return (
    <div className="app-shell">
      <div className="topbar">
        <div className="brand">
          <div className="brand-mark">RGT</div>
          <div>
            <div className="brand-name">{t('app.brand_name')}</div>
            <div className="brand-sub" style={{fontSize: 10}}>{t('app.brand_sub')}</div>
          </div>
        </div>
        <div style={{display:'flex', alignItems:'center', gap:8}}>
          <LanguageSwitcher />
          <button className="profile-pill profile-pill-btn" onClick={onEditProfile} title={t('profile.edit')}>
            <div className="profile-avatar" style={{background: profile.color}}>
              {profile.name.charAt(0).toUpperCase()}
            </div>
            <span>{profile.name}</span>
          </button>
        </div>
      </div>

      <div className="hub-hero">
        <div className="hub-eyebrow">{t('hub.eyebrow')}</div>
        <h1 className="hub-title">{t('hub.title_a')}<br/><em>{t('hub.title_b')}</em></h1>
        <p className="hub-blurb">{t('hub.blurb')}</p>
        <div className="progress-strip">
          {games.map((g, i) => (
            <div key={g.id} className={progress[g.id]?.best != null ? 'done' : (i === completed ? 'current' : '')} />
          ))}
        </div>
        <div className="progress-meta">
          <span>{t('hub.progress.cats', { n: completed, t: total })}</span>
          <span>{t('hub.progress.pct', { n: pct })}</span>
        </div>
      </div>

      <div className="levels">
        {games.map((g, i) => {
          const unlocked = isUnlocked(i);
          const best = progress[g.id]?.best;
          const complete = best != null;
          return (
            <button key={g.id}
              className={`level-card ${complete ? 'complete' : ''} ${!unlocked ? 'locked' : ''}`}
              onClick={() => unlocked && onSelect(g.id)}
              disabled={!unlocked}>
              <div className="level-num">
                <RobotGlyph color="currentColor" size={32} variant={i} />
                <span style={{position:'absolute', bottom: 2, right: 4, fontSize: 9, fontFamily:'var(--font-mono)', color:'var(--ink-3)'}}>{g.num}</span>
              </div>
              <div className="level-info">
                <div className="level-cat">{g.tagline}</div>
                <div className="level-name">{g.name}</div>
                <div className="level-desc">{g.blurb}</div>
                <div className="level-meta">
                  <span>{t('hub.level.limit', { n: g.duration / 60 })}</span>
                  <span className="dot"></span>
                  <span>{t('hub.level.max', { n: g.maxScore })}</span>
                  <span className="dot"></span>
                  <span>{t('hub.level.age', { age: g.age })}</span>
                </div>
              </div>
              <div className="level-best">
                {unlocked && complete ? (
                  <>
                    <span style={{fontSize:10}}>{t('hub.level.best')}</span>
                    <strong>{best}</strong>
                  </>
                ) : unlocked ? (
                  <>
                    <span style={{fontSize:10}}>{t('hub.level.ready')}</span>
                    <strong style={{color:'var(--accent-ink)'}}>▶</strong>
                  </>
                ) : null}
              </div>
            </button>
          );
        })}
      </div>

      <div className="leaderboard">
        <div className="section-title">
          <span>{t('hub.lb.title')}</span>
          <span className="right">{t('hub.lb.subtitle')}</span>
        </div>
        <div className="lb-list">
          {allEntries.map((e, i) => (
            <div key={i} className={`lb-row ${e.isYou ? 'you' : ''}`}>
              <div className="rank">#{i+1}</div>
              <div>
                <div className="who">{e.who}{e.isYou ? t('hub.lb.you_suffix') : ''}</div>
              </div>
              <div></div>
              <div className="pts">{e.score}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

function GameRouter({ gameId, onClose, onComplete }) {
  const game = GAMES.find(g => g.id === gameId);
  if (!game) return null;
  const Comp = {
    robotek: GameRobotek,
    inverse: GameInverse,
    delivery: GameDelivery,
    mergen: GameMergen,
    flag: GameFlag,
    sorting: GameSorting,
    basketball: GameBasketball,
  }[gameId];
  return (
    <div className="game-screen">
      <GameHeader game={game} onClose={onClose} />
      {Comp ? <Comp game={game} onComplete={onComplete} /> :
        <div style={{padding: 40, textAlign:'center'}}>Game not implemented yet.</div>}
    </div>
  );
}

function App() {
  const [progress, setProgress] = useSA(loadProgress());
  const [profile, setProfile] = useSA(loadProfile());
  const [editingProfile, setEditingProfile] = useSA(false);
  const [active, setActive] = useSA(null);
  const [, force] = useSA(0);

  // Re-render whole app on locale change so all child components see new t() values
  useEA(() => {
    const fn = () => force(v => v + 1);
    if (window._localeSubs) window._localeSubs.add(fn);
    return () => { if (window._localeSubs) window._localeSubs.delete(fn); };
  }, []);

  const commitProfile = (name) => {
    const p = saveProfile(name);
    if (p) { setProfile(p); setEditingProfile(false); }
  };

  // action: 'next' (default) → advance to next level; 'hub' → close back to the hub.
  const onComplete = (score, status, save, action = 'next') => {
    if (save) {
      const cur = progress[active] || {};
      const isBest = cur.best == null || score > cur.best;
      const np = {
        ...progress,
        [active]: {
          best: isBest ? score : cur.best,
          last: score,
          attempts: (cur.attempts || 0) + 1,
          bestTime: isBest ? Math.round(performance.now()) : cur.bestTime,
        }
      };
      setProgress(np);
      saveProgress(np);
      const overall = Object.values(np).reduce((s, p) => s + (p.best || 0), 0);
      postLeaderboard({ player_name: profile.name, score: overall });
    }
    if (action === 'hub') {
      setActive(null);
      return;
    }
    // advance to next level
    const games = window.GAMES || [];
    const idx = games.findIndex(g => g.id === active);
    if (idx >= 0 && idx < games.length - 1) {
      setActive(games[idx+1].id);
    } else {
      setActive(null);
    }
  };

  // First-visit gate: no profile → only show name prompt, nothing else.
  if (!profile) {
    return <NamePromptOverlay onSave={commitProfile} />;
  }

  return (
    <>
      <Hub
        progress={progress}
        onSelect={(id) => setActive(id)}
        profile={profile}
        onEditProfile={() => setEditingProfile(true)} />
      {active && (
        <GameRouter gameId={active} onClose={() => setActive(null)} onComplete={onComplete} />
      )}
      {editingProfile && (
        <NamePromptOverlay
          initialName={profile.name}
          onSave={commitProfile}
          onCancel={() => setEditingProfile(false)} />
      )}
    </>
  );
}

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