// Quiz screen + Glossary + Mural + Trophies + Videos
const { useState: useStateQ, useEffect: useEffectQ, useMemo, useRef: useRefQ } = React;

// Reusable nav header for secondary screens — back to map + jump to any module
function NavHeader({ title, icon, onClose, current, onNav }) {
  const tabs = [
    { id: 'map', icon: '🗺️', label: 'Mapa' },
    { id: 'videos', icon: '🎬', label: 'Vídeos' },
    { id: 'glossary', icon: '📖', label: 'Dicionário' },
    { id: 'trophies', icon: '🏆', label: 'Troféus' },
    { id: 'mural', icon: '👥', label: 'Mural' },
  ];
  return (
    <div className="nav-header">
      <div className="nav-row">
        <button className="btn-ghost small nav-back" onClick={onClose}>← Mapa</button>
        <h2 className="nav-title">{icon} {title}</h2>
        <button className="icon-btn" onClick={onClose} title="Fechar">✕</button>
      </div>
      <div className="nav-tabs">
        {tabs.map(t => (
          <button
            key={t.id}
            className={`nav-tab ${current === t.id ? 'active' : ''}`}
            onClick={() => onNav(t.id)}
            title={t.label}
          >
            <span className="nt-icon">{t.icon}</span>
            <span className="nt-label">{t.label}</span>
          </button>
        ))}
      </div>
    </div>
  );
}

function arraysEqual(a, b) {
  if (!Array.isArray(a) || !Array.isArray(b) || a.length !== b.length) return false;
  const A = [...a].sort((x, y) => x - y);
  const B = [...b].sort((x, y) => x - y);
  return A.every((v, i) => v === B[i]);
}

function isCorrect(q, answer) {
  if (q.type === 'mc') return answer === q.correct;
  if (q.type === 'vf') {
    if (!Array.isArray(answer) || answer.length !== q.correct.length) return false;
    return q.correct.every((v, i) => v === answer[i]);
  }
  if (q.type === 'multi') return arraysEqual(q.correct, Array.isArray(answer) ? answer : []);
  return false;
}

function Confetti({ count = 60, big = false }) {
  const pieces = Array.from({ length: count });
  const colors = ['#fbbf24', '#22d3ee', '#fb7185', '#a78bfa', '#4ade80', '#f97316', '#f472b6'];
  const shapes = ['square', 'circle', 'star'];
  return (
    <div className={`confetti ${big ? 'big' : ''}`} aria-hidden="true">
      {pieces.map((_, i) => {
        const shape = shapes[i % shapes.length];
        const color = colors[i % colors.length];
        return (
          <span
            key={i}
            className={`confetti-piece shape-${shape}`}
            style={{
              left: `${Math.random() * 100}%`,
              background: shape !== 'star' ? color : 'transparent',
              color,
              animationDelay: `${Math.random() * 0.5}s`,
              animationDuration: `${1 + Math.random() * 1}s`,
              transform: `rotate(${Math.random() * 360}deg)`
            }}
          >{shape === 'star' ? '★' : ''}</span>
        );
      })}
    </div>
  );
}

function CelebrationBurst({ kind = 'good' }) {
  // Random celebratory message + emoji combo
  const goodMessages = [
    { msg: 'INCRÍVEL!', emoji: '🎉' },
    { msg: 'MANDOU BEM!', emoji: '⭐' },
    { msg: 'FANTÁSTICO!', emoji: '🚀' },
    { msg: 'PERFEITO!', emoji: '✨' },
    { msg: 'ARRASOU!', emoji: '🌟' },
    { msg: 'GENIAL!', emoji: '💫' },
    { msg: 'BOOM!', emoji: '💥' },
    { msg: 'UAU!', emoji: '🎊' }
  ];
  const pick = useMemo(() => goodMessages[Math.floor(Math.random() * goodMessages.length)], []);
  if (kind !== 'good') return null;
  return (
    <div className="celebration-burst">
      <div className="burst-emoji">{pick.emoji}</div>
      <div className="burst-text">{pick.msg}</div>
    </div>
  );
}

// Fisher-Yates shuffle (returns new array)
function shuffled(arr) {
  const a = arr.slice();
  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;
}

