/* global React, ReactDOM */
const { useState, useEffect, useRef, useMemo } = React;

const CATS = {
  historia:   { label:'Historia',   color:'#FFD60A', emoji:'🏛️' },
  ciencia:    { label:'Ciencia',    color:'#00E5A8', emoji:'🔬' },
  deportes:   { label:'Deportes',   color:'#FF6B35', emoji:'⚽' },
  arte:       { label:'Arte',       color:'#FF4D8D', emoji:'🎨' },
  musica:     { label:'Música',     color:'#38BDF8', emoji:'🎵' },
  geografia:  { label:'Geografía',  color:'#8E66FF', emoji:'🌍' },
};

const fmtNum = n => (n||0).toLocaleString('es-ES');

function App() {
  const [profile, setProfile] = useState(window.TR_ENGINE.getProfile());
  const [route, setRoute] = useState({ name: 'home' });
  useEffect(() => { window.TR_ENGINE.saveProfile(profile); }, [profile]);

  const go = (name, params={}) => setRoute({ name, ...params });

  if (route.name === 'home')      return <Home profile={profile} go={go} />;
  if (route.name === 'modes')     return <ModeSelect go={go} profile={profile} />;
  if (route.name === 'categories')return <CategorySelect mode={route.mode} go={go} />;
  if (route.name === 'play')      return <Game mode={route.mode} categories={route.categories} profile={profile} setProfile={setProfile} go={go} />;
  if (route.name === 'results')   return <Results result={route.result} go={go} />;
  if (route.name === 'leaderboard')return <Leaderboard go={go} />;
  if (route.name === 'profile')   return <ProfileScreen profile={profile} setProfile={setProfile} go={go} />;
  return null;
}

// ============== HOME ==============
function Home({ profile, go }) {
  const today = window.TR_ENGINE.todayKey();
  const dailyDone = profile.dailyDone[today];
  return (
    <div className="screen screen-violet">
      <div className="confetti-bg"/>
      <div className="app-bar">
        <button className="avatar" onClick={()=>go('profile')} style={{background:profile.avatar}}>{profile.initials}</button>
        <div className="bal">
          <span className="pill pill-yellow">🪙 {fmtNum(profile.coins)}</span>
          <span className="pill pill-cyan">💎 {fmtNum(profile.gems)}</span>
        </div>
      </div>

      <div className="hero-text">
        <div className="greeting">¡Hola, {profile.name}!</div>
        <h1>¿Listo para arrasar?</h1>
      </div>

      <div className="lvl-card">
        <div className="lvl-row">
          <div className="lvl-badge">{profile.level}</div>
          <div className="lvl-info">
            <div className="lvl-title">Nivel {profile.level}</div>
            <div className="lvl-sub">{profile.xp} / {window.TR_ENGINE.xpForLevel(profile.level)} XP</div>
          </div>
          <div className="lvl-streak">🔥 {profile.streakDays}</div>
        </div>
        <div className="bar-wrap"><div className="bar-fill" style={{width:`${(profile.xp/window.TR_ENGINE.xpForLevel(profile.level))*100}%`}}/></div>
      </div>

      <button className="play-btn" onClick={()=>{ window.TR_SFX.tap(); go('modes'); }}>
        <div className="play-l">
          <div className="play-eyebrow">Empezar</div>
          <div className="play-title">¡Jugar ahora!</div>
          <div className="play-sub">3 modos · 6 categorías</div>
        </div>
        <div className="play-icon">▶</div>
      </button>

      <div className="quick-grid">
        <button className="quick" onClick={()=>{ if(!dailyDone){ window.TR_SFX.tap(); go('play',{mode:'daily'}); } }} disabled={dailyDone}>
          <div className="quick-emoji">🗓️</div>
          <div className="quick-title">Diaria</div>
          <div className="quick-sub">{dailyDone ? `✓ Hecha · ${dailyDone.score}` : '5 preguntas hoy'}</div>
        </button>
        <button className="quick" onClick={()=>go('leaderboard')}>
          <div className="quick-emoji">🏆</div>
          <div className="quick-title">Ranking</div>
          <div className="quick-sub">Mejores partidas</div>
        </button>
      </div>
      <BottomNav active="home" go={go}/>
    </div>
  );
}

