// Lesson intro, completion, profile, paywall, catalog screens

function LessonIntroScreen({ theme, lang, lesson, onStart, onClose }) {
  const title = lesson ? loc(lesson.title, lang) : (lang==='fr'?'D\u00e9fi de chapitre':'Chapter challenge');
  const unitLabel = lesson ? loc(lesson.unitLabel, lang) : (lang==='fr'?'Le\u00e7on':'Lesson');
  const intro = lesson?.intro || {};
  const body = loc(intro.body, lang) || (lang==='fr'
    ? 'Mets en pratique ce que tu as appris sur le compte en T avec 8 exercices vari\u00e9s.'
    : 'Put what you learned about T-accounts into practice with 8 varied exercises.');
  const xp = lesson?.xp || 40;
  const minutes = lesson?.estMinutes || 3;
  const exoCount = lesson?.exercises?.length || 8;
  return (
    <div style={{ height: '100%', background: theme.bg, display: 'flex', flexDirection: 'column', padding: '60px 24px 32px' }}>
      <button onClick={onClose} style={{
        width: 36, height: 36, background: 'transparent', border: 'none', padding: 0, cursor: 'pointer',
        alignSelf: 'flex-start', marginBottom: 20,
      }}>
        <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#AFAFAF" strokeWidth="3" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
      </button>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        <div style={{ animation: 'miloBob 3s ease-in-out infinite' }}>
          <MiloFull size={160} emotion="excited" pose="celebrate"/>
        </div>
        <div style={{
          marginTop: 16, padding: '4px 12px', borderRadius: 12,
          background: theme.primarySoft, color: theme.primaryDark,
          fontFamily: theme.fontBody, fontSize: 12, fontWeight: 800,
          letterSpacing: 1, textTransform: 'uppercase',
        }}>{unitLabel} · {minutes} min</div>
        <h1 style={{
          fontFamily: theme.font, fontSize: 28, fontWeight: theme.headingWeight,
          color: theme.ink, margin: '14px 0 8px', lineHeight: 1.2, letterSpacing: -0.5,
        }}>{title}</h1>
        <p style={{ fontFamily: theme.fontBody, fontSize: 15, color: theme.inkSoft, margin: 0, lineHeight: 1.5, maxWidth: 280 }}>
          {body}
        </p>
        <div style={{ display: 'flex', gap: 20, marginTop: 24 }}>
          <MiniStat icon="⚡" value={'+' + xp} label={lang==='fr'?'XP':'XP'} theme={theme}/>
          <MiniStat icon="⏱" value={minutes + ' min'} label={lang==='fr'?'Dur\u00e9e':'Time'} theme={theme}/>
          <MiniStat icon="📝" value={String(exoCount)} label={lang==='fr'?'Exos':'Exos'} theme={theme}/>
        </div>
      </div>
      <Button theme={theme} full size="lg" variant="success" onClick={onStart}>
        {lang==='fr'?'Commencer':'Start'}
      </Button>
    </div>
  );
}

function MiniStat({ icon, value, label, theme }) {
  return (
    <div style={{ textAlign: 'center' }}>
      <div style={{ fontSize: 24 }}>{icon}</div>
      <div style={{ fontFamily: theme.fontBody, fontSize: 17, fontWeight: 800, color: theme.ink, marginTop: 2 }}>{value}</div>
      <div style={{ fontFamily: theme.fontBody, fontSize: 11, fontWeight: 700, color: theme.inkSoft, letterSpacing: 0.5, textTransform: 'uppercase' }}>{label}</div>
    </div>
  );
}