// ----- Quiz Screen -----
function QuizScreen({ user, mission, progress, onExit, onComplete, onOpenGlossary }) {
  const [queue, setQueue] = useStateQ(() => shuffled(mission.questions.map((_, i) => i)));
  const [pos, setPos] = useStateQ(0);
  const [confirmExit, setConfirmExit] = useStateQ(false);
  const [answer, setAnswer] = useStateQ(null);
  const [submitted, setSubmitted] = useStateQ(false);
  const [correct, setCorrect] = useStateQ(false);
  const [results, setResults] = useStateQ({});
  const [showSummary, setShowSummary] = useStateQ(false);
  const [shake, setShake] = useStateQ(false);
  const [streak, setStreak] = useStateQ(0);
  const [showCelebration, setShowCelebration] = useStateQ(false);
  const [resumed, setResumed] = useStateQ(false);

  const total = mission.questions.length;

  // ----- Resume on mount -----
  useEffectQ(() => {
    const mp = progress.missions[mission.id];
    const r = mp?.resume;
    if (r && !mp?.completed && r.results && r.queue && r.pos != null) {
      setQueue(r.queue);
      setPos(r.pos);
      setResults(r.results);
      setStreak(r.streak || 0);
      setResumed(true);
    }
    // eslint-disable-next-line
  }, []);

  const currentIdx = queue[pos];
  const q = currentIdx != null ? mission.questions[currentIdx] : null;

  // Reset answer per question
  useEffectQ(() => {
    if (!q) return;
    if (q.type === 'mc') setAnswer(null);
    else if (q.type === 'vf') setAnswer(q.statements.map(() => null));
    else if (q.type === 'multi') setAnswer([]);
    setSubmitted(false);
    setCorrect(false);
  }, [pos, queue]);

  // ----- Persist resume state -----
  useEffectQ(() => {
    if (showSummary) return;
    const mp = { ...(progress.missions[mission.id] || {}) };
    mp.resume = {
      queue,
      pos,
      results,
      streak,
      answeredCount: Object.keys(results).length
    };
    const newProg = { ...progress, missions: { ...progress.missions, [mission.id]: mp } };
    window.AppStorage.saveProgress(user.id, newProg);
    // eslint-disable-next-line
  }, [pos, results, streak]);

  function canSubmit() {
    if (!q) return false;
    if (q.type === 'mc') return answer !== null;
    if (q.type === 'vf') return Array.isArray(answer) && answer.every(v => v !== null);
    if (q.type === 'multi') return Array.isArray(answer) && answer.length === q.pickCount;
    return false;
  }

  function handleSubmit() {
    if (!canSubmit() || submitted) return;
    const ok = isCorrect(q, answer);
    setSubmitted(true);
    setCorrect(ok);
    setResults(prev => {
      const old = prev[currentIdx] || { correct: false, attempts: 0 };
      return {
        ...prev,
        [currentIdx]: { correct: ok || old.correct, attempts: old.attempts + 1 }
      };
    });
    if (ok) {
      setStreak(s => s + 1);
      setShowCelebration(true);
      setTimeout(() => setShowCelebration(false), 1400);
    } else {
      setStreak(0);
      setShake(true);
      setTimeout(() => setShake(false), 500);
    }
  }

  function handleNext() {
    if (pos + 1 < queue.length) {
      setPos(pos + 1);
    } else {
      // Clear resume state when reaching summary
      const mp = { ...(progress.missions[mission.id] || {}) };
      mp.resume = null;
      const newProg = { ...progress, missions: { ...progress.missions, [mission.id]: mp } };
      window.AppStorage.saveProgress(user.id, newProg);
      setShowSummary(true);
      // Scroll to top so users see the hero
      window.scrollTo({ top: 0, behavior: 'instant' });
    }
  }

  function retryWrong() {
    const wrong = mission.questions.map((_, i) => i).filter(i => !results[i]?.correct);
    if (wrong.length === 0) return;
    setQueue(shuffled(wrong));
    setPos(0);
    setShowSummary(false);
  }

  // Compute stars: 1 ponto base por acerto, -0.34 por tentativa extra. >=80% pct sem retries = 3⭐, etc.
  function computeStars() {
    const correctCount = mission.questions.filter((_, i) => results[i]?.correct).length;
    const totalAttempts = mission.questions.reduce((s, _, i) => s + (results[i]?.attempts || 0), 0);
    const extraAttempts = Math.max(0, totalAttempts - total); // erros + retries
    const pct = correctCount / total;
    if (pct < 0.6) return 0;
    // Penaliza: cada erro/retry tira pontos. 0 erros = 3, 1–2 erros = 2, 3+ erros = 1
    if (extraAttempts === 0 && pct >= 1) return 3;
    if (extraAttempts <= 2 && pct >= 0.8) return 2;
    return 1;
  }

  function finishMission() {
    const correctCount = mission.questions.filter((_, i) => results[i]?.correct).length;
    const totalAttempts = mission.questions.reduce((s, _, i) => s + (results[i]?.attempts || 0), 0);
    const stars = computeStars();
    onComplete({ stars, correctCount, total, results, totalAttempts });
  }

  // ----- Summary -----
  if (showSummary) {
    const correctCount = mission.questions.filter((_, i) => results[i]?.correct).length;
    const totalAttempts = mission.questions.reduce((s, _, i) => s + (results[i]?.attempts || 0), 0);
    const extraAttempts = Math.max(0, totalAttempts - total);
    const pct = correctCount / total;
    const stars = computeStars();
    const wrongIdxs = mission.questions.map((_, i) => i).filter(i => !results[i]?.correct);

    // Compute simulated overall progress (this mission counts at the new stars level)
    const simulatedMissions = window.MISSIONS.map(mm => {
      if (mm.id === mission.id) {
        const prevStars = progress.missions[mm.id]?.stars || 0;
        return { ...mm, stars: Math.max(prevStars, stars), completed: true };
      }
      const mp = progress.missions[mm.id];
      return { ...mm, stars: mp?.stars || 0, completed: !!mp?.completed };
    });
    const totalStarsAcc = simulatedMissions.reduce((s, m) => s + m.stars, 0);
    const maxStarsAcc = window.MISSIONS.length * 3;
    const completedCount = simulatedMissions.filter(m => m.completed).length;
    const earnedBadges = new Set(progress.badges || []);
    if (stars > 0) earnedBadges.add(`mission_${mission.id}`);
    if (stars === 3) earnedBadges.add('mestre_cosmico');
    const allThree = simulatedMissions.every(m => m.stars === 3);
    if (allThree) earnedBadges.add('lenda_cosmica');

    const isNewBest = stars > (progress.missions[mission.id]?.stars || 0);
    const nextMissionIdx = window.MISSIONS.findIndex(m => m.id === mission.id) + 1;
    const nextMission = nextMissionIdx < window.MISSIONS.length ? window.MISSIONS[nextMissionIdx] : null;
    const justUnlockedNext = stars > 0 && nextMission && !(progress.missions[nextMission.id]?.stars > 0);

    const headlineMsg = stars === 3 ? { text: 'MISSÃO PERFEITA!', sub: 'Você é uma LENDA do espaço! 🌟', cls: 'great', emoji: '🏆' }
      : stars === 2 ? { text: 'EXCELENTE, CADETE!', sub: 'Quase perfeito! Continue assim! 🎉', cls: 'good', emoji: '🎉' }
      : stars === 1 ? { text: 'MISSÃO CONCLUÍDA!', sub: 'Bom trabalho! Tente de novo pra brilhar mais! 💪', cls: 'ok', emoji: '🚀' }
      : { text: 'NÃO DESISTA!', sub: 'Cada erro é um passo pro acerto! Bora de novo! 💪', cls: 'low', emoji: '🌠' };

    return (
      <div className="screen summary-screen v2" style={{ '--accent': mission.accent }}>
        <window.Screens.StarfieldBg />
        {stars > 0 && <Confetti count={120} big />}
        {stars === 3 && <Confetti count={80} big />}

        <div className="summary-stack">
          {/* HERO */}
          <div className="summary-hero">
            <div className="hero-emoji-ring">
              <div className="ring-orbit"></div>
              <div className="ring-orbit r2"></div>
              <div className="hero-emoji">{headlineMsg.emoji}</div>
            </div>
            <h1 className={`hero-title ${headlineMsg.cls}`}>{headlineMsg.text}</h1>
            <p className="hero-sub">{headlineMsg.sub}</p>
            <div className="hero-mission-tag">
              <span className="mt-icon">{mission.icon}</span>
              <span>{mission.title}</span>
            </div>

            <div className="big-stars-v2">
              {[0, 1, 2].map(i => (
                <span key={i}
                  className={i < stars ? 'big-star on' : 'big-star off'}
                  style={{ animationDelay: `${i * 0.25}s` }}>★</span>
              ))}
            </div>

            {isNewBest && stars > 0 && (
              <div className="new-best-tag">✨ NOVO RECORDE! ✨</div>
            )}

            {extraAttempts > 0 && stars < 3 && (
              <div className="attempts-hint">
                💡 {extraAttempts === 1 ? '1 erro' : `${extraAttempts} erros`} no caminho · Acerte tudo de primeira para 3⭐!
              </div>
            )}
          </div>

          {/* STATS GRID */}
          <div className="stats-grid">
            <div className="stat-tile good">
              <div className="stat-emoji">🎯</div>
              <div className="stat-num">{correctCount}/{total}</div>
              <div className="stat-label">Acertos</div>
            </div>
            <div className="stat-tile">
              <div className="stat-emoji">⭐</div>
              <div className="stat-num">{totalStarsAcc}<span className="stat-of">/{maxStarsAcc}</span></div>
              <div className="stat-label">Estrelas Totais</div>
            </div>
            <div className="stat-tile">
              <div className="stat-emoji">🌍</div>
              <div className="stat-num">{completedCount}<span className="stat-of">/{window.MISSIONS.length}</span></div>
              <div className="stat-label">Missões</div>
            </div>
            <div className="stat-tile">
              <div className="stat-emoji">🏅</div>
              <div className="stat-num">{earnedBadges.size}</div>
              <div className="stat-label">Medalhas</div>
            </div>
          </div>

          {/* UNLOCK CARD */}
          {justUnlockedNext && (
            <div className="unlock-card">
              <div className="unlock-spark">✨🔓✨</div>
              <div className="unlock-body">
                <div className="unlock-label">Você destravou:</div>
                <div className="unlock-mission">
                  <span className="um-icon">{nextMission.icon}</span>
                  <strong>{nextMission.title}</strong>
                </div>
              </div>
            </div>
          )}

          {/* MISSIONS PATH */}
          <div className="path-card">
            <h3 className="path-title">🗺️ Sua Jornada</h3>
            <div className="path-row">
              {simulatedMissions.map((mm, i) => (
                <div key={mm.id} className={`path-node ${mm.id === mission.id ? 'current' : ''} ${mm.stars > 0 ? 'done' : ''}`}>
                  <div className="path-icon">{mm.stars > 0 ? mm.icon : '🔒'}</div>
                  <div className="path-stars">
                    {[0,1,2].map(s => <span key={s} className={s < mm.stars ? 'mini-on' : 'mini-off'}>★</span>)}
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* ACTIONS */}
          <div className="summary-actions-v2">
            {wrongIdxs.length > 0 && (
              <button className="btn-secondary big" onClick={retryWrong}>
                🔄 Treinar erradas ({wrongIdxs.length})
              </button>
            )}
            <button className="btn-primary big" onClick={finishMission}>
              {nextMission && stars > 0 ? `${nextMission.icon} Próxima Missão! →` : '🏠 Voltar ao Mapa'}
            </button>
          </div>
        </div>
      </div>
    );
  }

  if (!q) return null;

  const progressPct = ((pos + (submitted ? 1 : 0)) / queue.length) * 100;

  return (
    <div className="screen quiz-screen" style={{ '--accent': mission.accent }}>
      <window.Screens.StarfieldBg />

      <header className="quiz-header">
        <button className="btn-ghost small" onClick={() => setConfirmExit(true)}>🏠 Sair</button>
        <div className="quiz-title">
          <span className="qt-icon">{mission.icon}</span>
          <strong>{mission.title}</strong>
        </div>
        <button className="icon-btn" onClick={onOpenGlossary} title="Dicionário Espacial">📖</button>
      </header>

      {confirmExit && (
        <div className="screen-overlay" onClick={() => setConfirmExit(false)}>
          <div className="exit-dialog" onClick={e => e.stopPropagation()}>
            <div className="big-emoji">🚀</div>
            <h2>Sair da missão?</h2>
            <p>Não se preocupe! <strong>Seu progresso fica salvo</strong> e você pode continuar de onde parou quando voltar.</p>
            <div className="exit-progress">
              <div className="ep-label">Progresso desta missão:</div>
              <div className="ep-bar">
                <div className="ep-fill" style={{ width: `${(Object.keys(results).length / total) * 100}%` }} />
              </div>
              <div className="ep-count">{Object.keys(results).length} de {total} respondidas</div>
            </div>
            <div className="form-actions">
              <button className="btn-ghost" onClick={() => setConfirmExit(false)}>
                ↩ Continuar respondendo
              </button>
              <button className="btn-primary" onClick={onExit}>
                🏠 Voltar ao Mapa
              </button>
            </div>
          </div>
        </div>
      )}

      {resumed && (
        <div className="resume-banner">
          ▶ Continuando de onde você parou!
        </div>
      )}

      <div className="quiz-progress">
        <div className="progress-bar tall">
          <div className="progress-fill" style={{ width: `${progressPct}%` }} />
          <div className="progress-rocket" style={{ left: `${progressPct}%` }}>🚀</div>
        </div>
        <span className="progress-label">{pos + 1}/{queue.length}</span>
      </div>

      {streak >= 2 && (
        <div className="streak-badge">
          🔥 Sequência de {streak}!
        </div>
      )}

      <div className={`quiz-card ${shake ? 'shake' : ''} ${submitted && correct ? 'glow-good' : ''}`}>
        <div className="q-meta">
          <span className="q-number">Pergunta {pos + 1}</span>
        </div>

        <h3 className="q-prompt">{q.prompt}</h3>

        {q.type === 'mc' && (
          <div className="options">
            {q.options.map((opt, i) => {
              let cls = 'option';
              if (submitted) {
                if (correct && i === q.correct) cls += ' correct';
                else if (i === answer && !correct) cls += ' wrong';
              } else if (answer === i) cls += ' selected';
              return (
                <button
                  key={i}
                  className={cls}
                  onClick={() => !submitted && setAnswer(i)}
                  disabled={submitted}
                >
                  <span className="opt-letter">{String.fromCharCode(65 + i)}</span>
                  <span className="opt-text">{opt}</span>
                  {submitted && correct && i === q.correct && <span className="opt-badge">✓</span>}
                  {submitted && !correct && i === answer && <span className="opt-badge wrong">✗</span>}
                </button>
              );
            })}
          </div>
        )}

        {q.type === 'vf' && (
          <div className="vf-list">
            {q.statements.map((s, i) => {
              const cur = Array.isArray(answer) ? answer[i] : null;
              const showResult = submitted;
              const isRight = q.correct[i];
              return (
                <div
                  key={i}
                  className={`vf-row ${showResult ? (cur === isRight ? 'correct' : 'wrong') : ''}`}
                >
                  <span className="vf-text">{s}</span>
                  <div className="vf-buttons">
                    <button
                      className={`vf-btn ${cur === true ? 'sel' : ''} ${showResult && correct && isRight === true ? 'right' : ''}`}
                      onClick={() => {
                        if (submitted) return;
                        setAnswer(prev => {
                          const next = Array.isArray(prev) ? [...prev] : q.statements.map(() => null);
                          next[i] = true;
                          return next;
                        });
                      }}
                      disabled={submitted}
                    >V</button>
                    <button
                      className={`vf-btn ${cur === false ? 'sel' : ''} ${showResult && correct && isRight === false ? 'right' : ''}`}
                      onClick={() => {
                        if (submitted) return;
                        setAnswer(prev => {
                          const next = Array.isArray(prev) ? [...prev] : q.statements.map(() => null);
                          next[i] = false;
                          return next;
                        });
                      }}
                      disabled={submitted}
                    >F</button>
                  </div>
                </div>
              );
            })}
          </div>
        )}

        {q.type === 'multi' && (
          <div className="multi-area">
            <div className="multi-hint">
              Marque <strong>{q.pickCount}</strong> opções • Selecionou: {(Array.isArray(answer) ? answer : []).length}/{q.pickCount}
            </div>
            <div className="options multi">
              {q.options.map((opt, i) => {
                const sel = (Array.isArray(answer) ? answer : []).includes(i);
                const isAnsCorrect = q.correct.includes(i);
                let cls = 'option';
                if (submitted) {
                  if (correct && isAnsCorrect) cls += ' correct';
                  else if (sel && !correct) cls += ' wrong';
                } else if (sel) cls += ' selected';
                return (
                  <button
                    key={i}
                    className={cls}
                    onClick={() => {
                      if (submitted) return;
                      setAnswer(prev => {
                        const cur = Array.isArray(prev) ? prev : [];
                        if (cur.includes(i)) return cur.filter(x => x !== i);
                        if (cur.length < q.pickCount) return [...cur, i];
                        return cur;
                      });
                    }}
                    disabled={submitted}
                  >
                    <span className="opt-check">{sel ? '✓' : ''}</span>
                    <span className="opt-text">{opt}</span>
                  </button>
                );
              })}
            </div>
          </div>
        )}

        {submitted && (
          <div className={`feedback ${correct ? 'good' : 'bad'}`}>
            <div className="feedback-head">
              <window.Avatars.Bit size={64} mood={correct ? 'party' : 'sad'} />
              <div>
                <strong>{correct ? '🎉 Mandou bem, Cadete!' : '🤔 Hmm, não foi dessa vez!'}</strong>
                {correct ? (
                  <p>{q.explain}</p>
                ) : (
                  <>
                    <p className="learn-block"><strong>📘 Vamos aprender:</strong> {q.explain}</p>
                    <p className="study-tip">💡 <strong>Dica:</strong> revise os <strong>vídeos da Profª.</strong> e o <strong>Dicionário Espacial 📖</strong> para fixar o conteúdo. Depois, use <strong>"🔄 Treinar erradas"</strong> no fim da missão!</p>
                  </>
                )}
              </div>
            </div>
          </div>
        )}

        <div className="quiz-actions">
          {!submitted ? (
            <button className="btn-primary big" onClick={handleSubmit} disabled={!canSubmit()}>
              Responder ✓
            </button>
          ) : (
            <button className="btn-primary big" onClick={handleNext}>
              {pos + 1 < queue.length ? 'Próxima →' : 'Ver resultado 🏁'}
            </button>
          )}
        </div>
      </div>

      {showCelebration && (
        <>
          <Confetti count={50} />
          <CelebrationBurst kind="good" />
        </>
      )}
    </div>
  );
}

// ----- Glossary -----
function GlossaryScreen({ onClose, onView, onNav }) {
  const [search, setSearch] = useStateQ('');
  const filtered = useMemo(() => {
    const s = search.toLowerCase().trim();
    if (!s) return window.GLOSSARY;
    return window.GLOSSARY.filter(g =>
      g.term.toLowerCase().includes(s) || g.def.toLowerCase().includes(s)
    );
  }, [search]);

  useEffectQ(() => { if (onView) onView(); }, []);

  return (
    <div className="screen glossary-screen">
      <window.Screens.StarfieldBg />
      <NavHeader title="Dicionário Espacial" icon="📖" onClose={onClose} current="glossary" onNav={onNav} />
      <div className="search-box">
        <input
          type="text"
          placeholder="🔍 Buscar uma palavra..."
          value={search}
          onChange={e => setSearch(e.target.value)}
        />
      </div>
      <div className="glossary-list">
        {filtered.length === 0 && <div className="empty">Nenhuma palavra encontrada.</div>}
        {filtered.map(g => (
          <div key={g.term} className="glossary-item">
            <h4>{g.icon || '✨'} {g.term}</h4>
            <p>{g.def}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

// ----- Mural -----
function MuralScreen({ user, onClose, onNav }) {
  const [entries, setEntries] = useStateQ([]);
  const [loading, setLoading] = useStateQ(true);

  useEffectQ(() => {
    window.AppStorage.getMural().then(e => {
      setEntries(e || []);
      setLoading(false);
    });
  }, []);

  function timeAgo(ts) {
    const diff = Date.now() - ts;
    const m = Math.floor(diff / 60000);
    if (m < 1) return 'agora';
    if (m < 60) return `${m} min atrás`;
    const h = Math.floor(m / 60);
    if (h < 24) return `${h} h atrás`;
    return `${Math.floor(h / 24)} d atrás`;
  }

  return (
    <div className="screen mural-screen">
      <window.Screens.StarfieldBg />
      <NavHeader title="Mural da Turma" icon="👥" onClose={onClose} current="mural" onNav={onNav} />
      <p className="mural-sub">Conquistas dos colegas que escolheram compartilhar!</p>
      {loading && <div className="loading">Carregando...</div>}
      {!loading && entries.length === 0 && (
        <div className="empty-mural">
          <div className="big-emoji">📭</div>
          <p>Nenhuma publicação ainda.</p>
          <p className="hint">Termine uma missão e seja o(a) primeiro(a) a publicar!</p>
        </div>
      )}
      <div className="mural-list">
        {entries.map((e, i) => {
          const av = window.Avatars.get(e.avatar);
          const Av = av.component;
          return (
            <div key={i} className="mural-card" style={{ borderColor: av.color }}>
              <Av size={56} />
              <div className="mural-body">
                <div className="mural-head">
                  <strong>{e.nick}</strong>
                  <span className="mural-time">{timeAgo(e.ts)}</span>
                </div>
                <div className="mural-msg">
                  Concluiu a missão <strong>{e.missionIcon} {e.missionTitle}</strong>
                </div>
                <div className="mural-stars">
                  <window.Screens.StarBadge stars={e.stars} />
                  <span className="mural-score">{e.correctCount}/{e.total} acertos</span>
                </div>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ----- Trophies -----
function TrophiesScreen({ user, progress, onClose, onNav }) {
  const allBadges = window.BADGES;
  const earned = new Set(progress.badges || []);
  const totalStars = window.MISSIONS.reduce((sum, m) => sum + (Number.isFinite(progress.missions[m.id]?.stars) ? progress.missions[m.id].stars : 0), 0);
  const rank = window.Avatars.getRank(totalStars);
  const maxStars = window.MISSIONS.length * 3;
  const rankProgress = rank.next ? Math.round(((totalStars - rank.min) / (rank.next.min - rank.min)) * 100) : 100;

  return (
    <div className="screen trophies-screen">
      <window.Screens.StarfieldBg />
      <NavHeader title="Sala de Troféus" icon="🏆" onClose={onClose} current="trophies" onNav={onNav} />
      <div className="trophy-hero">
        <window.Avatars.RankedAvatar avatarId={user.avatar} stars={totalStars} size={100} />
        <h3>{user.nick}</h3>
        <p>{user.name}</p>
        <div style={{
          display: 'inline-flex', alignItems: 'center', gap: 8,
          marginTop: 6, padding: '6px 14px', borderRadius: 999,
          background: `${rank.color}22`, border: `2px solid ${rank.color}`,
          color: rank.color, fontWeight: 700, fontSize: 15
        }}>
          <span style={{ fontSize: 18 }}>{rank.emoji}</span>
          <span>Patente: {rank.title}</span>
        </div>
        {rank.next && (
          <div style={{ marginTop: 10, maxWidth: 360, marginLeft: 'auto', marginRight: 'auto' }}>
            <div style={{ fontSize: 13, color: '#94a3b8', marginBottom: 4 }}>
              Próxima patente: <strong style={{ color: rank.next.color }}>{rank.next.emoji} {rank.next.title}</strong> — faltam <strong>{rank.next.min - totalStars}⭐</strong>
            </div>
            <div style={{ height: 8, borderRadius: 999, background: '#1e293b', overflow: 'hidden' }}>
              <div style={{ width: `${rankProgress}%`, height: '100%', background: `linear-gradient(90deg, ${rank.color}, ${rank.next.color})`, transition: 'width .5s' }} />
            </div>
          </div>
        )}
        <div className="trophy-stats">
          <div><strong>⭐ {totalStars}/{maxStars}</strong><span>estrelas</span></div>
          <div><strong>🏅 {earned.size}</strong><span>medalhas</span></div>
        </div>
      </div>
      <h4 className="section-title">Medalhas</h4>
      <div className="badges-grid">
        {allBadges.map(b => {
          const got = earned.has(b.id);
          return (
            <div key={b.id} className={`badge-card ${got ? 'earned' : 'locked'}`}>
              <div className="badge-icon">{got ? b.icon : '🔒'}</div>
              <strong>{b.name}</strong>
              <p>{got ? b.desc : b.hint}</p>
            </div>
          );
        })}
      </div>
      <h4 className="section-title">Missões</h4>
      <div className="missions-progress">
        {window.MISSIONS.map(m => {
          const mp = progress.missions[m.id];
          const stars = mp?.stars || 0;
          return (
            <div key={m.id} className="mission-progress-row">
              <span className="mp-icon">{m.icon}</span>
              <span className="mp-title">{m.title}</span>
              <window.Screens.StarBadge stars={stars} />
            </div>
          );
        })}
      </div>
    </div>
  );
}

// ----- Videos -----

function VideoPlayer({ video }) {
  const [src, setSrc] = useStateQ(null);
  useEffectQ(() => {
    let revoke = null;
    if (video.kind === 'file') {
      // Modo API: usa fileUrl direto. Modo local: busca blob no IndexedDB.
      if (video.fileUrl) {
        setSrc(video.fileUrl);
      } else if (video.blobId) {
        window.AppStorage.getVideoBlob(video.blobId).then(blob => {
          if (blob) {
            const url = URL.createObjectURL(blob);
            revoke = url;
            setSrc(url);
          }
        });
      }
    }
    return () => { if (revoke) URL.revokeObjectURL(revoke); };
  }, [video.id]);

  const ytId = video.youtubeId || video.youtube;
  if (video.kind === 'youtube' && ytId) {
    return (
      <div className="video-embed">
        <iframe
          src={`https://www.youtube.com/embed/${ytId}?autoplay=1`}
          title={video.title}
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
        ></iframe>
      </div>
    );
  }
  if (video.kind === 'file') {
    return (
      <div className="video-embed">
        {src ? (
          <video src={src} controls autoPlay style={{ width: '100%', height: '100%', background: '#000' }} />
        ) : (
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: '100%', color: '#94a3b8' }}>
            Carregando vídeo...
          </div>
        )}
      </div>
    );
  }
  return null;
}

function VideosScreen({ onClose, onNav }) {
  const [videos, setVideos] = useStateQ([]);
  const [loading, setLoading] = useStateQ(true);
  const [playing, setPlaying] = useStateQ(null);

  useEffectQ(() => {
    window.AppStorage.getVideos().then(v => {
      setVideos(v || []);
      setLoading(false);
    });
  }, []);

  function fmtSize(bytes) {
    if (!bytes) return '';
    if (bytes < 1024 * 1024) return (bytes / 1024).toFixed(0) + ' KB';
    return (bytes / 1024 / 1024).toFixed(1) + ' MB';
  }

  return (
    <div className="screen videos-screen">
      <window.Screens.StarfieldBg />
      <NavHeader title="Vídeos da Aula" icon="🎬" onClose={onClose} current="videos" onNav={onNav} />

      <p className="videos-sub">Assista os vídeos da Profª. para reforçar o aprendizado!</p>

      {loading && <div className="loading">Carregando...</div>}
      {!loading && videos.length === 0 && (
        <div className="empty-videos">
          <div className="big-emoji">🎥</div>
          <p>Nenhum vídeo ainda!</p>
          <p className="hint">A Profª. ainda não adicionou os vídeos. Volte depois!</p>
        </div>
      )}

      <div className="video-list">
        {videos.map(v => (
          <div key={v.id} className="video-card">
            {playing === v.id ? (
              <VideoPlayer video={v} />
            ) : (
              <div className="video-thumb" onClick={() => setPlaying(v.id)}>
                {(v.kind === 'youtube' && (v.youtubeId || v.youtube)) ? (
                  <img src={`https://img.youtube.com/vi/${v.youtubeId || v.youtube}/hqdefault.jpg`} alt={v.title} />
                ) : (
                  <div className="thumb-placeholder">{v.kind === 'file' ? '📁🎬' : '🎬'}</div>
                )}
                <div className="play-overlay">▶</div>
                {v.kind === 'file' && <div className="kind-pill">📁 Arquivo</div>}
                {v.kind === 'youtube' && <div className="kind-pill yt">▶ YouTube</div>}
              </div>
            )}
            <div className="video-meta">
              <h4>{v.title}</h4>
              {(v.description || v.desc) && <p>{v.description || v.desc}</p>}
              {v.kind === 'file' && (
                <p className="muted small">📁 {v.fileName} • {fmtSize(v.fileSize)}</p>
              )}
              <div className="video-actions">
                {playing !== v.id && (
                  <button className="btn-ghost small" onClick={() => setPlaying(v.id)}>▶ Assistir</button>
                )}
                {playing === v.id && (
                  <button className="btn-ghost small" onClick={() => setPlaying(null)}>⏸ Fechar</button>
                )}
                {v.kind === 'youtube' && (
                  <a className="btn-ghost small" href={v.url} target="_blank" rel="noopener noreferrer">🔗 Abrir no YouTube</a>
                )}
              </div>
            </div>
          </div>
        ))}
      </div>

    </div>
  );
}

// ----- Share dialog -----
function ShareDialog({ user, mission, result, onShare, onSkip }) {
  return (
    <div className="screen-overlay">
      <div className="share-dialog">
        <div className="share-icon">{mission.icon}</div>
        <h2>Missão concluída!</h2>
        <p>Você quer publicar essa conquista no Mural da Turma?</p>
        <div className="share-stars">
          {[0, 1, 2].map(i => (
            <span key={i} className={i < result.stars ? 'big-star on' : 'big-star off'}>★</span>
          ))}
        </div>
        <div className="share-actions">
          <button className="btn-ghost" onClick={onSkip}>🔒 Manter só pra mim</button>
          <button className="btn-primary" onClick={onShare}>📢 Publicar no Mural!</button>
        </div>
      </div>
    </div>
  );
}

window.QuizScreens = { QuizScreen, GlossaryScreen, MuralScreen, TrophiesScreen, VideosScreen, ShareDialog, isCorrect };