// ============== MODE SELECT ==============
function ModeSelect({ go }) {
  const modes = [
    { id:'quick',    title:'Partida rápida', sub:'5 preguntas · 15s c/u', emoji:'⚡', color:'#FFD60A' },
    { id:'survival', title:'Supervivencia',  sub:'Hasta fallar · 10s c/u', emoji:'💀', color:'#FF4D8D' },
    { id:'daily',    title:'Diaria',         sub:'Mismas para todos hoy', emoji:'🗓️', color:'#00E5A8' },
  ];
  return (
    <div className="screen screen-violet">
      <Header title="Elegir categoría" onBack={()=>go('home')}/>
      <div className="list">
        {modes.map(m => (
          <button key={m.id} className="mode-card" style={{background:m.color}} onClick={()=>{
            window.TR_SFX.tap();
            if (m.id === 'daily') go('play',{mode:'daily'});
            else go('categories',{mode:m.id});
          }}>
            <div className="mode-emoji">{m.emoji}</div>
            <div className="mode-text">
              <div className="mode-title">{m.title}</div>
              <div className="mode-sub">{m.sub}</div>
            </div>
            <div className="mode-arrow">›</div>
          </button>
        ))}
      </div>
    </div>
  );
}

// ============== CATEGORY SELECT ==============
function CategorySelect({ mode, go }) {
  const [sel, setSel] = useState(Object.keys(CATS));
  const toggle = (k) => {
    window.TR_SFX.tap();
    setSel(s => s.includes(k) ? (s.length>1 ? s.filter(x=>x!==k) : s) : [...s, k]);
  };
  return (
    <div className="screen screen-violet">
      <Header title="Categorías" onBack={()=>go('modes')} sub={`${sel.length}/6 seleccionadas`}/>
      <div className="cat-grid">
        {Object.entries(CATS).map(([k,v]) => {
          const active = sel.includes(k);
          return (
            <button key={k} className={`cat-tile ${active?'active':''}`} onClick={()=>toggle(k)} style={{background:active?v.color:'rgba(255,255,255,0.1)',color:active?'#0E0828':'white'}}>
              <div className="cat-emoji">{v.emoji}</div>
              <div className="cat-name">{v.label}</div>
              <div className="cat-count">{window.QUESTIONS[k].length} preg.</div>
            </button>
          );
        })}
      </div>
      <div className="footer-cta">
        <button className="cta-btn" onClick={()=>{ window.TR_SFX.tap(); go('play',{mode, categories:sel}); }}>Empezar</button>
      </div>
    </div>
  );
}

