/* Runner - bilan de seance : temps par brin, maitrise honnete, erreurs nommees. Extrait de runner.jsx (decoupage 2026-06-12, sans changement de logique). */

function bilanTone({ ratio, passedShare }) {
  if (ratio == null) return { title: "Séance terminée.", note: "", color: "var(--ink)" };
  if (passedShare >= 0.5) return { title: "Séance survolée.", note: "Beaucoup de blocs passés : reviens-y pour les acquérir pour de vrai.", color: "var(--warn)" };
  if (ratio >= 0.8) return { title: "Bien joué.", note: "La plupart des items sont acquis — continue à ce rythme.", color: "var(--good)" };
  if (ratio >= 0.5) return { title: "Séance bouclée.", note: "Du solide, et des écarts à reprendre dès la prochaine fois.", color: "var(--ochre)" };
  return { title: "Séance difficile.", note: "C'est normal au début : ce sont justement ces écarts qui font progresser.", color: "var(--warn)" };
}

function RunnerBilan({ session, go }) {
  const s = session.summary || {};
  const counts = s.counts || {};
  const strands = s.strands || {};
  const tags = Object.keys(s.errorTags || {}).map(k => ({ tag: k, n: s.errorTags[k] })).sort((a, b) => b.n - a.n);
  const plannedMinutes = Math.round(Number(session.plannedMinutes || s.plannedMinutes || 0));
  const activeMinutes = Math.round(Number(s.minutesActive || 0));
  const durationText = plannedMinutes > 0 ? `${plannedMinutes} min prévues · ${activeMinutes} min actives` : `${activeMinutes} min actives`;

  // Unités explicites (cf. audit §passages) : acquis ≠ à reprendre ≠ passé.
  const total = s.blocksTotal || 0;
  const mastered = s.blocksMastered != null ? s.blocksMastered : (s.blocksCompleted || 0);
  const fragile = s.blocksPartial || 0;   // gradué sans maîtrise = à reprendre
  const passed = s.blocksSkipped || 0;    // passé = non-acquis explicite
  const ratio = total ? mastered / total : null;
  const passedShare = total ? passed / total : 0;
  const tone = bilanTone({ ratio, passedShare });

  // Réussite réelle = accuracy au niveau des tentatives (les passages en sont exclus).
  const graded = (counts.correct || 0) + (counts.errors || 0);
  const accuracy = s.accuracy != null ? s.accuracy : (graded ? (counts.correct || 0) / graded : null);
  const accPct = accuracy != null ? Math.round(accuracy * 100) : null;
  const corrected = counts.corrected || 0;
  const countLabel = (n, one, many) => `${n} ${n === 1 ? one : many}`;

  return (
    <div style={{ maxWidth: 620, margin: "30px auto 0", textAlign: "center" }} className="fade-up">
      <Eyebrow>Séance terminée</Eyebrow>
      <h1 style={{ fontSize: 40, margin: "10px 0 6px", color: tone.color }}>{tone.title}</h1>
      <p className="muted" style={{ fontSize: 16 }}>{mastered}/{total} items acquis · {durationText}.</p>
      {tone.note && <p className="faint" style={{ fontSize: 14, margin: "4px 0 0" }}>{tone.note}</p>}
      <div className="card" style={{ padding: 20, margin: "22px 0", display: "grid", gap: 16, textAlign: "left" }}>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(3,1fr)", gap: 14 }}>
          {[
            { v: `${mastered}/${total}`, l: "Items acquis", color: tone.color },
            { v: fragile, l: "À reprendre", color: fragile > 0 ? "var(--ochre)" : "var(--ink-faint)" },
            { v: passed, l: "Passés", color: passed > 0 ? "var(--warn)" : "var(--ink-faint)" },
          ].map((x, i) => (
            <div key={i}><div style={{ fontFamily: "var(--serif)", fontSize: 26, color: x.color }}>{x.v}</div><div className="faint" style={{ fontSize: 12 }}>{x.l}</div></div>
          ))}
        </div>
        <div className="faint" style={{ fontSize: 12.5, display: "grid", gap: 3 }}>
          <span>Réussite réelle {accPct != null ? `${accPct}%` : "—"} · {countLabel(counts.reviewed || 0, "carte notée", "cartes notées")} · {countLabel(counts.correct || 0, "bonne", "bonnes")} / {countLabel(counts.errors || 0, "ratée", "ratées")}</span>
          {corrected > 0 && <span>{corrected} reprise{corrected > 1 ? "s" : ""} corrigée{corrected > 1 ? "s" : ""} après erreur</span>}
          {(counts.produced || 0) > 0 && <span>Productions : {counts.produced || 0} tentées → {counts.producedOk || 0} validées</span>}
        </div>
        {Object.keys(strands).some(k => strands[k] > 0) && (
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Minutes par brin</div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
              {Object.keys(strands).filter(k => strands[k] > 0).map(k => (
                <span key={k} className="chip" style={{ fontSize: 12 }}>{STRAND_LABEL[k] || k} · {strands[k]}′</span>
              ))}
            </div>
          </div>
        )}
        {tags.length > 0 && (
          <div>
            <div className="eyebrow" style={{ marginBottom: 8 }}>Erreurs nommées</div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>{tags.map(t => <span key={t.tag} className="chip" style={{ fontSize: 12, background: "var(--warn-tint)", color: "var(--warn)", borderColor: "transparent" }}>{t.tag} ×{t.n}</span>)}</div>
          </div>
        )}
      </div>
      <div style={{ display: "flex", gap: 10, justifyContent: "center" }}>
        <Btn kind="primary" icon="today" onClick={() => go("today")}>Retour à Aujourd'hui</Btn>
        <Btn kind="secondary" icon="chart" onClick={() => go("pilotage")}>Voir le pilotage</Btn>
      </div>
    </div>
  );
}

