// Speed mode — "FastFingers" style for accounting
// 3 screens: intro, run, results
// Micro-exos answered in 1 tap. Combo multiplier. Countdown timer. Haptic feedback.

// ─── Data pool ─────────────────────────────────────────────

const SPEED_MODES = {
  debitCredit: {
    k: 'debitCredit',
    title_fr: 'Débit ou Crédit ?',
    title_en: 'Debit or Credit?',
    subtitle_fr: 'Dans quelle colonne ?',
    subtitle_en: 'Which side?',
    duration: 60,
    icon: '⚡',
    color: '#E07A3E',
    choices_fr: ['Débit', 'Crédit'],
    choices_en: ['Debit', 'Credit'],
  },
  actifPassif: {
    k: 'actifPassif',
    title_fr: 'Actif ou Passif ?',
    title_en: 'Asset or Liability?',
    subtitle_fr: 'Classe chaque compte',
    subtitle_en: 'Classify each account',
    duration: 30,
    icon: '⚖️',
    color: '#4A7A8C',
    choices_fr: ['Actif', 'Passif'],
    choices_en: ['Asset', 'Liability'],
  },
  classePCG: {
    k: 'classePCG',
    title_fr: 'Quelle classe PCG ?',
    title_en: 'Which PCG class?',
    subtitle_fr: 'Les 7 classes du plan comptable',
    subtitle_en: 'The 7 accounting classes',
    duration: 45,
    icon: '🔢',
    color: '#6B3A7A',
    choices_fr: ['1', '2', '3', '4', '5', '6', '7'],
    choices_en: ['1', '2', '3', '4', '5', '6', '7'],
  },
  blitz: {
    k: 'blitz',
    title_fr: 'Blitz éclair',
    title_en: 'Lightning blitz',
    subtitle_fr: 'Tout, mélangé, 90 s',
    subtitle_en: 'Everything, mixed, 90 s',
    duration: 90,
    icon: '🔥',
    color: '#C94A3F',
  },
};

// Pool of micro-questions for debitCredit
const POOL_DEBIT_CREDIT_FR = [
  { q: 'Achat de fournitures 500 € (payé banque)', a: 'Débit', hint: 'Classe 6 au débit' },
  { q: 'Vente marchandises 1 200 € encaissée', a: 'Crédit', hint: 'Produit → crédit du 707' },
  { q: 'Salaires versés 3 500 €', a: 'Débit', hint: 'Charge de personnel au débit' },
  { q: 'Encaissement d\u2019un client 2 000 €', a: 'Débit', hint: 'Banque augmente → débit' },
  { q: 'Paiement loyer 800 €', a: 'Débit', hint: 'Charge externe au débit' },
  { q: 'Emprunt reçu 50 000 €', a: 'Crédit', hint: 'Dette financière → crédit' },
  { q: 'Remboursement emprunt 1 000 €', a: 'Débit', hint: 'On diminue la dette' },
  { q: 'Facture client émise 4 000 €', a: 'Débit', hint: '411 Clients au débit' },
  { q: 'TVA collectée sur vente', a: 'Crédit', hint: 'Dette envers l\u2019État' },
  { q: 'Achat immobilisation 8 000 €', a: 'Débit', hint: 'Classe 2 au débit' },
  { q: 'Apport en capital 20 000 €', a: 'Crédit', hint: 'Capitaux propres → crédit' },
  { q: 'Dépense carburant 80 €', a: 'Débit', hint: 'Charge externe' },
  { q: 'Intérêts bancaires perçus 50 €', a: 'Crédit', hint: 'Produit financier' },
  { q: 'Dotation aux amortissements', a: 'Débit', hint: 'Charge calculée' },
  { q: 'Facture fournisseur reçue', a: 'Crédit', hint: '401 Fournisseurs au crédit' },
];

const POOL_ACTIF_PASSIF_FR = [
  { q: 'Créances clients', a: 'Actif' },
  { q: 'Emprunt bancaire', a: 'Passif' },
  { q: 'Stock de marchandises', a: 'Actif' },
  { q: 'Capital social', a: 'Passif' },
  { q: 'Matériel de bureau', a: 'Actif' },
  { q: 'Dettes fournisseurs', a: 'Passif' },
  { q: 'Trésorerie en banque', a: 'Actif' },
  { q: 'Résultat de l\u2019exercice (bénéfice)', a: 'Passif' },
  { q: 'Immobilisations corporelles', a: 'Actif' },
  { q: 'Provisions pour risques', a: 'Passif' },
  { q: 'Brevets & licences', a: 'Actif' },
  { q: 'TVA à décaisser', a: 'Passif' },
  { q: 'Disponibilités', a: 'Actif' },
  { q: 'Réserves', a: 'Passif' },
  { q: 'Titres de participation', a: 'Actif' },
];