// ============== GAME ==============
function Game({ mode, categories, profile, setProfile, go }) {
  const totalQuestions = mode === 'quick' ? 5 : (mode === 'daily' ? 5 : 999);
  const timePerQ = mode === 'survival' ? 10 : 15;
  const questions = useMemo(() => {
    const seed = mode === 'daily' ? window.TR_ENGINE.seedFromDate() : null;
    return window.TR_ENGINE.pickQuestions({ mode, count: totalQuestions, categories, seed });
  }, []);

  const [idx, setIdx] = useState(0);
  const [score, setScore] = useState(0);
  const [streak, setStreak] = useState(0);
  const [timeLeft, setTimeLeft] = useState(timePerQ);
  const [picked, setPicked] = useState(null);
  const [aiQuestions, setAiQuestions] = useState([]);
  const [aiLoading, setAiLoading] = useState(false);
  const tickRef = useRef(null);

  const allQ = [...questions, ...aiQuestions];
  const q = allQ[idx];
  const isLast = mode !== 'survival' && idx >= totalQuestions - 1;

  useEffect(() => {
    if (picked !== null) return;
    setTimeLeft(timePerQ);
    tickRef.current = setInterval(() => {
      setTimeLeft(t => {
        if (t <= 1) { clearInterval(tickRef.current); handleAnswer(-1); return 0; }
        if (t <= 4) window.TR_SFX.tickFast(); else if (t <= 10) window.TR_SFX.tick();
        return t - 1;
      });
    }, 1000);
    return () => clearInterval(tickRef.current);
  }, [idx, q?.q]);

  // For survival, pre-load AI question when getting close to the end
  useEffect(() => {
    if (mode !== 'survival') return;
    if (idx >= allQ.length - 3 && !aiLoading && window.claude) {
      const cats = categories || Object.keys(CATS);
      const cat = cats[Math.floor(Math.random()*cats.length)];
      setAiLoading(true);
      window.TR_ENGINE.generateAIQuestion(cat)
        .then(qq => setAiQuestions(a => [...a, qq]))
        .catch(()=>{})
        .finally(()=>setAiLoading(false));
    }
  }, [idx, mode, allQ.length, aiLoading]);

  const handleAnswer = (i) => {
    clearInterval(tickRef.current);
    setPicked(i);
    const correct = i === q.correct;
    if (correct) {
      const pts = window.TR_ENGINE.scoreFor(timeLeft, streak, q.difficulty || 1);
      setScore(s => s + pts);
      setStreak(s => s + 1);
      window.TR_SFX.correct();
    } else {
      setStreak(0);
      window.TR_SFX.wrong();
    }
    setTimeout(() => {
      if (mode === 'survival' && !correct) finish();
      else if (isLast) finish(correct ? 1 : 0);
      else { setIdx(i => i + 1); setPicked(null); }
    }, 1400);
  };

  const finish = (lastCorrect=0) => {
    const total = idx + 1;
    const finalScore = score + (lastCorrect ? 0 : 0);
    let p = { ...profile };
    p.totalGames += 1;
    p.totalQuestions += total;
    p.totalCorrect += Math.round(finalScore > 0 ? streak + (lastCorrect? 1:0) : 0); // approx; tracking handled per-q ideally
    p.coins += Math.floor(finalScore / 50);
    p = window.TR_ENGINE.addXp(p, Math.floor(finalScore / 10));
    p = window.TR_ENGINE.tickDailyStreak(p);
    if (mode === 'quick' && finalScore > p.bestQuick) p.bestQuick = finalScore;
    if (mode === 'survival' && total - 1 > p.bestSurvival) p.bestSurvival = total - 1;
    if (mode === 'daily') p.dailyDone[window.TR_ENGINE.todayKey()] = { score: finalScore, total };
    window.TR_ENGINE.recordScore(mode, finalScore, { questions: total });
    setProfile(p);
    if (finalScore > 500 || mode === 'survival' && total > 5) window.TR_SFX.win();
    else window.TR_SFX.lose();
    go('results', { result: { mode, score: finalScore, total, questions: total, streak: p.streakDays } });
  };

  if (!q) { finish(); return null; }

  const ringColor = timeLeft <= 5 ? '#FF3B30' : timeLeft <= 9 ? '#FF9F0A' : '#30D158';
  const dashOffset = 314 - (timeLeft / timePerQ) * 314;

  return (
    <div className="screen screen-game">
      <div className="game-bar">
        <button className="back game-close" onClick={()=>go('home')}>×</button>
        <div className="game-info">
          <div className="cat-mini">{CATS[q.category]?.emoji} {CATS[q.category]?.label}</div>
          <div className="score-pill">⚡ {fmtNum(score)}</div>
        </div>
      </div>
      <div className="progress-strip">
        {Array.from({length: mode==='survival' ? Math.min(5, allQ.length) : totalQuestions}).map((_,i)=><span key={i} className={i<idx?'done':i===idx?'current':''}/>) }
      </div>
      <div className="qcount">PREGUNTA {idx+1} DE {mode==='survival' ? '∞' : totalQuestions}</div>

      <div className="timer-wrap">
        <svg width="120" height="120" viewBox="0 0 120 120">
          <circle cx="60" cy="60" r="50" fill="none" stroke="rgba(255,255,255,0.18)" strokeWidth="10"/>
          <circle cx="60" cy="60" r="50" fill="none" stroke={ringColor} strokeWidth="10" strokeLinecap="round" strokeDasharray="314" strokeDashoffset={dashOffset} transform="rotate(-90 60 60)" style={{transition:'stroke-dashoffset 1s linear, stroke 0.3s'}}/>
        </svg>
        <div className="timer-num" style={{color: timeLeft <= 5 ? '#FF3B30' : 'white'}}>{timeLeft}</div>
      </div>

      <div className="question-card">
        <div className="question">{q.q}</div>
        {q.ai && <span className="ai-tag">IA</span>}
      </div>

      <div className="answers">
        {q.a.map((opt, i) => {
          const isCorrect = picked !== null && i === q.correct;
          const isWrong = picked === i && i !== q.correct;
          const dimmed = picked !== null && !isCorrect && !isWrong;
          const slot = ['#FFD60A','#FF4D8D','#38BDF8','#00E5A8'][i];
          return (
            <button key={i} className={`ans ${isCorrect?'ans-correct':''} ${isWrong?'ans-wrong':''} ${dimmed?'ans-dim':''}`} disabled={picked !== null} onClick={()=>handleAnswer(i)} style={{background: picked===null ? 'white' : isCorrect ? '#00E5A8' : isWrong ? '#FF4D8D' : 'rgba(255,255,255,0.4)'}}>
              <span className="ans-letter" style={{background:slot,color:'#0E0828'}}>{['A','B','C','D'][i]}</span>
              <span className="ans-text">{opt}</span>
              {isCorrect && <span className="ans-check">✓</span>}
              {isWrong && <span className="ans-check">✗</span>}
            </button>
          );
        })}
      </div>
    </div>
  );
}