// ── Completion screen ─────────────────────────
function CompletionScreen({ theme, lang, completion, onContinue }) {
  const c = completion || {};
  const title = loc(c.title, lang) || (lang==='fr'?'Le\u00e7on termin\u00e9e !':'Lesson complete!');
  const subtitle = loc(c.subtitle, lang) || (lang==='fr'?'Tu as tout d\u00e9chir\u00e9. Milo est fier.':'You crushed it. Milo is proud.');
  const cardColors = ['#FFC800', theme.success, '#00B4E6', '#FF9500'];
  const cardIcons = ['⚡', '🎯', '⏱', '🔥'];
  const stats = (c.stats && c.stats.length) ? c.stats.map(function (s) {
    return { label: loc(s.label, lang), value: s.value };
  }) : [
    { label: lang==='fr'?'XP gagn\u00e9s':'XP earned', value: '+40' },
    { label: lang==='fr'?'Pr\u00e9cision':'Accuracy', value: '87 %' },
    { label: lang==='fr'?'Temps':'Time', value: '2:14' },
  ];
  // Pad to 4 cards (4th is always streak)
  const cards = stats.slice(0, 3).concat([{ label: lang==='fr'?'Streak':'Streak', value: '8 🔥' }]);
  return (
    <div style={{ height: '100%', background: theme.bg, display: 'flex', flexDirection: 'column', padding: '60px 24px 32px' }}>
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center' }}>
        {/* Confetti dots */}
        <div style={{ position: 'relative', width: 220, height: 220 }}>
          {[...Array(12)].map((_, i) => {
            const a = (i / 12) * Math.PI * 2;
            const r = 110;
            return <div key={i} style={{
              position: 'absolute', left: 110 + Math.cos(a) * r - 4, top: 110 + Math.sin(a) * r - 4,
              width: 8, height: 8, borderRadius: 2,
              background: ['#FFC800','#58CC02','#CE82FF','#FF4B4B','#00B4E6'][i % 5],
              transform: `rotate(${i*30}deg)`,
              animation: `pop 0.6s ease-out ${i*0.05}s both`,
            }}/>;
          })}
          <div style={{ position: 'absolute', inset: 0, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
            <MiloFull size={180} emotion="love" pose="celebrate" accessory="grad"/>
          </div>
        </div>
        <h1 style={{ fontFamily: theme.font, fontSize: 30, fontWeight: theme.headingWeight, color: theme.ink, margin: '16px 0 8px' }}>
          {title}
        </h1>
        <p style={{ fontFamily: theme.fontBody, color: theme.inkSoft, fontSize: 15, margin: '0 0 24px' }}>
          {subtitle}
        </p>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, width: '100%' }}>
          {cards.map(function (card, i) {
            return <StatBox key={i} theme={theme} color={cardColors[i]} label={card.label} value={card.value} icon={cardIcons[i]}/>;
          })}
        </div>
      </div>
      <Button theme={theme} full size="lg" variant="success" onClick={onContinue}>
        {lang==='fr'?'Continuer':'Continue'}
      </Button>
      <style>{`@keyframes pop{0%{transform:scale(0)}60%{transform:scale(1.3)}100%{transform:scale(1)}}`}</style>
    </div>
  );
}

function StatBox({ theme, color, label, value, icon }) {
  return (
    <div style={{
      background: theme.surface, border: `2px solid ${color}`, borderRadius: 14,
      padding: 12, boxShadow: `0 2px 0 ${color}`,
    }}>
      <div style={{
        fontFamily: theme.fontBody, fontSize: 10, fontWeight: 800,
        color, textTransform: 'uppercase', letterSpacing: 0.5,
      }}>{label}</div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 6, marginTop: 4 }}>
        {icon && <span style={{ fontSize: 16 }}>{icon}</span>}
        <span style={{ fontFamily: theme.fontBody, fontSize: 22, fontWeight: 800, color: theme.ink }}>{value}</span>
      </div>
    </div>
  );
}