const POOL_CLASSE_FR = [
  { q: 'Capital social', a: '1' },
  { q: 'Matériel industriel', a: '2' },
  { q: 'Stock de produits finis', a: '3' },
  { q: 'Fournisseurs', a: '4' },
  { q: 'Clients', a: '4' },
  { q: 'Banque', a: '5' },
  { q: 'Achats de marchandises', a: '6' },
  { q: 'Ventes de marchandises', a: '7' },
  { q: 'Emprunts auprès des banques', a: '1' },
  { q: 'Amortissements du matériel', a: '2' },
  { q: 'Salaires bruts', a: '6' },
  { q: 'Production vendue', a: '7' },
  { q: 'TVA déductible', a: '4' },
  { q: 'Caisse', a: '5' },
  { q: 'Charges financières', a: '6' },
  { q: 'Impôt sur les bénéfices', a: '6' },
  { q: 'Réserve légale', a: '1' },
  { q: 'Brevet acheté 5 000 €', a: '2' },
];

// English variants (abbreviated — same logic)
const POOL_DEBIT_CREDIT_EN = [
  { q: 'Office supplies bought €500 (bank)', a: 'Debit' },
  { q: 'Goods sold €1 200, cashed in', a: 'Credit' },
  { q: 'Salaries paid €3 500', a: 'Debit' },
  { q: 'Customer payment received €2 000', a: 'Debit' },
  { q: 'Rent paid €800', a: 'Debit' },
  { q: 'Loan received €50 000', a: 'Credit' },
  { q: 'Loan repayment €1 000', a: 'Debit' },
  { q: 'Customer invoice issued €4 000', a: 'Debit' },
  { q: 'VAT collected on sale', a: 'Credit' },
  { q: 'Equipment purchase €8 000', a: 'Debit' },
  { q: 'Capital contribution €20 000', a: 'Credit' },
  { q: 'Supplier invoice received', a: 'Credit' },
];
const POOL_ACTIF_PASSIF_EN = [
  { q: 'Accounts receivable', a: 'Asset' },
  { q: 'Bank loan', a: 'Liability' },
  { q: 'Inventory', a: 'Asset' },
  { q: 'Share capital', a: 'Liability' },
  { q: 'Office equipment', a: 'Asset' },
  { q: 'Accounts payable', a: 'Liability' },
  { q: 'Cash at bank', a: 'Asset' },
  { q: 'Net income (profit)', a: 'Liability' },
  { q: 'Property, plant & eq.', a: 'Asset' },
  { q: 'Provisions', a: 'Liability' },
];
const POOL_CLASSE_EN = [
  { q: 'Share capital', a: '1' },
  { q: 'Industrial equipment', a: '2' },
  { q: 'Finished goods inventory', a: '3' },
  { q: 'Suppliers', a: '4' },
  { q: 'Customers', a: '4' },
  { q: 'Bank', a: '5' },
  { q: 'Purchases', a: '6' },
  { q: 'Sales', a: '7' },
  { q: 'Deductible VAT', a: '4' },
  { q: 'Cash', a: '5' },
];

function buildRun(modeKey, lang) {
  const mode = SPEED_MODES[modeKey];
  // Préférence : données extraites automatiquement depuis les leçons (window.SPEED_POOL).
  // Fallback : pools hardcodés plus haut (pour robustesse en dev / si contenu vide).
  function pickPool(mk, fallbackFr, fallbackEn) {
    const auto = window.SPEED_POOL && window.SPEED_POOL[mk];
    if (auto && auto[lang] && auto[lang].length >= 6) return auto[lang];
    return lang === 'fr' ? fallbackFr : fallbackEn;
  }
  const pools = {
    debitCredit: { items: pickPool('debitCredit', POOL_DEBIT_CREDIT_FR, POOL_DEBIT_CREDIT_EN), choices: mode[`choices_${lang}`] },
    actifPassif: { items: pickPool('actifPassif', POOL_ACTIF_PASSIF_FR, POOL_ACTIF_PASSIF_EN), choices: mode[`choices_${lang}`] },
    classePCG:   { items: pickPool('classePCG',   POOL_CLASSE_FR,       POOL_CLASSE_EN),       choices: mode[`choices_${lang}`] },
  };
  if (modeKey === 'blitz') {
    const mix = [];
    ['debitCredit', 'actifPassif', 'classePCG'].forEach(function (mk) {
      pools[mk].items.forEach(function (item) {
        mix.push(Object.assign({}, item, { subMode: mk, choices: pools[mk].choices }));
      });
    });
    return shuffle(mix);
  }
  return shuffle(pools[modeKey].items.map(function (item) {
    return Object.assign({}, item, { subMode: modeKey, choices: pools[modeKey].choices });
  }));
}