// ============== RESULTS ==============
function Results({ result, go }) {
  const { mode, score, total } = result;
  const isWin = score > 500;
  return (
    <div className="screen screen-result">
      <div className="confetti-bg"/>
      <div className="result-wrap">
        <div className="result-emoji">{isWin?'🎉':'💪'}</div>
        <div className="result-title">{isWin?'¡Genial!':'¡A por la próxima!'}</div>
        <div className="result-score">{fmtNum(score)}</div>
        <div className="result-sub">puntos · {total} preguntas</div>

        <div className="result-stats">
          <div className="rstat"><div className="rstat-num">+{Math.floor(score/10)}</div><div className="rstat-lbl">XP</div></div>
          <div className="rstat"><div className="rstat-num">+{Math.floor(score/50)}</div><div className="rstat-lbl">🪙</div></div>
        </div>

        <button className="cta-btn" onClick={()=>go('home')}>Continuar</button>
        {mode !== 'daily' && <button className="cta-ghost" onClick={()=>go('modes')}>Otra partida</button>}
      </div>
    </div>
  );
}

// ============== LEADERBOARD ==============
function Leaderboard({ go }) {
  const lb = window.TR_ENGINE.getLeaderboard();
  const labels = { quick:'Rápida', survival:'Supervivencia', daily:'Diaria' };
  return (
    <div className="screen screen-violet">
      <Header title="Tus mejores" onBack={()=>go('home')}/>
      <div className="lb-list">
        {lb.length === 0 && <div className="empty">Aún no hay partidas. ¡Empieza ya!</div>}
        {lb.map((s, i) => (
          <div key={i} className={`lb-row ${i<3?'lb-top':''}`}>
            <div className="lb-rank">{i+1}</div>
            <div className="lb-mode">{labels[s.mode] || s.mode}</div>
            <div className="lb-date">{new Date(s.date).toLocaleDateString('es-ES',{day:'numeric',month:'short'})}</div>
            <div className="lb-score">{fmtNum(s.score)}</div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ============== PROFILE ==============
function ProfileScreen({ profile, setProfile, go }) {
  const [name, setName] = useState(profile.name);
  const [muted, setMuted] = useState(window.TR_SFX.isMuted());
  const colors = ['#FFD60A','#FF4D8D','#38BDF8','#00E5A8','#8E66FF','#FF6B35'];
  const save = () => {
    const initials = name.trim().split(/\s+/).map(s=>s[0]).slice(0,2).join('').toUpperCase() || 'TÚ';
    setProfile({...profile, name: name.trim() || 'Tú', initials});
    go('home');
  };
  const acc = profile.totalQuestions ? Math.round(profile.totalCorrect/profile.totalQuestions*100) : 0;
  return (
    <div className="screen screen-violet">
      <Header title="Perfil" onBack={()=>go('home')}/>
      <div className="profile-hero">
        <div className="profile-avatar" style={{background:profile.avatar}}>{profile.initials}</div>
        <input className="profile-name" value={name} onChange={e=>setName(e.target.value)} maxLength={18}/>
        <div className="profile-lvl">Nivel {profile.level}</div>
      </div>
      <div className="color-pick">
        {colors.map(c => (
          <button key={c} className={`swatch ${profile.avatar===c?'sel':''}`} style={{background:c}} onClick={()=>setProfile({...profile,avatar:c})}/>
        ))}
      </div>
      <div className="stats-grid">
        <Stat label="Partidas" value={profile.totalGames}/>
        <Stat label="Mejor rápida" value={fmtNum(profile.bestQuick)}/>
        <Stat label="Mejor supervivencia" value={profile.bestSurvival}/>
        <Stat label="Racha máx" value={`${profile.maxStreak}d`}/>
        <Stat label="Monedas" value={fmtNum(profile.coins)}/>
        <Stat label="Precisión" value={`${acc}%`}/>
      </div>
      <button className="toggle-row" onClick={()=>{ const m=!muted; setMuted(m); window.TR_SFX.toggle(m); }}>
        <span>{muted?'🔇':'🔊'} Sonido</span>
        <span className={`toggle-pip ${muted?'off':'on'}`}/>
      </button>
      <div className="footer-cta">
        <button className="cta-btn" onClick={save}>Guardar</button>
      </div>
    </div>
  );
}

function Stat({label,value}){return <div className="stat"><div className="stat-num">{value}</div><div className="stat-lbl">{label}</div></div>;}


function BottomNav({active, go}) {
  const items = [
    ['home','Inicio','⌂',()=>go('home')],
    ['play','Jugar','▷',()=>go('modes')],
    ['ranking','Ranking','🏆',()=>go('leaderboard')],
    ['profile','Perfil','♙',()=>go('profile')],
  ];
  return <nav className="bottom-nav">{items.map(([id,label,icon,fn])=>(
    <button key={id} className={active===id?'nav-active':''} onClick={fn}>
      <span>{icon}</span><small>{label}</small>
    </button>
  ))}</nav>;
}

function Header({title, sub, onBack}) {
  return (
    <div className="head">
      <button className="back" onClick={onBack}>‹</button>
      <div>
        <div className="head-title">{title}</div>
        {sub && <div className="head-sub">{sub}</div>}
      </div>
    </div>
  );
}

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