// ── Profile ─────────────────────────────────────
function ProfileScreen({ theme, lang, onTabClick, progress, goal, accuracy }) {
  // Stats réelles dérivées de la progression + du contenu des leçons
  const prog = progress || { u1: 0, u2: 0, u3: 0, u4: 0 };
  const units = (window.LESSON_INDEX && window.LESSON_INDEX.tracks[0]?.units) || [];
  let totalLessonsDone = 0;
  let totalXP = 0;
  let unitsComplete = 0;
  let totalLessonsInTrack = 0;
  let exercisesDone = 0;
  units.forEach(function (u) {
    totalLessonsInTrack += u.lessons.length;
    const done = Math.min(u.lessons.length, prog[u.id] || 0);
    totalLessonsDone += done;
    if (done === u.lessons.length && u.lessons.length > 0) unitsComplete++;
    for (let i = 0; i < done; i++) {
      const lesson = window.getLesson(u.lessons[i]);
      if (lesson) {
        totalXP += lesson.xp || 30;
        exercisesDone += (lesson.exercises || []).length;
      }
    }
  });
  const totalUnits = units.length;

  // Succès dynamiques, pourcentages calculés à partir de la progression réelle.
  const pct = (x) => Math.max(0, Math.min(1, x));
  const goldTargetEx = 100;
  const goldP = pct(exercisesDone / goldTargetEx);
  const brainP = totalUnits > 0 ? pct(unitsComplete / totalUnits) : 0;
  const brainLvl = unitsComplete;
  const streakLvl = 2; // streak réel viendra avec le tracking de dates
  const goldLvl = Math.min(3, Math.floor(exercisesDone / 25));
  // « Sans faute » : nb de leçons faites SANS aucune erreur (hits >= 1 et misses === 0).
  const acc = accuracy || {};
  const perfectLessons = Object.keys(acc).filter(function (id) {
    const a = acc[id];
    return a && a.hits >= 1 && a.misses === 0;
  }).length;
  const perfectTarget = 10;
  const perfectP = pct(perfectLessons / perfectTarget);
  const perfectLvl = Math.min(3, Math.floor(perfectLessons / 3));

  const ach = {
    fr: [
      { k: 'streak',  t: 'En feu',         s: '7 jours de suite',             p: 1,       col: '#FF9500',     lvl: streakLvl },
      { k: 'gold',    t: 'Médaille d\u2019or', s: exercisesDone + ' / ' + goldTargetEx + ' exos', p: goldP,    col: theme.gold, lvl: goldLvl },
      { k: 'brain',   t: 'Cerveau',        s: unitsComplete + ' / ' + totalUnits + ' unités',   p: brainP,   col: '#CE82FF',   lvl: brainLvl },
      { k: 'perfect', t: 'Sans faute',     s: perfectLessons + ' / ' + perfectTarget + ' leçons parfaites',    p: perfectP, col: theme.success, lvl: perfectLvl },
    ],
    en: [
      { k: 'streak',  t: 'On fire',       s: '7 day streak',                  p: 1,       col: '#FF9500',     lvl: streakLvl },
      { k: 'gold',    t: 'Gold medal',    s: exercisesDone + ' / ' + goldTargetEx + ' exercises', p: goldP, col: theme.gold, lvl: goldLvl },
      { k: 'brain',   t: 'Brain',         s: unitsComplete + ' / ' + totalUnits + ' units',    p: brainP,   col: '#CE82FF',   lvl: brainLvl },
      { k: 'perfect', t: 'Perfect',       s: perfectLessons + ' / ' + perfectTarget + ' perfect lessons',     p: perfectP, col: theme.success, lvl: perfectLvl },
    ],
  };
  const achievements = ach[lang] || ach.fr;
  const goalLabels = {
    fr: { student: 'Étudiant·e', pro: 'Pro en formation', entrepreneur: 'Freelance/TPE', curious: 'Curieux·se' },
    en: { student: 'Student', pro: 'Learning pro', entrepreneur: 'Freelance/SME', curious: 'Curious' },
  };
  const goalChip = goal ? goalLabels[lang][goal] : null;

  return (
    <div style={{ height: '100%', background: theme.bg, display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 110 }}>
        {/* hero */}
        <div style={{
          padding: '60px 20px 20px',
          background: `linear-gradient(180deg, ${theme.primarySoft}, transparent)`,
        }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
            <div style={{
              width: 84, height: 84, borderRadius: '50%',
              background: theme.surface, border: `3px solid ${theme.primary}`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: `0 4px 0 ${theme.primaryDark}`,
            }}>
              <MiloHead size={70} emotion="wink" accessory="tie"/>
            </div>
            <div style={{ flex: 1 }}>
              <div style={{ fontFamily: theme.font, fontSize: 22, fontWeight: theme.headingWeight, color: theme.ink }}>
                Camille L.
              </div>
              <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.inkSoft, marginTop: 2 }}>
                @camille · {lang==='fr'?'Inscrit·e en avril 2026':'Joined April 2026'}
              </div>
              <div style={{ display: 'flex', gap: 10, marginTop: 8, flexWrap: 'wrap' }}>
                {goalChip && <Chip theme={theme} color={theme.primary}>🎯 {goalChip}</Chip>}
                <Chip theme={theme} color="#FF9500">🔥 7</Chip>
              </div>
            </div>
          </div>
        </div>

        {/* stats grid */}
        <div style={{ padding: '16px 20px' }}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10 }}>
            <StatBox theme={theme} color="#FF9500" label={lang==='fr'?'Jours de suite':'Day streak'} value="7" icon="🔥"/>
            <StatBox theme={theme} color="#FFC800" label="XP" value={String(totalXP)} icon="⚡"/>
            <StatBox theme={theme} color="#00B4E6" label={lang==='fr'?'Leçons':'Lessons'} value={totalLessonsDone + ' / ' + totalLessonsInTrack} icon="📘"/>
            <StatBox theme={theme} color={theme.success} label={lang==='fr'?'Unités':'Units'} value={unitsComplete + ' / ' + totalUnits} icon="🎯"/>
          </div>

          <h3 style={{
            fontFamily: theme.font, fontSize: 20, fontWeight: theme.headingWeight,
            color: theme.ink, margin: '24px 0 10px',
          }}>{lang==='fr'?'Succ\u00e8s':'Achievements'}</h3>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
            {achievements.map(a => (
              <div key={a.k} style={{
                display: 'flex', alignItems: 'center', gap: 12,
                background: theme.surface, border: `1px solid ${theme.border}`,
                borderRadius: 14, padding: 12,
              }}>
                <div style={{
                  width: 54, height: 54, borderRadius: '50%',
                  background: a.col, color: '#fff',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                  fontSize: 24, fontWeight: 900, fontFamily: theme.font,
                  boxShadow: `0 3px 0 ${shadeColor(a.col, -20)}`,
                }}>{a.lvl + 1}</div>
                <div style={{ flex: 1 }}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 4 }}>
                    <span style={{ fontFamily: theme.fontBody, fontSize: 15, fontWeight: 800, color: theme.ink }}>{a.t}</span>
                    <span style={{ fontFamily: theme.fontBody, fontSize: 12, color: theme.inkSoft, fontWeight: 700 }}>
                      Lv. {a.lvl}
                    </span>
                  </div>
                  <div style={{ fontFamily: theme.fontBody, fontSize: 12, color: theme.inkSoft, marginBottom: 6 }}>{a.s}</div>
                  <ProgressBar theme={theme} value={a.p*100} color={a.col} height={8}/>
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
      <BottomTabs theme={theme} active="profile" onTabClick={onTabClick}/>
    </div>
  );
}