function shuffle(arr) {
  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;
}

// ─── Intro screen ──────────────────────────────────────────

function SpeedIntroScreen({ theme, lang, onStart, onClose, bestScores = {} }) {
  const modes = ['debitCredit', 'actifPassif', 'classePCG', 'blitz'];
  return (
    <div style={{ height: '100%', background: '#0F1411', color: '#fff', display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden' }}>
      {/* ambient bolts */}
      <SpeedBacksplash/>

      {/* close */}
      <div style={{ padding: '58px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center', position: 'relative', zIndex: 2 }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 12, background: 'rgba(255,255,255,0.08)',
          border: 'none', color: '#fff', cursor: 'pointer', fontSize: 18,
        }}>✕</button>
        <div style={{ fontFamily: theme.fontBody, fontSize: 11, fontWeight: 800, letterSpacing: 2, color: '#FFC93A' }}>
          {lang==='fr'?'MODE SPEED':'SPEED MODE'}
        </div>
        <div style={{ width: 36 }}/>
      </div>

      {/* hero */}
      <div style={{ padding: '12px 24px 8px', position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'flex-end', gap: 14 }}>
          <div style={{ position: 'relative' }}>
            <MiloHead size={92} emotion="excited" accessory="lightning"/>
            <div style={{
              position: 'absolute', right: -6, top: -6,
              fontSize: 26, animation: 'speedBolt 1.2s ease-in-out infinite alternate',
            }}>⚡</div>
          </div>
          <div style={{ flex: 1 }}>
            <h1 style={{
              fontFamily: theme.font, fontSize: 38, fontWeight: theme.headingWeight,
              margin: 0, lineHeight: 0.95, letterSpacing: -1,
              color: '#fff',
            }}>
              {lang==='fr'?'Speed':'Speed'}<br/>
              <span style={{ color: '#FFC93A' }}>{lang==='fr'?'drill':'drill'}</span>
            </h1>
            <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.7)', marginTop: 6, lineHeight: 1.4 }}>
              {lang==='fr'
                ? 'Un réflexe par seconde. Enchaîne, combo, record.'
                : 'One reflex per second. Chain, combo, record.'}
            </div>
          </div>
        </div>
      </div>

      {/* stats */}
      <div style={{
        margin: '18px 20px 0', display: 'grid', gridTemplateColumns: '1fr 1fr 1fr', gap: 8,
        position: 'relative', zIndex: 2,
      }}>
        <SpeedStat label={lang==='fr'?'Record':'Best'} value={bestScores.best || '—'}/>
        <SpeedStat label={lang==='fr'?'Streak':'Streak'} value={`${bestScores.streak || 7}🔥`}/>
        <SpeedStat label={lang==='fr'?'Précision':'Accuracy'} value={`${bestScores.acc || 84}%`}/>
      </div>

      {/* mode list */}
      <div style={{ padding: '22px 20px 20px', overflow: 'auto', flex: 1, position: 'relative', zIndex: 2 }}>
        <div style={{
          fontFamily: theme.fontBody, fontSize: 11, fontWeight: 800,
          color: 'rgba(255,255,255,0.45)', letterSpacing: 2, textTransform: 'uppercase', marginBottom: 10,
        }}>
          {lang==='fr'?'Choisis ton mode':'Pick a mode'}
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {modes.map(mk => <SpeedModeCard key={mk} modeKey={mk} theme={theme} lang={lang} onClick={() => onStart(mk)} best={bestScores[mk]}/>)}
        </div>
      </div>

      <style>{`
        @keyframes speedBolt {
          from { transform: scale(1) rotate(-6deg); filter: drop-shadow(0 0 6px #FFC93A); }
          to { transform: scale(1.12) rotate(6deg); filter: drop-shadow(0 0 16px #FFC93A); }
        }
      `}</style>
    </div>
  );
}

function SpeedBacksplash() {
  return (
    <div style={{ position: 'absolute', inset: 0, overflow: 'hidden', opacity: 0.35, pointerEvents: 'none' }}>
      <div style={{
        position: 'absolute', top: -60, right: -60, width: 260, height: 260, borderRadius: '50%',
        background: 'radial-gradient(circle, #FFC93A 0%, transparent 60%)', filter: 'blur(20px)',
      }}/>
      <div style={{
        position: 'absolute', bottom: -80, left: -40, width: 220, height: 220, borderRadius: '50%',
        background: 'radial-gradient(circle, #C94A3F 0%, transparent 60%)', filter: 'blur(20px)',
      }}/>
      {/* diagonal streaks */}
      <svg style={{ position: 'absolute', inset: 0, width: '100%', height: '100%' }} preserveAspectRatio="none" viewBox="0 0 400 800">
        <line x1="-30" y1="200" x2="160" y2="60" stroke="#FFC93A" strokeWidth="1" opacity="0.4"/>
        <line x1="-30" y1="260" x2="200" y2="70" stroke="#FFC93A" strokeWidth="1" opacity="0.25"/>
        <line x1="240" y1="760" x2="440" y2="520" stroke="#FFC93A" strokeWidth="1" opacity="0.3"/>
      </svg>
    </div>
  );
}