// ── Paywall ─────────────────────────────────────
function PaywallScreen({ theme, lang, onClose }) {
  const [plan, setPlan] = React.useState('yearly');
  const benefits_fr = [
    { icon: '♾️', t: 'Exercices illimit\u00e9s', s: 'Plus de c\u0153urs \u00e0 recharger' },
    { icon: '📜', t: 'Certifications reconnues', s: 'Dipl\u00f4mes valid\u00e9s par des experts-comptables' },
    { icon: '🎯', t: 'Parcours personnalis\u00e9', s: 'Milo adapte chaque le\u00e7on \u00e0 ton niveau' },
    { icon: '📊', t: 'Cas pratiques avanc\u00e9s', s: 'Bilans r\u00e9els, situations d\u2019entreprise' },
    { icon: '💬', t: 'R\u00e9ponses aux questions', s: 'Support d\u2019experts en 24h' },
  ];
  const benefits_en = [
    { icon: '♾️', t: 'Unlimited exercises', s: 'No more waiting for hearts' },
    { icon: '📜', t: 'Real certifications', s: 'Diplomas signed by CPAs' },
    { icon: '🎯', t: 'Custom learning path', s: 'Milo adapts each lesson to your level' },
    { icon: '📊', t: 'Advanced case studies', s: 'Real balance sheets, business scenarios' },
    { icon: '💬', t: 'Expert Q&A', s: 'Expert answers within 24h' },
  ];
  const benefits = lang === 'fr' ? benefits_fr : benefits_en;

  return (
    <div style={{
      height: '100%', background: theme.ink,
      display: 'flex', flexDirection: 'column', padding: '60px 0 32px',
      color: '#fff',
    }}>
      <div style={{ padding: '0 20px' }}>
        <button onClick={onClose} style={{
          width: 36, height: 36, background: 'transparent', border: 'none', padding: 0, cursor: 'pointer',
          marginBottom: 16,
        }}>
          <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="rgba(255,255,255,0.6)" strokeWidth="3" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
        </button>
      </div>

      <div style={{ flex: 1, overflow: 'auto', padding: '0 20px' }}>
        <div style={{ textAlign: 'center' }}>
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '4px 14px', borderRadius: 999, background: 'rgba(255,255,255,0.1)', fontFamily: theme.fontBody, fontSize: 12, fontWeight: 800, letterSpacing: 1, textTransform: 'uppercase' }}>
            <span style={{ color: theme.gold }}>★</span> Comptly Pro
          </div>
          <h1 style={{ fontFamily: theme.font, fontSize: 32, fontWeight: theme.headingWeight, margin: '14px 0 6px', letterSpacing: -0.5, lineHeight: 1.1 }}>
            {lang==='fr'?'Passe au niveau sup\u00e9rieur':'Unlock your potential'}
          </h1>
          <p style={{ fontFamily: theme.fontBody, fontSize: 15, color: 'rgba(255,255,255,0.7)', margin: 0, lineHeight: 1.4 }}>
            {lang==='fr'?'La comptabilit\u00e9, sans limite, sans pub.':'Accounting without limits, without ads.'}
          </p>
        </div>

        <div style={{
          margin: '24px auto', width: 'fit-content',
          background: `linear-gradient(135deg, ${theme.primary}, ${theme.gold})`,
          borderRadius: '50%', padding: 8,
        }}>
          <div style={{ background: '#fff', borderRadius: '50%', padding: 8 }}>
            <MiloHead size={90} emotion="love" accessory="grad"/>
          </div>
        </div>

        <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
          {benefits.map((b, i) => (
            <div key={i} style={{
              display: 'flex', gap: 12, alignItems: 'center',
              background: 'rgba(255,255,255,0.05)', border: '1px solid rgba(255,255,255,0.1)',
              borderRadius: 12, padding: 12,
            }}>
              <div style={{ fontSize: 24 }}>{b.icon}</div>
              <div>
                <div style={{ fontFamily: theme.fontBody, fontSize: 15, fontWeight: 800 }}>{b.t}</div>
                <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: 'rgba(255,255,255,0.6)', marginTop: 2 }}>{b.s}</div>
              </div>
            </div>
          ))}
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, margin: '24px 0 8px' }}>
          {[
            { k: 'monthly', t: lang==='fr'?'Mensuel':'Monthly', price: '12,99 €', sub: lang==='fr'?'/ mois':'/ month' },
            { k: 'yearly', t: lang==='fr'?'Annuel':'Yearly', price: '79,99 €', sub: lang==='fr'?'/ an (-50 %)':'/ year (-50%)', best: true },
          ].map(p => (
            <button key={p.k} onClick={() => setPlan(p.k)} style={{
              background: plan === p.k ? 'rgba(255,255,255,0.15)' : 'rgba(255,255,255,0.05)',
              border: `2px solid ${plan === p.k ? theme.gold : 'rgba(255,255,255,0.15)'}`,
              borderRadius: 14, padding: 14, cursor: 'pointer',
              color: '#fff', textAlign: 'left', position: 'relative',
            }}>
              {p.best && (
                <div style={{
                  position: 'absolute', top: -10, left: '50%', transform: 'translateX(-50%)',
                  background: theme.gold, color: theme.ink, padding: '3px 10px', borderRadius: 8,
                  fontFamily: theme.fontBody, fontSize: 10, fontWeight: 800, letterSpacing: 0.5, textTransform: 'uppercase',
                }}>{lang==='fr'?'Meilleur':'Best value'}</div>
              )}
              <div style={{ fontFamily: theme.fontBody, fontSize: 13, fontWeight: 700, color: 'rgba(255,255,255,0.7)' }}>{p.t}</div>
              <div style={{ fontFamily: theme.font, fontSize: 22, fontWeight: 800, marginTop: 2 }}>{p.price}</div>
              <div style={{ fontFamily: theme.fontBody, fontSize: 12, color: 'rgba(255,255,255,0.5)' }}>{p.sub}</div>
            </button>
          ))}
        </div>
      </div>

      <div style={{ padding: '12px 20px 0' }}>
        <button style={{
          width: '100%', height: 56, background: theme.gold,
          border: `2px solid ${shadeColor(theme.gold, -15)}`, borderRadius: 14,
          boxShadow: `0 4px 0 ${shadeColor(theme.gold, -20)}`,
          fontFamily: theme.fontBody, fontSize: 16, fontWeight: 800,
          textTransform: 'uppercase', letterSpacing: 0.5, color: theme.ink,
          cursor: 'pointer',
        }}>
          {lang==='fr'?'Essayer 7 jours gratuits':'Try 7 days free'}
        </button>
        <div style={{ textAlign: 'center', fontFamily: theme.fontBody, fontSize: 11, color: 'rgba(255,255,255,0.4)', marginTop: 8 }}>
          {lang==='fr'?'R\u00e9siliation \u00e0 tout moment':'Cancel anytime'}
        </div>
      </div>
    </div>
  );
}

// ── Catalog screen (cours) ─────────────────────
// Construit des groupes (un par track) avec leurs unités.
function buildTrackGroupsFromIndex(lang) {
  const palette = ['#E07A3E', '#4A7A8C', '#5A8A3A', '#8C6B4A', '#6B3A7A', '#B8854A'];
  if (!window.LESSON_INDEX) return [];
  return window.LESSON_INDEX.tracks.map(function (track, trackIdx) {
    const trackColor = track.color || palette[trackIdx % palette.length];
    const levelLabel = window.loc(track.level, lang) || (lang === 'fr' ? 'Débutant' : 'Beginner');
    const trackTitle = window.loc(track.title, lang);
    const trackSubtitle = window.loc(track.subtitle, lang);
    const courses = track.units.map(function (u, i) {
      const firstLessonId = u.lessons[0];
      const firstLesson = window.getLesson(firstLessonId);
      const unitTitle = window.loc(u.title, lang);
      const theme = unitTitle.split('—')[1]?.trim() || unitTitle;
      return {
        t: theme,
        s: firstLesson ? window.loc(firstLesson.subtitle, lang) : '',
        dur: (u.lessons.length * 6) + ' min',
        lvl: levelLabel,
        col: trackColor,
        tag: trackIdx === 0 && i === 0 ? (lang === 'fr' ? 'Populaire' : 'Popular') : null,
        count: u.lessons.length,
        firstLessonId,
      };
    });
    return {
      id: track.id,
      title: trackTitle,
      subtitle: trackSubtitle,
      icon: track.icon,
      courses,
    };
  });
}