function SpeedStat({ label, value }) {
  return (
    <div style={{
      background: 'rgba(255,255,255,0.06)', border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: 14, padding: '10px 12px',
    }}>
      <div style={{ fontFamily: 'ui-monospace, monospace', fontSize: 10, fontWeight: 700, letterSpacing: 1.5, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>{label}</div>
      <div style={{ fontFamily: '"Fraunces", Georgia, serif', fontSize: 22, fontWeight: 600, color: '#fff', marginTop: 2 }}>{value}</div>
    </div>
  );
}

function SpeedModeCard({ modeKey, theme, lang, onClick, best }) {
  const m = SPEED_MODES[modeKey];
  const title = m[`title_${lang}`];
  const subtitle = m[`subtitle_${lang}`] || '';
  return (
    <button onClick={onClick} style={{
      textAlign: 'left', background: 'rgba(255,255,255,0.05)',
      border: '1px solid rgba(255,255,255,0.1)', borderRadius: 18,
      padding: '14px 16px', cursor: 'pointer', color: '#fff',
      display: 'flex', alignItems: 'center', gap: 14,
      fontFamily: theme.fontBody, position: 'relative', overflow: 'hidden',
    }}>
      <div style={{
        width: 56, height: 56, borderRadius: 14,
        background: `linear-gradient(135deg, ${m.color}, ${shadeColor(m.color, -20)})`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        fontSize: 28, flexShrink: 0,
        boxShadow: `0 4px 14px ${m.color}60`,
      }}>{m.icon}</div>
      <div style={{ flex: 1 }}>
        <div style={{ fontFamily: theme.font, fontSize: 19, fontWeight: theme.headingWeight, color: '#fff', letterSpacing: -0.3 }}>
          {title}
        </div>
        <div style={{ fontSize: 12, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>{subtitle}</div>
        <div style={{ display: 'flex', gap: 10, marginTop: 6, fontSize: 11, color: 'rgba(255,255,255,0.5)', fontWeight: 700 }}>
          <span>⏱ {m.duration}s</span>
          {best && <span>· 🏆 {best}</span>}
        </div>
      </div>
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#fff" strokeWidth="2.5" strokeLinecap="round"><path d="M9 6l6 6-6 6"/></svg>
    </button>
  );
}

// ─── Run screen ────────────────────────────────────────────

function SpeedRunScreen({ theme, lang, modeKey, onEnd, onClose }) {
  const mode = SPEED_MODES[modeKey];
  const [queue, setQueue] = React.useState(() => buildRun(modeKey, lang));
  const [idx, setIdx] = React.useState(0);
  const [timeLeft, setTimeLeft] = React.useState(mode.duration);
  const [score, setScore] = React.useState(0);
  const [combo, setCombo] = React.useState(0);
  const [bestCombo, setBestCombo] = React.useState(0);
  const [correct, setCorrect] = React.useState(0);
  const [wrong, setWrong] = React.useState(0);
  const [feedback, setFeedback] = React.useState(null); // 'correct' | 'wrong'
  const [shake, setShake] = React.useState(false);
  const [popup, setPopup] = React.useState(null); // {text, color}
  const [countdown, setCountdown] = React.useState(3); // 3-2-1-GO
  const running = countdown === 0 && timeLeft > 0;
  const answeredRef = React.useRef(0);

  // Countdown start
  React.useEffect(() => {
    if (countdown > 0) {
      const t = setTimeout(() => setCountdown(c => c - 1), 700);
      return () => clearTimeout(t);
    }
  }, [countdown]);

  // Timer
  React.useEffect(() => {
    if (!running) return;
    const t = setInterval(() => {
      setTimeLeft(s => {
        if (s <= 0.1) { clearInterval(t); return 0; }
        return +(s - 0.1).toFixed(1);
      });
    }, 100);
    return () => clearInterval(t);
  }, [running]);

  React.useEffect(() => {
    if (timeLeft <= 0 && countdown === 0) {
      setTimeout(() => onEnd({ score, correct, wrong, bestCombo, mode: modeKey }), 400);
    }
  }, [timeLeft, countdown]);

  const current = queue[idx % queue.length];

  const answer = (choice) => {
    if (!running || feedback) return;
    const isRight = choice === current.a;
    answeredRef.current++;
    if (isRight) {
      const multi = 1 + Math.floor(combo / 3);
      const base = 10 + Math.floor(combo / 2);
      const delta = base * multi;
      setScore(s => s + delta);
      setCombo(c => {
        const nc = c + 1;
        setBestCombo(bc => Math.max(bc, nc));
        return nc;
      });
      setCorrect(c => c + 1);
      setFeedback('correct');
      // bonus time for streaks
      if ((combo + 1) % 5 === 0) {
        setTimeLeft(t => Math.min(t + 2, mode.duration + 5));
        setPopup({ text: lang==='fr'?'+2 sec':'+2 sec', color: '#4ADE80' });
      } else if (combo + 1 >= 3) {
        setPopup({ text: `×${multi} ${lang==='fr'?'COMBO':'COMBO'}`, color: '#FFC93A' });
      } else {
        setPopup({ text: `+${delta}`, color: '#4ADE80' });
      }
    } else {
      setCombo(0);
      setWrong(w => w + 1);
      setFeedback('wrong');
      setShake(true);
      setTimeLeft(t => Math.max(0, t - 2));
      setPopup({ text: lang==='fr'?'−2 sec':'−2 sec', color: '#F87171' });
      setTimeout(() => setShake(false), 400);
    }
    setTimeout(() => {
      setFeedback(null);
      setPopup(null);
      setIdx(i => i + 1);
    }, 380);
  };

  const pct = (timeLeft / mode.duration) * 100;
  const timerColor = pct > 40 ? '#FFC93A' : pct > 20 ? '#F59E0B' : '#F87171';

  return (
    <div style={{
      height: '100%', background: '#0F1411', color: '#fff',
      display: 'flex', flexDirection: 'column', position: 'relative', overflow: 'hidden',
      transform: shake ? 'translateX(0)' : 'none',
      animation: shake ? 'speedShake 0.3s' : 'none',
    }}>
      {/* gradient pulse on correct/wrong */}
      {feedback && (
        <div style={{
          position: 'absolute', inset: 0, pointerEvents: 'none', zIndex: 1,
          background: feedback === 'correct'
            ? 'radial-gradient(circle at center, #4ADE8055 0%, transparent 55%)'
            : 'radial-gradient(circle at center, #F8717155 0%, transparent 55%)',
          animation: 'speedFlash 0.4s ease-out',
        }}/>
      )}

      {/* top — HUD */}
      <div style={{ padding: '58px 18px 0', position: 'relative', zIndex: 2 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <button onClick={onClose} style={{
            width: 32, height: 32, borderRadius: 10, background: 'rgba(255,255,255,0.08)',
            border: 'none', color: '#fff', cursor: 'pointer', fontSize: 14,
          }}>✕</button>
          <div style={{ flex: 1 }}>
            {/* timer bar */}
            <div style={{ height: 16, background: 'rgba(255,255,255,0.08)', borderRadius: 12, overflow: 'hidden', position: 'relative' }}>
              <div style={{
                height: '100%', width: `${pct}%`,
                background: `linear-gradient(90deg, ${timerColor}, ${shadeColor(timerColor, -15)})`,
                borderRadius: 12, transition: 'width 0.15s linear',
                boxShadow: `0 0 16px ${timerColor}80`,
              }}/>
              <div style={{
                position: 'absolute', right: 10, top: 0, bottom: 0,
                display: 'flex', alignItems: 'center',
                fontFamily: 'ui-monospace, SF Mono, monospace', fontSize: 11, fontWeight: 800, color: '#fff',
                textShadow: '0 1px 2px rgba(0,0,0,0.5)',
              }}>{timeLeft.toFixed(1)}s</div>
            </div>
          </div>
        </div>

        {/* score + combo */}
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{
            flex: 1, background: 'rgba(255,255,255,0.05)', borderRadius: 12,
            padding: '8px 12px', border: '1px solid rgba(255,255,255,0.1)',
          }}>
            <div style={{ fontSize: 9, fontWeight: 800, letterSpacing: 1.5, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>Score</div>
            <div style={{ fontFamily: 'ui-monospace, SF Mono, monospace', fontSize: 22, fontWeight: 800, color: '#fff', letterSpacing: -0.5, lineHeight: 1 }}>
              {score.toString().padStart(4, '0')}
            </div>
          </div>
          <div style={{
            flex: 1, background: combo >= 3 ? 'linear-gradient(135deg, #FFC93A, #F59E0B)' : 'rgba(255,255,255,0.05)',
            borderRadius: 12, padding: '8px 12px',
            border: combo >= 3 ? '1px solid #FFC93A' : '1px solid rgba(255,255,255,0.1)',
            color: combo >= 3 ? '#0F1411' : '#fff',
            transition: 'all 0.2s',
          }}>
            <div style={{ fontSize: 9, fontWeight: 800, letterSpacing: 1.5, opacity: 0.7, textTransform: 'uppercase' }}>Combo</div>
            <div style={{ fontFamily: 'ui-monospace, SF Mono, monospace', fontSize: 22, fontWeight: 800, letterSpacing: -0.5, lineHeight: 1 }}>
              ×{combo}{combo >= 5 && ' 🔥'}
            </div>
          </div>
        </div>
      </div>

      {/* Question area */}
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', padding: '20px 18px', position: 'relative', zIndex: 2 }}>
        {countdown > 0 ? (
          <div style={{ flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center', flexDirection: 'column' }}>
            <div style={{
              fontFamily: theme.font, fontSize: 140, fontWeight: 600,
              color: '#FFC93A', lineHeight: 1, letterSpacing: -5,
              textShadow: '0 0 40px rgba(255,201,58,0.5)',
              animation: 'speedCountdown 0.7s',
            }}>{countdown}</div>
            <div style={{ fontFamily: theme.fontBody, fontSize: 14, fontWeight: 700, color: 'rgba(255,255,255,0.6)', letterSpacing: 2, textTransform: 'uppercase' }}>
              {lang==='fr'?'Prêt·e ?':'Ready?'}
            </div>
          </div>
        ) : (
          <>
            {/* sub-mode hint for blitz */}
            {modeKey === 'blitz' && current?.subMode && (
              <div style={{
                alignSelf: 'center', fontFamily: theme.fontBody, fontSize: 10, fontWeight: 800,
                color: '#FFC93A', letterSpacing: 2, textTransform: 'uppercase',
                padding: '4px 10px', background: 'rgba(255,201,58,0.15)', borderRadius: 6,
                marginBottom: 10,
              }}>
                {SPEED_MODES[current.subMode][`title_${lang}`]}
              </div>
            )}

            {/* question card */}
            <div key={idx} style={{
              flex: 1, display: 'flex', alignItems: 'center', justifyContent: 'center',
              animation: 'speedIn 0.25s ease-out',
            }}>
              <div style={{
                background: '#fff', color: '#0F1411', borderRadius: 22,
                padding: '28px 22px', textAlign: 'center', width: '100%',
                boxShadow: '0 20px 60px rgba(0,0,0,0.5)', position: 'relative',
              }}>
                <div style={{
                  fontFamily: theme.fontBody, fontSize: 10, fontWeight: 800, letterSpacing: 2,
                  color: '#94A3B8', textTransform: 'uppercase', marginBottom: 10,
                }}>
                  Question {answeredRef.current + 1}
                </div>
                <div style={{
                  fontFamily: theme.font, fontSize: 26, fontWeight: theme.headingWeight,
                  color: '#0F1411', lineHeight: 1.2, letterSpacing: -0.4,
                }}>
                  {current?.q}
                </div>
              </div>
            </div>

            {/* popup (combo / +pts) */}
            {popup && (
              <div style={{
                position: 'absolute', top: '42%', left: '50%',
                transform: 'translate(-50%, -50%)',
                fontFamily: '"Fraunces", Georgia, serif', fontSize: 44, fontWeight: 700,
                color: popup.color, letterSpacing: -1,
                textShadow: `0 0 20px ${popup.color}80`,
                animation: 'speedPopup 0.4s ease-out forwards',
                pointerEvents: 'none', zIndex: 10,
              }}>{popup.text}</div>
            )}

            {/* choices */}
            <div style={{
              marginTop: 16,
              display: 'grid',
              gridTemplateColumns: current?.choices?.length > 2 ? 'repeat(4, 1fr)' : '1fr 1fr',
              gap: current?.choices?.length > 2 ? 8 : 12,
            }}>
              {current?.choices?.map((c, i) => {
                const isRight = feedback && c === current.a;
                const isPickedWrong = feedback === 'wrong' && c !== current.a; // we don't track which was picked here → keep neutral
                let bg = i % 2 === 0 ? '#2A6F4E' : '#B35A3C';
                if (current?.choices?.length > 2) bg = ['#2A6F4E','#4A7A8C','#B35A3C','#6B3A7A','#C9A14A','#E07A3E','#1B3A5C'][i % 7];
                if (feedback === 'correct' && isRight) bg = '#22C55E';
                if (feedback === 'wrong' && isRight) bg = '#22C55E';
                return (
                  <button key={c} onClick={() => answer(c)} disabled={!!feedback} style={{
                    padding: current?.choices?.length > 2 ? '20px 0' : '28px 0',
                    background: bg, border: `2px solid ${shadeColor(bg, -20)}`,
                    borderRadius: 18, cursor: feedback ? 'default' : 'pointer',
                    fontFamily: theme.font, fontSize: current?.choices?.length > 2 ? 22 : 26,
                    fontWeight: theme.headingWeight, color: '#fff',
                    boxShadow: `0 5px 0 ${shadeColor(bg, -25)}`,
                    transition: 'transform 0.06s, box-shadow 0.06s',
                    letterSpacing: -0.3,
                  }}
                  onMouseDown={e => { e.currentTarget.style.transform = 'translateY(3px)'; e.currentTarget.style.boxShadow = `0 2px 0 ${shadeColor(bg, -25)}`; }}
                  onMouseUp={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = `0 5px 0 ${shadeColor(bg, -25)}`; }}
                  onMouseLeave={e => { e.currentTarget.style.transform = ''; e.currentTarget.style.boxShadow = `0 5px 0 ${shadeColor(bg, -25)}`; }}
                  >{c}</button>
                );
              })}
            </div>
          </>
        )}
      </div>

      <style>{`
        @keyframes speedShake {
          0%, 100% { transform: translateX(0); }
          25% { transform: translateX(-8px); }
          75% { transform: translateX(8px); }
        }
        @keyframes speedFlash {
          from { opacity: 1; } to { opacity: 0; }
        }
        @keyframes speedIn {
          from { opacity: 0; transform: translateY(12px) scale(0.98); }
          to { opacity: 1; transform: translateY(0) scale(1); }
        }
        @keyframes speedPopup {
          0% { opacity: 0; transform: translate(-50%, -30%) scale(0.6); }
          30% { opacity: 1; transform: translate(-50%, -60%) scale(1.15); }
          100% { opacity: 0; transform: translate(-50%, -90%) scale(1); }
        }
        @keyframes speedCountdown {
          from { opacity: 0; transform: scale(1.8); }
          to { opacity: 1; transform: scale(1); }
        }
      `}</style>
    </div>
  );
}

// ─── Results screen ────────────────────────────────────────

function SpeedResultsScreen({ theme, lang, result, onReplay, onClose }) {
  const { score, correct, wrong, bestCombo, mode } = result;
  const total = correct + wrong;
  const acc = total ? Math.round((correct / total) * 100) : 0;
  const modeName = SPEED_MODES[mode]?.[`title_${lang}`] || '';
  const isRecord = score > 780; // demo

  // Grade
  let grade = { t: 'C', color: '#F59E0B', label: lang==='fr'?'Pas mal':'Not bad' };
  if (acc >= 90 && bestCombo >= 8) grade = { t: 'S', color: '#FFC93A', label: lang==='fr'?'Maître du débit':'Debit master' };
  else if (acc >= 80) grade = { t: 'A', color: '#4ADE80', label: lang==='fr'?'Excellent':'Excellent' };
  else if (acc >= 70) grade = { t: 'B', color: '#60A5FA', label: lang==='fr'?'Solide':'Solid' };

  return (
    <div style={{ height: '100%', background: '#0F1411', color: '#fff', display: 'flex', flexDirection: 'column', overflow: 'hidden', position: 'relative' }}>
      {/* confetti streaks for high scores */}
      {acc >= 70 && (
        <div style={{ position: 'absolute', inset: 0, pointerEvents: 'none', overflow: 'hidden' }}>
          {[...Array(18)].map((_, i) => (
            <div key={i} style={{
              position: 'absolute',
              left: `${Math.random() * 100}%`,
              top: -20,
              width: 6, height: 14,
              background: ['#FFC93A', '#4ADE80', '#F87171', '#60A5FA'][i % 4],
              animation: `speedConfetti ${2 + Math.random() * 2}s ${Math.random()}s linear infinite`,
              transform: `rotate(${Math.random() * 360}deg)`,
            }}/>
          ))}
        </div>
      )}

      <div style={{ padding: '58px 20px 0', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, borderRadius: 12, background: 'rgba(255,255,255,0.08)',
          border: 'none', color: '#fff', cursor: 'pointer', fontSize: 18,
        }}>✕</button>
        <div style={{ fontFamily: theme.fontBody, fontSize: 10, fontWeight: 800, letterSpacing: 2, color: 'rgba(255,255,255,0.5)' }}>
          {modeName}
        </div>
        <div style={{ width: 36 }}/>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '8px 20px 20px', position: 'relative', zIndex: 2 }}>
        {/* big grade */}
        <div style={{ textAlign: 'center', padding: '16px 0 8px' }}>
          {isRecord && (
            <div style={{
              display: 'inline-block', padding: '4px 12px', marginBottom: 10,
              background: 'linear-gradient(135deg, #FFC93A, #F59E0B)', color: '#0F1411',
              fontFamily: theme.fontBody, fontSize: 11, fontWeight: 900,
              letterSpacing: 2, textTransform: 'uppercase', borderRadius: 6,
              boxShadow: '0 4px 20px rgba(255,201,58,0.5)',
            }}>🏆 {lang==='fr'?'NOUVEAU RECORD':'NEW RECORD'}</div>
          )}
          <div style={{
            fontFamily: theme.font, fontSize: 140, fontWeight: 600,
            color: grade.color, lineHeight: 0.9, letterSpacing: -6,
            textShadow: `0 0 60px ${grade.color}60`,
          }}>{grade.t}</div>
          <div style={{
            fontFamily: theme.font, fontSize: 22, fontWeight: theme.headingWeight, color: '#fff',
            marginTop: 4, letterSpacing: -0.4,
          }}>{grade.label}</div>
        </div>

        {/* big score */}
        <div style={{
          background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
          borderRadius: 18, padding: '18px 20px', textAlign: 'center', margin: '12px 0',
        }}>
          <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: 2, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>
            {lang==='fr'?'Score final':'Final score'}
          </div>
          <div style={{
            fontFamily: 'ui-monospace, SF Mono, monospace', fontSize: 56, fontWeight: 800,
            color: '#fff', letterSpacing: -2, lineHeight: 1,
          }}>{score.toString().padStart(4, '0')}</div>
        </div>

        {/* stats grid */}
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
          <ResultStat icon="✓" label={lang==='fr'?'Bonnes':'Correct'} value={correct} color="#4ADE80"/>
          <ResultStat icon="✗" label={lang==='fr'?'Ratées':'Missed'} value={wrong} color="#F87171"/>
          <ResultStat icon="🎯" label={lang==='fr'?'Précision':'Accuracy'} value={`${acc}%`} color="#60A5FA"/>
          <ResultStat icon="🔥" label={lang==='fr'?'Combo max':'Best combo'} value={`×${bestCombo}`} color="#FFC93A"/>
        </div>

        {/* Milo commentary */}
        <div style={{
          marginTop: 16, background: 'rgba(255,255,255,0.05)', borderRadius: 18,
          border: '1px solid rgba(255,255,255,0.1)',
          padding: '14px', display: 'flex', gap: 12, alignItems: 'flex-start',
        }}>
          <MiloHead size={56} emotion={acc >= 80 ? 'excited' : acc >= 60 ? 'happy' : 'focused'}/>
          <div style={{ flex: 1, fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.85)', lineHeight: 1.5 }}>
            {acc >= 80
              ? (lang==='fr'?'Réflexes de comptable ninja. Ta main sait avant ta tête.':'Ninja-level reflexes. Your hand knows before your brain does.')
              : acc >= 60
              ? (lang==='fr'?'Bon rythme ! Vise 3 combos de suite la prochaine fois.':'Good pace! Try chaining 3 combos next time.')
              : (lang==='fr'?'Ralentis, respire, relis. La vitesse viendra.':'Slow down, breathe, re-read. Speed will come.')}
          </div>
        </div>
      </div>

      {/* actions */}
      <div style={{ padding: '12px 20px 28px', display: 'flex', flexDirection: 'column', gap: 10, position: 'relative', zIndex: 2 }}>
        <button onClick={onReplay} style={{
          height: 56, background: '#FFC93A', color: '#0F1411', border: 'none',
          borderRadius: 16, fontFamily: theme.fontBody, fontSize: 16, fontWeight: 800,
          letterSpacing: 1, textTransform: 'uppercase', cursor: 'pointer',
          boxShadow: '0 5px 0 #C99D12',
        }}>⚡ {lang==='fr'?'Rejouer':'Replay'}</button>
        <button onClick={onClose} style={{
          height: 48, background: 'transparent', color: 'rgba(255,255,255,0.7)',
          border: '1px solid rgba(255,255,255,0.15)', borderRadius: 14,
          fontFamily: theme.fontBody, fontSize: 14, fontWeight: 700, cursor: 'pointer',
        }}>{lang==='fr'?'Retour':'Back'}</button>
      </div>

      <style>{`
        @keyframes speedConfetti {
          0% { transform: translateY(0) rotate(0deg); opacity: 1; }
          100% { transform: translateY(120vh) rotate(720deg); opacity: 0.4; }
        }
      `}</style>
    </div>
  );
}

function ResultStat({ icon, label, value, color }) {
  return (
    <div style={{
      background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
      borderRadius: 14, padding: '12px 14px',
    }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
        <div style={{ fontSize: 16 }}>{icon}</div>
        <div style={{ fontSize: 10, fontWeight: 800, letterSpacing: 1.5, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase' }}>{label}</div>
      </div>
      <div style={{ fontFamily: '"Fraunces", Georgia, serif', fontSize: 28, fontWeight: 600, color, marginTop: 4, lineHeight: 1 }}>{value}</div>
    </div>
  );
}

Object.assign(window, { SpeedIntroScreen, SpeedRunScreen, SpeedResultsScreen, SPEED_MODES });