function CatalogScreen({ theme, lang, onTabClick, onLessonClick }) {
  const trackGroups = buildTrackGroupsFromIndex(lang);

  return (
    <div style={{ height: '100%', background: theme.bg, display: 'flex', flexDirection: 'column' }}>
      <div style={{ flex: 1, overflow: 'auto', paddingBottom: 110 }}>
        <div style={{ padding: '60px 20px 12px' }}>
          <h1 style={{ fontFamily: theme.font, fontSize: 30, fontWeight: theme.headingWeight, color: theme.ink, margin: 0, letterSpacing: -0.5 }}>
            {lang==='fr'?'Catalogue':'Courses'}
          </h1>
          <p style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.inkSoft, margin: '4px 0 0' }}>
            {lang==='fr'?'Explore par th\u00e8me ou par niveau':'Browse by topic or level'}
          </p>
          {/* search */}
          <div style={{
            marginTop: 14, background: theme.surface, border: `1px solid ${theme.border}`,
            borderRadius: 14, padding: '10px 14px', display: 'flex', alignItems: 'center', gap: 10,
          }}>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={theme.inkSoft} strokeWidth="2"><circle cx="11" cy="11" r="7"/><path d="M21 21l-4-4"/></svg>
            <span style={{ fontFamily: theme.fontBody, fontSize: 14, color: theme.inkSoft }}>
              {lang==='fr'?'Rechercher un cours…':'Search a course…'}
            </span>
          </div>
        </div>

        <div style={{ padding: '8px 20px' }}>
          {trackGroups.map((group) => (
            <div key={group.id} style={{ marginBottom: 20 }}>
              <div style={{
                display: 'flex', alignItems: 'baseline', gap: 8,
                marginTop: 10, marginBottom: 8,
              }}>
                {group.icon && <span style={{ fontSize: 18 }}>{group.icon}</span>}
                <h3 style={{
                  fontFamily: theme.font, fontSize: 18, fontWeight: theme.headingWeight,
                  color: theme.ink, margin: 0, letterSpacing: -0.3,
                }}>{group.title}</h3>
              </div>
              {group.subtitle && (
                <div style={{ fontFamily: theme.fontBody, fontSize: 12, color: theme.inkSoft, marginBottom: 10 }}>
                  {group.subtitle}
                </div>
              )}
              {group.courses.map((c, i) => (
                <div key={i} onClick={() => onLessonClick({ lessonId: c.firstLessonId, title: c.t })} style={{
                  display: 'flex', gap: 14, padding: 14, marginBottom: 10,
                  background: theme.surface, border: `1px solid ${theme.border}`,
                  borderRadius: 16, cursor: 'pointer',
                  boxShadow: `0 2px 0 ${theme.border}`,
                }}>
                  <div style={{
                    width: 56, height: 56, borderRadius: 14, flexShrink: 0,
                    background: c.col, color: '#fff',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                    fontFamily: theme.font, fontSize: 22, fontWeight: 800,
                    boxShadow: `0 3px 0 ${shadeColor(c.col, -20)}`,
                  }}>{c.t.charAt(0)}</div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    <div style={{ display: 'flex', alignItems: 'center', gap: 6 }}>
                      <div style={{ fontFamily: theme.fontBody, fontSize: 16, fontWeight: 800, color: theme.ink }}>{c.t}</div>
                      {c.tag && <Chip theme={theme} color={c.col}>{c.tag}</Chip>}
                    </div>
                    <div style={{ fontFamily: theme.fontBody, fontSize: 13, color: theme.inkSoft, marginTop: 2 }}>{c.s}</div>
                    <div style={{ display: 'flex', gap: 10, marginTop: 6, fontFamily: theme.fontBody, fontSize: 12, color: theme.inkSoft }}>
                      <span>📚 {c.count} {lang==='fr'?'leçons':'lessons'}</span><span>·</span><span>⏱ {c.dur}</span><span>·</span><span>{c.lvl}</span>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          ))}
        </div>
      </div>
      <BottomTabs theme={theme} active="catalog" onTabClick={onTabClick}/>
    </div>
  );
}

Object.assign(window, { LessonIntroScreen, CompletionScreen, ProfileScreen, PaywallScreen, CatalogScreen, StatBox, MiniStat });
