const { useState, useEffect, useRef, useMemo, useCallback } = React;

/* ================================================================== profondeur 3D (tout le site)
 * Chaque élément .relief s'incline vers la souris (en vraie 3D, avec perspective), se soulève,
 * et un reflet glisse sur sa surface. Force d'inclinaison : data-force (degrés), plus faible sur les grandes surfaces. */
(() => {
  let courant = null;
  const relacher = (el) => {
    el.classList.remove("survole", "appuie");
    el.style.rotate = "";
  };
  let attente = null;
  addEventListener("pointermove", (e) => {
    if (attente) { attente = e; return; }  // un seul calcul par image affichee
    attente = e;
    requestAnimationFrame(() => { const ev = attente; attente = null; incliner(ev); });
  }, { passive: true });
  const incliner = (e) => {
    const el = e.target.closest?.(".relief");
    if (courant && courant !== el) relacher(courant);
    courant = el;
    if (!el) return;
    const r = el.getBoundingClientRect();
    const px = (e.clientX - r.left) / r.width, py = (e.clientY - r.top) / r.height;
    if (r.width * r.height > 260000) return;  // trop grand pour etre incline sans ralentir : il garde juste son relief
    const force = parseFloat(el.dataset.force) || (r.width > 300 ? 2.2 : 5);
    const ax = -(py - 0.5), ay = px - 0.5, n = Math.hypot(ax, ay);
    if (el.parentElement) el.parentElement.style.perspective = "1100px";
    el.style.rotate = n > 0.01 ? `${ax} ${ay} 0 ${force * n * 2}deg` : "";
    el.style.setProperty("--mx", `${px * 100}%`);
    el.style.setProperty("--my", `${py * 100}%`);
    el.classList.add("survole");
  };
  addEventListener("pointerdown", (e) => e.target.closest?.("button.relief, .btn.relief")?.classList.add("appuie"));
  addEventListener("pointerup", () => document.querySelectorAll(".relief.appuie").forEach((el) => el.classList.remove("appuie")));
  document.addEventListener("pointerleave", () => courant && relacher(courant));
})();

/* ================================================================== constantes */
const NOMS_LECONS = {  // (les cours en fichiers ajoutent leur titre tout seuls, voir api/etat)
  lecture: "Lire des histoires", nommer: "Nommer", couleur: "Les couleurs", groupe: "Le groupe nominal", situer: "Situer dans l'espace",
  conjuguer: "Conjuguer", compter: "Compter & pluriels", question: "Répondre aux questions",
  raconter: "Raconter au passé", comprendre: "Comprendre une consigne",
  nature: "Nature des mots", fonction: "Fonction dans la phrase",
  politesse: "Politesse & présentations", dialogue: "Conversation avec mémoire",
  accueil: "Accueillir chaleureusement", humeur: "Parler de son humeur", journee: "Raconter sa journée",
  gouts: "Goûts & passions", sur_elle: "Parler d'elle, honnêtement", projets: "Projets & envies",
  au_revoir: "Remercier & dire au revoir", causerie: "Vraie conversation (adulte)",
  empathie: "Réconforter", bonnes_nouvelles: "Se réjouir avec toi", conseils: "Donner un conseil", limites: "Ce qu'elle ne peut pas savoir",
  culture: "Culture générale", calcul: "Calcul en mots", demande_aide: "Aider (poser les bonnes questions)", retours: "Corrections & compliments",
  opinions: "Avoir un avis", blagues: "Blagues", vouvoiement: "Vouvoyer", fetes: "Vœux & souhaits", recits: "Écouter un souvenir", comprendre: "Bien interpréter un message", wiki: "Chercher sur Wikipédia", meteo: "Regarder la météo", rebondir: "Rebondir sur ce que tu dis", lecture_adulte: "Lire le français des adultes",
  doute: "Douter de soi", qui_sait: "Qui sait quoi ?", toi_ou_moi: "Toi ou moi ?", tenir_bon: "Ne pas se laisser manipuler",
  vrai_faux: "Vrai ou faux", personnalite: "Rester soi-même", soi: "Parler de soi (ses vraies données)", definir: "Le sens des mots",
  inconnu: "Dire ce qu'elle ne connaît pas", dico: "Utiliser le dictionnaire",
};
const COULEURS_NATURE = {
  "déterminant": "#5b80a5", nom: "#d65f37", adjectif: "#dfa92f", verbe: "#2f6f6a", auxiliaire: "#5f9e96",
  pronom: "#9d6390", "préposition": "#8fab8b", adverbe: "#bf8450", ponctuation: "#a59f94", concept: "#24232b",
  morceau: "#c9bfae",
};
const STRATEGIES = {
  mutation: ["Mutation", "change quelques réglages au hasard"],
  faiblesse: ["Faiblesse", "s'entraîne là où elle échoue"],
  croisement: ["Croisement", "mélange deux anciennes versions"],
  audace: ["Audace", "transforme son architecture"],
};
const pct = (x, d = 1) => (x == null ? "—" : (Math.round(x * 100 * 10 ** d) / 10 ** d).toLocaleString("fr-FR") + " %");
const moyenne = (xs) => (xs.length ? xs.reduce((a, b) => a + b, 0) / xs.length : 0);
const couleurScore = (s) => (s >= 0.95 ? "var(--sarcelle)" : s >= 0.6 ? "var(--moutarde)" : "var(--tomate)");

/* ================================================================== hooks */
let PUBLIC_JEXA = true;
const abonnesPublic = new Set();
fetch("/api/principal", { cache: "no-store" }).then((r) => r.json()).then((d) => { PUBLIC_JEXA = !!d.public; abonnesPublic.forEach((f) => f(PUBLIC_JEXA)); }).catch(() => {});
function usePublic() {
  const [p, setP] = useState(PUBLIC_JEXA);
  useEffect(() => { abonnesPublic.add(setP); setP(PUBLIC_JEXA); return () => abonnesPublic.delete(setP); }, []);
  return p;
}

function useEtat() {
  const [etat, setEtat] = useState(null);
  const [vivant, setVivant] = useState(true);
  useEffect(() => {
    let stop = false;
    const tick = async () => {
      try {
        const r = await fetch("/api/etat");
        if (!stop) {
          const e = await r.json();
          e.lecons.forEach((l) => { if (l.titre) NOMS_LECONS[l.nom] = l.titre; });  // les cours en fichiers
          setEtat(e); setVivant(true);
        }
      } catch { if (!stop) setVivant(false); }
    };
    tick();
    const id = setInterval(tick, 2000);
    return () => { stop = true; clearInterval(id); };
  }, []);
  return [etat, vivant];
}

/** Fait glisser un nombre en douceur vers sa nouvelle valeur. */
function useTween(cible, duree = 900) {
  const [v, setV] = useState(cible || 0);
  const depart = useRef(v);
  useEffect(() => {
    if (cible == null) return;
    const de = depart.current, t0 = performance.now();
    let raf;
    const step = (t) => {
      const k = Math.min(1, (t - t0) / duree), e = 1 - Math.pow(1 - k, 3);
      const x = de + (cible - de) * e;
      setV(x); depart.current = x;
      if (k < 1) raf = requestAnimationFrame(step);
    };
    raf = requestAnimationFrame(step);
    return () => cancelAnimationFrame(raf);
  }, [cible]);
  return v;
}

/** Détecte les grands moments (nouvelle version, nouveau niveau) pour les annoncer. */
function useAnnonces(etat) {
  const [annonces, setAnnonces] = useState([]);
  const avant = useRef(null);
  useEffect(() => {
    if (!etat) return;
    const p = avant.current;
    const ajout = [];
    if (p && etat.version > p.version) ajout.push({ type: "version", texte: `Jexa v${etat.version} est née !`,
      detail: etat.versions.at(-1) ? `stratégie « ${etat.versions.at(-1).strategie} » · ${pct(etat.versions.at(-1).score)}` : "" });
    if (p && etat.niveau > p.niveau) ajout.push({ type: "niveau", texte: `Niveau ${etat.niveau} débloqué`,
      detail: NOMS_LECONS[etat.lecons.filter((l) => l.statut === "active").at(-1)?.nom] || "" });
    avant.current = { version: etat.version, niveau: etat.niveau };
    if (ajout.length) {
      const avecId = ajout.map((a) => ({ ...a, id: Math.random() }));
      setAnnonces((x) => [...x, ...avecId]);
      avecId.forEach((a) => setTimeout(() => setAnnonces((x) => x.filter((y) => y.id !== a.id)), 6000));
    }
  }, [etat]);
  return annonces;
}

/* ================================================================== petits éléments */
/** Un pare-feu : si un bloc plante, il affiche un petit message a sa place (le reste de la page continue). */
class Garde extends React.Component {
  constructor(p) { super(p); this.state = { erreur: null }; }
  static getDerivedStateFromError(erreur) { return { erreur }; }
  componentDidCatch(e) { console.error("[bloc]", e); }
  render() {
    if (!this.state.erreur) return this.props.children;
    return <div style={{ padding: "14px 16px", borderRadius: 16, background: "var(--tomate-c)", color: "var(--tomate)", fontSize: 13.5 }}>
      Ce bloc a eu un souci ({String(this.state.erreur.message || this.state.erreur).slice(0, 120)}).
      <button className="btn" onClick={() => this.setState({ erreur: null })} style={{ marginLeft: 10, background: "var(--surface)", color: "var(--encre)", fontSize: 12.5 }}>Réessayer</button></div>;
  }
}

const Carte = ({ titre, sous, accent, actions, children, style, delai = 0 }) => (
  <section className="carte profond" style={{ animationDelay: `${delai}ms`, ...style }}>
    <div className="carte-tete">
      <div>
        <div className="carte-titre">
          <span className="point" style={{ background: accent, boxShadow: `0 0 0 5px color-mix(in srgb, ${accent} 18%, transparent)` }} />
          <h2>{titre}</h2>
        </div>
        {sous && <div className="sous">{sous}</div>}
      </div>
      {actions}
    </div>
    <Garde>{children}</Garde>
  </section>
);

const Onglets = ({ valeur, options, onChange }) => {
  const refs = useRef({});
  const [barre, setBarre] = useState({ left: 0, width: 0 });
  useEffect(() => {
    const el = refs.current[valeur];
    if (el) setBarre({ left: el.offsetLeft, width: el.offsetWidth });
  }, [valeur]);
  return (
    <div style={{ position: "relative", display: "inline-flex", background: "var(--creme)", borderRadius: 99, padding: 5, gap: 2, flexWrap: "wrap" }}>
      <span style={{ position: "absolute", top: 5, bottom: 5, left: barre.left, width: barre.width, background: "var(--encre)",
                     borderRadius: 99, transition: "all .35s var(--ease)" }} />
      {options.map(([k, label]) => (
        <button key={k} ref={(el) => (refs.current[k] = el)} onClick={() => onChange(k)} style={{
          position: "relative", border: 0, borderRadius: 99, padding: "9px 18px", fontSize: 14, fontWeight: 700,
          background: "transparent", color: valeur === k ? "var(--papier)" : "var(--doux)", transition: "color .3s",
        }}>{label}</button>
      ))}
    </div>
  );
};

const Barre = ({ valeur, couleur, hauteur = 10, fond = "var(--creme)" }) => (
  <div style={{ background: fond, borderRadius: 99, height: hauteur, overflow: "hidden" }}>
    <div style={{ width: `${Math.max(0, Math.min(1, valeur || 0)) * 100}%`, height: "100%", background: couleur, borderRadius: 99,
                  transition: "width 1s var(--ease)" }} />
  </div>
);

function Anneau({ valeur, taille = 58, epaisseur = 7, couleur, children }) {
  const v = useTween(valeur || 0);
  const r = (taille - epaisseur) / 2, c = 2 * Math.PI * r;
  return (
    <div style={{ position: "relative", width: taille, height: taille, flexShrink: 0 }}>
      <svg width={taille} height={taille} style={{ transform: "rotate(-90deg)" }}>
        <circle cx={taille / 2} cy={taille / 2} r={r} fill="none" stroke="var(--creme)" strokeWidth={epaisseur} />
        <circle cx={taille / 2} cy={taille / 2} r={r} fill="none" stroke={couleur} strokeWidth={epaisseur}
                strokeLinecap="round" strokeDasharray={c} strokeDashoffset={c * (1 - v)} />
      </svg>
      <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center" }}>{children}</div>
    </div>
  );
}

function Courbe({ points, largeur = 120, hauteur = 34, couleur = "var(--sarcelle)", aire = false, epaisseur = 2.5 }) {
  const id = useMemo(() => "g" + Math.random().toString(36).slice(2), []);
  if (!points || points.length < 2) return <svg width={largeur} height={hauteur} />;
  const lo = aire ? Math.min(...points) * 0.95 : 0, hi = aire ? Math.max(...points) * 1.02 || 1 : 1;
  const xs = points.map((_, i) => (i / (points.length - 1)) * (largeur - 8) + 4);
  const ys = points.map((p) => hauteur - 4 - ((p - lo) / (hi - lo || 1)) * (hauteur - 8));
  const d = xs.map((x, i) => `${i ? "L" : "M"}${x.toFixed(1)},${ys[i].toFixed(1)}`).join(" ");
  return (
    <svg width="100%" viewBox={`0 0 ${largeur} ${hauteur}`} style={{ overflow: "visible", maxWidth: largeur, display: "block" }}>
      {aire && <>
        <defs><linearGradient id={id} x1="0" x2="0" y1="0" y2="1">
          <stop offset="0" stopColor={couleur} stopOpacity=".28" /><stop offset="1" stopColor={couleur} stopOpacity="0" />
        </linearGradient></defs>
        <path d={`${d} L${xs.at(-1)},${hauteur} L${xs[0]},${hauteur} Z`} fill={`url(#${id})`} />
      </>}
      <path d={d} fill="none" stroke={couleur} strokeWidth={epaisseur} strokeLinecap="round" strokeLinejoin="round"
            style={{ "--long": 2000, strokeDasharray: 2000, animation: "trace 1.6s var(--ease) both" }} />
      <circle cx={xs.at(-1)} cy={ys.at(-1)} r={epaisseur + 1.5} fill={couleur} />
      <circle cx={xs.at(-1)} cy={ys.at(-1)} r={epaisseur + 1.5} fill={couleur} style={{ transformOrigin: `${xs.at(-1)}px ${ys.at(-1)}px`, animation: "onde 2s infinite" }} />
    </svg>
  );
}

const Vide = ({ texte, enfant }) => <div className="vide">{enfant}{texte}</div>;

/* ================================================================== en-tête */
function Stat({ label, valeur, format, couleur }) {
  const v = useTween(valeur);
  return (
    <div style={{ background: "#ffffff0d", border: "1px solid #ffffff14", borderRadius: 24, padding: "12px 20px", minWidth: 104 }}>
      <div style={{ fontSize: 11, textTransform: "uppercase", letterSpacing: ".14em", opacity: .55, fontWeight: 700 }}>{label}</div>
      <div className="serif" style={{ fontSize: 28, fontWeight: 800, color: couleur, lineHeight: 1.15, fontVariantNumeric: "tabular-nums" }}>
        {format(v)}</div>
    </div>
  );
}

/** Turbo : un interrupteur. ON = Jexa prend tout le PC (s'eteint seul apres 12 h si tu oublies). */
function Turbo() {
  const [on, setOn] = useState(false);
  useEffect(() => {
    const lire = () => fetch("/api/turbo").then((r) => r.json()).then((d) => setOn(d.jusqua > 0)).catch(() => {});
    lire();
    const a = setInterval(lire, 15000);
    return () => clearInterval(a);
  }, []);
  const basculer = () => {
    const v = !on;
    setOn(v);
    fetch("/api/turbo", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ on: v }) })
      .then((r) => r.json()).then((d) => setOn(d.jusqua > 0)).catch(() => setOn(!v));
  };
  return (
    <label title={on ? "Turbo activé : Jexa utilise tout le PC (sauf si tu lances un jeu)" : "Activer le turbo quand tu n'utilises pas le PC"}
           style={{ display: "flex", alignItems: "center", gap: 10, cursor: "pointer", userSelect: "none", padding: "10px 14px", borderRadius: 99,
                    background: on ? "#ff8a3d26" : "#ffffff10", transition: "background .3s" }}>
      <input type="checkbox" checked={on} onChange={basculer} style={{ position: "absolute", opacity: 0, width: 0, height: 0 }} />
      <span style={{ width: 46, height: 26, borderRadius: 99, position: "relative", flexShrink: 0, transition: "background .3s",
                     background: on ? "linear-gradient(135deg, #ff8a3d, var(--tomate))" : "#ffffff2a", boxShadow: "inset 0 2px 4px #0004" }}>
        <span style={{ position: "absolute", top: 3, left: on ? 23 : 3, width: 20, height: 20, borderRadius: 99, background: "#fff",
                       boxShadow: "0 2px 5px #0006", transition: "left .3s var(--ease)", display: "grid", placeItems: "center", fontSize: 11 }}>{on ? "⚡" : ""}</span>
      </span>
      <span style={{ lineHeight: 1.15 }}>
        <b style={{ fontSize: 15 }}>Turbo</b>
        <span style={{ display: "block", fontSize: 11.5, opacity: .7 }}>{on ? "tout le PC pour Jexa" : "désactivé"}</span>
      </span>
    </label>
  );
}

/** La discussion avec les PC d'aide : ton ami t'écrit depuis Jexa Aide, tu lui réponds d'ici. */
function Messagerie() {
  const [ms, setMs] = useState([]);
  const [texte, setTexte] = useState("");
  const fil = useRef(null);
  const lire = () => fetch("/api/messages").then((r) => r.json()).then(setMs).catch(() => {});
  useEffect(() => { lire(); const a = setInterval(lire, 4000); return () => clearInterval(a); }, []);
  useEffect(() => { fil.current && (fil.current.scrollTop = fil.current.scrollHeight); }, [ms.length]);
  const envoyer = (e) => {
    e.preventDefault();
    if (!texte.trim()) return;
    fetch("/api/messages", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ texte }) }).then(lire);
    setTexte("");
  };
  return (
    <div style={{ marginTop: 14 }}>
      <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".1em", marginBottom: 8 }}>Discussion avec les PC d'aide</div>
      <div ref={fil} style={{ maxHeight: 220, overflowY: "auto", display: "flex", flexDirection: "column", gap: 6, padding: 4 }}>
        {ms.length === 0 && <div style={{ fontSize: 13, color: "var(--doux)" }}>Pas encore de message. Ton ami peut t'écrire depuis Jexa Aide.</div>}
        {ms.map((m, i) => {
          const moi = m.qui === "moi";
          return (
            <div key={i} style={{ alignSelf: moi ? "flex-end" : "flex-start", maxWidth: "75%", background: moi ? "var(--encre)" : "var(--surface)",
                                  color: moi ? "var(--papier)" : "var(--encre)", border: moi ? "none" : "1px solid var(--ligne)", borderRadius: 16, padding: "7px 12px", fontSize: 14 }}>
              {!moi && <div style={{ fontSize: 11, fontWeight: 700, color: "var(--sarcelle)" }}>{m.qui}</div>}
              {m.texte}
              <div style={{ fontSize: 10.5, opacity: .55, marginTop: 2 }}>{new Date(m.t * 1000).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })}</div>
            </div>
          );
        })}
      </div>
      <form onSubmit={envoyer} style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <input value={texte} onChange={(e) => setTexte(e.target.value)} placeholder="Écrire aux PC d'aide…"
               style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "9px 16px", fontSize: 14, fontFamily: "inherit", outline: "none", background: "var(--surface)", color: "var(--encre)" }} />
        <button className="btn relief" style={{ background: "var(--tomate)", color: "#fff" }}>Envoyer</button>
      </form>
    </div>
  );
}

/** Les PC d'aide du réseau local : qui est connecté, ce qu'il entraîne, et le code pour en ajouter un. */
function Aides() {
  const [d, setD] = useState(null);
  useEffect(() => {
    // une reponse sans liste (erreur passagere du serveur) ne remplace pas la derniere bonne : le bloc ne plante plus
    const lire = () => fetch("/api/aides").then((r) => r.json()).then((x) => { if (x && Array.isArray(x.aides)) setD(x); }).catch(() => {});
    lire();
    const a = setInterval(lire, 4000);
    return () => clearInterval(a);
  }, []);
  if (!d) return null;
  const k = (v) => (v >= 1e6 ? (v / 1e6).toLocaleString("fr-FR", { maximumFractionDigits: 1 }) + " M" : v >= 1000 ? Math.round(v / 1000) + " k" : Math.round(v || 0));
  return (
    <div style={{ marginTop: 22, borderTop: "1px solid var(--ligne)", paddingTop: 18 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, flexWrap: "wrap", marginBottom: 12 }}>
        <h3 style={{ fontSize: 19 }}>PC d'aide du réseau</h3>
        {d.code && <span className="pill" style={{ background: "var(--moutarde-c)", color: "#8a6511" }}>code : <span className="mono" style={{ letterSpacing: ".15em" }}>{d.code}</span></span>}
        <span style={{ fontSize: 12.5, color: "var(--doux)" }}>Lance « Jexa Aide » sur l'autre PC : il trouve celui-ci tout seul. Jexa reste ici.</span>
      </div>
      {d.chef_arrete && <div style={{ fontSize: 13.5, color: "var(--tomate)" }}>L'entraînement est arrêté : les aides attendent qu'il reprenne.</div>}
      {!d.aides.length ? <div className="vide" style={{ padding: 22 }}>Aucun PC d'aide pour l'instant.</div> : (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(260px, 1fr))", gap: 10 }}>
          {d.aides.map((a) => (
            <div key={a.nom} className="relief" style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 20, padding: 14 }}>
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <span style={{ width: 9, height: 9, borderRadius: 99, background: a.connectee ? "#5fbf8f" : "var(--tomate)", animation: a.pas != null ? "pulse 1.4s infinite" : "none" }} />
                <b>{a.nom}</b>
                {a.turbo && <span className="pill" style={{ background: "#ff8a3d26", color: "var(--tomate)", padding: "2px 9px", fontSize: 11.5 }}>⚡ turbo</span>}
              </div>
              <div style={{ fontSize: 12.5, color: "var(--doux)", margin: "4px 0 8px" }}>{a.gpu || "?"} · {a.faits} essai(s) entraîné(s){a.vitesse ? ` · ${k(a.vitesse)} morceaux/s` : ""}</div>
              {a.pas != null ? <><Barre valeur={a.pas / a.total} couleur="var(--tomate)" hauteur={8} />
                <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 4 }}>entraîne un essai : pas {a.pas} / {a.total}</div></>
                : <div style={{ fontSize: 12.5, color: a.connectee ? "var(--sarcelle)" : "var(--tomate)" }}>{a.connectee ? "prête, attend le prochain cycle" : "déconnectée"}</div>}
            </div>
          ))}
        </div>
      )}
      <Messagerie />
    </div>
  );
}

const MODES_PERF = { normal: "#8fd3c4", turbo: "#ff8a3d", discret: "#9fbad6" };

/** Les performances des dernières 24 h : vitesse d'apprentissage, carte graphique, et le mode à chaque minute. */
function Performances() {
  const [d, setD] = useState(null);
  const [vue, setVue] = useState("vitesse");
  const [vivante, setVivante] = useState(null);  // ce que fait l'IA en ce moment (entrainement, examen...)
  useEffect(() => {
    const lire = () => fetch("/api/etat").then((r) => r.json()).then((e) => setVivante(e.direct?.actif ? (e.direct.avancement || "actif") : null)).catch(() => {});
    lire();
    const a = setInterval(lire, 10000);
    return () => clearInterval(a);
  }, []);
  useEffect(() => {
    const lire = () => fetch("/api/perf").then((r) => r.json()).then(setD).catch(() => {});
    lire();
    const a = setInterval(lire, 10000);  // toutes les 10 s : le graphique vit tout seul
    return () => clearInterval(a);
  }, []);
  if (!d) return <div className="chargement" style={{ height: 300, borderRadius: "var(--r-l)" }} />;
  const maintenant = Date.now() / 1000;
  const h = (p) => -(maintenant - p.t) / 3600;  // en heures avant maintenant (-24 … 0)
  const fmtH = (x) => (x >= -0.02 ? "maint." : `-${Math.round(-x)} h`);
  const k = (v) => (v >= 1e6 ? (v / 1e6).toLocaleString("fr-FR", { maximumFractionDigits: 1 }) + " M" : v >= 1000 ? (v / 1000).toLocaleString("fr-FR", { maximumFractionDigits: 1 }) + " k" : Math.round(v).toLocaleString("fr-FR"));
  const vues = {
    vitesse: { titre: "Morceaux lus par seconde", y: (p) => p.morceaux_s, f: (v) => k(v), min: 0 },
    gpu: { titre: "Carte graphique utilisée (%)", y: (p) => p.gpu, f: (v) => Math.round(v) + " %", min: 0, max: 100 },
    vram: { titre: "Mémoire graphique (Go)", y: (p) => p.vram / 1024, f: (v) => v.toFixed(1) + " Go", min: 0 },
    temp: { titre: "Température (°C)", y: (p) => p.temp, f: (v) => Math.round(v) + " °C" },
  };
  const v = vues[vue];
  const pts = d.filter((p) => v.y(p) != null).map((p) => ({ x: h(p), y: v.y(p), couleur: MODES_PERF[p.mode],
    info: `${new Date(p.t * 1000).toLocaleTimeString("fr-FR", { hour: "2-digit", minute: "2-digit" })} · ${p.mode} · ${k(p.morceaux_s)} morceaux/s${p.gpu != null ? ` · GPU ${Math.round(p.gpu)} %` : ""}` }));
  const aidesPts = d.filter((p) => p.aides_morceaux_s > 0).map((p) => ({ x: h(p), y: p.aides_morceaux_s, info: `${p.aides} PC d'aide connecte(s)` }));
  const totalPts = d.filter((p) => p.aides_morceaux_s > 0).map((p) => ({ x: h(p), y: p.morceaux_s + p.aides_morceaux_s, info: "PC principal + PC d'aide" }));
  const minutes = (m) => d.filter((p) => p.mode === m).length;
  const tout = (p) => p.morceaux_s + (p.aides_morceaux_s || 0);  // ton PC + les PC d'aide
  const moy = d.length ? d.reduce((s, p) => s + tout(p), 0) / d.length : 0;
  const total = d.reduce((s, p) => s + tout(p) * 60, 0);
  const actif = d.length && maintenant - d.at(-1).t < 180;
  const etape = vivante ? (vivante.includes("examen") ? "examen en cours" : "entraînement") : null;
  return (
    <div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(150px, 1fr))", gap: 10, marginBottom: 16 }}>
        <Tuile label="En ce moment" valeur={actif && etape !== "examen en cours" ? k(tout(d.at(-1))) + " /s" : etape === "examen en cours" ? "examen 📝" : etape ? "démarrage…" : "à l'arrêt"} couleur="var(--tomate)"
               sous={actif && d.at(-1).aides_morceaux_s ? `dont ${k(d.at(-1).aides_morceaux_s)} /s par les PC d'aide` : "PC principal"} />
        <Tuile label="Moyenne 24 h" valeur={k(moy) + " /s"} couleur="var(--sarcelle)" />
        <Tuile label="Lu en 24 h" valeur={k(total) + " morceaux"} couleur="var(--moutarde)" />
        <Tuile label="Temps d'entraînement" valeur={`${Math.floor(d.length / 60)} h ${String(d.length % 60).padStart(2, "0")}`} couleur="var(--bleu)" />
        <Tuile label="Turbo / discret" valeur={`${Math.round(minutes("turbo") / 6) / 10} h / ${Math.round(minutes("discret") / 6) / 10} h`} couleur="var(--prune)" />
      </div>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 10, alignItems: "center" }}>
        {Object.entries(vues).map(([c, x]) => (
          <button key={c} className="btn relief" onClick={() => setVue(c)} style={{ fontSize: 12.5, padding: "6px 13px",
            background: vue === c ? "var(--encre)" : "var(--creme)", color: vue === c ? "#fff" : "var(--encre)" }}>{x.titre}</button>
        ))}
        <span style={{ marginLeft: "auto", display: "flex", gap: 12, fontSize: 12.5, color: "var(--doux)" }}>
          {Object.entries(MODES_PERF).map(([m, c]) => <span key={m}><span style={{ display: "inline-block", width: 9, height: 9, borderRadius: 99, background: c, marginRight: 5 }} />{m}</span>)}
        </span>
      </div>
      {pts.length ? (
        <Graphe series={[{ nom: "PC principal", points: pts, couleur: "var(--encre-2)", rayon: 2.6 },
          ...(vue === "vitesse" && aidesPts.length ? [{ nom: "PC d'aide", points: aidesPts, couleur: "var(--prune)", rayon: 2.6 },
                                                     { nom: "total", points: totalPts, couleur: "var(--tomate)", rayon: 1.6, opacite: 0.6 }] : [])]} hauteur={260} formatY={v.f} formatX={fmtH} xMin={-24} xMax={0} yMin={v.min} yMax={v.max} titreX="heures" />
      ) : <div className="vide">Pas encore de mesures : elles arrivent une fois par minute pendant l'entraînement.</div>}
    </div>
  );
}

/** Pause : Jexa s'arrête ou reprend son entraînement. */
function Pauses() {
  const [p, setP] = useState({ jexa: false, nexus: false });
  useEffect(() => {
    const lire = () => fetch("/api/pause").then((r) => r.json()).then(setP).catch(() => {});
    lire();
    const a = setInterval(lire, 10000);
    return () => clearInterval(a);
  }, []);
  const basculer = (m) => {
    const v = !p[m];
    setP((x) => ({ ...x, [m]: v }));
    fetch("/api/pause", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ modele: m, pause: v }) })
      .then((r) => r.json()).then((d) => setP((x) => ({ ...x, ...d })));
  };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
      {[["nexus", "Jexa"]].map(([m, l]) => (
        <button key={m} className="btn relief sombre" onClick={() => basculer(m)} title={p[m] ? `Reprendre l'entraînement de ${l}` : `Mettre l'entraînement de ${l} en pause`}
                style={{ background: p[m] ? "#dfa92f33" : "#ffffff10", color: "#fff", padding: "7px 14px", fontSize: 13, display: "flex", alignItems: "center", gap: 8, minWidth: 128 }}>
          <span style={{ width: 18, textAlign: "center" }}>{p[m] ? "▶" : "⏸"}</span>
          <span>{l}</span>
          <span style={{ marginLeft: "auto", fontSize: 11, opacity: .75 }}>{p[m] ? "en pause" : "apprend"}</span>
        </button>
      ))}
    </div>
  );
}

function EnTete({ etat, vivant }) {
  const estPublic = usePublic();
  const actif = etat?.direct?.actif;
  const moy = etat ? moyenne(etat.lecons.filter((l) => l.score != null).map((l) => l.score)) : 0;
  return (
    <header className="profond sombre" style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 24, flexWrap: "wrap",
                     padding: "30px 36px", background: "var(--encre)", color: "var(--papier)", borderRadius: "var(--r-xl)",
                     boxShadow: "0 30px 50px -28px #24232bcc", position: "relative", zIndex: 5, animation: "monte .6s var(--ease)" }}>
      <div style={{ position: "absolute", inset: 0, borderRadius: "inherit", overflow: "hidden", pointerEvents: "none" }}>
        <svg style={{ position: "absolute", right: -40, top: -60, opacity: .07 }} width="360" height="360">
          {[0, 1, 2, 3, 4].map((i) => <circle key={i} cx="180" cy="180" r={40 + i * 32} fill="none" stroke="#fff" strokeWidth="2" />)}
        </svg>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 20, position: "relative" }}>
        <div style={{ position: "relative", width: 70, height: 70 }}>
          {actif && [0, 1].map((i) => <span key={i} style={{ position: "absolute", inset: 0, borderRadius: 99, background: "var(--tomate)",
                       animation: `onde 2.4s ${i * 1.2}s infinite` }} />)}
          <div style={{ position: "relative", width: 70, height: 70, borderRadius: 99, background: "var(--tomate)", display: "grid",
                        placeItems: "center", boxShadow: "inset 0 -6px 0 #0002" }}>
            <span className="serif" style={{ fontWeight: 900, fontSize: 38 }}>J</span>
          </div>
        </div>
        <div>
          <h1 style={{ fontSize: 44, fontWeight: 900, lineHeight: 1 }}>Jexa</h1>
          <div style={{ fontSize: 14.5, marginTop: 8, display: "flex", alignItems: "center", gap: 9, opacity: .8 }}>
            <span style={{ width: 9, height: 9, borderRadius: 99, background: !vivant ? "var(--tomate)" : actif ? "#7fd1a8" : "var(--moutarde)",
                           animation: actif ? "pulse 1.6s infinite" : "none" }} />
            {!vivant ? "Indisponible pour le moment" : actif ? "En train de s'améliorer, en direct" : "Au repos pour le moment"}
          </div>
        </div>
      </div>
      {etat && (
        <div style={{ display: "flex", gap: 10, flexWrap: "wrap", position: "relative" }}>
          <Stat label="Version" valeur={etat.version} format={(v) => "v" + Math.round(v)} couleur="var(--tomate)" />
          <Stat label="Niveau" valeur={etat.niveau} format={(v) => Math.round(v)} couleur="var(--moutarde)" />
          <Stat label="Cycle" valeur={etat.cycle} format={(v) => Math.round(v)} couleur="#9fbad6" />
          <Stat label="Réussite" valeur={moy} format={(v) => pct(v)} couleur="#8fd3c4" />
          <Stat label="Paramètres" valeur={etat.params} format={(v) => (v / 1e6).toLocaleString("fr-FR", { maximumFractionDigits: 2 }) + " M"} couleur="#c9d8b5" />
          {!estPublic && <div style={{ alignSelf: "center" }}><Turbo /></div>}
          {!estPublic && <div style={{ alignSelf: "center" }}><Pauses /></div>}
        </div>
      )}
    </header>
  );
}

/* ================================================================== laboratoire en direct */
function Laboratoire({ etat }) {
  const d = etat.direct;
  const n = 4;
  const champ = d.cycle.match(/\|\s*([\d.]+)%\s*===/);
  const base = champ ? parseFloat(champ[1]) / 100 : null;
  const slots = Array.from({ length: n }, (_, i) => d.essais[i]);
  return (
    <Carte titre="Le laboratoire, en direct" accent="var(--bleu)" delai={60}
           sous={d.actif ? `${d.cycle.replace(/=/g, "").trim()} · Jexa teste ${n} variantes d'elle-même` : "Jexa se repose : son entraînement reprendra bientôt"}
           actions={<span className="pill" style={{ background: d.actif ? "var(--sarcelle-c)" : "var(--creme)", color: d.actif ? "var(--sarcelle)" : "var(--doux)" }}>
             <span style={{ width: 8, height: 8, borderRadius: 99, background: "currentColor", animation: d.actif ? "pulse 1.2s infinite" : "none" }} />
             {d.actif ? "en direct" : "en pause"}</span>}>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 2.2fr) minmax(240px, 1fr)", gap: 24 }} className="grille-labo">
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 12 }}>
          {slots.map((e, i) => <Essai key={i + (e ? "-ok" : "-att")} essai={e} base={base}
                                      enCours={d.actif && !e && i === d.essais.length} index={i} avancement={d.avancement} />)}
        </div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 700, textTransform: "uppercase", letterSpacing: ".12em", color: "var(--doux)", marginBottom: 10 }}>
            Grands moments</div>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {[...d.evenements].reverse().slice(0, 5).map((ev, i) => {
              const niveau = ev.startsWith("***");
              return (
                <div key={ev} style={{ display: "flex", gap: 10, alignItems: "center", fontSize: 13.5, animation: `glisse .5s ${i * 60}ms var(--ease) both` }}>
                  <span style={{ width: 28, height: 28, borderRadius: 99, flexShrink: 0, display: "grid", placeItems: "center", fontSize: 13,
                                 background: niveau ? "var(--moutarde-c)" : "var(--tomate-c)" }}>{niveau ? "★" : "✦"}</span>
                  <span style={{ color: "var(--encre-2)" }}>{ev.replace(/^(\*\*\*|>>>)\s*/, "")}</span>
                </div>
              );
            })}
            {!d.evenements.length && <span style={{ color: "var(--doux)", fontSize: 14 }}>Rien encore.</span>}
          </div>
        </div>
      </div>
    </Carte>
  );
}

function Essai({ essai, base, enCours, index, avancement }) {
  if (!essai) return (
    <div className={enCours ? "chargement" : ""} style={{ borderRadius: "var(--r-l)", padding: 18, minHeight: 150,
         border: "1.5px dashed var(--ligne)", display: "grid", placeItems: "center", color: "var(--doux)", fontSize: 13.5, textAlign: "center",
         background: enCours ? undefined : "transparent" }}>
      {enCours ? <span><span style={{ fontSize: 22, display: "block", animation: "pulse 1s infinite" }}>⚗</span>Variante {index + 1} en test…
                   {avancement && <span style={{ display: "block", fontSize: 12, marginTop: 6, color: "var(--encre-2)" }}>{avancement}</span>}
                   {/(\d+)%/.test(avancement || "") && <span style={{ display: "block", width: 120, margin: "8px auto 0" }}>
                     <Barre valeur={+avancement.match(/(\d+)%/)[1] / 100} couleur="var(--tomate)" hauteur={6} /></span>}</span>
               : <span style={{ opacity: .6 }}>Variante {index + 1}</span>}
    </div>
  );
  const [nom] = STRATEGIES[essai.strategie] || [essai.strategie];
  const gain = base != null ? essai.reel - base : 0;
  return (
    <div className={essai.mieux ? "relief sombre" : "relief"} style={{ borderRadius: "var(--r-l)", padding: 18, background: essai.mieux ? "var(--sarcelle)" : "#fff",
                  color: essai.mieux ? "#fff" : "var(--encre)", border: "1px solid var(--ligne)", animation: "pop .55s var(--ease) both",
                  boxShadow: essai.mieux ? "0 14px 30px -14px #2f6f6aaa" : "none", position: "relative", overflow: "hidden" }}>
      {essai.mieux && <span className="pill" style={{ position: "absolute", top: 12, right: 12, background: "#ffffff26", fontSize: 11 }}>meilleure ✓</span>}
      <div style={{ fontSize: 12, fontWeight: 700, opacity: .7, textTransform: "uppercase", letterSpacing: ".1em" }}>Variante {index + 1}</div>
      <div className="serif" style={{ fontSize: 20, fontWeight: 800, margin: "2px 0 4px" }}>{nom}</div>
      <div className="mono" style={{ fontSize: 11.5, opacity: .7, minHeight: 32, overflow: "hidden", textOverflow: "ellipsis" }}>
        {essai.changements}</div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 8, marginTop: 8 }}>
        <span className="serif" style={{ fontSize: 30, fontWeight: 800, fontVariantNumeric: "tabular-nums" }}>{pct(essai.reel)}</span>
        {base != null && <span className="mono" style={{ fontSize: 13, fontWeight: 500, color: essai.mieux ? "#c8f0e2" : gain < 0 ? "var(--tomate)" : "var(--doux)" }}>
          {gain >= 0 ? "+" : ""}{(gain * 100).toFixed(1)}</span>}
      </div>
      <div style={{ fontSize: 12, opacity: .75, marginTop: 4 }}>Elle avait prédit {pct(essai.predit)} · {essai.secondes} s</div>
    </div>
  );
}

/* ================================================================== leçons */
const ICONES_GROUPES = { "Lecture et grammaire": "📖", "Conversation": "💬", "Français": "🇫🇷", "Mathématiques": "➗", "Python": "🐍",
                         "Web": "🌐", "Java": "☕", "Histoire": "🏛️", "Sciences": "🔬" };

/** Une leçon en petite tuile : anneau, nom, score. Un clic ouvre sa fiche complète. */
function TuileLecon({ l, ouvrir, i }) {
  const active = l.statut === "active", c = couleurScore(l.score);
  const nom = l.titre_court || NOMS_LECONS[l.nom] || l.nom;
  return (
    <div className={active ? "relief" : ""} data-force="3" onClick={() => active && ouvrir(l.nom)} title={active ? "Voir la fiche complète" : (l.prerequis?.length ? `Prérequis : ${l.prerequis.join(", ")}` : "Se débloque plus tard")}
         style={{ display: "flex", alignItems: "center", gap: 10, padding: "8px 12px 8px 8px", borderRadius: 18, cursor: active ? "pointer" : "default",
                  background: active ? "var(--surface)" : "transparent", border: `1.5px ${active ? "solid" : "dashed"} var(--ligne)`, opacity: active ? 1 : .55,
                  animation: `monte .4s ${Math.min(i, 12) * 25}ms var(--ease) both`, minWidth: 0 }}>
      {active ? (
        <Anneau valeur={l.score} couleur={c} taille={38} epaisseur={4}>
          <span className="mono" style={{ fontSize: 10.5, fontWeight: 600 }}>{Math.round((l.score || 0) * 100)}</span>
        </Anneau>
      ) : <div style={{ width: 38, height: 38, borderRadius: 99, background: "var(--creme)", display: "grid", placeItems: "center", fontSize: 14, flexShrink: 0 }}>🔒</div>}
      <div style={{ minWidth: 0, flex: 1 }}>
        <div style={{ fontWeight: 650, fontSize: 13.5, lineHeight: 1.25, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{nom}</div>
        <div style={{ fontSize: 11, color: "var(--doux)", display: "flex", gap: 6, alignItems: "center" }}>
          {l.niveau_cours && <b style={{ color: "var(--encre-2)" }}>{l.niveau_cours}</b>}
          {active ? (l.score >= 0.95 ? "maîtrisée ✓" : `secret ${pct(l.secret, 0)}`) : (l.prerequis?.length ? `après ${l.prerequis.join(", ")}` : "verrouillée")}
        </div>
      </div>
    </div>
  );
}

/** Un groupe de leçons (Conversation, Mathématiques...) : un résumé sur une ligne, déplié au clic. */
function GroupeLecons({ nom, lecons, ouvrir, deplie, basculer }) {
  const actives = lecons.filter((l) => l.statut === "active");
  const maitrisees = actives.filter((l) => l.score >= 0.95).length;
  const moy = actives.length ? moyenne(actives.map((l) => l.score || 0)) : 0;
  const verrous = lecons.length - actives.length;
  return (
    <div style={{ border: "1px solid var(--ligne)", borderRadius: 22, background: deplie ? "var(--papier)" : "transparent", transition: "background .3s" }}>
      <button onClick={basculer} style={{ all: "unset", cursor: "pointer", display: "flex", alignItems: "center", gap: 12, width: "100%", boxSizing: "border-box", padding: "12px 16px" }}>
        <span style={{ fontSize: 20 }}>{ICONES_GROUPES[nom] || "📚"}</span>
        <span style={{ fontWeight: 800, fontSize: 15.5 }}>{nom}</span>
        <span style={{ fontSize: 12.5, color: "var(--doux)" }}>{maitrisees}/{lecons.length} maîtrisées{verrous ? ` · ${verrous} 🔒` : ""}</span>
        <span style={{ flex: 1, maxWidth: 220, marginLeft: "auto" }}><Barre valeur={moy} couleur={couleurScore(moy)} hauteur={7} /></span>
        <span className="mono" style={{ fontSize: 12.5, width: 38, textAlign: "right" }}>{pct(moy, 0)}</span>
        <span style={{ transition: "transform .3s var(--ease)", transform: deplie ? "rotate(90deg)" : "none", color: "var(--doux)" }}>›</span>
      </button>
      {deplie && (
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(215px, 1fr))", gap: 8, padding: "0 14px 14px" }}>
          {[...actives, ...lecons.filter((l) => l.statut !== "active")].map((l, i) => <TuileLecon key={l.nom} l={l} ouvrir={ouvrir} i={i} />)}
        </div>
      )}
    </div>
  );
}

function Lecons({ etat }) {
  const [fiche, setFiche] = useState(null);  // la fiche detaillee ouverte
  const [ouverts, setOuverts] = useState(() => new Set());  // tout replie au depart : une ligne par categorie
  const groupes = {};
  etat.lecons.forEach((l) => (groupes[l.groupe || "Autres"] ||= []).push(l));
  const actives = etat.lecons.filter((l) => l.statut === "active");
  const maitrisees = actives.filter((l) => l.score >= 0.95).length;
  const basculer = (g) => setOuverts((s) => { const n = new Set(s); n.has(g) ? n.delete(g) : n.add(g); return n; });
  return (
    <Carte titre="Les leçons" accent="var(--moutarde)" delai={120}
           sous={`${maitrisees} maîtrisées sur ${etat.lecons.length} · ${Object.keys(groupes).length} catégories · clique sur une catégorie pour l'ouvrir`}
           actions={<button className="btn relief" onClick={() => setOuverts(ouverts.size ? new Set() : new Set(Object.keys(groupes)))}
                            style={{ background: "var(--creme)", fontSize: 12.5, padding: "7px 14px" }}>{ouverts.size ? "Tout replier" : "Tout déplier"}</button>}>
      {fiche && <FicheLecon nom={fiche} fermer={() => setFiche(null)} />}
      <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
        {Object.entries(groupes).map(([g, ls]) => (
          <GroupeLecons key={g} nom={g} lecons={ls} ouvrir={setFiche} deplie={ouverts.has(g)} basculer={() => basculer(g)} />
        ))}
      </div>
    </Carte>
  );
}

/* ================================================================== parler */
function MotParMot({ texte, onFin }) {
  const mots = texte.split(" ");
  const [n, setN] = useState(0);
  useEffect(() => {
    if (n >= mots.length) { onFin && onFin(); return; }
    const t = setTimeout(() => setN(n + 1), 85);
    return () => clearTimeout(t);
  }, [n]);
  return <>{mots.slice(0, n).map((m, i) => <span key={i} style={{ animation: "monte .3s var(--ease) both" }}>{m} </span>)}
    {n < mots.length && <span style={{ animation: "pulse .8s infinite" }}>▍</span>}</>;
}

function Parler({ onPensee }) {
  const [monde, setMonde] = useState([]);
  const [texte, setTexte] = useState("");
  const [fil, setFil] = useState([]);
  const [attente, setAttente] = useState(false);
  const zone = useRef(null);

  const changerMonde = async () => { setMonde(await (await fetch("/api/monde")).json()); setFil([]); };
  useEffect(() => { changerMonde(); }, []);
  useEffect(() => { zone.current && zone.current.scrollTo({ top: zone.current.scrollHeight, behavior: "smooth" }); }, [fil, attente]);

  const gnMonde = (i) => monde[i].texte.split(" ").slice(0, 2).join(" ").toLowerCase();
  const dejaPresente = fil.some((m) => m.qui === "toi" && m.texte.startsWith("je m'appelle"));
  const dejaBaptise = fil.find((m) => m.qui === "toi" && m.texte.includes("s'appelle max"));
  const suggestions = monde.length ? [
    fil.length === 0 ? "bonjour !" : "comment ça va ?",
    dejaPresente ? "comment je m'appelle ?" : "je m'appelle léo .",
    dejaBaptise ? `comment s'appelle ${gnMonde(0)} ?` : `${gnMonde(0)} s'appelle max .`,
    `où est ${gnMonde(1)} ?`,
    `est-ce que ${gnMonde(2)} est ${monde[2].texte.toLowerCase().split(" ").slice(3).join(" ")} ?`,
    "où est la tortue ?",
    "nature le chat a sauté sur la table .",
    "raconte Il était une fois un petit renard qui",
  ] : [];

  const joindre = async (f) => {
    if (attente) return;
    let d = conv;
    if (!d) d = { id: Date.now().toString(36), titre: "📎 " + f.name.slice(0, 38), monde: [], messages: [], date: Date.now() };
    d = { ...d, messages: [...d.messages, { qui: "toi", texte: "Fichier joint : " + f.name }] };
    setDiscussions((ds) => [d, ...ds.filter((x) => x.id !== d.id)]);
    setCourante(d.id); setAttente(true);
    try {
      const b64 = await new Promise((ok, ko) => { const r = new FileReader(); r.onload = () => ok(String(r.result).split(",")[1]); r.onerror = ko; r.readAsDataURL(f); });
      const r = await (await fetch("/api/fichier", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nom: f.name, donnees: b64 }) })).json();
      setParle(true);
      setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, fichier: r.texte ? { nom: f.name, texte: r.texte } : x.fichier,
        messages: [...x.messages, { qui: "jexa", texte: r.reponse || r.erreur, erreur: !!r.erreur, outil: { mot: f.name, source: "Ton fichier", definition: "" }, neuf: true }] } : x)));
    } catch {
      setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, messages: [...x.messages, { qui: "jexa", texte: "Je n'ai pas réussi à recevoir ce fichier.", erreur: true }] } : x)));
    } finally { setAttente(false); }
  };

  const envoyer = async (t = texte) => {
    if (!t.trim() || attente) return;
    setFil((f) => [...f, { qui: "toi", texte: t }]);
    setTexte(""); setAttente(true);
    try {
      const historique = fil.filter((m) => !m.erreur).map((m) => ({ qui: m.qui, texte: m.texte }));
      const r = await (await fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: t, monde, historique }) })).json();
      setFil((f) => [...f, { qui: "jexa", texte: r.reponse || r.erreur, erreur: !!r.erreur, correction: r.correction, id: Math.random() }]);
      if (r.jetons) onPensee({ ...r, question: t });
    } finally { setAttente(false); }
  };

  const fonds = ["var(--bleu-c)", "var(--moutarde-c)", "var(--sarcelle-c)"];
  return (
    <Carte titre="Parler avec Jexa" accent="var(--tomate)" delai={180}
           sous="Pose une question sur son petit monde, donne une consigne, ou demande une analyse"
           actions={<button className="btn relief" onClick={changerMonde} style={{ background: "var(--tomate-c)", color: "var(--tomate)" }}>↻ Nouveau monde</button>}>
      <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginBottom: 16 }}>
        {monde.map((e, i) => (
          <div key={e.texte} style={{ background: fonds[i % 3], borderRadius: 99, padding: "10px 18px", fontSize: 14.5, fontWeight: 500,
                                      animation: `pop .45s ${i * 80}ms var(--ease) both` }}>{e.texte}</div>
        ))}
      </div>
      <div ref={zone} style={{ background: "var(--creme)", borderRadius: "var(--r-l)", padding: 18, height: 320, overflowY: "auto",
                               display: "flex", flexDirection: "column", gap: 12 }}>
        {fil.length === 0 && <div style={{ margin: "auto", textAlign: "center", color: "var(--doux)" }}>
          <div className="serif" style={{ fontSize: 22, fontWeight: 700, color: "var(--encre-2)" }}>Bonjour !</div>
          <div style={{ fontSize: 14 }}>Dis-moi bonjour, présente-toi, ou apprends-moi le nom d'un animal : je m'en souviendrai pendant la conversation ↓</div>
        </div>}
        {fil.map((m, i) => (
          <div key={i} style={{ alignSelf: m.qui === "toi" ? "flex-end" : "flex-start", maxWidth: "86%", display: "flex", gap: 8,
                                alignItems: "flex-end", flexDirection: m.qui === "toi" ? "row-reverse" : "row", animation: "monte .3s var(--ease) both" }}>
            {m.qui === "jexa" && <span style={{ width: 30, height: 30, borderRadius: 99, background: "var(--tomate)", color: "#fff", flexShrink: 0,
                                                display: "grid", placeItems: "center", fontFamily: "Fraunces", fontWeight: 900, fontSize: 15 }}>J</span>}
            <div>
              <div style={{
                background: m.qui === "toi" ? "var(--encre)" : m.erreur ? "var(--tomate-c)" : "#fff",
                color: m.qui === "toi" ? "var(--papier)" : "var(--encre)",
                borderRadius: m.qui === "toi" ? "22px 22px 6px 22px" : "22px 22px 22px 6px", padding: "12px 17px",
                fontSize: 15.5, lineHeight: 1.5, boxShadow: m.qui === "toi" ? "none" : "0 3px 10px -6px #0003",
              }}>{m.qui === "jexa" && !m.erreur && i === fil.length - 1 ? <MotParMot texte={m.texte} /> : m.texte}</div>
              {m.correction && <div style={{ fontSize: 12.5, color: "var(--tomate)", marginTop: 5, marginLeft: 6 }}>
                <b>correction :</b> {m.correction}</div>}
            </div>
          </div>
        ))}
        {attente && <div style={{ display: "flex", gap: 5, padding: "8px 4px" }}>
          {[0, 1, 2].map((i) => <span key={i} style={{ width: 9, height: 9, borderRadius: 99, background: "var(--tomate)",
                                                        animation: `pulse 1s ${i * .15}s infinite` }} />)}</div>}
      </div>
      <div style={{ display: "flex", gap: 7, flexWrap: "wrap", margin: "14px 0" }}>
        {suggestions.map((s) => (
          <button key={s} className="btn relief" onClick={() => envoyer(s)} style={{ border: "1.5px solid var(--ligne)", background: "#fff8",
                  padding: "7px 13px", fontSize: 13, fontWeight: 500, color: "var(--encre-2)" }}>{s}</button>
        ))}
      </div>
      <form onSubmit={(e) => { e.preventDefault(); envoyer(); }} style={{ display: "flex", gap: 8 }}>
        <input value={texte} onChange={(e) => setTexte(e.target.value)} placeholder="Écris à Jexa…"
               style={{ flex: 1, minWidth: 0, border: "1.5px solid var(--ligne)", background: "#fff", borderRadius: 99,
                        padding: "15px 22px", fontSize: 15.5, fontFamily: "inherit", outline: "none", transition: "border-color .2s" }}
               onFocus={(e) => (e.target.style.borderColor = "var(--tomate)")} onBlur={(e) => (e.target.style.borderColor = "var(--ligne)")} />
        <button type="submit" className="btn relief" disabled={attente} style={{ background: "var(--tomate)", color: "#fff", padding: "0 28px", fontSize: 15 }}>
          Envoyer</button>
      </form>
    </Carte>
  );
}

/* ================================================================== cerveau : réseau vivant */
function ReseauVivant({ genome, pensee, actif, sansTexte, hauteur = 340, fond = "var(--creme)" }) {
  const canvas = useRef(null);
  const etatAnim = useRef({ particules: [], flash: 0 });
  useEffect(() => { if (pensee) etatAnim.current.flash = 1; }, [pensee]);

  useEffect(() => {
    const cv = canvas.current, ctx = cv.getContext("2d");
    let raf, larg, haut;
    const dpr = window.devicePixelRatio || 1;
    const taille = () => {
      larg = cv.clientWidth; haut = cv.clientHeight;
      cv.width = larg * dpr; cv.height = haut * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0);
    };
    taille();
    window.addEventListener("resize", taille);

    const nCol = genome.layers + 2;
    const parCol = (c) => (c === 0 || c === nCol - 1 ? 7 : Math.min(12, 5 + genome.heads));
    const activite = pensee ? pensee.activite.map((row) => moyenne(row)) : null;
    const maxA = activite ? Math.max(...activite) : 1;
    const noeuds = [];
    for (let c = 0; c < nCol; c++) {
      const n = parCol(c);
      for (let k = 0; k < n; k++) noeuds.push({ c, k, n, phase: Math.random() * 6.28 });
    }
    const marge = () => (larg < 500 ? 30 : 60);
    const echelle = () => Math.max(0.55, Math.min(1, (larg - 2 * marge()) / (nCol * 90)));
    const pos = (nd) => {
      const x = marge() + (nd.c / (nCol - 1)) * (larg - 2 * marge());
      const y = (haut - 30) / 2 + (nd.k - (nd.n - 1) / 2) * Math.min(32, (haut - 80) / nd.n);
      return [x, y];
    };
    const couleursCol = (c) => (c === 0 ? [91, 128, 165] : c === nCol - 1 ? [214, 95, 55] : [47, 111, 106]);
    const st = etatAnim.current;
    st.particules = [];  // les anciennes particules appartiennent à un autre réseau
    if (sansTexte) {  // image fixe : on montre directement le cerveau en pleine activité
      st.flash = 0.6;
      for (let k = 0; k < 160; k++) {
        const choix = noeuds.filter((x) => x.c === Math.floor(Math.random() * (nCol - 1)));
        st.particules.push({ de: choix[Math.floor(Math.random() * choix.length)], vers: null, t: Math.random(), v: 0.012 });
      }
    }

    const frame = (t) => {
      ctx.clearRect(0, 0, larg, haut);
      // liens
      ctx.lineWidth = 1;
      for (const a of noeuds) for (const b of noeuds) {
        if (b.c !== a.c + 1 || (a.k * 7 + b.k * 3) % 3) continue;
        const [x1, y1] = pos(a), [x2, y2] = pos(b);
        ctx.strokeStyle = `rgba(36,35,43,${0.05 + st.flash * 0.12})`;
        ctx.beginPath(); ctx.moveTo(x1, y1); ctx.bezierCurveTo((x1 + x2) / 2, y1, (x1 + x2) / 2, y2, x2, y2); ctx.stroke();
      }
      // naissance de particules (signal qui traverse le cerveau)
      const taux = (actif ? 0.35 : 0.08) + st.flash * 2.5;
      if (Math.random() < taux) {
        const a = noeuds.filter((n) => n.c === 0)[Math.floor(Math.random() * 7)];
        st.particules.push({ de: a, vers: null, t: 0, v: 0.012 + Math.random() * 0.014 });
      }
      for (const p of st.particules) {
        if (!p.vers) {
          const suiv = noeuds.filter((n) => n.c === p.de.c + 1);
          p.vers = suiv[Math.floor(Math.random() * suiv.length)];
          if (!p.vers) { p.mort = true; continue; }
        }
        p.t += p.v * (1 + st.flash * 1.5);
        if (p.t >= 1) {
          p.de = p.vers; p.vers = null; p.t = 0;
          if (p.de.c === nCol - 1) p.mort = true;
          continue;
        }
        const [x1, y1] = pos(p.de), [x2, y2] = pos(p.vers);
        const e = p.t, x = x1 + (x2 - x1) * e, y = y1 + (y2 - y1) * (e * e * (3 - 2 * e));
        const [r, g, b] = couleursCol(p.de.c);
        ctx.fillStyle = `rgba(${r},${g},${b},.9)`;
        ctx.beginPath(); ctx.arc(x, y, 2.6, 0, 6.28); ctx.fill();
        ctx.fillStyle = `rgba(${r},${g},${b},.15)`;
        ctx.beginPath(); ctx.arc(x, y, 7, 0, 6.28); ctx.fill();
      }
      st.particules = st.particules.filter((p) => !p.mort).slice(-260);
      // neurones
      for (const nd of noeuds) {
        const [x, y] = pos(nd);
        const a = activite ? (activite[Math.min(nd.c, activite.length - 1)] || 0) / maxA : 0.4;
        const respir = 0.5 + 0.5 * Math.sin(t / 700 + nd.phase);
        const [r, g, b] = couleursCol(nd.c);
        const rayon = (6 + a * 4 + respir * 1.5 + st.flash * 3) * echelle();
        ctx.fillStyle = `rgba(${r},${g},${b},${0.12 + 0.12 * respir})`;
        ctx.beginPath(); ctx.arc(x, y, rayon + 6, 0, 6.28); ctx.fill();
        ctx.fillStyle = `rgb(${r},${g},${b})`;
        ctx.beginPath(); ctx.arc(x, y, rayon, 0, 6.28); ctx.fill();
        ctx.fillStyle = "rgba(255,255,255,.55)";
        ctx.beginPath(); ctx.arc(x - rayon / 3, y - rayon / 3, rayon / 3.2, 0, 6.28); ctx.fill();
      }
      // étiquettes
      const court = larg < 600;
      ctx.font = `700 ${court ? 10 : 12}px DM Sans`; ctx.fillStyle = "#706a77"; ctx.textAlign = "center";
      for (let c = 0; c < (sansTexte ? 0 : nCol); c++) {
        const x = marge() + (c / (nCol - 1)) * (larg - 2 * marge());
        ctx.fillText(c === 0 ? "MOTS" : c === nCol - 1 ? (court ? "RÉP." : "RÉPONSE") : court ? `B${c}` : `BLOC ${c}`, x, haut - 14);
      }
      st.flash *= 0.985;
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);
    return () => { cancelAnimationFrame(raf); window.removeEventListener("resize", taille); };
  }, [genome.layers, genome.heads, pensee, actif]);

  if (sansTexte) return <canvas ref={canvas} style={{ width: "100%", height: hauteur, display: "block", background: fond, borderRadius: 28 }} />;
  return (
    <div>
      <div style={{ fontSize: 14, color: "var(--doux)", marginBottom: 12 }}>
        Les signaux traversent ses <b>{genome.layers} blocs</b> de neurones. Ils s'intensifient quand elle s'entraîne et
        s'illuminent quand tu lui parles{pensee ? <> — dernière pensée : <i>« {pensee.question} »</i></> : ""}.
      </div>
      <canvas ref={canvas} style={{ width: "100%", height: 340, background: "var(--creme)", borderRadius: "var(--r-l)", display: "block" }} />
    </div>
  );
}

/* ================================================================== cerveau : attention */
function Pensee({ pensee }) {
  const [couche, setCouche] = useState(0);
  const [tete, setTete] = useState(-1);
  if (!pensee || !pensee.attention.length) return <Vide enfant={<div style={{ fontSize: 30, marginBottom: 6 }}>💭</div>}
                            texte="Parle à Jexa : ici tu verras sur quels mots son attention se pose pour écrire chaque mot." />;
  const nC = pensee.attention.length, nT = pensee.attention[0].length;
  const c = Math.min(couche, nC - 1);
  const A = tete < 0 ? pensee.attention[c][0].map((_, i) => pensee.attention[c][0][i].map((_, j) =>
    moyenne(pensee.attention[c].map((h) => h[i][j])))) : pensee.attention[c][Math.min(tete, nT - 1)];
  const debut = pensee.debut_reponse;
  const lignes = A.slice(debut - 1, A.length - 1);
  const sortie = pensee.jetons.slice(debut);
  const cell = Math.max(11, Math.min(22, 640 / pensee.jetons.length));
  return (
    <div>
      <div style={{ display: "flex", gap: 18, flexWrap: "wrap", alignItems: "center", marginBottom: 14 }}>
        <Selecteur label="Couche" n={nC} v={c} set={setCouche} />
        <Selecteur label="Tête" n={nT} v={tete} set={setTete} toutes />
      </div>
      <div style={{ fontSize: 14, color: "var(--doux)", marginBottom: 14 }}>
        Chaque ligne = un mot qu'elle écrit (en orange). Plus une case est foncée, plus elle <b>regarde</b> ce mot pour décider.
      </div>
      <div style={{ overflowX: "auto", paddingBottom: 6, background: "var(--creme)", borderRadius: "var(--r-l)", padding: 18 }}>
        <div style={{ display: "inline-block" }} key={`${c}-${tete}-${pensee.question}`}>
          {lignes.map((row, i) => (
            <div key={i} style={{ display: "flex", alignItems: "center", animation: `glisse .4s ${i * 50}ms var(--ease) both` }}>
              <div className="mono" style={{ width: 110, fontSize: 13, textAlign: "right", paddingRight: 12, color: "var(--tomate)",
                                             fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{sortie[i]}</div>
              {pensee.jetons.map((_, j) => {
                const v = row[j] || 0, visible = j <= debut - 1 + i;
                return <div key={j} title={`${pensee.jetons[j]} : ${Math.round(v * 100)} %`} style={{
                  width: cell, height: cell, margin: 1.5, borderRadius: 99, transition: "background .4s",
                  background: visible ? `rgba(47,111,106,${0.07 + 0.93 * Math.sqrt(v)})` : "transparent",
                  transform: visible ? `scale(${0.75 + 0.25 * Math.sqrt(v)})` : "none",
                }} />;
              })}
            </div>
          ))}
          <div style={{ display: "flex", marginLeft: 110 }}>
            {pensee.jetons.map((w, j) => (
              <div key={j} className="mono" style={{ width: cell + 3, fontSize: 11, writingMode: "vertical-rl", transform: "rotate(180deg)",
                    height: 96, color: j >= debut ? "var(--tomate)" : w.startsWith("#") ? "var(--encre)" : "var(--doux)",
                    whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", paddingTop: 6 }}>{w}</div>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

const Selecteur = ({ label, n, v, set, toutes }) => (
  <div style={{ display: "flex", alignItems: "center", gap: 9 }}>
    <span style={{ fontSize: 13, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em" }}>{label}</span>
    <div style={{ display: "flex", gap: 4, flexWrap: "wrap" }}>
      {toutes && <button onClick={() => set(-1)} className="btn relief" style={{ padding: "6px 12px", background: v === -1 ? "var(--sarcelle)" : "var(--creme)",
                                                                           color: v === -1 ? "#fff" : "var(--encre)", fontSize: 13 }}>toutes</button>}
      {Array.from({ length: n }, (_, i) => (
        <button key={i} onClick={() => set(i)} style={{ width: 32, height: 32, borderRadius: 99, border: 0, fontWeight: 700, transition: "all .2s",
                background: v === i ? "var(--sarcelle)" : "var(--creme)", color: v === i ? "#fff" : "var(--encre)" }}>{i + 1}</button>
      ))}
    </div>
  </div>
);

/* ================================================================== cerveau : carte des mots */
function CarteMots({ version }) {
  const [points, setPoints] = useState(null);
  const [survol, setSurvol] = useState(null);
  const [filtre, setFiltre] = useState(null);
  useEffect(() => { fetch("/api/carte").then((r) => r.json()).then((d) => setPoints(Array.isArray(d) ? d : d.points)); }, [version]);
  if (!points) return <div className="chargement" style={{ height: 420, borderRadius: "var(--r-l)" }} />;
  const W = 760, H = 440, pad = 30;
  const types = Object.keys(COULEURS_NATURE).filter((t) => points.some((p) => p.type === t));
  return (
    <div>
      <div style={{ fontSize: 14, color: "var(--doux)", marginBottom: 12 }}>
        Chaque point est un mot, placé selon ce que Jexa a appris de lui : deux mots proches sont deux mots qu'elle juge semblables.
        Clique une catégorie pour voir si elle s'est regroupée toute seule.
      </div>
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
        {types.map((t) => (
          <button key={t} className="btn relief" onClick={() => setFiltre(filtre === t ? null : t)} style={{
            padding: "6px 13px", fontSize: 12.5, background: filtre === t ? COULEURS_NATURE[t] : COULEURS_NATURE[t] + "1f",
            color: filtre === t ? "#fff" : COULEURS_NATURE[t] }}>{t} · {points.filter((p) => p.type === t).length}</button>
        ))}
      </div>
      <svg viewBox={`0 0 ${W} ${H}`} style={{ width: "100%", background: "var(--creme)", borderRadius: "var(--r-l)", display: "block" }}>
        {points.map((p, i) => {
          const on = !filtre || filtre === p.type;
          return (
            <g key={p.mot} style={{ transform: `translate(${pad + p.x * (W - 2 * pad)}px, ${pad + p.y * (H - 2 * pad)}px)`,
                                    transition: "transform 1.2s var(--ease)", cursor: "pointer" }}
               onMouseEnter={() => setSurvol(p)} onMouseLeave={() => setSurvol(null)}>
              <circle r={on ? 6 : 3} fill={COULEURS_NATURE[p.type] || "#999"} opacity={on ? .88 : .12}
                      style={{ transition: "all .35s var(--ease)", animation: `pop .6s ${i * 3}ms var(--ease) both` }} />
              {filtre === p.type && <text x="9" y="4" fontSize="11" fontFamily="DM Mono" fill="var(--encre)">{p.mot}</text>}
            </g>
          );
        })}
        {survol && (
          <g style={{ transform: `translate(${pad + survol.x * (W - 2 * pad)}px, ${pad + survol.y * (H - 2 * pad) - 20}px)`, pointerEvents: "none" }}>
            <rect x={-(survol.mot.length * 4.3 + 12)} y="-15" width={survol.mot.length * 8.6 + 24} height="26" rx="13" fill="var(--encre)" />
            <text y="3" textAnchor="middle" fontSize="12.5" fontFamily="DM Mono" fill="var(--papier)">{survol.mot}</text>
          </g>
        )}
      </svg>
    </div>
  );
}

/* ================================================================== cerveau : architecture & méthode */
function Architecture({ etat }) {
  const g = etat.genome, m = etat.meta;
  const total = Object.values(m.strategies).reduce((a, b) => a + b, 0);
  const lisse = lisser(etat.miroir, 8);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(300px, 1fr))", gap: 28 }}>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 12 }}>Son cerveau actuel</h3>
        <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 8 }}>
          <Etage texte={`Mots → vecteurs de ${g.d_model} nombres`} fond="var(--bleu-c)" i={0} />
          {Array.from({ length: g.layers }, (_, i) => (
            <div key={i} style={{ width: "100%", background: "var(--sarcelle-c)", borderRadius: 24, padding: "12px 14px",
                                  animation: `monte .45s ${80 + i * 70}ms var(--ease) both` }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 8, flexWrap: "wrap" }}>
                <span style={{ fontSize: 13, fontWeight: 700, color: "var(--sarcelle)" }}>Bloc {i + 1}</span>
                <div style={{ display: "flex", gap: 5 }}>
                  {Array.from({ length: g.heads }, (_, h) => (
                    <span key={h} title="tête d'attention" style={{ width: 18, height: 18, borderRadius: 99, background: "var(--sarcelle)",
                          animation: `pulse ${1.6 + h * 0.2}s ${h * 0.15}s infinite` }} />
                  ))}
                </div>
                <span className="pill" style={{ background: "#fff", fontSize: 11.5, padding: "3px 10px" }}>réseau ×{g.ffn_mult} · {g.activation}</span>
              </div>
            </div>
          ))}
          <Etage texte="→ choix du mot suivant" fond="var(--tomate-c)" i={g.layers + 1} />
        </div>
        <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 14 }}>
          {[["apprentissage", g.lr.toExponential(1)], ["pas", g.steps], ["lots", g.batch], ["héritage", g.heritage ? "oui" : "non"], ["dropout", g.dropout.toFixed(2)]]
            .map(([k, v]) => <span key={k} className="pill mono" style={{ background: "var(--creme)", fontWeight: 500, fontSize: 12 }}>{k} <b>{v}</b></span>)}
        </div>
      </div>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 12 }}>Sa façon de s'améliorer</h3>
        {Object.entries(m.strategies).sort((a, b) => b[1] - a[1]).map(([s, w], i) => (
          <div key={s} style={{ marginBottom: 14, animation: `glisse .45s ${i * 70}ms var(--ease) both` }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 5 }}>
              <span><b>{(STRATEGIES[s] || [s])[0]}</b> <span style={{ fontSize: 13, color: "var(--doux)" }}>— {(STRATEGIES[s] || ["", ""])[1]}</span></span>
              <span className="mono" style={{ fontSize: 14 }}>{Math.round((w / total) * 100)} %</span>
            </div>
            <Barre valeur={w / total} couleur="var(--moutarde)" hauteur={12} />
          </div>
        ))}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", marginTop: 6 }}>
          <span className="pill" style={{ background: "var(--moutarde-c)" }}>force de mutation {m.force.toFixed(2)}</span>
          <span className="pill" style={{ background: "var(--moutarde-c)" }}>vitesse de révision {m.apprentissage.toFixed(2)}</span>
        </div>
        <h3 style={{ fontSize: 19, margin: "26px 0 6px" }}>Se connaît-elle ?</h3>
        <div style={{ fontSize: 14, color: "var(--doux)", marginBottom: 10 }}>
          Écart moyen entre le score qu'elle prédit et son vrai score :
          <b style={{ color: "var(--bleu)" }}> {lisse.length ? (lisse.at(-1) * 100).toFixed(1) + " points" : "—"}</b> (plus c'est bas, mieux elle se connaît)</div>
        <Courbe points={lisse} largeur={380} hauteur={80} couleur="var(--bleu)" aire />
      </div>
    </div>
  );
}
const lisser = (xs, k = 5) => xs.map((_, i) => moyenne(xs.slice(Math.max(0, i - k + 1), i + 1)));
const Etage = ({ texte, fond, i }) => (
  <div style={{ width: "100%", background: fond, borderRadius: 99, padding: "11px 16px", textAlign: "center", fontSize: 14, fontWeight: 700,
                animation: `monte .45s ${i * 70}ms var(--ease) both` }}>{texte}</div>
);

/* ================================================================== cerveau : histoire */
function Histoire({ etat }) {
  const scores = etat.versions.map((v) => v.score);
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 28 }}>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 4 }}>Score de chaque nouvelle version</h3>
        <div style={{ fontSize: 13.5, color: "var(--doux)", marginBottom: 12 }}>
          {etat.essais} essais au total · {etat.versions.length} versions retenues. Les chutes = un nouveau niveau, plus difficile.</div>
        <div style={{ background: "var(--creme)", borderRadius: "var(--r-l)", padding: 18 }}>
          <Courbe points={scores} largeur={520} hauteur={170} couleur="var(--tomate)" aire epaisseur={3} />
        </div>
        <h3 style={{ fontSize: 19, margin: "22px 0 10px" }}>Journal brut</h3>
        <pre className="mono" style={{ background: "var(--encre)", color: "#e9e2d2", borderRadius: "var(--r-l)", padding: "16px 20px",
                                       fontSize: 12, lineHeight: 1.65, overflowX: "auto", margin: 0, maxHeight: 220 }}>
          {etat.journal.length ? etat.journal.join("\n") : "Aucun entraînement en cours."}</pre>
      </div>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 12 }}>Ses versions</h3>
        <div style={{ position: "relative", maxHeight: 470, overflowY: "auto", paddingLeft: 22 }}>
          <div style={{ position: "absolute", left: 9, top: 6, bottom: 6, width: 3, background: "var(--ligne)", borderRadius: 3 }} />
          {[...etat.versions].reverse().map((v, i) => (
            <div key={v.v} style={{ position: "relative", padding: "8px 0 14px", animation: `glisse .45s ${Math.min(i, 10) * 50}ms var(--ease) both` }}>
              <span style={{ position: "absolute", left: -19, top: 13, width: 15, height: 15, borderRadius: 99,
                             background: i === 0 ? "var(--tomate)" : "var(--papier)", border: "3px solid var(--tomate)" }} />
              <div style={{ display: "flex", alignItems: "center", gap: 8, flexWrap: "wrap" }}>
                <span className="serif" style={{ fontSize: 19, fontWeight: 800 }}>v{v.v}</span>
                <span className="mono" style={{ fontSize: 14 }}>{pct(v.score)}</span>
                <span className="pill" style={{ background: "var(--moutarde-c)", fontSize: 12, padding: "3px 10px" }}>{(STRATEGIES[v.strategie] || [v.strategie])[0]}</span>
                <span style={{ fontSize: 12.5, color: "var(--doux)" }}>cycle {v.cycle}</span>
              </div>
              <div className="mono" style={{ fontSize: 12, color: "var(--doux)", marginTop: 2 }}>{v.changements.join(", ") || "—"}</div>
            </div>
          ))}
        </div>
      </div>
    </div>
  );
}

/* ================================================================== tableau de bord v2 : des données lisibles à la souris */
const fmtPct = (v, d = 1) => (v == null ? "—" : `${(v * 100).toFixed(d).replace(".", ",")} %`);
const fmtNb = (n) => (n == null ? "—" : n.toLocaleString("fr-FR"));
const fmtMo = (n) => (n >= 1e6 ? `${(n / 1e6).toFixed(2).replace(".", ",")} M` : n >= 1e3 ? `${(n / 1e3).toFixed(1).replace(".", ",")} k` : `${n}`);

/** Infobulle qui suit la souris (position fixe, au-dessus de tout). */
function Bulle({ x, y, children }) {
  if (x == null) return null;
  // rendue directement dans <body> : un parent incline en 3D ne peut ni la deplacer ni la couper
  return ReactDOM.createPortal(
    <div style={{ position: "fixed", left: x + 14, top: y + 14, zIndex: 1100, pointerEvents: "none", background: "var(--encre)", color: "var(--papier)",
                  borderRadius: 14, padding: "9px 12px", fontSize: 12.5, lineHeight: 1.5, boxShadow: "0 14px 30px -12px #000a", maxWidth: 320,
                  transform: x > innerWidth - 360 ? "translateX(calc(-100% - 28px))" : "none" }}>{children}</div>,
    document.body);
}

/** Graphique interactif : courbes et/ou nuage de points, axes gradués, viseur et infobulle au survol.
 *  series : [{ nom, couleur, points: [{ x, y, info }], ligne: true|false, rayon }] */
function Graphe({ series, hauteur = 240, formatY = fmtPct, formatX = (x) => x, yMin, yMax, xMin, xMax, titreX = "", titreY = "" }) {
  const ref = useRef(null);
  const [larg, setLarg] = useState(600);
  const [survol, setSurvol] = useState(null);  // { point, serie, sx, sy, cx, cy }
  useEffect(() => {
    const ro = new ResizeObserver(([e]) => setLarg(e.contentRect.width));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);
  const tous = series.flatMap((s) => s.points);
  if (!tous.length) return <div ref={ref} className="vide" style={{ padding: 30 }}>Pas encore de données.</div>;
  const m = { g: 52, d: 16, h: 14, b: 34 };
  const W = larg, H = hauteur, iw = W - m.g - m.d, ih = H - m.h - m.b;
  const xs = tous.map((p) => p.x), ys = tous.map((p) => p.y);
  const x0 = xMin ?? Math.min(...xs), x1 = xMax ?? (Math.max(...xs) === x0 ? x0 + 1 : Math.max(...xs));
  let y0 = yMin ?? Math.min(...ys), y1 = yMax ?? Math.max(...ys);
  if (y1 - y0 < 1e-6) { y0 -= 0.05; y1 += 0.05; }
  const marge = (y1 - y0) * 0.08;
  if (yMin == null) y0 -= marge;
  if (yMax == null) y1 += marge;
  const X = (v) => m.g + ((v - x0) / (x1 - x0)) * iw, Y = (v) => m.h + (1 - (v - y0) / (y1 - y0)) * ih;
  const graduations = Array.from({ length: 5 }, (_, i) => y0 + ((y1 - y0) * i) / 4);
  const gradX = Array.from({ length: Math.min(6, Math.round(x1 - x0) + 1) }, (_, i) => x0 + ((x1 - x0) * i) / Math.max(1, Math.min(5, Math.round(x1 - x0))));
  const bouge = (e) => {
    const r = ref.current.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
    let mieux = null, d = 1e9;
    series.forEach((s) => s.points.forEach((p) => {
      const dd = Math.hypot(X(p.x) - mx, (Y(p.y) - my) * 0.6);
      if (dd < d) { d = dd; mieux = { point: p, serie: s }; }
    }));
    setSurvol(mieux && d < 60 ? { ...mieux, cx: e.clientX, cy: e.clientY } : null);
  };
  return (
    <div ref={ref} style={{ position: "relative", width: "100%" }} onMouseMove={bouge} onMouseLeave={() => setSurvol(null)}>
      <svg width={W} height={H} style={{ display: "block", overflow: "visible" }}>
        {graduations.map((g, i) => (
          <g key={i}>
            <line x1={m.g} x2={W - m.d} y1={Y(g)} y2={Y(g)} stroke="var(--ligne)" strokeDasharray={i ? "3 4" : "0"} />
            <text x={m.g - 8} y={Y(g) + 4} textAnchor="end" fontSize="11" fill="var(--doux)" fontFamily="DM Mono">{formatY(g, 0)}</text>
          </g>
        ))}
        {gradX.map((g, i) => <text key={i} x={X(g)} y={H - 12} textAnchor="middle" fontSize="11" fill="var(--doux)" fontFamily="DM Mono">{formatX(Math.round(g))}</text>)}
        {titreX && <text x={W - m.d} y={H} textAnchor="end" fontSize="10.5" fill="var(--doux)">{titreX}</text>}
        {titreY && <text x={4} y={10} fontSize="10.5" fill="var(--doux)">{titreY}</text>}
        {series.map((s, k) => {
          const pts = [...s.points].sort((a, b) => a.x - b.x);
          const d = pts.map((p, i) => `${i ? "L" : "M"}${X(p.x).toFixed(1)},${Y(p.y).toFixed(1)}`).join(" ");
          return (
            <g key={k}>
              {s.ligne !== false && pts.length > 1 && <>
                <path d={`${d} L${X(pts.at(-1).x)},${m.h + ih} L${X(pts[0].x)},${m.h + ih} Z`} fill={s.couleur} opacity=".08" />
                <path d={d} fill="none" stroke={s.couleur} strokeWidth="2.6" strokeLinejoin="round" strokeLinecap="round"
                      style={{ strokeDasharray: 4000, strokeDashoffset: 0, animation: "trace 1.4s var(--ease) both", "--long": 4000 }} />
              </>}
              {pts.map((p, i) => (
                <circle key={i} cx={X(p.x)} cy={Y(p.y)} r={survol?.point === p ? (s.rayon || 3.5) + 3 : s.rayon || 3.5}
                        fill={p.couleur || s.couleur} opacity={s.opacite ?? 1} stroke="var(--papier)" strokeWidth="1.5" style={{ transition: "r .15s" }} />
              ))}
            </g>
          );
        })}
        {survol && <g pointerEvents="none">
          <line x1={X(survol.point.x)} x2={X(survol.point.x)} y1={m.h} y2={m.h + ih} stroke="var(--encre)" strokeOpacity=".25" strokeDasharray="3 3" />
          <line x1={m.g} x2={W - m.d} y1={Y(survol.point.y)} y2={Y(survol.point.y)} stroke="var(--encre)" strokeOpacity=".15" strokeDasharray="3 3" />
        </g>}
      </svg>
      <Bulle x={survol?.cx} y={survol?.cy}>
        {survol && <>
          <div style={{ fontWeight: 700, marginBottom: 2 }}><span style={{ display: "inline-block", width: 9, height: 9, borderRadius: 9, background: survol.serie.couleur, marginRight: 6 }} />
            {survol.serie.nom} · {formatY(survol.point.y, 2)}</div>
          {survol.point.info}
        </>}
      </Bulle>
    </div>
  );
}

const Tuile = ({ label, valeur, sous, couleur = "var(--encre)" }) => (
  <div className="relief" data-force="4" style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 20, padding: "12px 16px", minWidth: 120, flex: 1 }}>
    <div style={{ fontSize: 11, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".1em" }}>{label}</div>
    <div className="serif" style={{ fontSize: 26, fontWeight: 800, color: couleur, lineHeight: 1.2 }}>{valeur}</div>
    {sous && <div style={{ fontSize: 12, color: "var(--doux)" }}>{sous}</div>}
  </div>
);

/* ------------------------------------------------------------------ fiche détaillée d'une leçon */
function FicheLecon({ nom, fermer }) {
  const [f, setF] = useState(null);
  const [chargement, setChargement] = useState(true);
  const charger = () => { setChargement(true); fetch(`/api/lecon?nom=${encodeURIComponent(nom)}`).then((r) => r.json()).then((x) => { setF(x); setChargement(false); }); };
  useEffect(charger, [nom]);
  const reussis = f?.exemples?.filter((e) => e.ok).length;
  useEffect(() => { const k = (e) => e.key === "Escape" && fermer(); addEventListener("keydown", k); return () => removeEventListener("keydown", k); }, []);
  return ReactDOM.createPortal(
    <div onClick={fermer} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(36,35,43,.4)", display: "grid", placeItems: "center", padding: 20, animation: "monte .3s ease both" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ width: "min(980px, 96vw)", maxHeight: "92vh", overflowY: "auto", background: "var(--papier)", borderRadius: 32,
                                                         padding: "30px 34px", boxShadow: "0 40px 90px -30px #000a", animation: "pop .45s cubic-bezier(.34,1.56,.64,1) both" }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "flex-start", gap: 16 }}>
          <div>
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".12em" }}>Leçon</div>
            <h2 className="serif" style={{ fontSize: 34, fontWeight: 800 }}>{NOMS_LECONS[nom] || nom}</h2>
            <p style={{ color: "var(--encre-2)", fontSize: 15.5, maxWidth: 680, margin: "6px 0 0" }}>{f?.description}</p>
          </div>
          <button onClick={fermer} className="btn relief" style={{ background: "var(--creme)", fontSize: 16 }}>✕</button>
        </div>
        {!f ? <div className="chargement" style={{ height: 300, borderRadius: 24, marginTop: 24 }} /> : <>
          <div style={{ display: "flex", gap: 12, flexWrap: "wrap", margin: "22px 0" }}>
            <Tuile label="Score à l'examen" valeur={fmtPct(f.score)} couleur={couleurScore(f.score || 0)} sous={`${f.taille_examen} questions`} />
            <Tuile label="Examen secret" valeur={fmtPct(f.secret)} sous="combinaisons jamais vues" couleur="var(--bleu)" />
            <Tuile label="Part de l'entraînement" valeur={`×${(f.poids || 1).toFixed(1).replace(".", ",")}`} sous="poids dans les lots" couleur="var(--moutarde)" />
            <Tuile label="Mini-examen en direct" valeur={f.exemples[0]?.lecture ? fmtPct(moyenne(f.exemples.map((e) => e.taux))) : `${reussis}/${f.exemples.length}`}
                   sous="passé à l'instant" couleur="var(--sarcelle)" />
          </div>
          <h3 style={{ fontSize: 19, margin: "8px 0 8px" }}>Son score, essai après essai</h3>
          <div style={{ background: "var(--creme)", borderRadius: 22, padding: "16px 12px 6px" }}>
            <Graphe yMin={0} yMax={1} titreX="cycle" series={[
              { nom: "essais refusés", couleur: "#c9bfae", ligne: false, rayon: 3, opacite: 0.8,
                points: f.essais.filter((e) => !e.ok).map((e) => ({ x: e.c, y: e.s, info: <>cycle {e.c} · variante non retenue</> })) },
              { nom: "versions retenues", couleur: "#d65f37",
                points: f.historique.map((h) => ({ x: h.c, y: h.s, info: <>version v{h.v} · cycle {h.c}</> })) },
            ]} />
          </div>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", margin: "22px 0 10px" }}>
            <h3 style={{ fontSize: 19 }}>Mini-examen, passé en direct à l'instant</h3>
            <button className="btn relief" onClick={charger} disabled={chargement} style={{ background: "var(--sarcelle-c)", color: "var(--sarcelle)" }}>
              {chargement ? "Elle réfléchit…" : "↻ Nouvelles questions"}</button>
          </div>
          {f.exemples[0]?.lecture ? f.exemples.map((e, i) => (
            <div key={i} style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 20, padding: "14px 18px", marginBottom: 10, lineHeight: 2, fontSize: 15 }}>
              <div style={{ fontSize: 12, color: "var(--doux)", marginBottom: 4 }}>Une histoire jamais lue : <span style={{ color: "#2f6f6a", fontWeight: 700 }}>vert = elle avait deviné le morceau</span>,
                <span style={{ color: "#d65f37", fontWeight: 700 }}> rouge = elle s'est trompée</span> (survole pour voir ce qu'elle pensait). {fmtPct(e.taux)} de bons morceaux.</div>
              {e.lecture.map((m, k) => <MorceauLu key={k} m={m} />)}
            </div>
          )) : (
            <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
              {f.exemples.map((e, i) => (
                <div key={i} className="relief" data-force="1.5" style={{ background: "var(--surface)", border: `1.5px solid ${e.ok ? "var(--sarcelle-c)" : "var(--tomate-c)"}`, borderRadius: 20,
                                              padding: "12px 16px", display: "grid", gridTemplateColumns: "34px 1fr", gap: 12, animation: `glisse .4s ${i * 60}ms var(--ease) both` }}>
                  <span style={{ width: 30, height: 30, borderRadius: 99, display: "grid", placeItems: "center", fontWeight: 800, color: "#fff",
                                 background: e.ok ? "var(--sarcelle)" : "var(--tomate)" }}>{e.ok ? "✓" : "✗"}</span>
                  <div style={{ minWidth: 0, fontSize: 14 }}>
                    <div className="mono" style={{ color: "var(--doux)", fontSize: 12.5, wordBreak: "break-word" }}>{e.entree}</div>
                    <div style={{ marginTop: 4 }}><b style={{ color: "var(--doux)", fontWeight: 600 }}>Jexa :</b> {e.jexa || <i>(rien)</i>}</div>
                    {!e.ok && <div style={{ color: "var(--sarcelle)" }}><b style={{ fontWeight: 600 }}>attendu :</b> {e.attendu}
                      {e.variantes > 1 && <span style={{ color: "var(--doux)" }}> (ou {e.variantes - 1} autre{e.variantes > 2 ? "s" : ""} bonne{e.variantes > 2 ? "s" : ""} réponse{e.variantes > 2 ? "s" : ""})</span>}</div>}
                  </div>
                </div>
              ))}
            </div>
          )}
        </>}
      </div>
    </div>
  , document.body);
}

function MorceauLu({ m }) {
  const [p, setP] = useState(null);
  return (
    <span onMouseMove={(e) => setP({ x: e.clientX, y: e.clientY })} onMouseLeave={() => setP(null)}
          style={{ whiteSpace: "pre-wrap", background: m.ok ? "rgba(47,111,106,.13)" : "rgba(214,95,55,.16)", borderBottom: `2px solid ${m.ok ? "#2f6f6a" : "#d65f37"}`,
                   borderRadius: 4, cursor: "help" }}>
      {m.vrai}
      <Bulle x={p?.x} y={p?.y}>{m.ok ? <>✓ Elle avait deviné « {m.vrai.trim()} »</> : <>✗ Elle pensait « <b>{m.devine.trim()}</b> », c'était « {m.vrai.trim()} »</>}</Bulle>
    </span>
  );
}

/* ------------------------------------------------------------------ carte des mots : zoom, recherche, voisins (fluide) */
const CARTE_W = 1000, CARTE_H = 620, CARTE_PAD = 30;
const carteXY = (p) => [CARTE_PAD + p.x * (CARTE_W - 2 * CARTE_PAD), CARTE_PAD + p.y * (CARTE_H - 2 * CARTE_PAD)];
const motNet = (w) => w.replace("▁", "");

/** La carte des mots, dessinee sur un canvas : des milliers de points sans ramer. Seul ce qui est visible est dessine,
    les etiquettes ne se chevauchent pas, et un clic choisit le point le plus proche (pas besoin de viser pile). */
const CarteMots2 = React.memo(function CarteMots2({ version }) {
  const [donnees, setDonnees] = useState(null);
  const [filtre, setFiltre] = useState(null);
  const [cherche, setCherche] = useState("");
  const [choisi, setChoisi] = useState(null);
  const [survol, setSurvol] = useState(null);
  const toile = useRef(null), boite = useRef(null), vue = useRef({ x: 0, y: 0, z: 1 }), glisse = useRef(null), raf = useRef(0), etat = useRef({});
  const charger = () => fetch("/api/carte").then((r) => r.json()).then((d) => setDonnees(Array.isArray(d) ? { points: d } : d)).catch(() => {});
  useEffect(() => { charger(); }, [version]);
  useEffect(() => { if (donnees?.calcul) { const t = setTimeout(charger, 15000); return () => clearTimeout(t); } }, [donnees]);
  const points = donnees?.points;
  const trouve = points && cherche.trim() ? points.find((p) => motNet(p.mot).toLowerCase() === cherche.trim().toLowerCase()) : null;

  // une grille pour trouver vite le point sous la souris
  const grille = useMemo(() => {
    const g = new Map();
    (points || []).forEach((p, i) => { const [x, y] = carteXY(p), k = `${Math.floor(x / 20)},${Math.floor(y / 20)}`; (g.get(k) || g.set(k, []).get(k)).push(i); });
    return g;
  }, [points]);
  const versMonde = (cx, cy) => { const c = toile.current, s = CARTE_W / c.clientWidth, v = vue.current; return [(cx * s - v.x) / v.z, (cy * s - v.y) / v.z]; };
  const plusProche = (cx, cy) => {
    const [wx, wy] = versMonde(cx, cy), v = vue.current, rayon = (14 * CARTE_W / toile.current.clientWidth) / v.z;  // 14 pixels a l'ecran
    let best = null, bd = rayon * rayon;
    for (let gx = Math.floor((wx - rayon) / 20); gx <= Math.floor((wx + rayon) / 20); gx++)
      for (let gy = Math.floor((wy - rayon) / 20); gy <= Math.floor((wy + rayon) / 20); gy++)
        for (const i of grille.get(`${gx},${gy}`) || []) {
          const p = points[i];
          if (filtre && p.type !== filtre) continue;
          const [x, y] = carteXY(p), d = (x - wx) ** 2 + (y - wy) ** 2;
          if (d < bd) { bd = d; best = i; }
        }
    return best;
  };

  const dessiner = () => {
    raf.current = 0;
    const c = toile.current;
    if (!c || !points) return;
    const dpr = devicePixelRatio || 1, W = c.clientWidth, H = c.clientHeight;
    if (c.width !== Math.round(W * dpr)) { c.width = Math.round(W * dpr); c.height = Math.round(H * dpr); }
    const g = c.getContext("2d"), v = vue.current, e = W / CARTE_W, { choisi: ch, trouve: tr, survol: su, filtre: fi } = etat.current;
    g.setTransform(dpr, 0, 0, dpr, 0, 0);
    g.clearRect(0, 0, W, H);
    const ecran = (p) => { const [x, y] = carteXY(p); return [(x * v.z + v.x) * e, (y * v.z + v.y) * e]; };
    const voisins = new Set((ch?.voisins || []).map((x) => x.mot));
    const index = etat.current.index;
    // les liens vers les vrais voisins
    const centre = ch && index.get(ch.mot);
    if (centre) {
      const [cx, cy] = ecran(centre);
      (ch.voisins || []).forEach((x) => { const q = index.get(x.mot); if (!q) return; const [qx, qy] = ecran(q);
        g.strokeStyle = `rgba(214,95,55,${0.25 + Math.max(0, x.sim) * 0.7})`; g.lineWidth = 2; g.beginPath(); g.moveTo(cx, cy); g.lineTo(qx, qy); g.stroke(); });
    }
    const rayon = Math.min(7, 2.2 + v.z * 0.6);
    const forts = [];
    for (const p of points) {
      const [x, y] = ecran(p);
      if (x < -10 || y < -10 || x > W + 10 || y > H + 10) continue;  // seulement ce qui est visible
      const on = !fi || fi === p.type, fort = voisins.has(p.mot) || ch?.mot === p.mot || tr === p.mot || su === p.mot;
      if (fort) { forts.push(p); continue; }
      g.globalAlpha = on ? (p.type === "morceau" ? 0.28 : 0.85) : 0.06;
      g.fillStyle = COULEURS_NATURE[p.type] || "#999";
      g.beginPath(); g.arc(x, y, p.type === "morceau" ? rayon * 0.6 : rayon, 0, 6.283); g.fill();
    }
    g.globalAlpha = 1;
    // les etiquettes : les mots les plus courants d'abord, sans chevauchement ; plus on zoome, plus il y en a
    const pris = new Set(), place = (x, y, l) => {
      const cases = []; for (let i = Math.floor(x / 10); i <= Math.floor((x + l) / 10); i++) for (let j = Math.floor((y - 12) / 10); j <= Math.floor((y + 4) / 10); j++) cases.push(i + "," + j);
      if (cases.some((k) => pris.has(k))) return false; cases.forEach((k) => pris.add(k)); return true;
    };
    g.font = "600 12.5px 'DM Sans', sans-serif"; g.textBaseline = "alphabetic"; g.lineJoin = "round";
    const etiquette = (p, fort) => {
      const [x, y] = ecran(p), t = motNet(p.mot);
      g.font = `${fort ? 800 : 600} ${fort ? 14.5 : 12.5}px 'DM Sans', sans-serif`;
      const l = g.measureText(t).width;
      if (!fort && !place(x + 7, y + 4, l)) return;
      g.strokeStyle = "#fffaf0"; g.lineWidth = 4; g.strokeText(t, x + 7, y + 4); g.fillStyle = "#3a3843"; g.fillText(t, x + 7, y + 4);
    };
    forts.forEach((p) => { const [x, y] = ecran(p); g.fillStyle = COULEURS_NATURE[p.type] || "#999"; g.beginPath(); g.arc(x, y, rayon * 1.7, 0, 6.283); g.fill();
      g.strokeStyle = "#24232b"; g.lineWidth = 2; g.stroke(); });
    forts.forEach((p) => { const [x, y] = ecran(p); place(x + 7, y + 4, 60); });
    const limite = 120 * v.z * v.z;
    for (const p of etat.current.parRang) {
      if (p.rang > limite && !(fi && fi === p.type && v.z > 2.5)) break;
      if (p.type === "morceau" || (fi && fi !== p.type)) continue;
      const [x, y] = ecran(p);
      if (x < 0 || y < 0 || x > W || y > H) continue;
      etiquette(p, false);
    }
    forts.forEach((p) => etiquette(p, true));
  };
  const redessiner = () => { if (!raf.current) raf.current = requestAnimationFrame(dessiner); };
  etat.current = { ...etat.current, choisi, trouve: trouve?.mot, survol: survol?.p?.mot, filtre };
  if (points && etat.current.points !== points) {
    etat.current.points = points;
    etat.current.index = new Map(points.map((p) => [p.mot, p]));
    etat.current.parRang = [...points].filter((p) => p.type !== "morceau").sort((a, b) => a.rang - b.rang);
  }
  useEffect(() => { redessiner(); });
  useEffect(() => {
    const c = toile.current;
    if (!c) return;
    const ro = new ResizeObserver(() => redessiner());
    ro.observe(c);
    const molette = (e) => {  // zoom autour de la souris (ecouteur non passif : la page ne defile pas)
      e.preventDefault();
      const r = c.getBoundingClientRect(), s = CARTE_W / r.width, mx = (e.clientX - r.left) * s, my = (e.clientY - r.top) * s, v = vue.current;
      const z = Math.min(40, Math.max(1, v.z * Math.exp(-e.deltaY * 0.0015)));
      vue.current = { z, x: mx - ((mx - v.x) * z) / v.z, y: my - ((my - v.y) * z) / v.z };
      redessiner();
    };
    c.addEventListener("wheel", molette, { passive: false });
    return () => { ro.disconnect(); c.removeEventListener("wheel", molette); };
  }, [points]);
  if (!points) return <div className="chargement" style={{ height: 520, borderRadius: "var(--r-l)" }} />;

  const types = Object.keys(COULEURS_NATURE).filter((t) => points.some((p) => p.type === t));
  const choisir = (p) => fetch(`/api/voisins?mot=${encodeURIComponent(motNet(p.mot))}`).then((r) => r.json()).then(setChoisi);
  const centrer = (p) => { const [x, y] = carteXY(p); vue.current = { z: 6, x: CARTE_W / 2 - x * 6, y: CARTE_H / 2 - y * 6 }; redessiner(); };
  const local = (e) => { const r = toile.current.getBoundingClientRect(); return [e.clientX - r.left, e.clientY - r.top]; };
  const debut = (e) => {
    if (e.button !== 0) return;
    toile.current.setPointerCapture(e.pointerId);  // le glisser continue meme si la souris sort de la carte
    glisse.current = { x: e.clientX, y: e.clientY, v: vue.current, bouge: false, ou: local(e) };
  };
  const pendant = (e) => {
    const g = glisse.current;
    if (g) {
      const s = CARTE_W / toile.current.clientWidth, dx = (e.clientX - g.x) * s, dy = (e.clientY - g.y) * s;
      if (Math.abs(dx) + Math.abs(dy) > 4) g.bouge = true;
      vue.current = { ...g.v, x: g.v.x + dx, y: g.v.y + dy };
      redessiner();
      return;
    }
    const i = plusProche(...local(e));
    const p = i != null ? points[i] : null;
    if ((p?.mot || null) !== (survol?.p?.mot || null) || (p && (Math.abs(e.clientX - (survol?.x || 0)) > 30))) setSurvol(p ? { p, x: e.clientX, y: e.clientY } : null);
  };
  const fin = () => {
    const g = glisse.current;
    glisse.current = null;
    if (!g || g.bouge) return;
    const i = plusProche(...g.ou);  // un simple clic : le point le plus proche de l'endroit ou on a appuye
    if (i != null) choisir(points[i]);
  };
  return (
    <div>
      <div style={{ display: "flex", gap: 10, flexWrap: "wrap", alignItems: "center", marginBottom: 12 }}>
        <input value={cherche} onChange={(e) => setCherche(e.target.value)} placeholder="Chercher un mot (ex. chat)…"
               onKeyDown={(e) => { if (e.key === "Enter" && trouve) { centrer(trouve); choisir(trouve); } }}
               style={{ border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "9px 16px", fontSize: 14, fontFamily: "inherit", outline: "none", background: "var(--surface)", width: 230 }} />
        {cherche && <span style={{ fontSize: 13, color: trouve ? "var(--sarcelle)" : "var(--tomate)" }}>{trouve ? "↵ Entrée pour y aller" : "pas un mot entier de son vocabulaire"}</span>}
        <button className="btn relief" onClick={() => { vue.current = { x: 0, y: 0, z: 1 }; setChoisi(null); redessiner(); }} style={{ background: "var(--creme)", fontSize: 13 }}>⟲ Recentrer</button>
        <span style={{ fontSize: 12.5, color: "var(--doux)" }}>molette = zoom · glisser = se déplacer · clic = ses vrais voisins</span>
      </div>
      {donnees.calcul && <div style={{ fontSize: 12.5, color: "var(--doux)", marginBottom: 10, display: "flex", alignItems: "center", gap: 8 }}>
        <span className="point-direct" style={{ display: "inline-block", width: 8, height: 8, borderRadius: 99, background: "var(--tomate)", animation: "pulse 1.2s infinite" }} />
        Je range les mots par familles de sens (environ 2 minutes, une seule fois)… la carte se mettra à jour toute seule.</div>}
      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 12 }}>
        {types.map((t) => (
          <button key={t} className="btn relief" onClick={() => setFiltre(filtre === t ? null : t)} style={{
            padding: "6px 13px", fontSize: 12.5, background: filtre === t ? COULEURS_NATURE[t] : COULEURS_NATURE[t] + "1f",
            color: filtre === t ? "#fff" : COULEURS_NATURE[t] }}>{t} · {points.filter((p) => p.type === t).length}</button>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: choisi ? "minmax(0,1fr) 260px" : "1fr", gap: 14 }}>
        <canvas ref={toile} onPointerDown={debut} onPointerMove={pendant} onPointerUp={fin} onPointerCancel={() => (glisse.current = null)}
                onPointerLeave={() => setSurvol(null)}
                style={{ width: "100%", aspectRatio: `${CARTE_W} / ${CARTE_H}`, background: "radial-gradient(ellipse at 50% 40%, #fffaf0, var(--creme))", borderRadius: "var(--r-l)",
                         display: "block", cursor: survol ? "pointer" : "grab", touchAction: "none", boxShadow: "inset 0 2px 10px rgba(90,60,20,.08)" }} />
        {choisi && (
          <div className="relief" data-force="2" style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 22, padding: 16, alignSelf: "start", animation: "glisse .35s var(--ease) both" }}>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center" }}>
              <div style={{ fontSize: 12, color: "var(--doux)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".1em" }}>Les plus proches de</div>
              <button onClick={() => setChoisi(null)} style={{ border: 0, background: "transparent", cursor: "pointer", color: "var(--doux)", fontSize: 16 }} title="Fermer">✕</button>
            </div>
            <div className="serif" style={{ fontSize: 26, fontWeight: 800, marginBottom: 8 }}>{motNet(choisi.mot)}</div>
            {choisi.erreur && <div style={{ fontSize: 13, color: "var(--tomate)" }}>{choisi.erreur}</div>}
            {(choisi.voisins || []).map((v) => (
              <button key={v.mot} onClick={() => { const q = points.find((p) => p.mot === v.mot); if (q) { centrer(q); choisir(q); } }}
                      style={{ display: "grid", gridTemplateColumns: "1fr 70px", gap: 8, alignItems: "center", marginBottom: 6, fontSize: 14, width: "100%", border: 0,
                               background: "transparent", cursor: "pointer", textAlign: "left", fontFamily: "inherit", color: "var(--encre)", padding: 0 }} title="Aller à ce mot">
                <span>{motNet(v.mot)}</span>
                <Barre valeur={Math.max(0, v.sim)} couleur="var(--tomate)" hauteur={7} />
              </button>
            ))}
            <div style={{ fontSize: 11.5, color: "var(--doux)", marginTop: 8 }}>Calculé dans son cerveau complet (similarité cosinus), pas sur la carte. Clic sur un voisin pour y aller.</div>
          </div>
        )}
      </div>
      <Bulle x={survol?.x} y={survol?.y}>{survol && <><b>{motNet(survol.p.mot)}</b> · {survol.p.type}<br /><span style={{ opacity: .7 }}>clic : voir ses voisins</span></>}</Bulle>
    </div>
  );
});

/* ------------------------------------------------------------------ innovations */
const BlocInnov = ({ titre, sous, children }) => (
  <div style={{ background: "rgba(127,127,127,.07)", borderRadius: "var(--r-l)", padding: "18px 20px" }}>
    <div className="serif" style={{ fontSize: 19, fontWeight: 800 }}>{titre}</div>
    {sous && <div style={{ fontSize: 13, color: "var(--doux)", margin: "2px 0 12px" }}>{sous}</div>}
    {children}
  </div>
);
const NoeudInnov = ({ n, prof, noeuds }) => (
  <div style={{ marginLeft: prof * 18 }}>
    <div style={{ display: "flex", gap: 10, alignItems: "center", padding: "5px 0", fontSize: 14, flexWrap: "wrap" }}>
      <span style={{ width: 9, height: 9, borderRadius: 9, background: prof ? "var(--sarcelle)" : "var(--tomate)", flex: "none" }} />
      <b>{n.nom}</b><span style={{ color: "var(--doux)" }}>{fmtNb(n.taille)} neurones/couche</span>
      {n.conflits > 0 && <span style={{ fontSize: 12, color: "var(--moutarde)" }}>tension {n.conflits}/3</span>}
    </div>
    {noeuds.filter((e) => e.parent === n.nom).map((e) => <NoeudInnov key={e.nom} n={e} prof={prof + 1} noeuds={noeuds} />)}
  </div>
);
const Innovations = React.memo(function Innovations({ etat }) {
  const [d, setD] = useState(null);
  useEffect(() => {
    const lire = () => fetch("/api/innovations").then((r) => r.ok ? r.json() : Promise.reject()).then(setD).catch(() => setD((x) => x || false));
    lire();
    const t = setInterval(lire, 30000);
    return () => clearInterval(t);
  }, [etat.version]);
  if (d === false) return <div style={{ padding: "40px 10px", textAlign: "center", color: "var(--doux)", fontSize: 15 }}>Les innovations arrivent au prochain redémarrage de Jexa.</div>;
  if (!d) return <div className="chargement" style={{ height: 420, borderRadius: "var(--r-l)" }} />;
  const cats = Object.entries(d.cours);
  const maxEx = Math.max(1, ...cats.map(([, v]) => v.exercices));
  const noeuds = d.mitose.noeuds || [];
  const racines = noeuds.filter((n) => !n.parent || !noeuds.some((m) => m.nom === n.parent));
  const nuits = d.reves.nuits || [];
  const maxNuit = Math.max(1, ...nuits.map((x) => x.trouvees));
  const g = d.gravure || {};
  const gh = (g.historique || []).slice(-1)[0];
  const niv = d.effort.niveaux || {};
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        <Tuile label="Cours" valeur={fmtNb(d.total_cours)} sous={`${fmtNb(d.total_exercices)} exercices`} couleur="var(--tomate)" />
        <Tuile label="Régions" valeur={fmtNb(noeuds.length)} sous="nées par matière ou par mitose" couleur="var(--sarcelle)" />
        <Tuile label="Jumeau critique" valeur={pct(d.critique.auc, 0)} sous={`repère ses erreurs (AUC) · ${fmtNb(d.critique.n || 0)} exemples`} couleur="var(--bleu)" />
        <Tuile label="Neurones gravés" valeur={fmtNb(g.neurones || 0)} sous={`${fmtNb(g.groupes || 0)} réponses prouvées`} couleur="var(--prune)" />
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(300px, 100%), 1fr))", gap: 16 }}>
        <BlocInnov titre="Les cours" sous="Chaque matière, ses exercices, et les révisions qu'elle s'écrit elle-même">
          {cats.map(([k, v]) => (
            <div key={k} style={{ margin: "7px 0" }}>
              <div style={{ display: "flex", justifyContent: "space-between", gap: 8, fontSize: 13.5 }}>
                <b>{k}</b><span style={{ color: "var(--doux)", textAlign: "right" }}>{v.cours} cours · {fmtNb(v.exercices)} ex.{v.revisions ? ` · ${v.revisions} révisions` : ""}</span>
              </div>
              <div style={{ height: 6, borderRadius: 6, background: "rgba(127,127,127,.15)", marginTop: 4 }}>
                <div style={{ width: `${(v.exercices / maxEx) * 100}%`, height: "100%", borderRadius: 6, background: "var(--sarcelle)" }} />
              </div>
            </div>
          ))}
        </BlocInnov>
        <BlocInnov titre="La mitose" sous={d.mitose.actif ? "Une région qui se contredit se divise en deux" : "En pause"}>
          {racines.map((n) => <NoeudInnov key={n.nom} n={n} prof={0} noeuds={noeuds} />)}
          {(d.mitose.historique || []).slice(-4).reverse().map((h, i) => (
            <div key={i} style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 6 }}>cycle {h.cycle} · {h.type === "fusion" ? `fusion de ${h.fille} dans ${h.mere}` : `${h.mere} → ${h.fille}`}</div>
          ))}
        </BlocInnov>
        <BlocInnov titre="Le sommeil contradictoire" sous="La même question posée autrement : si ses réponses diffèrent, elle révise">
          <div style={{ display: "flex", gap: 3, alignItems: "flex-end", height: 70 }}>
            {nuits.map((n, i) => (
              <div key={i} title={`cycle ${n.cycle} : ${n.trouvees} contradictions, ${n.resolues} tranchées`}
                   style={{ flex: 1, height: `${(n.trouvees / maxNuit) * 100}%`, minHeight: 2, background: "var(--moutarde)", borderRadius: 3 }} />
            ))}
          </div>
          <div style={{ fontSize: 13, marginTop: 10 }}>
            {Object.entries(d.reves.contradictions).slice(0, 5).map(([k, v]) => <div key={k} style={{ color: "var(--doux)" }}>{k.replace(/^cours_/, "").replaceAll("_", " ")} · {v}</div>)}
          </div>
        </BlocInnov>
        <BlocInnov titre="Son propre professeur" sous="Elle réécrit le cours qu'elle rate le plus, avec des exercices neufs">
          {d.prof.length ? d.prof.slice().reverse().map((p, i) => (
            <div key={i} style={{ fontSize: 13.5, margin: "6px 0" }}><b>{p.titre}</b><span style={{ color: "var(--doux)" }}> · {p.rates} ratés gardés, {p.reussis} déjà sus</span></div>
          )) : <div style={{ fontSize: 13.5, color: "var(--doux)" }}>Pas encore de révision écrite.</div>}
        </BlocInnov>
        <BlocInnov titre="Le cœur qui dose l'effort" sous="Léger pour « salut », intense quand c'est dur ou qu'elle doute">
          {["leger", "normal", "intense"].map((k) => niv[k] && (
            <div key={k} style={{ display: "flex", justifyContent: "space-between", fontSize: 13.5, margin: "6px 0" }}>
              <b>{k === "leger" ? "Léger" : k === "normal" ? "Normal" : "Intense"}</b>
              <span style={{ color: "var(--doux)" }}>{fmtNb(niv[k].reponses)} réponses · {fmtNb(niv[k].ms_moyen)} ms</span>
            </div>
          ))}
          <div style={{ fontSize: 13, color: "var(--doux)", marginTop: 8 }}>{d.effort.relances || 0} relance{(d.effort.relances || 0) > 1 ? "s" : ""} quand elle doutait, dont {d.effort.relances_utiles || 0} utile{(d.effort.relances_utiles || 0) > 1 ? "s" : ""}</div>
        </BlocInnov>
        <BlocInnov titre="L'aiguilleur prophète" sous="Il devine quelles régions serviront au prochain message et les prépare à l'avance">
          {d.prophete && d.prophete.stats && d.prophete.stats.messages ? <>
            <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>
              {fmtNb(d.prophete.stats.messages)} messages observés · prédictions justes : <b>{pct(d.prophete.stats.precision, 0)}</b>
              {" "}· {fmtNb(d.prophete.stats.evitees || 0)} chargements disque évités
            </div>
            {(d.prophete.liens || []).slice(0, 5).map((l, i) => (
              <div key={i} style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 4 }}>{l.de} → {l.vers} · {l.force}</div>
            ))}
          </> : <div style={{ fontSize: 13.5, color: "var(--doux)" }}>Il apprend en regardant les prochaines conversations.</div>}
        </BlocInnov>
        <BlocInnov titre="Les neurones gravés par la preuve" sous="Écrits directement, gardés seulement s'ils réussissent sans rien abîmer">
          {gh ? <div style={{ fontSize: 13.5, lineHeight: 1.6 }}>
            Dernière séance (cycle {gh.cycle}) : <b>{gh.graves}</b> réponse{gh.graves > 1 ? "s" : ""} gravée{gh.graves > 1 ? "s" : ""} sur {gh.echecs} erreur{gh.echecs > 1 ? "s" : ""},
            {" "}{gh.abimeraient} refusées car elles changeaient d'autres réponses, {gh.indiscernables} trop proches d'autres questions,
            {" "}<b>{gh.appris}</b> effacées car apprises pour de vrai.
          </div> : <div style={{ fontSize: 13.5, color: "var(--doux)" }}>Première gravure au prochain cycle.</div>}
          {(g.exemples || []).slice(-3).map((e, i) => (
            <div key={i} style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 6, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{e.lecon.replace(/^cours_/, "")} → {e.reponse}</div>
          ))}
        </BlocInnov>
      </div>
    </div>
  );
});

/* ------------------------------------------------------------------ architecture détaillée */
const Architecture2 = React.memo(function Architecture2({ etat }) {
  const [a, setA] = useState(null);
  const [survol, setSurvol] = useState(null);
  useEffect(() => { fetch("/api/architecture").then((r) => r.json()).then(setA); }, [etat.version]);
  if (!a) return <div className="chargement" style={{ height: 420, borderRadius: "var(--r-l)" }} />;
  const g = a.genome, m = etat.meta;
  const palette = ["#5b80a5", "#93ad8f", "#2f6f6a", "#5f9e96", "#dfa92f", "#d65f37", "#9d6390", "#bf8450"];
  const coul = (nom) => nom.includes("embedding") ? palette[0] : nom.includes("Positions") ? palette[1] : nom.includes("attention") ? palette[2] :
                        nom.includes("réseau") ? palette[4] : nom.includes("sortie") ? palette[5] : palette[7];
  const blocs = Array.from({ length: g.layers }, (_, i) => a.parties.filter((p) => p.nom.startsWith(`Bloc ${i + 1} `)));
  const strats = Object.entries(a.strategies);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        <Tuile label="Paramètres" valeur={fmtMo(a.total)} sous={`${fmtNb(a.total)} nombres réglés`} couleur="var(--tomate)" />
        <Tuile label="Taille en mémoire" valeur={`${a.memoire_mo.toString().replace(".", ",")} Mo`} sous="en 32 bits" />
        <Tuile label="Vocabulaire" valeur={fmtNb(a.vocab)} sous="morceaux de mots" couleur="var(--bleu)" />
        <Tuile label="Mémoire de travail" valeur={`${a.max_len}`} sous="morceaux lus d'un coup" couleur="var(--sarcelle)" />
        <Tuile label="Blocs × têtes" valeur={`${g.layers} × ${g.heads}`} sous={`${a.tete_dim} dimensions par tête`} couleur="var(--moutarde)" />
      </div>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 8 }}>Où sont ses {fmtMo(a.total)} paramètres ?</h3>
        <div style={{ display: "flex", height: 34, borderRadius: 99, overflow: "hidden", boxShadow: "var(--ombre-3d)" }}>
          {a.parties.map((p) => (
            <div key={p.nom} onMouseMove={(e) => setSurvol({ p, x: e.clientX, y: e.clientY })} onMouseLeave={() => setSurvol(null)}
                 style={{ width: `${p.part * 100}%`, background: coul(p.nom), opacity: survol && survol.p !== p ? 0.55 : 1, transition: "opacity .2s",
                          borderRight: "1px solid rgba(255,255,255,.35)" }} />
          ))}
        </div>
        <div style={{ display: "flex", gap: 14, flexWrap: "wrap", marginTop: 8, fontSize: 12.5, color: "var(--doux)" }}>
          {[["Mots → vecteurs", palette[0]], ["Positions", palette[1]], ["Attention", palette[2]], ["Réseaux internes", palette[4]], ["Sortie", palette[5]], ["Normalisations", palette[7]]].map(([n, c]) => (
            <span key={n}><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 3, background: c, marginRight: 5 }} />{n}</span>
          ))}
        </div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1.2fr) minmax(0, 1fr)", gap: 22 }} className="grille-labo">
        <div>
          <h3 style={{ fontSize: 19, marginBottom: 10 }}>Le chemin d'une pensée, de bas en haut</h3>
          <div style={{ display: "flex", flexDirection: "column-reverse", gap: 7 }}>
            <Etage2 texte={`Les morceaux deviennent des vecteurs de ${g.d_model} nombres`} params={a.parties.filter((p) => p.nom.includes("embedding") || p.nom.includes("Positions"))} fond="var(--bleu-c)" setSurvol={setSurvol} />
            {blocs.map((parts, i) => (
              <div key={i} className="relief" data-force="2" style={{ background: "var(--sarcelle-c)", borderRadius: 22, padding: "10px 14px", animation: `monte .4s ${i * 60}ms var(--ease) both` }}
                   onMouseMove={(e) => setSurvol({ bloc: i + 1, parts, x: e.clientX, y: e.clientY })} onMouseLeave={() => setSurvol(null)}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <b style={{ color: "var(--sarcelle)", fontSize: 13.5 }}>Bloc {i + 1}</b>
                  <div style={{ display: "flex", gap: 4 }}>{Array.from({ length: g.heads }, (_, h) => <span key={h} title={`tête d'attention ${h + 1}`}
                    style={{ width: 16, height: 16, borderRadius: 99, background: "var(--sarcelle)", opacity: 0.55 + 0.45 * ((h + 1) / g.heads) }} />)}</div>
                  <span className="pill" style={{ background: "#fff", fontSize: 11.5, padding: "2px 9px" }}>réseau {g.d_model} → {a.ffn} → {g.d_model} · {g.activation}</span>
                  <span className="mono" style={{ marginLeft: "auto", fontSize: 12, color: "var(--doux)" }}>{fmtMo(parts.reduce((s, p) => s + p.params, 0))}</span>
                </div>
              </div>
            ))}
            <Etage2 texte="Choix du morceau suivant parmi tout le vocabulaire" params={a.parties.filter((p) => p.nom.includes("sortie") || p.nom.includes("finale"))} fond="var(--tomate-c)" setSurvol={setSurvol} />
          </div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 12 }}>
            {[["taux d'apprentissage", g.lr.toExponential(1)], ["pas par essai", fmtNb(g.steps)], ["lot", g.batch], ["échauffement", fmtPct(g.warmup, 0)],
              ["dropout", g.dropout.toFixed(2)], ["weight decay", g.weight_decay.toFixed(3)], ["héritage", g.heritage ? "oui" : "non"], ["calcul", "bfloat16"]]
              .map(([k, v]) => <span key={k} className="pill mono" style={{ background: "var(--creme)", fontWeight: 500, fontSize: 12 }}>{k} <b>{v}</b></span>)}
          </div>
        </div>
        <div>
          <h3 style={{ fontSize: 19, marginBottom: 10 }}>Ses stratégies pour s'améliorer</h3>
          <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
            {strats.sort((x, y) => y[1].gagnes - x[1].gagnes).map(([s, v]) => (
              <div key={s} className="relief" data-force="2.5" style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 18, padding: "10px 14px" }}>
                <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
                  <b>{(STRATEGIES[s] || [s])[0]}</b>
                  <span className="mono" style={{ fontSize: 12.5 }}>{v.gagnes}/{v.essais} réussis · {fmtPct(v.essais ? v.gagnes / v.essais : 0, 0)}</span>
                </div>
                <div style={{ fontSize: 12.5, color: "var(--doux)", margin: "2px 0 6px" }}>{(STRATEGIES[s] || ["", ""])[1]} · utilisée {fmtPct((m.strategies[s] || 0) / Object.values(m.strategies).reduce((x, y) => x + y, 0), 0)} du temps
                  {v.gagnes ? ` · gain moyen +${(v.gain / v.gagnes * 100).toFixed(1)} pts` : ""}</div>
                <Barre valeur={v.essais ? v.gagnes / v.essais : 0} couleur="var(--moutarde)" hauteur={8} />
              </div>
            ))}
          </div>
          <h3 style={{ fontSize: 19, margin: "20px 0 6px" }}>Se connaît-elle ?</h3>
          <div style={{ fontSize: 13, color: "var(--doux)", marginBottom: 6 }}>Écart entre le score qu'elle prédit pour chaque essai et le vrai (plus bas = elle se connaît mieux).</div>
          <div style={{ background: "var(--creme)", borderRadius: 20, padding: "12px 8px 4px" }}>
            <Graphe hauteur={170} yMin={0} formatY={(v) => `${(v * 100).toFixed(1).replace(".", ",")} pts`} titreX="essai" series={[
              { nom: "écart", couleur: "#c9bfae", ligne: false, rayon: 2.5, points: a.erreur_miroir.map((e, i) => ({ x: i + 1, y: e, info: <>essai n°{i + 1}</> })) },
              { nom: "moyenne glissante", couleur: "#5b80a5", rayon: 0.01, points: lisser(a.erreur_miroir, 8).map((e, i) => ({ x: i + 1, y: e, info: <>moyenne des 8 derniers essais</> })) },
            ]} />
          </div>
        </div>
      </div>
      <Bulle x={survol?.x} y={survol?.y}>
        {survol?.p && <><b>{survol.p.nom}</b><br />{fmtNb(survol.p.params)} paramètres · {fmtPct(survol.p.part)} du cerveau</>}
        {survol?.bloc && <><b>Bloc {survol.bloc}</b>{survol.parts.map((p) => <div key={p.nom}>{p.nom.split("· ")[1]} : {fmtNb(p.params)}</div>)}</>}
        {survol?.etage && <><b>{survol.etage}</b>{survol.parts.map((p) => <div key={p.nom}>{p.nom} : {fmtNb(p.params)}</div>)}</>}
      </Bulle>
    </div>
  );
}, (a, b) => a.etat.version === b.etat.version);
const Etage2 = ({ texte, params, fond, setSurvol }) => (
  <div className="relief" data-force="2" onMouseMove={(e) => setSurvol({ etage: texte, parts: params, x: e.clientX, y: e.clientY })} onMouseLeave={() => setSurvol(null)}
       style={{ background: fond, borderRadius: 99, padding: "11px 18px", fontSize: 13.5, fontWeight: 700, display: "flex", justifyContent: "space-between", gap: 10 }}>
    <span>{texte}</span><span className="mono" style={{ fontWeight: 500, color: "var(--doux)" }}>{fmtMo(params.reduce((s, p) => s + p.params, 0))}</span>
  </div>
);

/* ------------------------------------------------------------------ l'histoire complète */
const Histoire2 = React.memo(function Histoire2({ etat }) {
  const [ouverte, setOuverte] = useState(null);
  const ess = etat.tous_essais || [];
  const pts = ess.map((e, i) => ({ ...e, i: i + 1 }));
  const vs = etat.versions;
  const coulStrat = { mutation: "#5b80a5", faiblesse: "#d65f37", croisement: "#9d6390", audace: "#dfa92f", naissance: "#2f6f6a" };
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 22 }}>
      <div style={{ display: "flex", gap: 12, flexWrap: "wrap" }}>
        <Tuile label="Essais" valeur={fmtNb(ess.length)} sous="variantes testées" />
        <Tuile label="Versions" valeur={vs.length} sous="retenues" couleur="var(--tomate)" />
        <Tuile label="Taux de réussite" valeur={fmtPct(ess.length ? (vs.length - 1) / Math.max(1, ess.length - 1) : 0, 0)} sous="variantes meilleures" couleur="var(--sarcelle)" />
        <Tuile label="Temps d'entraînement" valeur={`${Math.round(ess.reduce((s, e) => s + (e.secondes || 0), 0) / 3600 * 10) / 10} h`.replace(".", ",")} sous="cumulé" couleur="var(--bleu)" />
      </div>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 4 }}>Chaque essai, gardé ou refusé</h3>
        <div style={{ fontSize: 13, color: "var(--doux)", marginBottom: 8 }}>Les gros points = versions retenues. Couleur = stratégie. Les chutes = un nouveau niveau, plus difficile (ou de nouveaux cours).</div>
        <div style={{ background: "var(--creme)", borderRadius: 22, padding: "16px 12px 6px" }}>
          <Graphe hauteur={280} titreX="essai n°" series={[
            { nom: "variante", couleur: "#c9bfae", ligne: false, rayon: 3,
              points: pts.filter((e) => !e.accepte).map((e) => ({ x: e.i, y: e.score, couleur: coulStrat[e.strategie] + "88",
                info: <>essai n°{e.i} · cycle {e.cycle} · niveau {e.niveau}<br />{(STRATEGIES[e.strategie] || [e.strategie])[0]} : {e.changements.join(", ") || "—"}<br />
                  {e.predit != null && <>prédit {fmtPct(e.predit)} · </>}{e.secondes ? `${Math.round(e.secondes)} s` : ""} · <span style={{ color: "#f6b8a4" }}>non retenue</span></> })) },
            { nom: "version retenue", couleur: "#d65f37", rayon: 6,
              points: pts.filter((e) => e.accepte).map((e) => ({ x: e.i, y: e.score, couleur: coulStrat[e.strategie],
                info: <>v{e.version} · cycle {e.cycle} · niveau {e.niveau}<br />{(STRATEGIES[e.strategie] || [e.strategie])[0]} : {e.changements.join(", ") || "—"}<br />
                  {e.predit != null && <>prédit {fmtPct(e.predit)} · </>}{fmtMo(e.params)} paramètres</> })) },
          ]} />
        </div>
        <div style={{ display: "flex", gap: 12, flexWrap: "wrap", marginTop: 8, fontSize: 12.5, color: "var(--doux)" }}>
          {Object.entries(coulStrat).map(([s, c]) => <span key={s}><span style={{ display: "inline-block", width: 10, height: 10, borderRadius: 9, background: c, marginRight: 5 }} />{(STRATEGIES[s] || [s])[0]}</span>)}
        </div>
      </div>
      <div>
        <h3 style={{ fontSize: 19, marginBottom: 10 }}>Ses versions (clique pour voir ce qui a changé)</h3>
        <div style={{ display: "flex", flexDirection: "column", gap: 8 }}>
          {[...vs].reverse().map((v, k) => {
            const avant = vs[vs.length - 2 - k];
            const deltas = avant ? Object.entries(v.scores || {}).map(([n, s]) => [n, s - ((avant.scores || {})[n] ?? s)]).filter(([, d]) => Math.abs(d) >= 0.005)
                                   .sort((a, b) => Math.abs(b[1]) - Math.abs(a[1])) : [];
            const ouv = ouverte === v.v;
            return (
              <div key={v.v} className="relief" data-force="1.5" onClick={() => setOuverte(ouv ? null : v.v)}
                   style={{ background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 20, padding: "12px 16px", cursor: "pointer" }}>
                <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>
                  <span className="serif" style={{ fontSize: 22, fontWeight: 800, color: "var(--tomate)", width: 56 }}>v{v.v}</span>
                  <span className="mono" style={{ fontSize: 14 }}>{fmtPct(v.score)}</span>
                  <span className="pill" style={{ background: coulStrat[v.strategie] + "22", color: coulStrat[v.strategie], fontSize: 12 }}>{(STRATEGIES[v.strategie] || [v.strategie])[0]}</span>
                  <span style={{ fontSize: 12.5, color: "var(--doux)" }}>cycle {v.cycle} · {fmtMo(v.params)} param. · {new Date(v.t * 1000).toLocaleString("fr-FR", { dateStyle: "short", timeStyle: "short" })}</span>
                  <span style={{ marginLeft: "auto", color: "var(--doux)", transform: ouv ? "rotate(180deg)" : "none", transition: "transform .3s" }}>▾</span>
                </div>
                <div className="mono" style={{ fontSize: 12, color: "var(--doux)", marginTop: 2 }}>{v.changements.join(", ") || "—"}</div>
                <div style={{ display: "grid", gridTemplateRows: ouv ? "1fr" : "0fr", transition: "grid-template-rows .35s var(--ease)" }}>
                  <div style={{ overflow: "hidden" }}>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 10 }}>
                      {!avant && <span style={{ fontSize: 13, color: "var(--doux)" }}>Sa naissance.</span>}
                      {avant && !deltas.length && <span style={{ fontSize: 13, color: "var(--doux)" }}>Changements trop fins pour être visibles leçon par leçon.</span>}
                      {deltas.map(([n, d]) => (
                        <span key={n} className="pill" style={{ background: d > 0 ? "var(--sarcelle-c)" : "var(--tomate-c)", color: d > 0 ? "var(--sarcelle)" : "var(--tomate)", fontSize: 12 }}>
                          {NOMS_LECONS[n] || n} {d > 0 ? "+" : ""}{(d * 100).toFixed(1).replace(".", ",")}</span>
                      ))}
                    </div>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
      </div>
    </div>
  );
}, (a, b) => a.etat.version === b.etat.version && (a.etat.tous_essais || []).length === (b.etat.tous_essais || []).length);

/* ------------------------------------------------------------------ le réseau vivant, réaliste (vraies activations, vraie attention) */
function ReseauReel({ pensee, setPensee }) {
  const cv = useRef(null);
  const [survol, setSurvol] = useState(null);
  const [couche, setCouche] = useState(null);
  useEffect(() => {  // pas encore de pensée : on lui pose une petite question pour voir son cerveau travailler
    if (pensee?.attention?.length) return;
    (async () => {
      const monde = await (await fetch("/api/monde")).json();
      const q = `où est ${monde[0].texte.split(" ").slice(0, 2).join(" ").toLowerCase()} ?`;
      const r = await (await fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: q, monde, historique: [] }) })).json();
      if (r.jetons && r.attention?.length) setPensee({ ...r, question: q });
    })();
  }, [pensee]);
  const data = useMemo(() => {
    if (!pensee?.attention?.length) return null;
    const n = pensee.jetons.length, garde = Math.min(18, n), d0 = n - garde;  // les derniers jetons (la question et la réponse)
    const L = pensee.activite.length;  // entrée + chaque bloc
    const act = pensee.activite.map((row) => row.slice(d0));
    const maxParCouche = act.map((row) => Math.max(...row));
    const att = pensee.attention.map((couche) => couche[0].map((_, i) => couche[0][i].map((_, j) => moyenne(couche.map((h) => h[i][j]))))
                                 .slice(d0).map((row) => row.slice(d0)));
    return { garde, L, act, maxParCouche, att, jetons: pensee.jetons.slice(d0).map((w) => w.replace("▁", "").replace(/^<lecon:/, "<")),
             debut: pensee.debut_reponse - d0 };
  }, [pensee]);
  useEffect(() => {
    if (!data) return;
    const c = cv.current, ctx = c.getContext("2d");
    let raf, W, H;
    const dpr = devicePixelRatio || 1;
    const taille = () => { W = c.clientWidth; H = c.clientHeight; c.width = W * dpr; c.height = H * dpr; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); };
    taille(); addEventListener("resize", taille);
    const gx = 120, dx = () => (W - gx - 40) / (data.L - 1), dy = () => (H - 50) / Math.max(1, data.garde - 1);
    const pos = (l, t) => [gx + l * dx(), 25 + t * dy()];
    // liens : pour chaque jeton de chaque couche, ses 2 liens d'attention les plus forts vers la couche précédente
    const liens = [];
    for (let l = 1; l < data.L; l++)
      for (let i = 0; i < data.garde; i++) {
        const row = data.att[l - 1][i];
        row.map((w, j) => [w, j]).filter(([, j]) => j <= i).sort((a, b) => b[0] - a[0]).slice(0, 2).forEach(([w, j]) => liens.push({ l, i, j, w }));
      }
    const parts = liens.flatMap((k) => (k.w > 0.15 ? [{ k, t: Math.random() }] : []));
    c.__liens = liens; c.__pos = pos;
    const frame = (now) => {
      ctx.clearRect(0, 0, W, H);
      const foc = couche;
      for (const k of liens) {
        const [x1, y1] = pos(k.l - 1, k.j), [x2, y2] = pos(k.l, k.i);
        const actif = foc == null || foc === k.l;
        ctx.strokeStyle = `rgba(47,111,106,${(actif ? 0.08 : 0.02) + k.w * (actif ? 0.65 : 0.1)})`; ctx.lineWidth = 0.6 + k.w * 3;
        ctx.beginPath(); ctx.moveTo(x1, y1); ctx.bezierCurveTo((x1 + x2) / 2, y1, (x1 + x2) / 2, y2, x2, y2); ctx.stroke();
      }
      for (const p of parts) {  // l'information qui circule, plus vite sur les liens forts
        p.t += 0.006 + p.k.w * 0.02;
        if (p.t > 1) p.t = 0;
        const [x1, y1] = pos(p.k.l - 1, p.k.j), [x2, y2] = pos(p.k.l, p.k.i), u = p.t, e = u * u * (3 - 2 * u);
        ctx.fillStyle = `rgba(223,169,47,${0.4 + p.k.w * 0.6})`;
        ctx.beginPath(); ctx.arc(x1 + (x2 - x1) * u, y1 + (y2 - y1) * e, 1.6 + p.k.w * 2.4, 0, 6.28); ctx.fill();
      }
      for (let l = 0; l < data.L; l++)
        for (let t = 0; t < data.garde; t++) {
          const [x, y] = pos(l, t), a = data.act[l][t] / data.maxParCouche[l];
          const rep = t >= data.debut;
          const respire = 1 + 0.06 * Math.sin(now / 500 + l + t);
          const [r, g, b] = rep ? [214, 95, 55] : l === 0 ? [91, 128, 165] : [47, 111, 106];
          ctx.fillStyle = `rgba(${r},${g},${b},${0.12 + a * 0.18})`; ctx.beginPath(); ctx.arc(x, y, (5 + a * 8) * respire + 5, 0, 6.28); ctx.fill();
          ctx.fillStyle = `rgba(${r},${g},${b},${0.45 + a * 0.55})`; ctx.beginPath(); ctx.arc(x, y, (3 + a * 6) * respire, 0, 6.28); ctx.fill();
        }
      ctx.font = "12px DM Mono"; ctx.textAlign = "right";
      data.jetons.forEach((w, t) => { const [, y] = pos(0, t); ctx.fillStyle = t >= data.debut ? "#d65f37" : "#706a77"; ctx.fillText(w.slice(0, 14), gx - 18, y + 4); });
      ctx.textAlign = "center"; ctx.font = "700 11px DM Sans"; ctx.fillStyle = "#706a77";
      for (let l = 0; l < data.L; l++) ctx.fillText(l === 0 ? "ENTRÉE" : `BLOC ${l}`, pos(l, 0)[0], H - 6);
      raf = requestAnimationFrame(frame);
    };
    raf = requestAnimationFrame(frame);
    return () => { cancelAnimationFrame(raf); removeEventListener("resize", taille); };
  }, [data, couche]);
  if (!data) return <div className="chargement" style={{ height: 460, borderRadius: "var(--r-l)" }} />;
  const bouge = (e) => {
    const r = cv.current.getBoundingClientRect(), mx = e.clientX - r.left, my = e.clientY - r.top;
    let best = null, d = 22;
    for (let l = 0; l < data.L; l++) for (let t = 0; t < data.garde; t++) {
      const [x, y] = cv.current.__pos(l, t), dd = Math.hypot(x - mx, y - my);
      if (dd < d) { d = dd; best = { l, t }; }
    }
    setSurvol(best ? { ...best, x: e.clientX, y: e.clientY } : null);
    setCouche(best ? best.l || null : null);
  };
  const s = survol;
  const sources = s && s.l > 0 ? data.att[s.l - 1][s.t].map((w, j) => [w, j]).filter(([, j]) => j <= s.t).sort((a, b) => b[0] - a[0]).slice(0, 3) : [];
  return (
    <div>
      <div style={{ fontSize: 14, color: "var(--doux)", marginBottom: 10 }}>
        Sa vraie pensée en répondant à <i>« {pensee.question || "…"} »</i>. Chaque ligne = un morceau de texte, chaque colonne = une couche de son cerveau.
        La <b>taille</b> d'un neurone = son activité réelle ; les <b>liens</b> = l'attention réelle (où elle regarde) ; en <span style={{ color: "var(--tomate)" }}>orange</span>, sa réponse.
        Survole un neurone pour l'examiner.
      </div>
      <canvas ref={cv} onMouseMove={bouge} onMouseLeave={() => { setSurvol(null); setCouche(null); }}
              style={{ width: "100%", height: 34 * data.garde + 40, background: "radial-gradient(ellipse at 50% 30%, #fffaf0, var(--creme))", borderRadius: "var(--r-l)",
                       display: "block", boxShadow: "inset 0 2px 10px rgba(90,60,20,.08)", cursor: "crosshair" }} />
      <Bulle x={s?.x} y={s?.y}>{s && <>
        <b>« {data.jetons[s.t]} »</b> · {s.l === 0 ? "entrée" : `bloc ${s.l}`}<br />
        activité {fmtPct(data.act[s.l][s.t] / data.maxParCouche[s.l], 0)} du maximum de la couche
        {sources.length > 0 && <><br />regarde surtout : {sources.map(([w, j]) => `« ${data.jetons[j]} » ${fmtPct(w, 0)}`).join(", ")}</>}
      </>}</Bulle>
    </div>
  );
}

function Cerveau({ etat, pensee, setPensee, vue, setVue }) {
  return (
    <Carte titre="Son cerveau, en temps réel" accent="var(--sarcelle)" delai={240} sous="Tout ce que tu vois est calculé à partir de son vrai cerveau"
           actions={<Onglets valeur={vue} onChange={setVue} options={[["reseau", "Réseau vivant"], ["pensee", "Attention"],
                     ["carte", "Carte des mots"], ["archi", "Architecture"], ["innov", "Innovations"], ["histoire", "Histoire"]]} />}>
      <div key={vue} style={{ animation: "monte .4s var(--ease) both" }}>
        {vue === "reseau" && <ReseauReel pensee={pensee} setPensee={setPensee} />}
        {vue === "pensee" && <Pensee pensee={pensee} />}
        {vue === "carte" && <CarteMots2 version={etat.version} />}
        {vue === "archi" && <Architecture2 etat={etat} />}
        {vue === "innov" && <Innovations etat={etat} />}
        {vue === "histoire" && <Histoire2 etat={etat} />}
      </div>
    </Carte>
  );
}

/* ================================================================== annonces */
function Annonces({ annonces }) {
  return (
    <div style={{ position: "fixed", right: 22, bottom: 22, display: "flex", flexDirection: "column", gap: 10, zIndex: 50 }}>
      {annonces.map((a) => (
        <div key={a.id} style={{ background: a.type === "niveau" ? "var(--moutarde)" : "var(--encre)", color: a.type === "niveau" ? "var(--encre)" : "var(--papier)",
                                 borderRadius: 26, padding: "16px 22px", minWidth: 260, boxShadow: "0 20px 40px -18px #000a",
                                 animation: "pop .6s var(--ease) both", display: "flex", gap: 14, alignItems: "center" }}>
          <span style={{ fontSize: 26 }}>{a.type === "niveau" ? "★" : "✦"}</span>
          <div>
            <div className="serif" style={{ fontSize: 19, fontWeight: 800 }}>{a.texte}</div>
            {a.detail && <div style={{ fontSize: 13, opacity: .8 }}>{a.detail}</div>}
          </div>
        </div>
      ))}
    </div>
  );
}

/* ================================================================== app */
const DAMIER = "repeating-conic-gradient(#e8dcc3 0 25%, #fcf8f0 0 50%) 0 0 / 12px 12px";

function Nouveaute({ v }) {
  if (v == null) return null;
  const copie = v < 0.08;
  return <div title="Différence avec la texture la plus proche qu'elle a vue (0 % = copie exacte)"
              style={{ fontSize: 10.5, fontWeight: 700, marginTop: 2, color: copie ? "var(--tomate)" : v < 0.25 ? "var(--doux)" : "var(--sarcelle)" }}>
    {copie ? "copie" : "inventé"} · {Math.round(v * 100)} %</div>;
}

function Dessin({ img, nom, nouveaute, choisi }) {
  return (
    <div title={nom} style={{ textAlign: "center", opacity: choisi === false ? 0.35 : 1, transition: "opacity .4s",
                              outline: choisi ? "3px solid var(--tomate)" : "none", outlineOffset: 2, borderRadius: 10 }}>
      {img ? <img src={img} alt={nom} style={{ width: "100%", aspectRatio: "1", imageRendering: "pixelated", borderRadius: 10, background: DAMIER, display: "block" }} />
           : <div style={{ width: "100%", aspectRatio: "1", borderRadius: 10, background: DAMIER, opacity: 0.5 }} />}
      {nom && <div style={{ fontSize: 11, color: "var(--doux)", marginTop: 3, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{nom}</div>}
      <Nouveaute v={nouveaute} />
    </div>
  );
}

function RegarderDessiner() {
  const [nom, setNom] = useState("pomme minecraft");
  const [imgs, setImgs] = useState([]);
  const [mots, setMots] = useState(null);
  const [encours, setEncours] = useState(false);
  const [erreur, setErreur] = useState("");
  const [guidage, setGuidage] = useState(2);
  const [nouv, setNouv] = useState([]);
  const [choisis, setChoisis] = useState(null);
  const source = useRef(null);
  useEffect(() => () => source.current && source.current.close(), []);
  const lancer = () => {
    if (source.current) source.current.close();
    setImgs([]); setMots(null); setErreur(""); setEncours(true); setNouv([]); setChoisis(null);
    const es = new EventSource("/api/direct/dessin?nom=" + encodeURIComponent(nom) + "&guidage=" + guidage);
    source.current = es;
    es.onmessage = (e) => {
      const d = JSON.parse(e.data);
      if (d.erreur) { setErreur(d.erreur); setEncours(false); es.close(); }
      if (d.mots) setMots(d.mots);
      if (d.images) setImgs(d.images);
      if (d.nouveaute) setNouv(d.nouveaute);
      if (d.choisis) setChoisis(d.choisis);
      if (d.fini) { setEncours(false); es.close(); }
    };
    es.onerror = () => { setEncours(false); es.close(); };
  };
  return (
    <div>
      <div style={{ display: "flex", gap: 8, marginBottom: 10 }}>
        <input value={nom} onChange={(e) => setNom(e.target.value)} placeholder="une pomme · une vraie pomme (photo) · une épée en diamant…" onKeyDown={(e) => e.key === "Enter" && !encours && lancer()}
               style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "7px 14px", fontFamily: "inherit", background: "var(--surface)" }} />
        <button className="btn relief" disabled={encours} onClick={lancer} style={{ background: "var(--encre)", color: "var(--papier)", fontSize: 13.5 }}>
          {encours ? "Elle dessine…" : "La regarder dessiner"}</button>
      </div>
      <div style={{ display: "flex", alignItems: "center", gap: 10, fontSize: 12.5, color: "var(--doux)", marginBottom: 10 }}>
        <span title="À chaque pixel, elle compare « pour ce nom » et « pour n'importe quoi », et accentue la différence">Force du nom</span>
        <input type="range" min="0" max="5" step="0.5" value={guidage} onChange={(e) => setGuidage(+e.target.value)} style={{ flex: 1, maxWidth: 220 }} />
        <span className="mono" style={{ minWidth: 70 }}>{guidage === 1 ? "normale" : guidage < 1 ? `faible ×${guidage}` : `×${guidage}`}</span>
      </div>
      {erreur && <div style={{ color: "var(--tomate)", fontSize: 13 }}>{erreur}</div>}
      {mots && <div style={{ fontSize: 12, color: "var(--doux)", marginBottom: 6 }}>mots compris : {mots.length ? mots.join(", ") : "aucun (dessin libre)"}</div>}
      {(imgs.length > 0 || encours) && <div style={{ display: "grid", gridTemplateColumns: "repeat(6, minmax(0, 1fr))", gap: 10 }}>
        {(imgs.length ? imgs : Array(12).fill(null)).map((u, i) => <Dessin key={i} img={u} nouveaute={nouv[i]}
          choisi={choisis ? choisis.includes(i) : undefined} />)}
      </div>}
      {choisis && <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 8 }}>Encadrés : les 4 essais qu'elle juge les plus fidèles au nom (sa propre critique).</div>}
    </div>
  );
}

function EnDirect() {
  const [d, setD] = useState(null);
  const [seulChoix, setSeulChoix] = useState(true);
  const vite = d && ((d.pixel && d.pixel.en_cours) || d.ecrit);
  useEffect(() => {
    let vivant = true;
    const tirer = () => fetch("/api/direct").then((r) => r.json()).then((x) => vivant && setD(x)).catch(() => {});
    tirer();
    const t = setInterval(tirer, vite ? 400 : 3000);  // plus vite quand elle est en train de dessiner ou d'ecrire
    return () => { vivant = false; clearInterval(t); };
  }, [vite]);
  if (!d) return <div className="chargement" style={{ height: 160, borderRadius: 16 }} />;
  const il = (t) => { const s = Math.max(0, Math.round(d.t - t)); return s < 60 ? `il y a ${s} s` : s < 3600 ? `il y a ${Math.round(s / 60)} min` : `il y a ${Math.round(s / 3600)} h`; };
  const px = d.pixel;
  const liste = seulChoix && d.focus?.mode === "choix" ? (d.choix || []) : d.exercices;
  const titre = (t, droite) => (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8, gap: 10 }}>
      <b style={{ fontSize: 15 }}>{t}</b>{droite && <span style={{ fontSize: 12.5, color: "var(--doux)" }}>{droite}</span>}
    </div>);
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 20 }}>
      <style>{`@keyframes clignote { 50% { opacity: 0 } } .curseur { display: inline-block; width: 2px; height: 1em; background: var(--encre); margin-left: 2px; vertical-align: -2px; animation: clignote 1s steps(1) infinite }
               @keyframes pulse-direct { 50% { opacity: .35 } } .point-direct { display: inline-block; width: 8px; height: 8px; border-radius: 99px; background: var(--tomate); margin-right: 6px; animation: pulse-direct 1.2s infinite }`}</style>
      <div>
        {titre(<>🎨 Atelier pixel {px && px.en_cours && <span style={{ fontSize: 12, color: "var(--tomate)", fontWeight: 600, marginLeft: 6 }}><span className="point-direct" />elle dessine</span>}</>,
               px && `${px.taille}×${px.taille} · pas ${px.pas} · perte ${px.perte}${px.perte_test != null ? ` (sur images jamais vues : ${px.perte_test})` : ""} · ${px.minutes}/${px.total} min · ${px.en_cours ? "en ce moment" : il(px.t)}`)}
        {!px ? <div className="vide">Pas d'entraînement d'image pour l'instant.</div> :
          <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(92px, 1fr))", gap: 10 }}>
            {px.dessins.map((x, i) => <Dessin key={i} img={x.img} nom={x.nom.replace(" minecraft", "")} nouveaute={x.nouveaute} />)}
          </div>}
        <div style={{ marginTop: 14 }}><RegarderDessiner /></div>
      </div>
      <div>
        {titre(<>✍️ Elle écrit {d.ecrit && <span style={{ fontSize: 12, color: "var(--tomate)", fontWeight: 600, marginLeft: 6 }}><span className="point-direct" />en ce moment</span>}</>,
               d.ecrit && d.ecrit.lecon.replace(/_/g, " "))}
        {!d.ecrit ? <div className="vide">Rien en ce moment : ses phrases s'écriront ici pendant son prochain examen.</div> :
          <div style={{ borderRadius: 14, padding: "12px 16px", background: "var(--surface)", border: "1.5px solid var(--ligne)", fontSize: 14 }}>
            <div style={{ color: "var(--doux)", marginBottom: 4 }}>{d.ecrit.q}</div>
            <div><b>Jexa :</b> {d.ecrit.r}<span className="curseur" /></div>
          </div>}
      </div>
      <div>
        {titre("📝 Ses derniers exercices", liste.length > 0 && `${liste.filter((e) => e.juste).length}/${liste.length} justes · ${il(liste[0].t)}`)}
        {d.focus?.mode === "choix" && (
          <div style={{ display: "flex", gap: 6, marginBottom: 8, flexWrap: "wrap", alignItems: "center" }}>
            {[[true, "Seulement mon choix"], [false, "Tout l'examen"]].map(([v, t]) => (
              <button key={t} className="btn" onClick={() => setSeulChoix(v)} style={{ fontSize: 12.5, padding: "5px 12px",
                background: seulChoix === v ? "var(--encre)" : "var(--creme)", color: seulChoix === v ? "var(--papier)" : "var(--encre)" }}>{t}</button>))}
            <span style={{ fontSize: 12, color: "var(--doux)" }}>L'examen porte toujours sur toutes ses leçons : c'est ce qui montre si elle oublie quelque chose.</span>
          </div>)}
        {!liste.length ? <div className="vide">{seulChoix && d.focus?.mode === "choix" ? "Les exercices de ton choix apparaîtront à son prochain examen." : "Les exercices apparaîtront au prochain examen de Jexa."}</div> :
          <div style={{ display: "flex", flexDirection: "column", gap: 8, maxHeight: 420, overflowY: "auto", paddingRight: 4 }}>
            {liste.map((e, i) => (
              <div key={e.t + "-" + i} style={{ borderRadius: 14, padding: "10px 14px", background: e.juste ? "var(--sarcelle-c)" : "var(--tomate-c)", fontSize: 13.5 }}>
                <div style={{ fontSize: 11.5, color: "var(--doux)", marginBottom: 4 }}>{e.juste ? "✓" : "✗"} {e.lecon.replace(/_/g, " ")}</div>
                <div style={{ color: "var(--doux)" }}>{e.q}</div>
                <div><b>Jexa :</b> {e.r || "…"}</div>
                {!e.juste && <div style={{ color: "var(--doux)" }}><b>Attendu :</b> {e.a}</div>}
              </div>))}
          </div>}
      </div>
    </div>
  );
}

/* ================================================================== le pilotage : demarrer, arreter, choisir ce qu'elle apprend */
function Voyant({ allume, texte }) {
  return <span style={{ display: "inline-flex", alignItems: "center", gap: 7, fontSize: 13, fontWeight: 700, color: allume ? "var(--sarcelle)" : "var(--doux)" }}>
    <span style={{ width: 9, height: 9, borderRadius: 99, background: allume ? "var(--sarcelle)" : "var(--ligne)", boxShadow: allume ? "0 0 0 4px var(--sarcelle-c)" : "none",
                   animation: allume ? "pulse 1.6s infinite" : "none" }} />{texte}</span>;
}

function Pilotage() {
  const [d, setD] = useState(null);
  const [attente, setAttente] = useState(null);
  const [mode, setMode] = useState("tout");
  const [choix, setChoix] = useState([]);
  const [filtre, setFiltre] = useState("");
  const [minutes, setMinutes] = useState(60);
  const [neuf, setNeuf] = useState(false);
  const [taille, setTaille] = useState("suite");
  const [ouvertes, setOuvertes] = useState({});
  const initialise = useRef(false);  // le choix enregistre n'est repris qu'au premier chargement : ensuite c'est le tien
  const charger = () => fetch("/api/controle").then((r) => r.json()).then((x) => {
    setD(x);
    if (!initialise.current) { initialise.current = true; setMode(x.jexa.focus.mode); setChoix(x.jexa.focus.lecons || []); }
  }).catch(() => {});
  useEffect(() => { charger(); const t = setInterval(charger, 5000); return () => clearInterval(t); }, []);
  const agir = async (corps, cle) => {
    setAttente(cle);
    try { const r = await (await fetch("/api/controle", { method: "POST", body: JSON.stringify(corps) })).json(); if (r.etat) setD((x) => ({ ...x, ...r.etat })); }
    finally { setAttente(null); }
  };
  if (!d) return <div className="chargement" style={{ height: 180, borderRadius: 20 }} />;
  const focus = { mode, ...(mode === "choix" ? { lecons: choix } : {}) };
  const actuel = d.jexa.focus;
  const focusChange = JSON.stringify(focus) !== JSON.stringify({ mode: actuel.mode, ...(actuel.mode === "choix" ? { lecons: actuel.lecons || [] } : {}) });
  const depuis = (t) => { if (!t) return ""; const m = Math.round((Date.now() / 1000 - t) / 60); return m < 60 ? `depuis ${m} min` : `depuis ${Math.floor(m / 60)} h ${m % 60} min`; };
  const groupes = {};
  (d.lecons || []).filter((l) => !filtre || (l.nom + " " + l.categorie).toLowerCase().includes(filtre.toLowerCase())).forEach((l) => { (groupes[l.categorie] ||= []).push(l); });
  const basculer = (id) => setChoix((c) => (c.includes(id) ? c.filter((x) => x !== id) : [...c, id]));
  const btn = (fond, texte) => ({ background: fond, color: texte, fontSize: 14 });
  const MODES = [["tout", "Tout", "Toutes ses leçons et tous ses cours"], ["cours", "Les cours", `Surtout les cours (${(d.lecons || []).filter((l) => l.cours).length})`],
                 ["choix", "Mon choix", choix.length ? `${choix.length} leçon${choix.length > 1 ? "s" : ""} choisie${choix.length > 1 ? "s" : ""}` : "Choisis des leçons ou des cours"]];
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(320px, 1fr))", gap: 18 }}>
      {/* ---------------- Jexa : le texte */}
      <div className="profond" style={{ background: "var(--surface)", borderRadius: 24, padding: 20, display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <JexaVivante taille={38} etat={d.jexa.tourne ? "reflechit" : "repos"} />
          <div style={{ flex: 1 }}><b className="serif" style={{ fontSize: 19 }}>Jexa · ses leçons</b><div><Voyant allume={d.jexa.tourne} texte={d.jexa.tourne ? `S'entraîne ${depuis(d.jexa.depuis)}` : d.jexa.gardien ? "Redémarre…" : "À l'arrêt"} /></div></div>
          {d.jexa.tourne || d.jexa.gardien
            ? <button className="btn relief" disabled={!!attente} onClick={() => agir({ action: "arreter", quoi: "jexa" }, "jexa")} style={btn("var(--tomate-c)", "var(--tomate)")}>{attente === "jexa" ? "Arrêt…" : "Arrêter"}</button>
            : <button className="btn relief" disabled={!!attente || (mode === "choix" && !choix.length)} onClick={() => agir({ action: "demarrer", quoi: "jexa", focus }, "jexa")} style={btn("var(--sarcelle)", "#fff")}>{attente === "jexa" ? "Démarrage…" : "Démarrer"}</button>}
        </div>
        <div>
          <div style={{ fontSize: 12, fontWeight: 800, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--doux)", marginBottom: 8 }}>Ce qu'elle apprend</div>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 8 }}>
            {MODES.map(([v, t, sous]) => (
              <button key={v} onClick={() => setMode(v)} className="relief" style={{ border: 0, borderRadius: 16, padding: "10px 12px", textAlign: "left", cursor: "pointer",
                background: mode === v ? "var(--encre)" : "var(--creme)", color: mode === v ? "var(--papier)" : "var(--encre)", transition: "background .2s" }}>
                <b style={{ fontSize: 14 }}>{t}</b><div style={{ fontSize: 11.5, opacity: .75, marginTop: 2 }}>{sous}</div></button>))}
          </div>
        </div>
        {mode !== "tout" && <div style={{ fontSize: 12, color: "var(--doux)", marginTop: -6 }}>
          70 % de l'entraînement sur ce choix, 30 % de révision de tout le reste : sinon elle oublierait ce qu'elle ne revoit plus.</div>}
        {mode === "choix" && (
          <div>
            <div style={{ display: "flex", gap: 8, marginBottom: 8 }}>
              <input value={filtre} onChange={(e) => setFiltre(e.target.value)} placeholder="Chercher une leçon ou un cours…"
                     style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 12, padding: "7px 12px", fontFamily: "inherit", background: "var(--papier)", color: "var(--encre)", outline: "none" }} />
              {choix.length > 0 && <button className="btn" onClick={() => setChoix([])} style={btn("var(--creme)", "var(--doux)")}>Tout décocher</button>}
            </div>
            <div style={{ maxHeight: 280, overflowY: "auto", display: "flex", flexDirection: "column", gap: 8, paddingRight: 4 }}>
              {Object.entries(groupes).map(([cat, ls]) => {
                const tous = ls.every((l) => choix.includes(l.id)), ouvert = ouvertes[cat] || !!filtre;
                return (
                  <div key={cat} style={{ background: "var(--papier)", borderRadius: 14, padding: "8px 10px" }}>
                    <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                      <button onClick={() => setOuvertes((o) => ({ ...o, [cat]: !o[cat] }))} style={{ border: 0, background: "transparent", cursor: "pointer", flex: 1, textAlign: "left", fontWeight: 800, fontSize: 13.5, color: "var(--encre)", padding: 0 }}>
                        {ouvert ? "▾" : "▸"} {cat} <span style={{ fontWeight: 500, color: "var(--doux)" }}>· {ls.filter((l) => choix.includes(l.id)).length}/{ls.length}</span></button>
                      <button className="btn" onClick={() => setChoix((c) => (tous ? c.filter((x) => !ls.some((l) => l.id === x)) : [...new Set([...c, ...ls.map((l) => l.id)])]))}
                              style={{ ...btn(tous ? "var(--encre)" : "var(--creme)", tous ? "var(--papier)" : "var(--encre)"), fontSize: 12, padding: "5px 10px" }}>{tous ? "Retirer" : "Tout"}</button>
                    </div>
                    {ouvert && <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginTop: 8 }}>
                      {ls.map((l) => {
                        const on = choix.includes(l.id);
                        return <button key={l.id} onClick={() => basculer(l.id)} title={`Note actuelle : ${Math.round(l.note * 100)} %`}
                                       style={{ border: 0, borderRadius: 99, padding: "5px 11px", fontSize: 12.5, cursor: "pointer", fontFamily: "inherit",
                                                background: on ? "var(--tomate)" : "var(--creme)", color: on ? "#fff" : "var(--encre)", transition: "background .2s" }}>
                          {l.nom} <span style={{ opacity: .7 }}>{Math.round(l.note * 100)}%</span></button>;
                      })}
                    </div>}
                  </div>);
              })}
            </div>
          </div>)}
        {focusChange && (
          <button className="btn relief" disabled={!!attente || (mode === "choix" && !choix.length)} onClick={() => agir({ action: "focus", quoi: null, focus }, "focus")}
                  style={btn("var(--encre)", "var(--papier)")}>{d.jexa.tourne ? "Appliquer (au prochain cycle, sans l'arrêter)" : "Enregistrer ce choix"}</button>)}
        {d.jexa.journal && <div className="mono" style={{ fontSize: 11.5, color: "var(--doux)", background: "var(--papier)", borderRadius: 12, padding: "8px 10px", whiteSpace: "pre-wrap", maxHeight: 110, overflow: "hidden" }}>{d.jexa.journal.join("\n")}</div>}
      </div>

      {/* ---------------- Les images : l'atelier pixel */}
      <div className="profond" style={{ background: "var(--surface)", borderRadius: 24, padding: 20, display: "flex", flexDirection: "column", gap: 14 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
          <div style={{ width: 38, height: 38, borderRadius: 12, background: "repeating-conic-gradient(#e8dcc3 0 25%, #fcf8f0 0 50%) 0 0 / 10px 10px", boxShadow: "var(--ombre-3d)" }} />
          <div style={{ flex: 1 }}><b className="serif" style={{ fontSize: 19 }}>Les images · l'atelier</b><div><Voyant allume={d.images.tourne} texte={d.images.tourne ? `S'entraîne ${depuis(d.images.depuis)}` : "À l'arrêt"} /></div></div>
          {d.images.tourne
            ? <button className="btn relief" disabled={!!attente} onClick={() => agir({ action: "arreter", quoi: "images" }, "images")} style={btn("var(--tomate-c)", "var(--tomate)")}>{attente === "images" ? "Arrêt…" : "Arrêter"}</button>
            : <button className="btn relief" disabled={!!attente} onClick={() => agir({ action: "demarrer", quoi: "images", minutes, neuf, taille }, "images")} style={btn("var(--sarcelle)", "#fff")}>{attente === "images" ? "Démarrage…" : "Démarrer"}</button>}
        </div>
        <div style={{ display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap", fontSize: 14 }}>
          <label style={{ display: "flex", alignItems: "center", gap: 8 }}>Durée
            <select value={minutes} onChange={(e) => setMinutes(+e.target.value)} style={{ borderRadius: 10, padding: "6px 10px", fontFamily: "inherit", background: "var(--papier)", color: "var(--encre)", border: "1.5px solid var(--ligne)" }}>
              {[15, 30, 60, 90, 120, 240, 480].map((m) => <option key={m} value={m}>{m < 60 ? `${m} min` : `${m / 60} h`}</option>)}</select></label>
          <label style={{ display: "flex", alignItems: "center", gap: 8 }}>Taille
            <select value={taille} onChange={(e) => setTaille(e.target.value)} style={{ borderRadius: 10, padding: "6px 10px", fontFamily: "inherit", background: "var(--papier)", color: "var(--encre)", border: "1.5px solid var(--ligne)" }}>
              <option value="suite">16×16 en priorité, puis 32×32 (75 % / 25 %)</option>
              <option value="16">16×16 seulement</option>
              <option value="32">32×32 seulement (photos)</option></select></label>
          <label style={{ display: "flex", alignItems: "center", gap: 8, cursor: "pointer" }}><input type="checkbox" checked={neuf} onChange={(e) => setNeuf(e.target.checked)} /> Repartir d'un cerveau neuf</label>
        </div>
        <div style={{ fontSize: 12.5, color: "var(--doux)" }}>16×16 : pixel art et photos. 32×32 : surtout les vraies photos (un chat, une pomme…), plus détaillées. Ses dessins de test se construisent en direct plus bas.</div>
        {d.images.journal && <div className="mono" style={{ fontSize: 11.5, color: "var(--doux)", background: "var(--papier)", borderRadius: 12, padding: "8px 10px", whiteSpace: "pre-wrap" }}>{d.images.journal.join("\n")}</div>}
        <div style={{ flex: 1 }} />
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
          <button className="btn relief" disabled={!!attente || (mode === "choix" && !choix.length)} onClick={() => agir({ action: "demarrer", quoi: "les deux", focus, minutes, neuf, taille }, "deux")}
                  style={{ ...btn("var(--encre)", "var(--papier)"), flex: 1 }}>{attente === "deux" ? "…" : "Démarrer les deux"}</button>
          <button className="btn relief" disabled={!!attente} onClick={() => agir({ action: "arreter", quoi: "les deux" }, "stop")}
                  style={{ ...btn("var(--tomate-c)", "var(--tomate)"), flex: 1 }}>{attente === "stop" ? "…" : "Tout arrêter"}</button>
        </div>
        <div style={{ fontSize: 11.5, color: "var(--doux)" }}>Les deux en même temps partagent la carte graphique : chacun va un peu moins vite.</div>
      </div>
    </div>
  );
}

function App() {
  const estPublic = usePublic();
  const [etat, vivant] = useEtat();
  const annonces = useAnnonces(etat);
  const [pensee, setPensee] = useState(null);
  const [vue, setVue] = useState("reseau");
  return (
    <div style={{ maxWidth: 1460, margin: "0 auto", padding: "26px 22px 70px", display: "flex", flexDirection: "column", gap: 22 }}>
      <EnTete etat={etat} vivant={vivant} />
      {!etat ? <div className="chargement" style={{ height: 300, borderRadius: "var(--r-xl)" }} /> : <>
        {!estPublic && <Carte titre="Pilotage" accent="var(--sarcelle)" delai={150} sous="Démarre, arrête, et choisis ce qu'elle apprend : tout, seulement les cours, certaines leçons, les images, ou les deux"><Pilotage /></Carte>}
        <Laboratoire etat={etat} />
        <div className="grille" style={{ display: "grid", gridTemplateColumns: "minmax(320px, 400px) minmax(0, 1fr)", gap: 22, alignItems: "start" }}>
          <Lecons etat={etat} />
          <div style={{ display: "flex", flexDirection: "column", gap: 22, minWidth: 0 }}>
            <Cerveau etat={etat} pensee={pensee} setPensee={setPensee} vue={vue} setVue={setVue} />
            {!estPublic && <Carte titre="En direct : ce qu'elle fait en ce moment" accent="var(--sarcelle)" delai={250} sous="Ses exercices d'examen et ses dessins de test, actualisés toutes les 3 secondes"><EnDirect /></Carte>}
            <Carte titre="Performances, sur 24 h" accent="var(--tomate)" delai={300} sous="Mesuré chaque minute pendant l'entraînement · survole un point pour le détail"><Performances />{!estPublic && <Aides />}</Carte>
          </div>
        </div>
      </>}
      <Annonces annonces={annonces} />
      <style>{`@media (max-width: 980px) { .grille, .grille-labo { grid-template-columns: 1fr !important; } }`}</style>
    </div>
  );
}

/* ================================================================== vitrine (image de présentation, sans texte) */
const ABS = (s) => ({ position: "absolute", ...s });

function Vitrine() {
  const [etat, setEtat] = useState(null);
  const [pensee, setPensee] = useState(null);
  const [carte, setCarte] = useState(null);
  useEffect(() => {
    (async () => {
      const e = await (await fetch("/api/etat")).json();
      const monde = await (await fetch("/api/monde")).json();
      const q = `où est ${monde[0].texte.split(" ").slice(0, 2).join(" ").toLowerCase()} ?`;
      const p = await (await fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: q, monde, historique: [] }) })).json();
      setCarte(await (await fetch("/api/carte")).json().then((d) => (Array.isArray(d) ? d : d.points)));
      setEtat(e); setPensee(p.jetons ? p : null);
    })();
  }, []);
  if (!etat) return null;

  // vraie carte d'attention (moyenne des têtes de la dernière couche), zoomée sur une vraie portion
  let grille = null;
  if (pensee) {
    const L = pensee.attention.at(-1);
    const debut = pensee.debut_reponse, n = pensee.jetons.length;
    const lignes = Math.min(9, n - debut), j0 = Math.max(0, debut - 16);
    grille = Array.from({ length: lignes }, (_, i) => Array.from({ length: debut - j0 + lignes }, (_, k) => {
      const j = j0 + k;
      return j <= debut - 1 + i ? moyenne(L.map((h) => h[debut - 1 + i][j])) : null;
    }));
  }
  const cell = grille ? Math.min(24, 270 / grille[0].length, 190 / grille.length) - 3 : 0;
  const vmax = grille ? Math.max(...grille.flat().filter((v) => v != null)) : 1;

  // l'écran
  const M = { x: 430, y: 120, w: 1060, h: 620 };
  const DESK = 836;

  return (
    <div style={{ width: 1920, height: 1080, position: "relative", overflow: "hidden", background: "#efe2c8" }}>
      {/* mur : tapisserie à rayures douces + lumière */}
      <div style={ABS({ inset: 0, background: "repeating-linear-gradient(90deg, #f3e7cf 0 46px, #ecdec2 46px 92px)" })} />
      <div style={ABS({ inset: 0, background: "radial-gradient(ellipse at 50% 40%, #fff6e400 0%, #d8c19a66 100%)" })} />
      <div style={ABS({ left: -260, top: 120, width: 1000, height: 1000, borderRadius: "50%", background: "radial-gradient(circle, #ffe2a6b0 0%, #ffe2a600 60%)" })} />
      {/* plinthe */}
      <div style={ABS({ left: 0, right: 0, top: 640, height: 10, background: "#e2cfac" })} />

      {/* étagère (gauche) */}
      <div style={ABS({ left: 120, top: 300, width: 250, height: 20, borderRadius: 10, background: "#b48a5a", boxShadow: "0 10px 16px -8px #0005" })} />
      {[["#2f6f6a", 34, 96], ["#d65f37", 28, 78], ["#dfa92f", 38, 110], ["#5b80a5", 26, 84]].map(([c, w, h], i) => (
        <div key={i} style={ABS({ left: 140 + i * 42, top: 300 - h, width: w, height: h, borderRadius: 10, background: c })} />
      ))}
      <div style={ABS({ left: 316, top: 248, width: 52, height: 52, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #f08a5d, #d65f37 60%, #a8431f)" })} />

      {/* horloge (droite) */}
      <div style={ABS({ left: 1625, top: 150, width: 170, height: 170, borderRadius: "50%", background: "#fcf8f0", border: "12px solid #24232b",
                        boxShadow: "0 18px 30px -16px #0007" })}>
        <div style={ABS({ left: 69, top: 24, width: 8, height: 54, borderRadius: 4, background: "#24232b" })} />
        <div style={ABS({ left: 72, top: 74, width: 48, height: 8, borderRadius: 4, background: "#d65f37", transform: "rotate(32deg)", transformOrigin: "0 50%" })} />
        <div style={ABS({ left: 66, top: 66, width: 14, height: 14, borderRadius: "50%", background: "#24232b" })} />
      </div>

      {/* ombre de l'écran sur le mur */}
      <div style={ABS({ left: M.x + 40, top: M.y + 60, width: M.w, height: M.h, borderRadius: 70, background: "#6b4f2a", opacity: .18, filter: "blur(40px)" })} />

      {/* bureau */}
      <div style={ABS({ left: 0, right: 0, top: DESK, bottom: 0, background: "linear-gradient(#b98a5c, #946640)" })} />
      <div style={ABS({ left: 0, right: 0, top: DESK - 10, height: 18, background: "#cfa271", boxShadow: "0 6px 10px -4px #0003" })} />

      {/* pied de l'écran */}
      <div style={ABS({ left: 890, top: M.y + M.h - 20, width: 140, height: DESK - (M.y + M.h) + 10, borderRadius: "26px 26px 8px 8px",
                        background: "linear-gradient(90deg,#8d8a84,#e2ded5 45%,#8d8a84)" })} />
      <div style={ABS({ left: 790, top: DESK - 24, width: 340, height: 26, borderRadius: 16, background: "linear-gradient(#e2ded5,#8d8a84)", boxShadow: "0 14px 22px -10px #0008" })} />

      {/* caisson de l'écran */}
      <div style={ABS({ left: M.x, top: M.y, width: M.w, height: M.h, borderRadius: 64, background: "linear-gradient(160deg,#3c3a44,#1f1e25)",
                        boxShadow: "0 40px 60px -30px #3a2a12aa, inset 0 2px 0 #ffffff26, inset 0 -6px 0 #0004" })}>
        <div style={ABS({ left: 30, top: 30, right: 30, bottom: 56, borderRadius: 40, background: "#f1e7d3", overflow: "hidden",
                          display: "grid", gridTemplateColumns: "1fr 330px", gap: 18, padding: 20, boxShadow: "inset 0 0 40px #0003" })}>
          <ReseauVivant genome={etat.genome} pensee={pensee} actif sansTexte hauteur={M.h - 30 - 56 - 40} fond="#fcf8f0" />
          <div style={{ display: "flex", flexDirection: "column", gap: 18 }}>
            <div style={{ flex: 1, background: "#fcf8f0", borderRadius: 26, display: "grid", placeItems: "center", overflow: "hidden" }}>
              {grille && <div>{grille.map((row, i) => (
                <div key={i} style={{ display: "flex" }}>{row.map((v, j) => (
                  <div key={j} style={{ width: cell, height: cell, margin: 1.5, borderRadius: 99,
                       background: v != null ? `rgba(47,111,106,${0.12 + 0.88 * Math.sqrt(v / vmax)})` : "transparent" }} />))}</div>
              ))}</div>}
            </div>
            <div style={{ flex: 1, background: "#fcf8f0", borderRadius: 26, overflow: "hidden" }}>
              {carte && <svg viewBox="0 0 330 250" width="100%" height="100%" preserveAspectRatio="xMidYMid meet">
                {carte.slice(0, 700).map((p, i) => <circle key={i} cx={20 + p.x * 290} cy={20 + p.y * 210} r={p.type === "morceau" ? 2.2 : 3.6}
                  fill={COULEURS_NATURE[p.type] || "#999"} opacity={p.type === "morceau" ? .45 : .9} />)}
              </svg>}
            </div>
          </div>
          {/* reflet de verre */}
          <div style={ABS({ left: 0, top: 0, width: "55%", height: "100%", background: "linear-gradient(115deg, #ffffff2e 0%, #ffffff00 40%)", pointerEvents: "none" })} />
        </div>
        {/* logo Jexa (orbe) et boutons */}
        <div style={ABS({ left: M.w / 2 - 15, bottom: 14, width: 30, height: 30, borderRadius: "50%", background: "radial-gradient(circle at 35% 30%, #f08a5d, #d65f37 60%, #a8431f)",
                          boxShadow: "0 0 0 4px #d65f3733" })} />
        {["#dfa92f", "#2f6f6a"].map((c, i) => (
          <div key={i} style={ABS({ left: M.w - 150 + i * 46, bottom: 24, width: 30, height: 10, borderRadius: 5, background: c })} />
        ))}
      </div>

      {/* clavier (touches sans lettres) et souris */}
      <div style={ABS({ left: 690, top: 900, width: 540, height: 110, borderRadius: 26, background: "#fcf8f0", boxShadow: "0 16px 24px -12px #0008, inset 0 -5px 0 #e2d6bf",
                        transform: "perspective(900px) rotateX(38deg)", transformOrigin: "50% 0" })}>
        {Array.from({ length: 4 }, (_, r) => (
          <div key={r} style={{ display: "flex", gap: 6, padding: r ? "0 18px" : "12px 18px 0", marginTop: r ? 6 : 0 }}>
            {Array.from({ length: r === 3 ? 1 : 13 }, (_, k) => (
              <div key={k} style={{ flex: 1, height: 16, borderRadius: 6, background: r === 3 ? "#e9dfcc" : (r === 1 && k === 12) ? "#d65f37" : "#ece3d1" }} />
            ))}
          </div>
        ))}
      </div>
      <div style={ABS({ left: 1290, top: 912, width: 66, height: 92, borderRadius: "34px 34px 30px 30px", background: "#fcf8f0", boxShadow: "0 14px 20px -10px #0008, inset 0 -5px 0 #e2d6bf" })} />

      {/* lampe (gauche) */}
      <div style={ABS({ left: 120, top: DESK - 30, width: 180, height: 34, borderRadius: 20, background: "#24232b" })} />
      <div style={ABS({ left: 202, top: 470, width: 16, height: DESK - 470, background: "#24232b", borderRadius: 8, transform: "rotate(12deg)", transformOrigin: "bottom" })} />
      <div style={ABS({ left: 220, top: 400, width: 200, height: 112, borderRadius: "100px 100px 22px 22px", background: "linear-gradient(#e8b947,#d29a22)",
                        transform: "rotate(30deg)", boxShadow: "0 30px 70px #ffd98877" })} />

      {/* tasse (droite du clavier) */}
      <div style={ABS({ left: 1470, top: DESK - 100, width: 96, height: 104, borderRadius: "14px 14px 36px 36px", background: "#fcf8f0", boxShadow: "inset -12px 0 0 #e6dac3, 0 12px 18px -10px #0007" })} />
      <div style={ABS({ left: 1556, top: DESK - 80, width: 34, height: 46, borderRadius: "0 26px 26px 0", border: "11px solid #fcf8f0", borderLeft: 0 })} />
      <div style={ABS({ left: 1478, top: DESK - 96, width: 80, height: 14, borderRadius: "50%", background: "#7a4a2a" })} />

      {/* plante (droite) */}
      {[[-70, -10, 130, -40], [0, -80, 150, 10], [60, -20, 120, 50], [-30, -140, 110, -10], [40, -150, 100, 40]].map(([x, y, s, r], i) => (
        <div key={i} style={ABS({ left: 1700 + x, top: 600 + y, width: s, height: s * 0.55, borderRadius: "100% 0", background: i % 2 ? "#2f6f6a" : "#5f9e96",
                                  transform: `rotate(${r}deg)` })} />
      ))}
      <div style={ABS({ left: 1660, top: DESK - 170, width: 140, height: 174, borderRadius: "18px 18px 44px 44px", background: "linear-gradient(90deg,#c9532d,#e06a40 50%,#c9532d)",
                        boxShadow: "0 14px 20px -10px #0007" })} />

      {/* carnet (gauche du clavier) */}
      <div style={ABS({ left: 360, top: 905, width: 260, height: 64, borderRadius: 14, background: "#2f6f6a", transform: "rotate(-5deg)", boxShadow: "0 14px 22px -12px #0008" })} />
      <div style={ABS({ left: 568, top: 900, width: 20, height: 72, borderRadius: 6, background: "#dfa92f", transform: "rotate(-5deg)" })} />

      {/* grain papier */}
      <div className="fond" style={{ position: "absolute", zIndex: 5 }} />
    </div>
  );
}

/* ================================================================== affiche de nuit (pub, sans texte) */
/** Le vrai réseau de Jexa (ses blocs, ses têtes, son activité réelle), dessiné comme une constellation lumineuse. */
function ConstellationJexa({ genome, pensee, largeur, hauteur, eveil }) {
  const ref = useRef(null);
  useEffect(() => {
    const cv = ref.current, ctx = cv.getContext("2d");
    cv.width = largeur * 2; cv.height = hauteur * 2; ctx.setTransform(2, 0, 0, 2, 0, 0);
    let seed = 11;
    const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);
    const nCol = genome.layers + 2;
    const activite = pensee ? pensee.activite.map((row) => moyenne(row)) : null;
    const maxA = activite ? Math.max(...activite) : 1;
    const noeuds = [];
    for (let c = 0; c < nCol; c++) {
      const n = c === 0 || c === nCol - 1 ? 7 : Math.min(11, 4 + genome.heads);
      for (let k = 0; k < n; k++) {
        const x = 70 + (c / (nCol - 1)) * (largeur - 140);
        const y = hauteur / 2 + (k - (n - 1) / 2) * Math.min(44, (hauteur - 80) / n);
        noeuds.push({ c, k, x, y });
      }
    }
    const col = (c) => (c === 0 ? [140, 180, 225] : c === nCol - 1 ? [255, 130, 80] : [110, 220, 200]);
    const courbe = (a, b) => { ctx.beginPath(); ctx.moveTo(a.x, a.y); ctx.bezierCurveTo((a.x + b.x) / 2, a.y, (a.x + b.x) / 2, b.y, b.x, b.y); };
    const surCourbe = (a, b, u) => {  // point sur la courbe de Bézier entre deux neurones
      const mx = (a.x + b.x) / 2, v = 1 - u;
      return [v * v * v * a.x + 3 * v * v * u * mx + 3 * v * u * u * mx + u * u * u * b.x,
              v * v * v * a.y + 3 * v * v * u * a.y + 3 * v * u * u * b.y + u * u * u * b.y];
    };
    // espace dégagé autour de Jexa : rien ne se dessine sous son orbe et son halo
    const cx = largeur / 2, cy = hauteur / 2, libre = 215;
    const pres = (n) => Math.hypot(n.x - cx, n.y - cy) < libre;
    const liens = [];
    for (const a of noeuds) for (const b of noeuds) {
      if (b.c === a.c + 1 && rnd() <= 0.22 && !pres(a) && !pres(b)) liens.push([a, b]);
    }
    // chemins de pensée : des signaux qui traversent tout le cerveau
    const teintes = [[255, 196, 90], [120, 235, 210], [255, 140, 90]];
    const chemins = teintes.map((teinte) => {
      const pts = [noeuds.filter((n) => n.c === 0)[Math.floor(rnd() * 7)]];
      for (let c = 1; c < nCol; c++) { const choix = noeuds.filter((n) => n.c === c); pts.push(choix[Math.floor(rnd() * choix.length)]); }
      return { teinte, pts, decalage: rnd() };
    });
    const vivants = noeuds.filter((n) => !pres(n));
    const t0 = performance.now();
    let raf;
    let cache = null;  // une fois éveillé, le décor ne bouge plus : on le dessine une seule fois
    const frame = (now) => {
      const t = now - t0;
      const k = eveil ? Math.min(1, Math.max(0, (t - 600) / 2600)) : 1;  // l'éveil : le cerveau s'allume peu à peu
      ctx.clearRect(0, 0, largeur, hauteur);
      if (cache) {
        ctx.globalCompositeOperation = "source-over"; ctx.drawImage(cache, 0, 0, largeur, hauteur);
        ctx.globalCompositeOperation = "lighter";
        for (const ch of chemins) impulsions(ch, t);
        raf = requestAnimationFrame(frame);
        return;
      }
      ctx.globalCompositeOperation = "lighter";
      ctx.shadowBlur = 0;
      ctx.strokeStyle = `rgba(150,230,215,${0.035 * k})`; ctx.lineWidth = 1;
      for (const [a, b] of liens) { courbe(a, b); ctx.stroke(); }
      for (const ch of chemins) {
        const [r, g, b] = ch.teinte;
        const segs = ch.pts.length - 1;
        const montre = Math.max(0, Math.min(segs, (k * 1.4 - 0.2) * segs));  // les chemins se tracent de gauche à droite
        ctx.shadowColor = `rgb(${r},${g},${b})`; ctx.shadowBlur = 22;
        ctx.strokeStyle = `rgba(${r},${g},${b},0.75)`; ctx.lineWidth = 3;
        for (let s = 0; s < Math.floor(montre); s++) { courbe(ch.pts[s], ch.pts[s + 1]); ctx.stroke(); }
        if (montre >= segs && !(k >= 1 && t > 4500)) impulsions(ch, t);  // pas d'impulsion dans l'image figée
      }
      for (const nd of vivants) {  // neurones, plus brillants là où sa vraie activité est forte (respiration pendant l'éveil)
        const [r, g, b] = col(nd.c);
        const act = activite ? (activite[Math.min(nd.c, activite.length - 1)] || 0) / maxA : 0.6;
        const allume = Math.min(1, Math.max(0, k * 1.6 - nd.c / nCol * 0.6));
        const respir = 0.85 + 0.15 * Math.sin(t / 600 + nd.k + nd.c * 1.7);
        ctx.shadowColor = `rgb(${r},${g},${b})`; ctx.shadowBlur = (22 * act + 6) * respir;
        ctx.fillStyle = `rgba(${r},${g},${b},${(0.55 + 0.45 * act) * allume})`;
        ctx.beginPath(); ctx.arc(nd.x, nd.y, (6 + 5 * act) * (0.6 + 0.4 * allume), 0, 6.28); ctx.fill();
      }
      if (k >= 1 && t > 4500) {  // éveil terminé : on fige le décor (sans les impulsions) dans une image
        cache = document.createElement("canvas"); cache.width = cv.width; cache.height = cv.height;
        const c2 = cache.getContext("2d"); c2.drawImage(cv, 0, 0);
      }
      raf = requestAnimationFrame(frame);
    };
    const impulsions = (ch, t) => {  // deux impulsions lumineuses qui parcourent chaque chemin
      const [r, g, b] = ch.teinte, segs = ch.pts.length - 1;
      ctx.shadowBlur = 0;
      for (let q = 0; q < 2; q++) {
        const pos = ((t / 2600 + ch.decalage + q * 0.5) % 1) * segs, s = Math.floor(pos);
        const [x, y] = surCourbe(ch.pts[s], ch.pts[s + 1], pos - s);
        ctx.fillStyle = `rgba(${r},${g},${b},.22)`; ctx.beginPath(); ctx.arc(x, y, 16, 0, 6.28); ctx.fill();
        ctx.fillStyle = `rgba(${r},${g},${b},.5)`; ctx.beginPath(); ctx.arc(x, y, 9, 0, 6.28); ctx.fill();
        ctx.fillStyle = `rgba(${r},${g},${b},1)`; ctx.beginPath(); ctx.arc(x, y, 5, 0, 6.28); ctx.fill();
      }
    };
    raf = requestAnimationFrame(frame);
    document.body.dataset.pret = "1";
    return () => cancelAnimationFrame(raf);
  }, [genome, pensee, largeur, hauteur, eveil]);
  return <canvas ref={ref} style={{ width: largeur, height: hauteur, display: "block" }} />;
}

/** Jexa en personnage : son orbe qui respire, avec des yeux qui clignent et regardent le spectateur. */
const OrbeJexa = ({ taille, eveil }) => (
  <div style={{ position: "relative", width: taille, height: taille,
                animation: eveil ? "eveilOrbe 2.6s 1.2s cubic-bezier(.2,.8,.2,1) both, respire 4s 3.8s ease-in-out infinite" : "respire 4s ease-in-out infinite" }}>
    {[1.9, 1.55, 1.25].map((k, i) => (
      <div key={i} style={ABS({ left: taille / 2 - (taille * k) / 2, top: taille / 2 - (taille * k) / 2, width: taille * k, height: taille * k, borderRadius: "50%",
                                border: `${3 - i * 0.5}px solid rgba(255,150,100,${0.12 + i * 0.1})`, boxShadow: `0 0 ${30 + i * 10}px rgba(255,120,70,${0.12 + i * 0.06})`,
                                animation: `onde ${5 + i}s ${i * 1.3}s ease-out infinite` })} />
    ))}
    <div style={ABS({ inset: -taille * 0.35, borderRadius: "50%", background: "radial-gradient(circle, rgba(255,120,70,.55) 0%, rgba(255,120,70,0) 65%)" })} />
    <div style={ABS({ inset: 0, borderRadius: "50%", background: "radial-gradient(circle at 36% 30%, #ffb08a 0%, #f07a4a 28%, #d65f37 58%, #8f3518 100%)",
                      boxShadow: "inset -18px -24px 40px rgba(80,20,5,.45), 0 0 60px rgba(255,120,70,.7)" })} />
    <div style={ABS({ left: taille * 0.2, top: taille * 0.12, width: taille * 0.34, height: taille * 0.22, borderRadius: "50%", background: "rgba(255,255,255,.35)", filter: "blur(6px)" })} />
    {[0.34, 0.58].map((x, i) => (
      <div key={i} style={ABS({ left: taille * x, top: taille * 0.4, width: taille * 0.09, height: taille * 0.2, borderRadius: 99, background: "#fff8ee",
                                boxShadow: "0 0 18px rgba(255,248,238,.9)", transformOrigin: "50% 50%",
                                animation: eveil ? "eveilYeux .9s 3.4s ease-out both, cligne 5s 5s infinite" : "cligne 5s 2s infinite" })} />
    ))}
  </div>
);
const EVEIL = new URLSearchParams(location.search).has("eveil");

function AfficheNuit() {
  const [etat, setEtat] = useState(null);
  const [pensee, setPensee] = useState(null);
  useEffect(() => {
    (async () => {
      setEtat(await (await fetch("/api/etat")).json());  // l'affiche apparaît tout de suite…
      const monde = await (await fetch("/api/monde")).json();
      const p = await (await fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: "bonjour !", monde, historique: [] }) })).json();
      if (p.jetons) setPensee(p);  // …puis s'ajuste à sa vraie activité
    })();
  }, []);
  if (!etat) return null;

  const M = { x: 400, y: 110, w: 1120, h: 640 };
  const S = { x: 30, y: 30, w: M.w - 60, h: M.h - 90 };  // écran
  const DESK = 840;
  let seed = 5;
  const rnd = () => ((seed = (seed * 16807) % 2147483647) / 2147483647);

  return (
    <div style={{ width: 1920, height: 1080, position: "relative", overflow: "hidden", background: "#15131c" }}>
      {/* mur de nuit */}
      <div style={ABS({ inset: 0, background: "repeating-linear-gradient(90deg, #1c1a25 0 46px, #191721 46px 92px)" })} />
      {/* la lumière de l'écran qui envahit la pièce */}
      <div style={ABS({ left: M.x - 500, top: M.y - 380, width: M.w + 1000, height: M.h + 900, borderRadius: "50%",
                        background: "radial-gradient(ellipse, rgba(70,190,170,.30) 0%, rgba(214,95,55,.12) 35%, rgba(0,0,0,0) 65%)" })} />

      {/* fenêtre arrondie, lune et étoiles */}
      <div style={ABS({ left: 110, top: 150, width: 210, height: 300, borderRadius: "105px 105px 18px 18px", background: "linear-gradient(#0e1530,#1f2d52)",
                        border: "12px solid #2b2733", boxShadow: "0 0 40px rgba(120,150,255,.12)", overflow: "hidden" })}>
        <svg width="186" height="276" style={ABS({ left: 0, top: 0 })}>
          <defs>
            <radialGradient id="halo"><stop offset="0" stopColor="#f6e7b8" stopOpacity=".55" /><stop offset="1" stopColor="#f6e7b8" stopOpacity="0" /></radialGradient>
            <mask id="croissant"><rect width="186" height="276" fill="#fff" /><circle cx="146" cy="62" r="30" fill="#000" /></mask>
            <filter id="lueurLune"><feGaussianBlur stdDeviation="3" /></filter>
          </defs>
          <circle cx="128" cy="72" r="70" fill="url(#halo)" />
          {/* le croissant, avec une lueur douce et des cratères */}
          <g mask="url(#croissant)">
            <circle cx="128" cy="72" r="34" fill="#fff3c9" filter="url(#lueurLune)" opacity=".8" />
            <circle cx="128" cy="72" r="32" fill="#f6e7b8" />
            <circle cx="112" cy="64" r="5" fill="#e5d29b" /><circle cx="118" cy="88" r="7" fill="#e5d29b" /><circle cx="104" cy="80" r="3" fill="#e5d29b" />
          </g>
          {/* un petit nuage qui passe */}
          <g opacity=".55" fill="#3a4a78">
            <rect x="22" y="196" width="120" height="22" rx="11" /><circle cx="62" cy="194" r="18" /><circle cx="92" cy="188" r="22" />
          </g>
          {/* étoiles qui scintillent (en forme d'étincelle) */}
          {[[30, 40, 7], [60, 120, 5], [150, 150, 6], [40, 250, 4], [160, 230, 5], [90, 30, 3], [20, 160, 3], [130, 260, 3]].map(([x, y, s], i) => (
            <path key={i} d={`M${x},${y - s} Q${x},${y} ${x + s},${y} Q${x},${y} ${x},${y + s} Q${x},${y} ${x - s},${y} Q${x},${y} ${x},${y - s} Z`}
                  fill="#fff" opacity={0.55 + (i % 3) * 0.2} />
          ))}
        </svg>
        <div style={ABS({ left: 87, top: 0, width: 12, height: "100%", background: "#2b2733" })} />
        <div style={ABS({ left: 0, top: 150, width: "100%", height: 12, background: "#2b2733" })} />
      </div>

      {/* étagère en silhouette, éclairée par l'écran */}
      <div style={ABS({ left: 1600, top: 300, width: 230, height: 18, borderRadius: 9, background: "#2a2530", boxShadow: "-8px 0 20px rgba(70,190,170,.15)" })} />
      {[[34, 92], [26, 70], [40, 106], [24, 80]].map(([w, h], i) => (
        <div key={i} style={ABS({ left: 1620 + i * 40, top: 300 - h, width: w, height: h, borderRadius: 9, background: ["#2b4f4c", "#5a3227", "#5f4a22", "#2e3b52"][i],
                                  boxShadow: "inset 6px 0 0 rgba(120,230,210,.18)" })} />
      ))}

      {/* ombre et caisson de l'écran */}
      <div style={ABS({ left: 890, top: M.y + M.h - 20, width: 140, height: DESK - (M.y + M.h) + 10, borderRadius: "26px 26px 8px 8px",
                        background: "linear-gradient(90deg,#2b2a30,#6d6a72 45%,#2b2a30)" })} />
      <div style={ABS({ left: 790, top: DESK - 24, width: 340, height: 26, borderRadius: 16, background: "linear-gradient(#77737c,#2b2a30)" })} />
      <div style={ABS({ left: M.x, top: M.y, width: M.w, height: M.h, borderRadius: 66, background: "linear-gradient(160deg,#34323c,#141318)",
                        boxShadow: "0 0 120px rgba(70,190,170,.25), inset 0 2px 0 #ffffff1c" })}>
        <div style={ABS({ left: S.x, top: S.y, width: S.w, height: S.h, borderRadius: 42, overflow: "hidden",
                          background: "radial-gradient(ellipse at 50% 50%, #12403b 0%, #0b2423 55%, #071514 100%)",
                          boxShadow: "inset 0 0 80px rgba(0,0,0,.6), 0 0 60px rgba(70,190,170,.35)" })}>
          <ConstellationJexa genome={etat.genome} pensee={pensee} largeur={S.w} hauteur={S.h} eveil={EVEIL} />
          {/* halo sombre puis Jexa au centre */}
          <div style={ABS({ left: S.w / 2 - 230, top: S.h / 2 - 230, width: 460, height: 460, borderRadius: "50%",
                            background: "radial-gradient(circle, rgba(7,21,20,.95) 0%, rgba(7,21,20,.85) 45%, rgba(7,21,20,0) 70%)" })} />
          <div style={ABS({ left: S.w / 2 - 125, top: S.h / 2 - 125 })}><OrbeJexa taille={250} eveil={EVEIL} /></div>
          <div style={ABS({ inset: 0, background: "linear-gradient(115deg, rgba(255,255,255,.08) 0%, rgba(255,255,255,0) 35%)" })} />
          <div style={ABS({ inset: 0, background: "repeating-linear-gradient(0deg, rgba(0,0,0,.08) 0 2px, rgba(0,0,0,0) 2px 4px)" })} />
        </div>
        <div style={ABS({ left: M.w / 2 - 14, bottom: 16, width: 28, height: 28, borderRadius: "50%", background: "#d65f37", boxShadow: "0 0 18px rgba(255,120,70,.9)" })} />
        {["#dfa92f", "#2f6f6a"].map((c, i) => (
          <div key={i} style={ABS({ left: M.w - 150 + i * 46, bottom: 25, width: 30, height: 10, borderRadius: 5, background: c, boxShadow: `0 0 10px ${c}` })} />
        ))}
      </div>

      {/* étincelles qui s'échappent de l'écran : elle prend vie */}
      {Array.from({ length: 34 }, (_, i) => {
        const ang = rnd() * Math.PI * 2, dist = 360 + rnd() * 420, s = 3 + rnd() * 6;
        const x = 960 + Math.cos(ang) * dist * 1.25, y = 430 + Math.sin(ang) * dist * 0.75;
        const c = ["#ffbe55", "#ff8050", "#7debd2", "#aac8ff"][i % 4];
        return <div key={i} style={ABS({ left: x, top: y, width: s, height: s, borderRadius: "50%", background: c, boxShadow: `0 0 ${s * 3}px ${c}`, opacity: 0.35 + rnd() * 0.55 })} />;
      })}

      {/* bureau dans la pénombre, éclairé par l'écran */}
      <div style={ABS({ left: 0, right: 0, top: DESK, bottom: 0, background: "linear-gradient(#3a2a20, #1d1510)" })} />
      <div style={ABS({ left: 0, right: 0, top: DESK - 10, height: 16, background: "#4a3628" })} />
      <div style={ABS({ left: 360, top: DESK - 10, width: 1200, height: 260, borderRadius: "50%", background: "radial-gradient(ellipse at 50% 0%, rgba(90,210,190,.30), rgba(0,0,0,0) 70%)" })} />

      {/* clavier et souris qui reflètent la lumière */}
      <div style={ABS({ left: 690, top: 900, width: 540, height: 110, borderRadius: 26, background: "#2a2830", boxShadow: "0 16px 24px -12px #000, inset 0 2px 0 rgba(120,230,210,.35)",
                        transform: "perspective(900px) rotateX(38deg)", transformOrigin: "50% 0" })}>
        {Array.from({ length: 4 }, (_, r) => (
          <div key={r} style={{ display: "flex", gap: 6, padding: r ? "0 18px" : "12px 18px 0", marginTop: r ? 6 : 0 }}>
            {Array.from({ length: r === 3 ? 1 : 13 }, (_, k) => (
              <div key={k} style={{ flex: 1, height: 16, borderRadius: 6, background: (r === 1 && k === 12) ? "#d65f37" : "#3a3842",
                                    boxShadow: "inset 0 1px 0 rgba(120,230,210,.25)" }} />
            ))}
          </div>
        ))}
      </div>
      {/* tapis, fil et souris en perspective */}
      <svg width="320" height="200" style={ABS({ left: 1225, top: 880 })}>
        <defs>
          <linearGradient id="corpsSouris" x1="0" y1="0" x2="1" y2="1"><stop offset="0" stopColor="#4a4752" /><stop offset=".55" stopColor="#2c2a33" /><stop offset="1" stopColor="#1b1a20" /></linearGradient>
          <filter id="ombreSouris"><feGaussianBlur stdDeviation="6" /></filter>
        </defs>
        <rect x="52" y="34" width="190" height="130" rx="34" fill="#1f2a2c" transform="skewX(-10)" />
        <rect x="52" y="34" width="190" height="130" rx="34" fill="none" stroke="rgba(120,230,210,.25)" strokeWidth="2" transform="skewX(-10)" />
        <path d="M118,52 C100,20 40,40 4,26" fill="none" stroke="#2c2a33" strokeWidth="5" strokeLinecap="round" />
        <ellipse cx="128" cy="140" rx="40" ry="14" fill="#000" opacity=".55" filter="url(#ombreSouris)" />
        <path d="M128,52 C156,52 170,78 168,108 C166,136 150,148 128,148 C106,148 90,136 88,108 C86,78 100,52 128,52 Z" fill="url(#corpsSouris)" />
        <path d="M128,54 L128,92" stroke="#15141a" strokeWidth="2.5" />
        <path d="M90,94 C104,100 152,100 166,94" fill="none" stroke="#15141a" strokeWidth="2" opacity=".7" />
        <rect x="123" y="62" width="10" height="20" rx="5" fill="#7debd2" />
        <rect x="123" y="62" width="10" height="20" rx="5" fill="#7debd2" filter="url(#ombreSouris)" opacity=".8" />
        <path d="M104,62 C110,56 120,54 126,54" fill="none" stroke="rgba(160,240,225,.55)" strokeWidth="3" strokeLinecap="round" />
        <path d="M92,104 C92,84 98,70 106,62" fill="none" stroke="rgba(120,230,210,.35)" strokeWidth="3" strokeLinecap="round" />
      </svg>

      {/* tasse fumante */}
      <div style={ABS({ left: 1470, top: DESK - 100, width: 96, height: 104, borderRadius: "14px 14px 36px 36px", background: "#3a3540", boxShadow: "inset 10px 0 0 rgba(120,230,210,.22)" })} />
      <div style={ABS({ left: 1556, top: DESK - 80, width: 34, height: 46, borderRadius: "0 26px 26px 0", border: "11px solid #3a3540", borderLeft: 0 })} />
      {[0, 1].map((i) => (
        <div key={i} style={ABS({ left: 1494 + i * 26, top: DESK - 190, width: 22, height: 80, borderRadius: 40, border: "4px solid rgba(255,255,255,.18)",
                                  borderLeftColor: "transparent", borderBottomColor: "transparent", transform: `rotate(${i ? 12 : -8}deg)` })} />
      ))}

      {/* plante : tiges, feuilles nervurées éclairées par l'écran, pot rétro */}
      <svg width="480" height="560" style={ABS({ left: 1500, top: DESK - 548 })}>
        <g transform="translate(240,556) scale(.82) translate(-180,-556)">
        <defs>
          <linearGradient id="feuille" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#3f6f68" /><stop offset=".5" stopColor="#24443f" /><stop offset="1" stopColor="#16302c" /></linearGradient>
          <linearGradient id="pot" x1="0" y1="0" x2="1" y2="0"><stop offset="0" stopColor="#7a3e28" /><stop offset=".3" stopColor="#9a5434" /><stop offset="1" stopColor="#3e1f15" /></linearGradient>
        </defs>
        {[
          // [base x, pointe x, pointe y, largeur, angle de la feuille]
          [178, 80, 170, 58, -55], [180, 125, 80, 54, -24], [182, 200, 40, 56, 6], [184, 280, 120, 58, 44], [180, 60, 290, 52, -78],
          [184, 300, 260, 54, 70], [181, 150, 210, 48, -18], [183, 230, 180, 48, 26], [182, 175, 130, 44, -4]
        ].map(([bx, tx, ty, w, a], i) => {
          const sx = (bx + tx) / 2 + (tx < bx ? -20 : 20), sy = (420 + ty) / 2;
          const lx = tx + Math.cos((a - 90) * Math.PI / 180) * 0, ly = ty;
          return (
            <g key={i}>
              <path d={`M${bx},430 Q${sx},${sy} ${tx},${ty + 40}`} fill="none" stroke="#1d3a36" strokeWidth="5" strokeLinecap="round" />
              <g transform={`translate(${lx},${ly + 40}) rotate(${a})`}>
                <path d={`M0,0 C${w},-30 ${w * 0.7},-110 0,-140 C${-w * 0.7},-110 ${-w},-30 0,0 Z`} fill="url(#feuille)" />
                <path d={`M0,0 C${w * 0.15},-50 ${w * 0.1},-100 0,-132`} fill="none" stroke="rgba(150,235,215,.35)" strokeWidth="2" />
                <path d={`M0,0 C${-w * 0.9},-34 ${-w * 0.66},-108 0,-140`} fill="none" stroke="rgba(120,230,210,.4)" strokeWidth="2.5" />
              </g>
            </g>
          );
        })}
        {/* pot */}
        <path d="M110,420 L250,420 L236,548 C236,556 124,556 124,548 Z" fill="url(#pot)" />
        <rect x="100" y="404" width="160" height="30" rx="12" fill="#a65c38" />
        <rect x="100" y="404" width="160" height="30" rx="12" fill="none" stroke="rgba(120,230,210,.25)" strokeWidth="2" />
        <ellipse cx="180" cy="410" rx="70" ry="7" fill="#1e120c" />
        <path d="M118,470 L242,470" stroke="#dfa92f" strokeWidth="6" opacity=".55" />
        <path d="M114,428 L126,546" stroke="rgba(120,230,210,.3)" strokeWidth="4" strokeLinecap="round" />
        </g>
      </svg>

      {/* carnet */}
      <div style={ABS({ left: 360, top: 905, width: 260, height: 64, borderRadius: 14, background: "#1f3533", transform: "rotate(-5deg)", boxShadow: "inset 0 2px 0 rgba(120,230,210,.3)" })} />
      <div style={ABS({ left: 568, top: 900, width: 20, height: 72, borderRadius: 6, background: "#7a5c20", transform: "rotate(-5deg)" })} />

      {/* vignettage + grain */}
      <div style={ABS({ inset: 0, background: "radial-gradient(ellipse at 50% 42%, rgba(0,0,0,0) 45%, rgba(0,0,0,.55) 100%)" })} />
      <div className="fond" style={{ position: "absolute", zIndex: 5, opacity: .5 }} />
    </div>
  );
}

/* ================================================================== le film (vidéo Kickstarter) */
const attendre = (ms) => new Promise((r) => setTimeout(r, ms));
const HISTOIRE_FILM = "raconte Il était une fois un petit renard qui";
// journal des moments clés : le montage son place chaque voix et chaque bruitage à l'instant exact
window.__ev = [];
const marque = (k, id) => window.__ev.push({ k, id, t: Date.now() / 1000 });

/** Pilote la vraie interface dans une iframe : défiler, cliquer, taper. */
function pilote(iframe) {
  const doc = () => iframe.contentDocument, win = () => iframe.contentWindow;
  const parTexte = (sel, txt) => [...doc().querySelectorAll(sel)].find((e) => e.textContent.trim().startsWith(txt));
  return {
    vers(el, marge = 40) { if (el) win().scrollTo({ top: el.getBoundingClientRect().top + win().scrollY - marge, behavior: "smooth" }); },
    section(titre) { const h = parTexte("h2", titre); return h && h.closest("section"); },
    cliquer(txt) { const b = parTexte("button", txt); if (b) { marque("son", "clic"); b.click(); } },
    async taper(texte) {
      const champ = doc().querySelector("input");
      const pose = Object.getOwnPropertyDescriptor(win().HTMLInputElement.prototype, "value").set;
      champ.focus();
      for (let i = 1; i <= texte.length; i++) {
        pose.call(champ, texte.slice(0, i));
        champ.dispatchEvent(new (win().Event)("input", { bubbles: true }));
        if (texte[i - 1] !== " ") marque("son", "touche");
        await attendre(55 + Math.random() * 45);
      }
    },
    envoyer() { marque("son", "envoi"); doc().querySelector("form button[type=submit]").click(); },
    async reponseFinie(max = 90000) {
      // attendre la vraie réponse de Jexa, puis la fin de son écriture mot à mot (le curseur ▍ disparaît)
      const t0 = Date.now();
      const bulles = () => [...doc().querySelectorAll("div")].filter((d) => d.style.borderRadius === "22px 22px 22px 6px");
      const n0 = bulles().length;
      while (Date.now() - t0 < max && bulles().length <= n0) await attendre(100);
      marque("son", "plume");
      await attendre(300);
      while (Date.now() - t0 < max && bulles().at(-1)?.textContent.includes("▍")) await attendre(150);
      marque("son", "plume_fin");
    },
  };
}

function Film() {
  const [scene, setScene] = useState("affiche");  // affiche | interface | affiche2
  const [legende, setLegende] = useState(null);
  const [fin, setFin] = useState(false);
  const iframe = useRef(null);

  useEffect(() => {
    (async () => {
      const voix = Object.fromEntries((await (await fetch("/film-voix")).json()).map((v) => [v.id, v]));
      /** La voix dit sa phrase, la légende s'affiche pendant toute sa durée. */
      const dire = async (id, apres = 400, gros = false) => {
        const v = voix[id];
        marque("voix", id);
        if (v.legende) setLegende({ texte: v.legende, gros, id: Math.random() });
        await attendre(v.duree * 1000);
        await attendre(apres);
      };
      setTimeout(() => {  // pendant l'intro, Jexa écrit déjà son histoire et on prépare la carte de ses mots
        fetch("/api/carte");
        fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: HISTOIRE_FILM, monde: [], historique: [], preparer: true }) });
      }, 3500);

      await attendre(500);
      marque("son", "eveil");
      await attendre(1900);
      await dire("nuit1", 350);
      await dire("nuit2", 900);
      marque("son", "carillon");
      await attendre(250);
      await dire("nom", 1300, true);
      await dire("qui", 600);
      await dire("zero", 700);
      setLegende(null);

      // la vraie interface
      marque("son", "transition");
      setScene("interface");
      marque("musique", "rythme");
      const p = pilote(iframe.current);
      await attendre(1500);
      p.vers(p.section("Les leçons"), 30);
      await dire("lecons", 1500);
      p.vers(p.section("Parler avec Jexa"), 30);
      await attendre(700);
      await dire("lu", 200);
      await p.taper(HISTOIRE_FILM);
      await attendre(350);
      p.envoyer();
      dire("ecrit", 0);
      await p.reponseFinie();
      await attendre(1400);
      setLegende(null);
      p.vers(p.section("Le laboratoire"), 30);
      marque("musique", "basse");
      await attendre(600);
      await dire("seule", 450);
      await dire("teste", 700);
      p.vers(p.section("Son cerveau"), 30);
      await attendre(400);
      p.cliquer("Réseau vivant");
      await dire("pense", 900);
      p.cliquer("Carte des mots");
      await attendre(1800);
      p.cliquer("Histoire");
      await dire("donnees", 1100);
      setLegende(null);

      // retour à la nuit, puis l'appel
      marque("son", "transition");
      setScene("affiche2");
      await attendre(1300);
      marque("musique", "envol");
      await dire("debut", 500);
      await dire("finance", 600);
      await dire("pourquoi", 800);
      await dire("grandir", 1000, true);
      setLegende(null);
      marque("son", "final");
      setFin(true);
      await attendre(900);
      await dire("kick", 5200);
      marque("fin", "fin");
      document.body.dataset.fini = "1";
    })();
  }, []);

  const calque = (visible) => ({ position: "absolute", inset: 0, opacity: visible ? 1 : 0, transition: "opacity 1.2s ease", pointerEvents: "none" });
  return (
    <div style={{ width: 1920, height: 1080, position: "relative", overflow: "hidden", background: "#15131c" }}>
      <iframe src="/affiche?eveil" style={{ ...calque(scene === "affiche"), width: 1920, height: 1080, border: 0 }} />
      <div style={{ ...calque(scene === "interface"), display: "grid", placeItems: "center",
                    background: "radial-gradient(ellipse at 50% 40%, #2a2733, #15131c)" }}>
        <div style={{ width: 1920 * 0.86, height: 1080 * 0.86, borderRadius: 34, overflow: "hidden", boxShadow: "0 40px 90px -20px #000c, 0 0 0 10px #2c2a33",
                      transform: scene === "interface" ? "scale(1)" : "scale(.94)", transition: "transform 2.4s cubic-bezier(.2,.8,.2,1)", willChange: "transform" }}>
          <iframe ref={iframe} src="/cerveau" style={{ width: 1920 * 0.86, height: 1080 * 0.86, border: 0 }} />
        </div>
      </div>
      <iframe src="/affiche" style={{ ...calque(scene === "affiche2"), width: 1920, height: 1080, border: 0 }} />

      {/* légendes */}
      {legende && (
        <div key={legende.id} style={{ position: "absolute", left: 0, right: 0, bottom: legende.gros ? 440 : 70, display: "grid", placeItems: "center",
                                       animation: "monte .6s cubic-bezier(.2,.8,.2,1) both" }}>
          <div className="serif" style={{ background: legende.gros ? "transparent" : "rgba(21,19,28,.86)", color: "#fcf8f0",
                                           fontSize: legende.gros ? 110 : 50, fontWeight: legende.gros ? 900 : 700, padding: legende.gros ? 0 : "18px 40px",
                                           borderRadius: 99, textShadow: legende.gros ? "0 0 60px rgba(255,120,70,.6), 0 6px 30px #000" : "none",
                                           letterSpacing: "-.01em" }}>{legende.texte}</div>
        </div>
      )}

      {/* carte de fin */}
      <div style={{ ...calque(fin), background: "rgba(15,13,20,.9)", display: "grid", placeItems: "center" }}>
        <div style={{ textAlign: "center", color: "#fcf8f0", transform: fin ? "none" : "translateY(30px)", transition: "transform 1.6s cubic-bezier(.2,.8,.2,1)" }}>
          <div style={{ display: "inline-block", marginBottom: 30 }}><OrbeJexa taille={170} /></div>
          <div className="serif" style={{ fontSize: 150, fontWeight: 900, lineHeight: 1 }}>Jexa</div>
          <div style={{ fontSize: 38, marginTop: 22, opacity: .85 }}>Une IA française construite de zéro, qui s'améliore sous vos yeux.</div>
          <div style={{ display: "inline-block", marginTop: 46, background: "#d65f37", borderRadius: 99, padding: "20px 48px", fontSize: 40, fontWeight: 700,
                        boxShadow: "0 20px 50px -14px rgba(214,95,55,.8)" }}>Soutenez le projet sur Kickstarter</div>
          <div style={{ marginTop: 40, fontSize: 24, letterSpacing: ".3em", textTransform: "uppercase", opacity: .55 }}>Hexa Labs</div>
        </div>
      </div>
    </div>
  );
}

/* ================================================================== la page de conversation */
// position de la souris partagée par toutes les animations (sans re-rendu React)
const SOURIS = { x: innerWidth / 2, y: innerHeight / 2 };
addEventListener("mousemove", (e) => { SOURIS.x = e.clientX; SOURIS.y = e.clientY; });
addEventListener("message", (e) => {  // dans Hexa Browser : la position de la souris dans toute la fenetre (coordonnees de notre cadre)
  if (e.source === window.parent && e.data && e.data.type === "hexa-souris") { SOURIS.x = e.data.x; SOURIS.y = e.data.y; }
});

/** Jexa vivante : respire, cligne des yeux, suit la souris du regard (mouvement amorti, 60 i/s).
 *  etat : "repos" | "ecoute" (tu écris) | "reflechit" (elle cherche) | "parle" (elle écrit sa réponse) */
function JexaVivante({ taille = 120, etat = "repos", lunes = false, yeuxFermes = false }) {
  const ref = useRef(null), yeux = useRef([]);
  const etatRef = useRef(etat);
  etatRef.current = etat;
  useEffect(() => {
    let raf, x = 0, y = 0, vx = 0, vy = 0;
    const boucle = () => {
      const r = ref.current?.getBoundingClientRect();
      if (r) {
        let cx = 0, cy = 0;
        if (etatRef.current === "reflechit") { cx = 0.6; cy = -0.75; }  // elle lève les yeux pour réfléchir
        else {
          const dx = SOURIS.x - (r.left + r.width / 2), dy = SOURIS.y - (r.top + r.height / 2);
          const d = Math.hypot(dx, dy) || 1, k = Math.min(1, d / 350);
          cx = (dx / d) * k; cy = (dy / d) * k;
        }
        // ressort amorti : le regard glisse, accélère, ralentit, sans à-coups
        vx = (vx + (cx - x) * 0.09) * 0.78; vy = (vy + (cy - y) * 0.09) * 0.78;
        x += vx; y += vy;
        yeux.current.forEach((el) => el && (el.style.transform = `translate(${x * taille * 0.06}px, ${y * taille * 0.06}px)`));
      }
      raf = requestAnimationFrame(boucle);
    };
    raf = requestAnimationFrame(boucle);
    return () => cancelAnimationFrame(raf);
  }, [taille]);
  const hautOeil = etat === "ecoute" ? 0.24 : etat === "parle" ? 0.19 : 0.21;
  const corps = { repos: "respire 4s ease-in-out infinite", ecoute: "penche 1.6s ease-in-out infinite",
                  reflechit: "respire 1.4s ease-in-out infinite", parle: "parle .42s ease-in-out infinite" }[etat];
  const couleurs = ["#dfa92f", "#7debd2", "#f08a5d"];
  return (
    <div ref={ref} style={{ position: "relative", width: taille, height: taille, flexShrink: 0 }}>
      <div style={ABS({ inset: -taille * 0.3, borderRadius: "50%", background: "radial-gradient(circle, rgba(240,122,74,.38), rgba(240,122,74,0) 65%)",
                        animation: `halo ${etat === "reflechit" ? 1.1 : 3.6}s ease-in-out infinite` })} />
      {(etat === "reflechit" || lunes) && [0, 1, 2].map((i) => (
        <div key={i} style={ABS({ inset: lunes ? -taille * (0.22 + i * 0.13) : -taille * 0.12, borderRadius: "50%",
                                  border: lunes ? `1px dashed rgba(214,95,55,${0.18 - i * 0.04})` : "none",
                                  animation: `tourne ${lunes ? 9 + i * 5 : 1.5 + i * 0.4}s linear infinite ${i % 2 ? "reverse" : ""}`, animationDelay: `${-i * 0.7}s` })}>
          <div style={ABS({ left: "50%", top: -taille * 0.035, width: taille * (lunes ? 0.08 - i * 0.012 : 0.07), height: taille * (lunes ? 0.08 - i * 0.012 : 0.07),
                            borderRadius: "50%", background: couleurs[i], boxShadow: `0 0 ${taille * 0.1}px ${couleurs[i]}` })} />
        </div>
      ))}
      <div style={{ position: "absolute", inset: 0, animation: corps, transformOrigin: "50% 85%" }}>
        <div style={ABS({ inset: 0, borderRadius: "50%", background: "radial-gradient(circle at 36% 30%, #ffb08a 0%, #f07a4a 28%, #d65f37 58%, #9a3c1c 100%)",
                          boxShadow: `inset ${-taille * 0.07}px ${-taille * 0.1}px ${taille * 0.16}px rgba(80,20,5,.4), 0 ${taille * 0.08}px ${taille * 0.2}px rgba(150,60,20,.35)` })} />
        <div style={ABS({ left: taille * 0.2, top: taille * 0.11, width: taille * 0.34, height: taille * 0.2, borderRadius: "50%", background: "rgba(255,255,255,.4)", filter: `blur(${taille * 0.025}px)` })} />
        {[0.2, 0.68].map((x, i) => (
          <div key={i} style={ABS({ left: taille * x, top: taille * 0.6, width: taille * 0.13, height: taille * 0.07, borderRadius: "50%",
                                    background: "rgba(255,170,150,.6)", filter: `blur(${taille * 0.02}px)`, opacity: yeuxFermes || etat === "parle" || etat === "ecoute" ? 1 : 0.55, transition: "opacity .4s" })} />
        ))}
        {[0.34, 0.57].map((x, i) => (
          <div key={i} ref={(el) => (yeux.current[i] = el)} style={ABS({ left: taille * x, top: taille * 0.36, width: taille * 0.09, height: taille * hautOeil,
                                                                      transition: "height .3s", willChange: "transform" })}>
            <div style={{ width: "100%", height: "100%", borderRadius: 99, background: "#fff8ee", boxShadow: `0 0 ${taille * 0.06}px rgba(255,248,238,.8)`,
                          animation: yeuxFermes ? "none" : "cligne 4.6s 1s infinite", transformOrigin: "50% 70%",
                          transform: yeuxFermes ? "scaleY(.12)" : "none", transition: "transform .25s cubic-bezier(.34,1.56,.64,1)" }} />
          </div>
        ))}
      </div>
    </div>
  );
}

/** Le fond vivant : des lucioles chaudes qui dérivent, fuient doucement la souris, et tourbillonnent quand Jexa réfléchit. */
function Lucioles({ agite }) {
  const ref = useRef(null), agiteRef = useRef(agite);
  agiteRef.current = agite;
  useEffect(() => {
    const cv = ref.current, ctx = cv.getContext("2d");
    let raf, W, H;
    const taille = () => { W = cv.clientWidth; H = cv.clientHeight; cv.width = W * 1.5; cv.height = H * 1.5; ctx.setTransform(1.5, 0, 0, 1.5, 0, 0); };
    taille(); addEventListener("resize", taille);
    const TEINTES = { jour: ["240,138,93", "223,169,47", "125,200,180", "214,95,55"], nuit: ["139,108,255", "63,214,201", "230,185,74", "190,160,255"] };
    const pts = Array.from({ length: 46 }, () => ({ x: Math.random() * W, y: Math.random() * H, r: 1.5 + Math.random() * 4.5,
      vx: (Math.random() - 0.5) * 0.25, vy: -0.08 - Math.random() * 0.22, c: Math.floor(Math.random() * 4), p: Math.random() * 6.28 }));
    const boucle = (t) => {
      ctx.clearRect(0, 0, W, H);
      const r = cv.getBoundingClientRect(), mx = SOURIS.x - r.left, my = SOURIS.y - r.top;
      const a = agiteRef.current ? 1 : 0;
      const nuit = document.documentElement.dataset.theme === "nexus", teintes = nuit ? TEINTES.nuit : TEINTES.jour;
      for (const q of pts) {
        const dx = q.x - mx, dy = q.y - my, d = Math.hypot(dx, dy) || 1;
        if (d < 140) { q.vx += (dx / d) * 0.05; q.vy += (dy / d) * 0.05; }  // elles s'écartent de la souris
        if (a) { q.vx += (-(q.y - H / 2) / H) * 0.04; q.vy += ((q.x - W / 2) / W) * 0.04; }  // tourbillon quand elle réfléchit
        q.vx *= 0.985; q.vy = q.vy * 0.985 - 0.0025;
        q.x += q.vx * (1 + a * 2); q.y += q.vy * (1 + a * 2);
        if (q.y < -10) { q.y = H + 10; q.x = Math.random() * W; }
        if (q.x < -10) q.x = W + 10; if (q.x > W + 10) q.x = -10; if (q.y > H + 10) q.y = -10;
        const lueur = 0.35 + 0.35 * Math.sin(t / 900 + q.p);
        // parallaxe : les grosses lucioles sont "proches" et bougent plus avec la souris que les petites, lointaines
        const prof = q.r / 6, ox = (mx - W / 2) * prof * 0.05, oy = (my - H / 2) * prof * 0.05, x = q.x + ox, y = q.y + oy;
        const c = teintes[q.c], l = nuit ? Math.min(1, lueur * 1.25) : lueur;
        ctx.fillStyle = `rgba(${c},${l * (nuit ? 0.32 : 0.25)})`; ctx.beginPath(); ctx.arc(x, y, q.r * (nuit ? 3.6 : 3), 0, 6.28); ctx.fill();
        ctx.fillStyle = `rgba(${c},${l})`; ctx.beginPath(); ctx.arc(x, y, q.r, 0, 6.28); ctx.fill();
      }
      raf = requestAnimationFrame(boucle);
    };
    raf = requestAnimationFrame(boucle);
    return () => { cancelAnimationFrame(raf); removeEventListener("resize", taille); };
  }, []);
  return <canvas ref={ref} style={{ position: "absolute", inset: 0, width: "100%", height: "100%", pointerEvents: "none" }} />;
}

/** Une lumière douce qui suit la souris dans le panneau. */
function Projecteur() {
  const ref = useRef(null);
  useEffect(() => {
    let raf, x = 0, y = 0;
    const boucle = () => {
      const el = ref.current, r = el?.parentElement.getBoundingClientRect();
      if (r) {
        x += (SOURIS.x - r.left - x) * 0.08; y += (SOURIS.y - r.top - y) * 0.08;
        const nuit = document.documentElement.dataset.theme === "nexus";
        el.style.background = nuit
          ? `radial-gradient(560px circle at ${x}px ${y}px, rgba(139,108,255,.20), rgba(63,214,201,.06) 45%, transparent 65%)`
          : `radial-gradient(600px circle at ${x}px ${y}px, rgba(255,214,170,.35), transparent 60%)`;
      }
      raf = requestAnimationFrame(boucle);
    };
    raf = requestAnimationFrame(boucle);
    return () => cancelAnimationFrame(raf);
  }, []);
  return <div ref={ref} style={{ position: "absolute", inset: 0, pointerEvents: "none" }} />;
}

/* ------------------------------------------------------------------ le compte Hexa et la mémoire à long terme */
// Le navigateur parle DIRECTEMENT au site Hexa : le serveur de Jexa ne voit jamais ton mot de passe.
const HEXA_API = (() => { try { return localStorage.getItem("hexa_api") || "https://hexa-mc.fr"; } catch { return "https://hexa-mc.fr"; } })();
const HEXA_SECOURS = "http://localhost:3000";  // si le site en ligne ne repond pas : le serveur Hexa de ce PC
const NOMS_SOUVENIRS = { prenom: "ton prénom", aime: "ce que tu aimes", journee: "ta journée" };
const lireJson = (k, d) => { try { return JSON.parse(localStorage.getItem(k)) ?? d; } catch { return d; } };
const ecrireJson = (k, v) => { try { v == null ? localStorage.removeItem(k) : localStorage.setItem(k, JSON.stringify(v)); } catch {} };

function TeteSkin({ pseudo, lettre, couleur, taille = 36 }) {
  const [skin, setSkin] = useState(null);
  useEffect(() => {
    setSkin(null);
    if (!pseudo) return;
    let fini = false;
    fetch(HEXA_API + "/api/csl/" + encodeURIComponent(pseudo) + ".json").then((r) => r.json()).then((d) => {
      const f = d && d.skins && (d.skins.slim || d.skins.default || Object.values(d.skins)[0]);
      if (!fini && f) setSkin(HEXA_API + "/api/csl/textures/" + f);
    }).catch(() => {});
    return () => { fini = true; };
  }, [pseudo]);
  const boite = { width: taille, height: taille, borderRadius: 10, flexShrink: 0, overflow: "hidden", position: "relative", boxShadow: "0 6px 14px -8px #0008" };
  if (!skin) return <span style={{ ...boite, background: couleur, color: "#fff", display: "grid", placeItems: "center", fontWeight: 700 }}>{lettre}</span>;
  const couche = (x) => ({ position: "absolute", inset: 0, backgroundImage: `url(${skin})`, backgroundSize: `${taille * 8}px auto`, backgroundPosition: `-${taille * x}px -${taille}px`, imageRendering: "pixelated" });
  return <span style={{ ...boite, background: "#0002" }}><span style={couche(1)} /><span style={couche(5)} /></span>;
}

function useCompteHexa() {
  const [compte, setCompte] = useState(() => lireJson("jexa_compte", null));
  const [souvenirs, setSouvenirs] = useState([]);
  const appel = async (chemin, options = {}, jeton = compte?.jeton, base = compte?.api) => {
    const essayer = (b) => fetch(b + "/api/jexa" + chemin, { ...options,
      headers: { "Content-Type": "application/json", ...(jeton ? { Authorization: "Bearer " + jeton } : {}) } })
      .then(async (r) => { const data = await r.json().catch(() => null); if (!data && r.status >= 500) throw new Error("hors ligne"); return [r, data || {}, b]; });
    let res;
    if (base) res = await essayer(base);
    else {  // le site en ligne d'abord, puis celui de ce PC
      try { res = await essayer(HEXA_API); if (res[0].status >= 500 || res[0].status === 404) throw new Error(); }
      catch { res = await essayer(HEXA_SECOURS); }
    }
    const [r, data, utilise] = res;
    data._api = utilise;
    if (r.status === 401 && jeton) { setCompte(null); ecrireJson("jexa_compte", null); }
    return { ok: r.ok, ...data };
  };
  const charger = async (jeton = compte?.jeton) => {
    if (!jeton) return;
    const r = await appel("/souvenirs", {}, jeton);
    if (r.ok) setSouvenirs(r.souvenirs || []);
  };
  useEffect(() => { charger(); }, [compte?.jeton]);
  return {
    compte, souvenirs,
    async connecter(identifiant, motDePasse, code) {
      const r = await appel("/connexion", { method: "POST", body: JSON.stringify({ identifiant, motDePasse, code: code || undefined }) }, null);
      if (r.jeton) { const c = { jeton: r.jeton, pseudo: r.pseudo, api: r._api }; setCompte(c); ecrireJson("jexa_compte", c); }
      return r;
    },
    // HEXA Link : code à usage unique (confirmé dans la popup HEXA Link) → jeton Jexa, sans mot de passe
    async connecterLien(codeLien) {
      const r = await appel("/lien", { method: "POST", body: JSON.stringify({ code: codeLien }) }, null);
      if (r.jeton) { const c = { jeton: r.jeton, pseudo: r.pseudo, api: r._api }; setCompte(c); ecrireJson("jexa_compte", c); }
      return r;
    },
    async deconnecter() { await appel("/deconnexion", { method: "POST" }).catch(() => {}); setCompte(null); setSouvenirs([]); ecrireJson("jexa_compte", null); },
    adopter(c) { setCompte(c); ecrireJson("jexa_compte", c); },  // Hexa Browser nous donne son compte (deja connecte)
    async retenir(cle, valeur) {
      setSouvenirs((s) => [{ cle, valeur, maj: Date.now() }, ...s.filter((x) => x.cle !== cle)]);
      await appel("/souvenirs", { method: "POST", body: JSON.stringify({ cle, valeur }) });
    },
    async oublier(cle) {  // cle absente = TOUT oublier (droit à l'oubli)
      setSouvenirs((s) => (cle ? s.filter((x) => x.cle !== cle) : []));
      await appel("/oublier", { method: "POST", body: JSON.stringify(cle ? { cle } : {}) });
    },
  };
}

const Fenetre = ({ titre, fermer, children, yeuxFermes }) => (
  <div onClick={fermer} style={{ position: "fixed", inset: 0, zIndex: 1000, background: "rgba(36,35,43,.35)", display: "grid", placeItems: "center", animation: "monte .3s ease both" }}>
    <div onClick={(e) => e.stopPropagation()} className="profond" style={{ width: "min(440px, 92vw)", background: "var(--papier)", borderRadius: 30, padding: "28px 30px", boxShadow: "0 40px 80px -30px #0008",
                                                       animation: "pop .5s cubic-bezier(.34,1.56,.64,1) both", position: "relative" }}>
      <button onClick={fermer} style={{ position: "absolute", top: 16, right: 18, border: 0, background: "transparent", fontSize: 18, color: "var(--doux)", cursor: "pointer" }}>✕</button>
      <div style={{ display: "flex", alignItems: "center", gap: 12, marginBottom: 18 }}>
        <JexaVivante taille={52} yeuxFermes={yeuxFermes} />
        <h2 className="serif" style={{ fontSize: 24, fontWeight: 800 }}>{titre}</h2>
      </div>
      {children}
    </div>
  </div>
);

/** Un œil tout simple : ouvert quand le mot de passe est caché, il se ferme (la paupière descend) quand on l'affiche. */
function OeilSimple({ ferme }) {
  const anim = "all .32s cubic-bezier(.34,1.56,.64,1)";
  return (
    <svg viewBox="0 0 24 24" width="22" height="22" fill="none" stroke="var(--encre-2)" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
      {/* le blanc de l'œil et la pupille s'aplatissent quand il se ferme */}
      <g style={{ transformOrigin: "12px 12px", transformBox: "view-box", transform: ferme ? "scaleY(.05)" : "none", transition: anim }}>
        <path d="M2.5 12s3.5-6.5 9.5-6.5S21.5 12 21.5 12s-3.5 6.5-9.5 6.5S2.5 12 2.5 12z" />
        <circle cx="12" cy="12" r="2.8" fill="var(--encre-2)" />
      </g>
      {/* la paupière fermée, avec trois petits cils */}
      <g style={{ opacity: ferme ? 1 : 0, transform: ferme ? "none" : "translateY(-3px)", transformBox: "view-box", transition: anim }}>
        <path d="M2.5 12.5q9.5 6 19 0" />
        <path d="M7 15.6l-1 2M12 16.8v2.2M17 15.6l1 2" />
      </g>
    </svg>
  );
}
function FenetreConnexion({ fermer, connecter }) {
  const [id, setId] = useState(""), [mdp, setMdp] = useState(""), [code, setCode] = useState("");
  const [besoin2fa, setBesoin2fa] = useState(false), [erreur, setErreur] = useState(""), [attente, setAttente] = useState(false);
  const [voir, setVoir] = useState(false);  // mot de passe visible -> Jexa ferme les yeux pour ne pas regarder
  const champ = { width: "100%", border: "1.5px solid var(--ligne)", borderRadius: 16, padding: "12px 16px", fontSize: 15.5, fontFamily: "inherit", outline: "none", background: "var(--surface)", marginBottom: 10 };
  const envoyer = async (e) => {
    e.preventDefault(); setErreur(""); setAttente(true);
    try {
      const r = await connecter(id, mdp, besoin2fa ? code : null);
      if (r.requires_2fa) setBesoin2fa(true);
      else if (r.jeton) fermer();
      else setErreur(r.erreur || "Connexion impossible.");
    } catch { setErreur("Je n'arrive pas à joindre le site Hexa."); }
    finally { setAttente(false); }
  };
  return (
    <Fenetre titre="Se connecter avec Hexa" fermer={fermer} yeuxFermes={voir && !besoin2fa}>
      <p style={{ fontSize: 14, color: "var(--doux)", marginTop: 0 }}>
        Avec ton compte Hexa, je me souviens de toi d'une discussion à l'autre. Tes souvenirs restent dans ton compte, et tu peux les effacer quand tu veux.</p>
      <form onSubmit={envoyer}>
        {!besoin2fa ? <>
          <input style={champ} placeholder="Pseudo ou e-mail" value={id} onChange={(e) => setId(e.target.value)} autoFocus />
          <div style={{ position: "relative" }}>
            <input style={{ ...champ, paddingRight: 52 }} type={voir ? "text" : "password"} placeholder="Mot de passe" value={mdp} onChange={(e) => setMdp(e.target.value)}
                   className="sans-oeil" />
            <button type="button" onClick={() => setVoir(!voir)} title={voir ? "Cacher le mot de passe" : "Afficher le mot de passe"}
                    style={{ position: "absolute", right: 7, top: 6, width: 38, height: 38, borderRadius: "50%", border: 0, cursor: "pointer", padding: 0,
                             display: "grid", placeItems: "center", background: "transparent" }}>
              <OeilSimple ferme={voir} /></button>
          </div>
          {/* la ligne reste toujours là : l'espacement ne saute pas, seul le texte change en fondu */}
          <div style={{ position: "relative", height: 18, margin: "-4px 0 12px 6px", fontSize: 12.5, color: "var(--doux)" }}>
            {[["Ton mot de passe reste secret.", !voir], ["(je ferme les yeux, promis !)", voir]].map(([txt, actif]) => (
              <span key={txt} style={{ position: "absolute", left: 0, top: 0, whiteSpace: "nowrap", opacity: actif ? 1 : 0,
                                       transform: actif ? "none" : "translateY(4px)", transition: "opacity .3s, transform .3s" }}>{txt}</span>
            ))}
          </div>
        </> : <input style={champ} placeholder="Code de double authentification" value={code} onChange={(e) => setCode(e.target.value)} autoFocus inputMode="numeric" />}
        {erreur && <div style={{ color: "var(--tomate)", fontSize: 13.5, marginBottom: 10 }}>{erreur}</div>}
        <button className="btn rebond relief" disabled={attente} style={{ width: "100%", background: "var(--tomate)", color: "#fff", padding: "13px", fontSize: 15.5 }}>
          {attente ? "Un instant…" : besoin2fa ? "Valider le code" : "Se connecter"}</button>
      </form>
      <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 14, textAlign: "center" }}>
        Pas de compte ? <a href="https://hexa-mc.fr/register" target="_blank" style={{ color: "var(--tomate)" }}>Crée-le sur Hexa</a></div>
    </Fenetre>
  );
}

function FenetreSouvenirs({ fermer, souvenirs, oublier }) {
  return (
    <Fenetre titre="Ce dont je me souviens" fermer={fermer}>
      {souvenirs.length === 0 ? <p style={{ color: "var(--doux)" }}>Rien pour l'instant ! Dis-moi ton prénom, ce que tu aimes, ou raconte-moi ta journée.</p> : (
        <div style={{ display: "flex", flexDirection: "column", gap: 8, marginBottom: 16 }}>
          {souvenirs.map((s) => (
            <div key={s.cle} className="relief" data-force="3" style={{ display: "flex", alignItems: "center", gap: 10, background: "var(--surface)", border: "1px solid var(--ligne)", borderRadius: 16, padding: "10px 14px" }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 12, color: "var(--doux)", fontWeight: 700, textTransform: "uppercase", letterSpacing: ".08em" }}>{NOMS_SOUVENIRS[s.cle] || s.cle}</div>
                <div style={{ fontSize: 15 }}>{s.valeur}</div>
              </div>
              <button onClick={() => oublier(s.cle)} title="Oublier" style={{ border: 0, background: "var(--creme)", borderRadius: 99, width: 30, height: 30, cursor: "pointer", color: "var(--doux)" }}>✕</button>
            </div>
          ))}
        </div>
      )}
      {souvenirs.length > 0 && <button className="btn relief" onClick={() => oublier()} style={{ width: "100%", background: "var(--tomate-c)", color: "var(--tomate)" }}>Tout oublier</button>}
      <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 12 }}>Stockés dans ton <b>Hexa Vault</b>. Jamais revendus.</div>
    </Fenetre>
  );
}

const lireDiscussions = () => { try { return JSON.parse(localStorage.getItem("jexa_discussions") || "[]"); } catch { return []; } };
const garderDiscussions = (d) => { try { localStorage.setItem("jexa_discussions", JSON.stringify(d.slice(0, 40))); } catch {} };
const lireNom = () => { try { return localStorage.getItem("jexa_nom") || ""; } catch { return ""; } };
const COLONNE = 760;  // largeur de la colonne centrale : messages, saisie et suggestions alignés

function Discuter() {
  const [etat, setEtat] = useState(null);
  const [discussions, setDiscussions] = useState(lireDiscussions);
  const [courante, setCourante] = useState(null);
  const [texte, setTexte] = useState("");
  const [attente, setAttente] = useState(false);
  const [parle, setParle] = useState(false);
  const [focus, setFocus] = useState(false);
  const [nom, setNom] = useState(lireNom);
  const [nomTemp, setNomTemp] = useState("");
  const { compte, souvenirs, connecter, deconnecter, retenir, oublier } = useCompteHexa();
  const [fenetre, setFenetre] = useState(null);  // null | "connexion" | "souvenirs"
  const [retenu, setRetenu] = useState(null);    // petite bulle "je retiens…"
  const [menu, setMenu] = useState(false);
  const prenom = souvenirs.find((s) => s.cle === "prenom")?.valeur;
  const nomAffiche = prenom || nom || compte?.pseudo || "";
  const zone = useRef(null), champ = useRef(null);
  const [estPublic, setEstPublic] = useState(true);
  useEffect(() => { fetch("/api/principal").then((r) => r.json()).then((d) => setEstPublic(!!d.public)).catch(() => {}); }, []);
  const modele = "nexus";  // Jexa (son cerveau a regions) : la seule IA, plus de choix a faire
  const [theme, setTheme] = useState(() => { try { return localStorage.getItem("jexa_theme") || "jour"; } catch { return "jour"; } });
  useEffect(() => {  // theme de nuit (violet et cyan) ou de jour (creme)
    try { localStorage.setItem("jexa_theme", theme); } catch {}
    if (theme === "nuit") document.documentElement.dataset.theme = "nexus"; else delete document.documentElement.dataset.theme;
    return () => { delete document.documentElement.dataset.theme; };
  }, [theme]);

  useEffect(() => { fetch("/api/etat").then((r) => r.json()).then(setEtat); }, []);
  useEffect(() => { garderDiscussions(discussions); }, [discussions]);
  const conv = discussions.find((d) => d.id === courante);
  useEffect(() => { zone.current && zone.current.scrollTo({ top: zone.current.scrollHeight, behavior: "smooth" }); });

  const heure = new Date().getHours();
  const salut = heure < 5 || heure >= 18 ? "Bonsoir" : "Bonjour";
  const nouvelle = () => { setMenu(false); setCourante(null); setTexte(""); setTimeout(() => champ.current?.focus(), 50); };

  const envoyer = async (t = texte) => {
    if (!t.trim() || attente) return;
    let d = conv;
    if (!d) {
      const monde = await (await fetch("/api/monde")).json();
      d = { id: Date.now().toString(36), titre: t.slice(0, 42), monde, messages: [], date: Date.now() };
    }
    const historique = d.messages.filter((m) => !m.erreur).map((m) => ({ qui: m.qui, texte: m.texte }));
    d = { ...d, messages: [...d.messages, { qui: "toi", texte: t }] };
    setDiscussions((ds) => [d, ...ds.filter((x) => x.id !== d.id)]);
    setCourante(d.id); setTexte(""); setAttente(true);
    try {
      const r = await (await fetch("/api/parler", { method: "POST", body: JSON.stringify({ texte: t, monde: d.monde, historique, souvenirs, modele, fichier: d.fichier }) })).json();
      if (compte && r.retenir?.length) {  // ce qu'elle retient part dans TON compte Hexa (base de données Hexa)
        r.retenir.forEach((s) => retenir(s.cle, s.valeur));
        setRetenu(r.retenir); setTimeout(() => setRetenu(null), 4500);
      }
      setParle(true);
      setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, messages: [...x.messages, { qui: "jexa", texte: r.reponse || r.erreur, erreur: !!r.erreur, correction: r.correction, outil: r.outil, modele: r.modele, neuf: true }] } : x)));
    } catch {
      setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, messages: [...x.messages, { qui: "jexa", texte: "Oups, je n'arrive pas à réfléchir pour le moment. Réessaie dans un instant.", erreur: true }] } : x)));
    } finally { setAttente(false); setTimeout(() => champ.current?.focus(), 50); }
  };
  const finiDeParler = () => {
    setParle(false);
    setDiscussions((ds) => ds.map((x) => ({ ...x, messages: x.messages.map((m) => ({ ...m, neuf: false })) })));
  };

  const humeur = attente ? "reflechit" : parle ? "parle" : texte ? "ecoute" : "repos";
  const idees = [
    { icone: "🌐", texte: "qui est Victor Hugo ?", label: "Qui est Victor Hugo ?" },
    { icone: "✉️", texte: "tu peux m'aider à écrire un message ?", label: "M'aider à écrire un message" },
    { icone: "📖", texte: "raconte Il était une fois une petite souris qui", label: "Raconte-moi une histoire" },
  ];
  const derniereJexa = conv ? conv.messages.map((m) => m.qui).lastIndexOf("jexa") : -1;

  const saisie = (grand) => (
    <div className="profond" style={{ width: "100%", maxWidth: COLONNE, position: "relative", borderRadius: 32, padding: 2,
                  background: focus ? "conic-gradient(from var(--angle), #f08a5d, #dfa92f, #7debd2, #f08a5d)" : "var(--ligne)",
                  animation: focus ? "anneau 4s linear infinite" : "none", boxShadow: focus ? "0 20px 50px -24px rgba(214,95,55,.6)" : "0 18px 40px -26px rgba(110,70,20,.45)",
                  transition: "box-shadow .4s" }}>
      <form onSubmit={(e) => { e.preventDefault(); envoyer(); }} style={{ background: "var(--surface)", borderRadius: 30, padding: grand ? "10px 10px 10px 20px" : "10px 10px 10px 22px",
            display: "flex", alignItems: "center", gap: 10 }}>
        <label title="Joindre un fichier (PDF, Word, HTML, texte, image…)" style={{ cursor: "pointer", fontSize: 20, alignSelf: "center", padding: "0 4px", opacity: .75 }}>
          📎<input type="file" style={{ display: "none" }} accept=".pdf,.docx,.html,.htm,.txt,.md,.csv,.json,.py,.js,.css,.png,.jpg,.jpeg,.webp,.gif,.bmp"
                   onChange={(e) => { const f = e.target.files[0]; e.target.value = ""; if (f) joindre(f); }} />
        </label>
        <textarea ref={champ} value={texte} rows={1} placeholder="Écris à Jexa…" onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
                  onChange={(e) => setTexte(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); envoyer(); } }}
                  style={{ flex: 1, border: 0, outline: "none", resize: "none", background: "transparent", fontFamily: "inherit", fontSize: 17, lineHeight: 1.6, color: "var(--encre)", padding: "6px 0" }} />
        <button type="submit" disabled={!texte.trim() || attente} className="envoi" style={{ width: 46, height: 46, borderRadius: "50%", border: 0, flexShrink: 0,
                background: texte.trim() ? "var(--tomate)" : "var(--creme-fonce)", color: "#fff", fontSize: 20, transition: "all .3s cubic-bezier(.34,1.56,.64,1)",
                transform: texte.trim() ? "scale(1) translateY(0)" : "scale(.86) translateY(2px)", opacity: texte.trim() ? 1 : 0.7, boxShadow: texte.trim() ? "0 8px 18px -8px rgba(214,95,55,.9)" : "none" }}>↑</button>
      </form>
    </div>
  );

  return (
    <div className="ecran-disc" style={{ display: "flex", height: "100vh", background: "var(--creme)" }}>
      {menu && <div className="voile-menu" onClick={() => setMenu(false)} />}
      <aside className={"cote" + (menu ? " ouvert" : "")} style={{ width: 272, display: "flex", flexDirection: "column", padding: "14px 12px 14px 16px", gap: 6, flexShrink: 0 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "6px 6px 18px" }}>
          <JexaVivante taille={40} etat={humeur} />
          <span className="serif" style={{ fontSize: 28, fontWeight: 900 }}>Jexa</span>
          <button onClick={() => setTheme(theme === "nuit" ? "jour" : "nuit")} title={theme === "nuit" ? "Passer en thème de jour" : "Passer en thème de nuit"}
                  className="relief" data-force="3" style={{ marginLeft: "auto", border: 0, width: 36, height: 36, borderRadius: 99, cursor: "pointer", fontSize: 16,
                  background: "var(--creme-fonce)", color: "var(--encre)" }}>{theme === "nuit" ? "☀" : "🌙"}</button>
        </div>
        <button onClick={nouvelle} className="btn rebond relief" style={{ background: "var(--tomate)", color: "#fff", textAlign: "left", padding: "12px 18px", fontSize: 15,
                boxShadow: "0 10px 20px -12px rgba(214,95,55,.9)" }}>＋ Nouvelle discussion</button>
        <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".12em", margin: "18px 8px 6px" }}>Nos discussions</div>
        <div style={{ flex: 1, overflowY: "auto", display: "flex", flexDirection: "column", gap: 2 }}>
          {discussions.length === 0 && <div style={{ fontSize: 14, color: "var(--doux)", padding: 8 }}>Pas encore de discussion. Dis-moi bonjour !</div>}
          {discussions.map((d, i) => (
            <div key={d.id} onClick={() => { setCourante(d.id); setMenu(false); }} className="ligne-disc relief" data-force="3" style={{ display: "flex", alignItems: "center", gap: 6, padding: "10px 12px", borderRadius: 16,
                 cursor: "pointer", background: d.id === courante ? "var(--surface)" : "transparent", fontSize: 14.5, animation: `glisse .45s ${i * 30}ms cubic-bezier(.34,1.56,.64,1) both` }}>
              <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.titre}</span>
              <span onClick={(e) => { e.stopPropagation(); setDiscussions((ds) => ds.filter((x) => x.id !== d.id)); if (d.id === courante) setCourante(null); }}
                    title="Effacer" style={{ color: "var(--doux)", fontSize: 13, opacity: .6 }}>✕</span>
            </div>
          ))}
        </div>
        {!estPublic && <a href="/atelier" className="ligne-disc relief" data-force="3" style={{ textDecoration: "none", color: "var(--encre)", fontSize: 14.5, padding: "10px 12px", borderRadius: 16, background: "var(--surface)",
           display: "flex", gap: 8, alignItems: "center" }}><span>🎨</span> L'atelier pixel</a>}
        {!estPublic && <a href="/coeur" className="ligne-disc relief" data-force="3" style={{ textDecoration: "none", color: "var(--encre)", fontSize: 14.5, padding: "10px 12px", borderRadius: 16, background: "var(--surface)",
           display: "flex", gap: 8, alignItems: "center" }}><span>💗</span> Le cœur de Jexa <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--doux)" }}>rien que toi</span></a>}
        <a href="/cerveau" className="ligne-disc relief" data-force="3" style={{ textDecoration: "none", color: "var(--encre)", fontSize: 14.5, padding: "10px 12px", borderRadius: 16, background: "var(--surface)",
           display: "flex", gap: 8, alignItems: "center" }}><span>🧠</span> Voir son cerveau et ses leçons</a>
        {compte ? (
          <button className="ligne-disc relief" data-force="3" onClick={() => { setMenu(false); setFenetre("souvenirs"); }} style={{ border: 0, textAlign: "left", fontFamily: "inherit", color: "var(--encre)",
                  fontSize: 14.5, padding: "10px 12px", borderRadius: 16, background: "var(--surface)", display: "flex", gap: 8, alignItems: "center", cursor: "pointer" }}>
            <span>💭</span> Mes souvenirs avec Jexa <span className="pill" style={{ marginLeft: "auto", background: "var(--sarcelle-c)", fontSize: 11, padding: "2px 8px" }}>{souvenirs.length}</span>
          </button>
        ) : (
          <button className="btn rebond relief" onClick={() => { setMenu(false); setFenetre("connexion"); }} style={{ background: "var(--encre)", color: "var(--papier)", padding: "11px 16px", fontSize: 14 }}>
            Se connecter avec Hexa</button>
        )}
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "12px 8px 2px" }}>
          <TeteSkin pseudo={compte?.pseudo} lettre={(nomAffiche || "?")[0].toUpperCase()} couleur={compte ? "var(--tomate)" : "var(--sarcelle)"} />
          <div style={{ minWidth: 0, flex: 1, lineHeight: 1.25 }}>
            <div style={{ fontSize: 14.5, fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{nomAffiche || "Invité"}</div>
            {compte && <div style={{ fontSize: 11.5, color: "var(--doux)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", marginTop: 2 }}>
              <a href="#" onClick={(e) => { e.preventDefault(); deconnecter(); }} style={{ color: "var(--doux)" }}>Se déconnecter</a></div>}
          </div>
          {etat && <span className="pill" style={{ flexShrink: 0, background: "var(--moutarde-c)", fontSize: 11, padding: "3px 8px", whiteSpace: "nowrap" }}>v{etat.version} · niv. {etat.niveau}</span>}
        </div>
      </aside>
      {fenetre === "connexion" && <FenetreConnexion fermer={() => setFenetre(null)} connecter={connecter} />}
      {fenetre === "souvenirs" && <FenetreSouvenirs fermer={() => setFenetre(null)} souvenirs={souvenirs} oublier={oublier} />}
      {retenu && (
        <div className="bulle-retenu" style={{ position: "fixed", bottom: 26, right: 30, zIndex: 60, background: "var(--encre)", color: "var(--papier)", borderRadius: 22, padding: "12px 18px",
                      boxShadow: "0 20px 40px -18px #000a", animation: "pop .5s cubic-bezier(.34,1.56,.64,1) both", fontSize: 14 }}>
          💭 Je retiens : {retenu.map((s) => `${NOMS_SOUVENIRS[s.cle] || s.cle} → ${s.valeur}`).join(" · ")}
        </div>
      )}

      {/* le grand panneau arrondi, encadré en haut et à droite par la couleur de la barre */}
      <main style={{ flex: 1, minWidth: 0, margin: "10px 10px 10px 0", borderRadius: 30, background: "var(--papier)", position: "relative", overflow: "hidden",
                     display: "flex", flexDirection: "column", boxShadow: "0 1px 0 #fff inset, 0 20px 50px -30px rgba(110,70,20,.4)", border: "1px solid var(--ligne)" }}>
        <Lucioles agite={attente} />
        <Projecteur />
        <div className="barre-mobile">
          <button type="button" onClick={() => setMenu(true)} aria-label="Ouvrir le menu" className="barre-bouton">☰</button>
          <span className="serif" style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 22, fontWeight: 900 }}><JexaVivante taille={28} etat={humeur} />Jexa</span>
          <button type="button" onClick={nouvelle} aria-label="Nouvelle discussion" className="barre-bouton">＋</button>
        </div>
        {!conv ? (
          <div className="accueil-disc" style={{ flex: 1, display: "flex", flexDirection: "column", alignItems: "center", justifyContent: "center", padding: 24, gap: 26, position: "relative" }}>
            <div style={{ animation: "atterrit 1.1s cubic-bezier(.34,1.56,.64,1) both" }}><JexaVivante taille={150} etat={humeur} lunes /></div>
            <h1 className="serif" style={{ fontSize: "clamp(34px, 9vw, 48px)", fontWeight: 800, textAlign: "center", margin: "18px 0 0" }}>
              {(salut + (nomAffiche ? `, ${nomAffiche}` : "") + " !").split("").map((c, i) => (
                <span key={i} style={{ display: "inline-block", whiteSpace: "pre", animation: `lettre .6s ${0.25 + i * 0.035}s cubic-bezier(.34,1.56,.64,1) both` }}>{c}</span>
              ))} <span style={{ color: "var(--tomate)", display: "inline-block", animation: "scintille 2.4s ease-in-out infinite" }}>✦</span></h1>
            {!nomAffiche ? (
              <form onSubmit={(e) => { e.preventDefault(); const n = nomTemp.trim(); if (n) { setNom(n); try { localStorage.setItem("jexa_nom", n); } catch {} } }}
                    style={{ display: "flex", flexWrap: "wrap", justifyContent: "center", gap: 8, alignItems: "center", marginTop: -10 }}>
                <span style={{ fontSize: 17, color: "var(--doux)", flexBasis: "100%", textAlign: "center" }}>Comment je t'appelle ?</span>
                <input value={nomTemp} onChange={(e) => setNomTemp(e.target.value)} placeholder="Ton prénom"
                       style={{ border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "10px 18px", fontSize: 16, fontFamily: "inherit", outline: "none", width: 170, background: "var(--surface)" }} />
                <button className="btn rebond relief" style={{ background: "var(--sarcelle)", color: "#fff" }}>Enchantée !</button>
              </form>
            ) : <div style={{ fontSize: 18, color: "var(--doux)", marginTop: -12, textAlign: "center", padding: "0 8px", textWrap: "balance" }}>Qu'est-ce qu'on fait ensemble aujourd'hui ?</div>}
            {saisie(true)}
            <div style={{ display: "flex", gap: 10, flexWrap: "wrap", justifyContent: "center", maxWidth: COLONNE }}>
              {idees.map((s, i) => (
                <button key={s.label} className="btn puce relief" onClick={() => envoyer(s.texte)}
                        style={{ background: "var(--surface)", border: "1.5px solid var(--ligne)", color: "var(--encre-2)", fontWeight: 500, padding: "10px 16px",
                                 animation: `pop .6s ${0.5 + i * 0.08}s cubic-bezier(.34,1.56,.64,1) both` }}>{s.icone} {s.label}</button>
              ))}
            </div>
          </div>
        ) : (
          <>
            <div ref={zone} className="fil-disc" style={{ flex: 1, overflowY: "auto", padding: "34px 24px 24px", position: "relative" }}>
              <div style={{ maxWidth: COLONNE, margin: "0 auto", display: "flex", flexDirection: "column", gap: 22 }}>
                {false && conv.monde?.length > 0 && (  // (son "petit monde" d'ecole : plus montre en discussion)
                  <div style={{ alignSelf: "center", display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center", fontSize: 13 }}>
                    <span style={{ color: "var(--doux)", alignSelf: "center" }}>Son petit monde :</span>
                    {conv.monde.map((e, i) => <span key={i} className="pill" style={{ background: ["var(--bleu-c)", "var(--moutarde-c)", "var(--sarcelle-c)"][i % 3], fontWeight: 500,
                                                                    animation: `pop .5s ${i * 0.1}s cubic-bezier(.34,1.56,.64,1) both` }}>{e.texte}</span>)}
                  </div>
                )}
                {conv.messages.map((m, i) => m.qui === "toi" ? (
                  <div key={i} className="relief sombre" style={{ alignSelf: "flex-end", maxWidth: "78%", background: "var(--encre)", color: "var(--papier)", padding: "13px 19px",
                                        borderRadius: "24px 24px 8px 24px", fontSize: 16.5, lineHeight: 1.55, transformOrigin: "100% 100%",
                                        animation: "bulleToi .55s cubic-bezier(.34,1.56,.64,1) both" }}>{m.texte}</div>
                ) : (
                  <div key={i} style={{ display: "flex", gap: 14, alignItems: "flex-start", transformOrigin: "0 0", animation: "bulleJexa .6s cubic-bezier(.34,1.56,.64,1) both" }}>
                    {/* une seule tête : à côté de sa dernière réponse (sauf quand elle réfléchit en dessous) */}
                    <div style={{ width: 38, flexShrink: 0 }}>{i === derniereJexa && !attente && <JexaVivante taille={38} etat={m.neuf && parle ? "parle" : "repos"} />}</div>
                    <div style={{ flex: 1, minWidth: 0, paddingTop: 6 }}>
                      {m.outil && (
                        <div className="pill" style={{ background: "var(--bleu-c)", color: "var(--bleu)", marginBottom: 8, fontSize: 12.5, animation: "pop .5s cubic-bezier(.34,1.56,.64,1) both" }}>
                          {{ "Wikipédia": "🌐", "Météo (Open-Meteo)": "🌦️", "Ton fichier": "📎" }[m.outil.source] || "📖"} J'ai cherché « {m.outil.mot} » {m.outil.source === "Météo (Open-Meteo)" ? "dans la météo" : `sur ${m.outil.source || "le Wiktionnaire"}`}
                          {m.outil.definition && m.outil.definition !== "(rien trouvé)" ? "" : " (introuvable)"}
                          {m.outil.phrase_pretee && <span style={{ opacity: .7 }}> · phrase pas encore écrite par elle-même</span>}</div>
                      )}
                      <div style={{ whiteSpace: "pre-line", fontSize: 16.5, lineHeight: 1.7, color: m.erreur ? "var(--doux)" : "var(--encre)", fontStyle: m.erreur ? "italic" : "normal" }}>
                        {m.neuf && !m.erreur ? <MotParMot texte={m.texte} onFin={finiDeParler} /> : m.texte}
                      </div>
                      {m.correction && <div style={{ fontSize: 13, color: "var(--tomate)", marginTop: 6 }}>correction : {m.correction}</div>}
                    </div>
                  </div>
                ))}
                {attente && (
                  <div style={{ display: "flex", gap: 14, alignItems: "center", animation: "bulleJexa .5s cubic-bezier(.34,1.56,.64,1) both" }}>
                    <JexaVivante taille={38} etat="reflechit" />
                    <span style={{ color: "var(--doux)", fontStyle: "italic" }}>
                      {"Jexa réfléchit…".split("").map((c, i) => <span key={i} style={{ display: "inline-block", whiteSpace: "pre", animation: `vague 1.6s ${i * 0.06}s ease-in-out infinite` }}>{c}</span>)}
                    </span>
                  </div>
                )}
              </div>
            </div>
            <div className="pied-disc" style={{ padding: "6px 24px 18px", display: "flex", flexDirection: "column", alignItems: "center", gap: 10, position: "relative" }}>
              {conv.monde?.length > 0 && !attente && (
                <div className="puces-disc" style={{ width: "100%", maxWidth: COLONNE, display: "flex", gap: 8, justifyContent: "center" }}>
                  {["qui est Marie Curie ?", "quel temps il fait ?", "donne-moi un conseil"].map((s) => (
                    <button key={s} className="btn puce relief" onClick={() => envoyer(s)} style={{ background: "var(--surface)", border: "1.5px solid var(--ligne)",
                            padding: "7px 14px", fontSize: 13.5, fontWeight: 500, color: "var(--encre-2)" }}>{s}</button>
                  ))}
                </div>
              )}
              {saisie(false)}
              <div style={{ fontSize: 12, color: "var(--doux)", textAlign: "center" }}>Jexa est jeune et apprend encore : elle peut se tromper.</div>
            </div>
          </>
        )}
      </main>
      <style>{`
        @property --angle { syntax: '<angle>'; initial-value: 0deg; inherits: false; }
        @keyframes anneau { to { --angle: 360deg; } }
        @keyframes penche { 0%,100% { transform: rotate(-5deg) scale(1.03); } 50% { transform: rotate(5deg) scale(1.03); } }
        @keyframes parle { 0%,100% { transform: scale(1, 1); } 50% { transform: scale(1.05, .94) translateY(2px); } }
        @keyframes tourne { to { transform: rotate(360deg); } }
        @keyframes halo { 0%,100% { opacity: .55; transform: scale(.95); } 50% { opacity: 1; transform: scale(1.07); } }
        @keyframes atterrit { 0% { opacity: 0; transform: translateY(-80px) scale(.6); } 60% { opacity: 1; transform: translateY(8px) scale(1.05, .95); } 100% { transform: none; } }
        @keyframes lettre { 0% { opacity: 0; transform: translateY(26px) rotate(8deg) scale(.6); } 100% { opacity: 1; transform: none; } }
        @keyframes scintille { 0%,100% { transform: scale(1) rotate(0); } 50% { transform: scale(1.35) rotate(45deg); } }
        @keyframes bulleToi { 0% { opacity: 0; transform: scale(.5) translateY(20px); } 100% { opacity: 1; transform: none; } }
        @keyframes bulleJexa { 0% { opacity: 0; transform: scale(.7) translate(-14px, 10px); } 100% { opacity: 1; transform: none; } }
        @keyframes vague { 0%,100% { transform: translateY(0); } 30% { transform: translateY(-4px); } }
        .puce { transition: transform .35s cubic-bezier(.34,1.56,.64,1), box-shadow .3s, border-color .3s !important; }
        .puce:hover { transform: translateY(-3px) rotate(-1.5deg) scale(1.04) !important; border-color: var(--tomate) !important; box-shadow: 0 12px 22px -14px rgba(214,95,55,.8) !important; }
        .rebond:active, .envoi:active { transform: scale(.9) !important; }
        .sans-oeil::-ms-reveal, .sans-oeil::-ms-clear { display: none; }
        @keyframes singeBalance { 0%,100% { transform: rotate(-3deg); } 50% { transform: rotate(3deg); } }
        .ligne-disc { transition: background .25s, transform .3s cubic-bezier(.34,1.56,.64,1); }
        .ligne-disc:hover { background: #fffdf8 !important; transform: translateX(4px); }
        .barre-mobile { display: none; }
        @media (max-width: 820px) {
          .ecran-disc { position: fixed; inset: 0; height: auto !important; overflow: hidden; }
          .accueil-disc { overflow-x: hidden !important; }
          .accueil-disc > :first-child { margin-top: auto; }
          .accueil-disc > :last-child { margin-bottom: auto; }
          .cote { position: fixed; top: 0; bottom: 0; left: 0; z-index: 90; width: min(84vw, 320px) !important; background: var(--creme);
                  padding: calc(env(safe-area-inset-top) + 14px) 12px calc(env(safe-area-inset-bottom) + 14px) calc(env(safe-area-inset-left) + 16px) !important;
                  transform: translateX(-105%); transition: transform .32s cubic-bezier(.2,.8,.2,1); box-shadow: 20px 0 50px -20px #0006; }
          .cote.ouvert { transform: none; }
          .voile-menu { position: fixed; inset: 0; z-index: 85; background: #0006; animation: monte .2s both; }
          main { margin: 0 !important; border-radius: 0 !important; border: 0 !important; }
          .barre-mobile { display: flex; align-items: center; justify-content: space-between; gap: 10px; position: relative; z-index: 5;
                          padding: calc(env(safe-area-inset-top) + 8px) calc(env(safe-area-inset-right) + 12px) 8px calc(env(safe-area-inset-left) + 12px);
                          border-bottom: 1px solid var(--ligne); background: color-mix(in srgb, var(--papier) 88%, transparent); }
          .barre-bouton { width: 42px; height: 42px; border: 0; border-radius: 99px; background: var(--creme-fonce); color: var(--encre); font-size: 20px; }
          .accueil-disc { justify-content: flex-start !important; overflow-y: auto; gap: 18px !important; padding: 18px 16px calc(env(safe-area-inset-bottom) + 18px) !important; }
          .fil-disc { padding: 18px 14px 12px !important; }
          .pied-disc { padding: 6px calc(env(safe-area-inset-right) + 12px) calc(env(safe-area-inset-bottom) + 10px) calc(env(safe-area-inset-left) + 12px) !important; }
          .puces-disc { overflow-x: auto; justify-content: flex-start !important; scrollbar-width: none; }
          .puces-disc button { flex: none; }
          .bulle-retenu { left: 12px; right: 12px !important; bottom: calc(env(safe-area-inset-bottom) + 90px) !important; }
          .ligne-disc:hover, .puce:hover { transform: none !important; }
        }
      `}</style>
    </div>
  );
}

/* ================================================================== le coeur : parler directement a son cerveau */
/** Un mot qu'elle a écrit : plus il est pâle et souligné, moins elle était sûre. Survol = ce qu'elle a failli dire. */
function MotCoeur({ m, survol }) {
  const sur = m.p;
  return (
    <span onMouseMove={(e) => survol({ m, x: e.clientX, y: e.clientY })} onMouseLeave={() => survol(null)}
          style={{ opacity: 0.45 + 0.55 * Math.min(1, sur * 1.4), cursor: "help", whiteSpace: "pre-wrap",
                   borderBottom: sur < 0.35 ? "2px dotted var(--tomate)" : "none", transition: "opacity .3s" }}>{m.mot}</span>
  );
}

function Coeur() {
  const [h, setH] = useState(null);
  const [etat, setEtat] = useState(null);
  const [texte, setTexte] = useState("");
  const [attente, setAttente] = useState(false);
  const [survol, setSurvol] = useState(null);
  const zone = useRef(null);
  const charger = () => fetch("/api/coeur").then((r) => r.json()).then((d) => { setH(d.historique || []); setEtat(d.etat); });
  useEffect(() => { charger(); }, []);
  useEffect(() => { zone.current && zone.current.scrollTo({ top: zone.current.scrollHeight, behavior: "smooth" }); }, [h?.length, attente]);
  const envoyer = async (e) => {
    e && e.preventDefault();
    const t = texte.trim();
    if (!t || attente) return;
    setTexte(""); setAttente(true);
    setH((x) => [...x, { qui: "toi", texte: t }]);
    try {
      const r = await (await fetch("/api/coeur", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ texte: t }) })).json();
      setH((x) => [...x, { qui: "jexa", texte: r.reponse || r.erreur, details: r.details }]);
      if (r.etat) setEtat(r.etat);
    } finally { setAttente(false); }
  };
  const derniere = h ? [...h].reverse().find((m) => m.details)?.details : null;
  const nom = (n) => NOMS_LECONS[n] || n;
  return (
    <div style={{ minHeight: "100vh", background: "var(--creme)", padding: "24px 28px", display: "grid", gridTemplateColumns: "minmax(0, 1fr) 340px", gap: 22 }}>
      <main className="profond" style={{ background: "var(--papier)", borderRadius: 30, border: "1px solid var(--ligne)", display: "flex", flexDirection: "column", height: "calc(100vh - 48px)", overflow: "hidden" }}>
        <div style={{ padding: "20px 28px 14px", borderBottom: "1px solid var(--ligne)", display: "flex", alignItems: "center", gap: 14 }}>
          <JexaVivante taille={44} etat={attente ? "reflechit" : "repos"} />
          <div style={{ flex: 1 }}>
            <h1 className="serif" style={{ fontSize: 26, fontWeight: 800 }}>Le cœur de Jexa</h1>
            <div style={{ fontSize: 13, color: "var(--doux)" }}>Sans habillage : pas de leçon choisie pour elle, pas de souvenirs ajoutés, pas d'outil, aucune phrase pré-écrite. Juste son cerveau.</div>
          </div>
          <a href="/" style={{ fontSize: 13, color: "var(--doux)" }}>← discussion</a>
          <button className="btn relief" onClick={() => { if (confirm("Effacer toute la discussion du cœur ?")) fetch("/api/coeur", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ effacer: true }) }).then(charger); }}
                  style={{ background: "var(--creme)", fontSize: 12.5 }}>Effacer</button>
        </div>
        <div ref={zone} style={{ flex: 1, overflowY: "auto", padding: "24px 28px", display: "flex", flexDirection: "column", gap: 18 }}>
          {h && h.length === 0 && <div className="vide">Une seule discussion, rien que toi et elle. Dis-lui ce que tu veux.</div>}
          {(h || []).map((m, i) => m.qui === "toi" ? (
            <div key={i} style={{ alignSelf: "flex-end", maxWidth: "75%", background: "var(--encre)", color: "var(--papier)", padding: "12px 18px", borderRadius: "22px 22px 6px 22px", fontSize: 16 }}>{m.texte}</div>
          ) : (
            <div key={i} style={{ display: "flex", gap: 12, alignItems: "flex-start", maxWidth: "85%" }}>
              <JexaVivante taille={34} etat="repos" />
              <div>
                <div style={{ fontSize: 16.5, lineHeight: 1.7 }}>
                  {m.details?.mots?.length ? m.details.mots.map((w, j) => <MotCoeur key={j} m={w} survol={setSurvol} />) : m.texte}
                </div>
                {m.details && <div style={{ fontSize: 11.5, color: "var(--doux)", marginTop: 4 }}>
                  sûre à {pct(m.details.confiance, 0)} en moyenne{m.details.previsible != null ? ` · tes mots étaient prévisibles à ${pct(m.details.previsible, 0)}` : ""}</div>}
              </div>
            </div>
          ))}
          {attente && <div style={{ color: "var(--doux)", fontStyle: "italic" }}>elle réfléchit…</div>}
        </div>
        <form onSubmit={envoyer} style={{ display: "flex", gap: 10, padding: "14px 22px 20px", borderTop: "1px solid var(--ligne)" }}>
          <input value={texte} onChange={(e) => setTexte(e.target.value)} placeholder="Parle-lui directement…" autoFocus
                 style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "12px 20px", fontSize: 16, fontFamily: "inherit", outline: "none", background: "var(--surface)", color: "var(--encre)" }} />
          <button className="btn relief" disabled={attente} style={{ background: "var(--tomate)", color: "#fff", padding: "12px 22px" }}>Envoyer</button>
        </form>
      </main>

      <aside style={{ display: "flex", flexDirection: "column", gap: 14, height: "calc(100vh - 48px)", overflowY: "auto" }}>
        <div className="carte profond" style={{ padding: "18px 20px" }}>
          <h3 style={{ fontSize: 17, marginBottom: 10 }}>Ce qui se passe en elle</h3>
          {!derniere ? <div style={{ fontSize: 13, color: "var(--doux)" }}>Parle-lui : tu verras ici ce que tes mots déclenchent.</div> : <>
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em" }}>Régions qui se sont allumées</div>
            {derniere.regions.map((r) => (
              <div key={r.nom} style={{ display: "grid", gridTemplateColumns: "100px 1fr 40px", gap: 8, alignItems: "center", fontSize: 13, margin: "6px 0" }}>
                <span>{r.nom}</span><Barre valeur={r.part} couleur="var(--sarcelle)" hauteur={7} /><span className="mono" style={{ fontSize: 11.5 }}>{pct(r.part, 0)}</span>
              </div>
            ))}
            <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: 12 }}>Sa confiance</div>
            <Barre valeur={derniere.confiance} couleur={couleurScore(derniere.confiance)} hauteur={9} />
            {derniere.surprises?.length > 0 && <>
              <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: 12 }}>Tes mots qui l'ont le plus surprise</div>
              <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 }}>
                {derniere.surprises.map((s) => <span key={s.mot} className="pill" style={{ background: "var(--tomate-c)", color: "var(--tomate)" }}>{s.mot} · {pct(s.p, 1)}</span>)}
              </div>
            </>}
          </>}
        </div>
        {etat && <div className="carte profond" style={{ padding: "18px 20px" }}>
          <h3 style={{ fontSize: 17, marginBottom: 4 }}>Ce qu'elle sait d'elle-même</h3>
          <div style={{ fontSize: 12.5, color: "var(--doux)", marginBottom: 10 }}>Ses vraies données, rien d'inventé.</div>
          <div style={{ fontSize: 14, lineHeight: 1.7 }}>
            Version <b>v{etat.version}</b> · cycle {etat.cycle}<br />
            {etat.params && <>{(etat.params / 1e6).toLocaleString("fr-FR", { maximumFractionDigits: 2 })} M de paramètres<br /></>}
            {etat.maitrisees} leçons maîtrisées sur {etat.lecons} · note {pct(etat.note, 1)}
          </div>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: 12 }}>Ce qu'elle sait le mieux</div>
          {etat.forces.map((f) => <div key={f.nom} style={{ fontSize: 13, display: "flex", justifyContent: "space-between", gap: 8 }}><span>{nom(f.nom)}</span><b>{pct(f.score, 0)}</b></div>)}
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: 12 }}>Ce qu'elle cherche encore</div>
          {etat.faiblesses.map((f) => <div key={f.nom} style={{ fontSize: 13, display: "flex", justifyContent: "space-between", gap: 8 }}><span>{nom(f.nom)}</span><b style={{ color: "var(--tomate)" }}>{pct(f.score, 0)}</b></div>)}
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--doux)", textTransform: "uppercase", letterSpacing: ".08em", marginTop: 12 }}>Ses régions</div>
          <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 6 }}>
            {etat.regions.map((r) => <span key={r.nom} className="pill" style={{ background: "var(--sarcelle-c)", color: "var(--sarcelle)" }}>{r.nom} · {r.taille}</span>)}
          </div>
        </div>}
      </aside>
      <Bulle x={survol?.x} y={survol?.y}>{survol && <>
        <b>« {survol.m.mot.trim()} »</b> · sûre à {pct(survol.m.p, 0)}
        {survol.m.alt?.length > 0 && <><br /><span style={{ opacity: .75 }}>elle a failli dire : {survol.m.alt.map((a) => `« ${a.mot.trim()} » ${pct(a.p, 0)}`).join(", ")}</span></>}
      </>}</Bulle>
    </div>
  );
}

/* ================================================================== l'atelier : entrainer et tester le pixel art */
const MODES_ATELIER = [
  ["redessiner", "Redessiner", "Elle refait ton image pixel par pixel : tu vois sa précision et où elle se trompe."],
  ["completer", "Compléter", "Elle garde le haut de ton image et invente le bas."],
  ["varier", "Varier", "Elle dessine de nouvelles versions à partir du nom de l'image."],
];

function Atelier() {
  const [etat, setEtat] = useState(null);
  const [img, setImg] = useState(null);  // { b64, url, nom }
  const [mode, setMode] = useState("redessiner");
  const [n, setN] = useState(4);
  const [res, setRes] = useState(null);
  const [attente, setAttente] = useState(false);
  const [nomLibre, setNomLibre] = useState("une épée en diamant minecraft");
  const [message, setMessage] = useState("");
  const [survol, setSurvol] = useState(false);
  useEffect(() => { fetch("/api/atelier").then((r) => r.json()).then(setEtat).catch(() => {}); }, []);
  const lireFichier = (f) => {
    const r = new FileReader();
    r.onload = () => setImg({ b64: String(r.result).split(",")[1], url: r.result, nom: f.name.replace(/\.[^.]+$/, "").replace(/[_-]+/g, " ") });
    r.readAsDataURL(f);
    setRes(null); setMessage("");
  };
  const lancer = async (corps) => {
    setAttente(true); setMessage("");
    try {
      const r = await (await fetch("/api/atelier", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(corps) })).json();
      if (r.erreur) setMessage(r.erreur); else setRes(r);
    } catch { setMessage("Le serveur ne répond pas."); } finally { setAttente(false); }
  };
  const apprendre = async () => {
    const r = await (await fetch("/api/atelier", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ donnees: img.b64, nom: img.nom, apprendre: true }) })).json();
    setMessage(r.ajoute ? `Ajoutée à ses textures (${r.ajoute}) : elle l'apprendra au prochain entraînement.` : "Impossible d'ajouter l'image.");
  };
  const pixelise = { imageRendering: "pixelated", width: "100%", maxWidth: 320, aspectRatio: "1", borderRadius: 14, display: "block",
                     background: "repeating-conic-gradient(#e8dcc3 0 25%, #fcf8f0 0 50%) 0 0 / 16px 16px" };
  return (
    <div style={{ minHeight: "100vh", background: "var(--creme)", padding: "26px 30px", maxWidth: 1300, margin: "0 auto" }}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
        <JexaVivante taille={46} etat={attente ? "reflechit" : "repos"} />
        <div style={{ flex: 1 }}>
          <h1 className="serif" style={{ fontSize: 32, fontWeight: 900 }}>L'atelier pixel</h1>
          <div style={{ fontSize: 14, color: "var(--doux)" }}>
            {etat ? <>{etat.images} textures apprises ({Object.entries(etat.par_taille).map(([t, k]) => `${k} en ${t}×${t}`).join(", ")}) · cerveaux entraînés : {etat.entraines.map((t) => `${t}×${t}`).join(", ") || "aucun"}</> : "…"}
          </div>
        </div>
        <a href="/" style={{ fontSize: 13, color: "var(--doux)" }}>← discussion</a>
      </div>

      <div style={{ display: "grid", gridTemplateColumns: "minmax(0, 1fr) minmax(0, 1.4fr)", gap: 20 }}>
        <div className="carte profond" style={{ padding: 22 }}>
          <h2 style={{ fontSize: 20, marginBottom: 12 }}>Ton image</h2>
          <label onDragOver={(e) => { e.preventDefault(); setSurvol(true); }} onDragLeave={() => setSurvol(false)}
                 onDrop={(e) => { e.preventDefault(); setSurvol(false); const f = e.dataTransfer.files[0]; if (f) lireFichier(f); }}
                 style={{ display: "grid", placeItems: "center", minHeight: 260, borderRadius: 20, cursor: "pointer", padding: 16,
                          border: `2px dashed ${survol ? "var(--tomate)" : "var(--ligne)"}`, background: survol ? "var(--tomate-c)" : "var(--surface)", transition: "all .2s" }}>
            <input type="file" accept="image/*" style={{ display: "none" }} onChange={(e) => e.target.files[0] && lireFichier(e.target.files[0])} />
            {img ? <img src={img.url} alt="" style={pixelise} /> :
              <div style={{ textAlign: "center", color: "var(--doux)" }}><div style={{ fontSize: 34 }}>🖼️</div>Dépose une image ici<br /><span style={{ fontSize: 12.5 }}>16×16, 32×32 ou 64×64 (les autres tailles sont ramenées sans flou)</span></div>}
          </label>
          {img && <>
            <div style={{ display: "flex", gap: 8, alignItems: "center", marginTop: 14 }}>
              <span style={{ fontSize: 13, color: "var(--doux)" }}>Nom :</span>
              <input value={img.nom} onChange={(e) => setImg({ ...img, nom: e.target.value })}
                     style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "8px 14px", fontFamily: "inherit", background: "var(--surface)" }} />
            </div>
            <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginTop: 12 }}>
              {MODES_ATELIER.map(([v, l, d]) => (
                <button key={v} className="btn relief" title={d} onClick={() => setMode(v)}
                        style={{ background: mode === v ? "var(--encre)" : "var(--creme)", color: mode === v ? "var(--papier)" : "var(--encre)", fontSize: 13.5 }}>{l}</button>
              ))}
              {mode !== "redessiner" && <select value={n} onChange={(e) => setN(+e.target.value)} style={{ borderRadius: 99, padding: "6px 10px", fontFamily: "inherit" }}>
                {[1, 2, 4, 6, 8].map((k) => <option key={k} value={k}>{k} essai{k > 1 ? "s" : ""}</option>)}</select>}
            </div>
            <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 8 }}>{MODES_ATELIER.find((x) => x[0] === mode)[2]}</div>
            <div style={{ display: "flex", gap: 8, marginTop: 14 }}>
              <button className="btn relief" disabled={attente} onClick={() => lancer({ donnees: img.b64, nom: img.nom, mode, n })}
                      style={{ background: "var(--tomate)", color: "#fff", flex: 1 }}>{attente ? "Elle dessine…" : "Lancer →"}</button>
              <button className="btn relief" onClick={apprendre} style={{ background: "var(--sarcelle-c)", color: "var(--sarcelle)" }} title="Ajouter cette image à ses textures d'entraînement">＋ Apprendre cette image</button>
            </div>
          </>}
          <div style={{ borderTop: "1px solid var(--ligne)", marginTop: 20, paddingTop: 16 }}>
            <h3 style={{ fontSize: 16, marginBottom: 8 }}>Ou dessiner à partir d'un nom</h3>
            <div style={{ display: "flex", gap: 8 }}>
              <input value={nomLibre} onChange={(e) => setNomLibre(e.target.value)} placeholder="une pomme minecraft, une pioche en fer…"
                     style={{ flex: 1, border: "1.5px solid var(--ligne)", borderRadius: 99, padding: "9px 16px", fontFamily: "inherit", background: "var(--surface)" }} />
              <button className="btn relief" disabled={attente} onClick={() => lancer({ nom: nomLibre, n: 8 })} style={{ background: "var(--encre)", color: "var(--papier)" }}>Dessiner</button>
            </div>
          </div>
          {message && <div style={{ marginTop: 12, fontSize: 13.5, color: message.startsWith("Ajoutée") ? "var(--sarcelle)" : "var(--tomate)" }}>{message}</div>}
        </div>

        <div className="carte profond" style={{ padding: 22 }}>
          <h2 style={{ fontSize: 20, marginBottom: 6 }}>Ce qu'elle en fait</h2>
          {!res && !attente && <div className="vide">Dépose une image à gauche, choisis un mode, puis « Lancer ».</div>}
          {attente && <div className="chargement" style={{ height: 300, borderRadius: 20 }} />}
          {res && !attente && <>
            <div style={{ fontSize: 13, color: "var(--doux)", marginBottom: 12 }}>
              {res.taille}×{res.taille} · mots compris : {res.mots.length ? res.mots.join(", ") : "aucun (dessin libre)"}{res.couleurs ? ` · ${res.couleurs} couleurs` : ""}
            </div>
            {res.mode === "redessiner" ? (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(3, 1fr)", gap: 14, alignItems: "start" }}>
                {[["Ton image (sa palette)", res.original], ["Son dessin", res.resultats[0]], ["Ses erreurs (rouge)", res.erreurs]].map(([t, u]) => (
                  <div key={t}><div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>{t}</div><img src={u} alt="" style={pixelise} /></div>
                ))}
                <div style={{ gridColumn: "1 / -1" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", fontSize: 14, marginBottom: 6 }}><b>Précision pixel par pixel</b><span className="mono">{pct(res.precision, 1)}</span></div>
                  <Barre valeur={res.precision} couleur={couleurScore(res.precision)} hauteur={10} />
                </div>
              </div>
            ) : (
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(140px, 1fr))", gap: 12 }}>
                {res.original && <div><div style={{ fontSize: 12.5, fontWeight: 700, marginBottom: 6 }}>Ton image</div><img src={res.original} alt="" style={pixelise} /></div>}
                {res.resultats.map((u, i) => <div key={i}><div style={{ fontSize: 12.5, color: "var(--doux)", marginBottom: 6 }}>Essai {i + 1}</div><img src={u} alt="" style={pixelise} /></div>)}
              </div>
            )}
          </>}
        </div>
      </div>
    </div>
  );
}

/* ================================================================== l'application Jexa (bureau et /app) */
// Connexion obligatoire avec un compte Hexa ; le serveur de Jexa verifie le jeton aupres d'Hexa et compte le quota.
const BUREAU = typeof window !== "undefined" && !!window.jexaBureau;  // dans l'application de bureau (Electron)
// dans Hexa Browser (onglet hexa://jexa) : le navigateur nous donne son compte, pas de deuxieme connexion
const INTEGRE = typeof location !== "undefined" && new URLSearchParams(location.search).has("integre") && window.parent !== window;
// dans le panneau de droite de Hexa Browser : Jexa travaille sur la page web ouverte
const COMPACT = INTEGRE && new URLSearchParams(location.search).has("compact");
const DEMANDES_PAGE = {};
function lirePageOuverte() {  // le navigateur nous donne le texte de la page ouverte (seulement quand tu poses une question)
  return new Promise((ok) => {
    const id = Math.random().toString(36).slice(2);
    DEMANDES_PAGE[id] = ok;
    window.parent.postMessage({ type: "hexa-jexa-page-demande", id }, "*");
    setTimeout(() => { if (DEMANDES_PAGE[id]) { delete DEMANDES_PAGE[id]; ok(null); } }, 5000);
  });
}
if (COMPACT) addEventListener("message", (e) => {
  if (e.source !== window.parent || !e.data || e.data.type !== "hexa-jexa-page") return;
  const ok = DEMANDES_PAGE[e.data.id]; delete DEMANDES_PAGE[e.data.id];
  if (ok) ok(e.data.texte || e.data.pdf ? { titre: e.data.titre || "la page", url: e.data.url, texte: e.data.texte || "", pdf: e.data.pdf } : null);
});

const STYLE_APP = `
  .app-jexa { position: fixed; inset: 0; display: grid; grid-template-columns: 290px minmax(0, 1fr); background: var(--creme); color: var(--encre); overflow: hidden; transition: grid-template-columns .35s var(--ease); }
  .app-panneau { position: relative; margin: 10px 10px 10px 0; border-radius: 30px; overflow: hidden; display: flex; flex-direction: column; min-width: 0; min-height: 0;
                 background: var(--papier); border: 1px solid var(--ligne);
                 box-shadow: 0 1px 0 rgba(255,255,255,.9) inset, 0 2px 4px rgba(90,60,20,.05), 0 24px 60px -28px rgba(110,70,20,.45), 0 60px 120px -60px rgba(110,70,20,.35); }
  .app-jexa.sans-barre .app-panneau { margin-left: 10px; }
  :root[data-theme="nexus"] .app-panneau { box-shadow: 0 1px 0 rgba(255,255,255,.06) inset, 0 24px 60px -28px rgba(0,0,0,.7), 0 60px 120px -60px rgba(90,50,200,.45); }
  .app-fen { width: 34px; height: 30px; border: 0; border-radius: 10px; background: transparent; color: var(--doux); display: grid; place-items: center; transition: background .2s, color .2s, transform .2s var(--ease); }
  .app-fen:hover { background: var(--creme-fonce); color: var(--encre); transform: translateY(-1px); }
  .app-fen.fermer:hover { background: var(--tomate); color: #fff; }
  .app-rond { border: 0; width: 36px; height: 36px; border-radius: 99px; display: grid; place-items: center; background: var(--creme-fonce); color: var(--encre); }
  .app-jexa.sans-barre { grid-template-columns: 0 minmax(0, 1fr); }
  .app-drag { -webkit-app-region: drag; }
  .app-drag button, .app-drag input, .app-drag a, .app-nodrag { -webkit-app-region: no-drag; }
  .app-cote { display: flex; flex-direction: column; min-height: 0; background: transparent; transition: transform .35s var(--ease), opacity .35s; }
  .app-jexa.sans-barre .app-cote { opacity: 0; pointer-events: none; }
  .app-jexa.sans-barre .app-cote { transform: translateX(-100%); }
  .app-item { display: flex; align-items: center; gap: 8px; width: 100%; text-align: left; border: 0; background: transparent; color: var(--encre);
              padding: 9px 12px; border-radius: 14px; font-size: 14px; transition: background .2s, transform .2s var(--ease); }
  .app-item:hover { background: color-mix(in srgb, var(--papier) 85%, transparent); transform: translateX(2px); }
  .app-item.actif { background: var(--surface); box-shadow: var(--ombre-3d); }
  .app-item .app-actions { opacity: 0; transition: opacity .2s; display: flex; gap: 2px; }
  .app-item:hover .app-actions { opacity: 1; }
  .app-mini { border: 0; background: transparent; color: var(--doux); border-radius: 8px; padding: 2px 6px; font-size: 13px; }
  .app-mini:hover { background: var(--creme-fonce); color: var(--encre); }
  @property --angle-bord { syntax: "<angle>"; initial-value: 0deg; inherits: false; }
  @keyframes tourne-bord { to { --angle-bord: 360deg; } }
  .bord-vivant { position: relative; border-radius: 28px; }
  .bord-vivant::before { content: ""; position: absolute; inset: -2px; border-radius: inherit; padding: 2px; pointer-events: none;
    background: conic-gradient(from var(--angle-bord), var(--tomate), var(--moutarde, #e6b94a), var(--sarcelle), var(--tomate));
    -webkit-mask: linear-gradient(#000 0 0) content-box, linear-gradient(#000 0 0); -webkit-mask-composite: xor; mask-composite: exclude;
    opacity: .25; transition: opacity .4s; animation: tourne-bord 6s linear infinite; }
  .bord-vivant.focus::before { opacity: .9; }
  .bord-vivant.pense::before { opacity: 1; animation-duration: 1.4s; }
  .app-bulle-toi { background: var(--encre); color: var(--papier); border-radius: 22px 22px 6px 22px; padding: 12px 18px; max-width: 78%;
                   box-shadow: var(--ombre-3d-sombre, 0 10px 24px -10px #0006); white-space: pre-wrap; line-height: 1.55; animation: glisse .4s var(--ease) both; }
  .app-jexa-msg { animation: monte .45s var(--ease) both; line-height: 1.65; font-size: 15.5px; }
  .app-jexa-msg p { margin: 0 0 10px; } .app-jexa-msg p:last-child { margin: 0; }
  .app-jexa-msg code { font-family: "DM Mono", monospace; background: var(--creme-fonce); padding: 1px 6px; border-radius: 6px; font-size: .92em; }
  .app-jexa-msg ul { margin: 4px 0 10px; padding-left: 20px; }
  .app-points span { display: inline-block; width: 7px; height: 7px; border-radius: 99px; background: var(--tomate); margin-right: 5px; animation: pulse 1s infinite; }
  .app-points span:nth-child(2) { animation-delay: .15s; } .app-points span:nth-child(3) { animation-delay: .3s; }
  .app-orbe { position: absolute; border-radius: 50%; filter: blur(60px); opacity: .55; pointer-events: none; animation: derive 14s ease-in-out infinite alternate; }
  .app-menu { position: absolute; z-index: 50; background: var(--papier); border-radius: 18px; padding: 6px; box-shadow: var(--ombre-3d-haute, 0 24px 48px -16px #0005);
              animation: pop .3s cubic-bezier(.34,1.56,.64,1) both; min-width: 260px; }
  .app-defile::-webkit-scrollbar { width: 10px; } .app-defile::-webkit-scrollbar-thumb { background: var(--ligne); border-radius: 99px; border: 3px solid transparent; background-clip: content-box; }
  @media (max-width: 760px) { .app-jexa, .app-jexa.sans-barre { grid-template-columns: minmax(0, 1fr); } .app-panneau, .app-jexa.sans-barre .app-panneau { grid-column: 1; margin: 6px; border-radius: 22px; }
                              .app-cote { position: fixed; z-index: 60; width: min(290px, 86vw); inset: 0 auto 0 0; background: var(--creme); box-shadow: 20px 0 40px -20px rgba(0,0,0,.35); }
                              .app-jexa:not(.ouvert-mobile) .app-cote { transform: translateX(-100%); } }
`;

const ICONES = {
  panneau: "M4 5h16v14H4zM9 5v14", plus: "M12 5v14M5 12h14", loupe: "M11 4a7 7 0 1 0 0 14 7 7 0 0 0 0-14zM20 20l-4-4",
  crayon: "M4 20h4L19 9l-4-4L4 16zM14 6l4 4", poubelle: "M5 7h14M10 7V4h4v3M7 7l1 13h8l1-13", fleche: "M12 19V5M6 11l6-6 6 6",
  trombone: "M16 7l-7.5 7.5a2.5 2.5 0 0 0 3.5 3.5L19 11a4.5 4.5 0 0 0-6.4-6.4L5 12.2a6.5 6.5 0 0 0 9.2 9.2",
  lune: "M20 14.5A8 8 0 1 1 9.5 4a6.5 6.5 0 0 0 10.5 10.5z", soleil: "M12 8a4 4 0 1 0 0 8 4 4 0 0 0 0-8zM12 2v2M12 20v2M4.9 4.9l1.4 1.4M17.7 17.7l1.4 1.4M2 12h2M20 12h2M4.9 19.1l1.4-1.4M17.7 6.3l1.4-1.4",
  souvenir: "M12 21s-7-4.5-7-10a4 4 0 0 1 7-2.6A4 4 0 0 1 19 11c0 5.5-7 10-7 10z", lien: "M10 14a4 4 0 0 0 5.7 0l3-3a4 4 0 0 0-5.7-5.7l-1 1M14 10a4 4 0 0 0-5.7 0l-3 3a4 4 0 0 0 5.7 5.7l1-1",
  sortie: "M15 4h4v16h-4M10 8l-4 4 4 4M6 12h10", globe: "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM3 12h18M12 3c3 3 3 15 0 18M12 3c-3 3-3 15 0 18",
  lettre: "M4 6h16v12H4zM4 7l8 6 8-6", livre: "M4 5a2 2 0 0 1 2-2h13v16H6a2 2 0 0 0-2 2zM4 5v16", pinceau: "M14 4l6 6-8 8-6-6zM6 12l-2 6 6-2",
  reduire: "M6 12h12", agrandir: "M6 6h12v12H6z", restaurer: "M8 8h10v10H8zM6 16V6h10", fermer: "M6 6l12 12M18 6L6 18", menu: "M4 7h16M4 12h16M4 17h16",
};
const Ico = ({ n, t = 18, e = 1.8 }) => (
  <svg width={t} height={t} viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth={e} strokeLinecap="round" strokeLinejoin="round" aria-hidden="true"><path d={ICONES[n]} /></svg>);

/** Les boutons de la fenetre (reduire, agrandir, fermer), dessines dans le style de Jexa. */
function BoutonsFenetre() {
  const [grand, setGrand] = useState(false);
  useEffect(() => { if (BUREAU && window.jexaBureau.surAgrandie) return window.jexaBureau.surAgrandie(setGrand); }, []);
  if (!BUREAU) return null;
  return (
    <div className="app-nodrag" style={{ display: "flex", gap: 4 }}>
      <button className="app-fen" title="Réduire" onClick={() => window.jexaBureau.reduire()}><Ico n="reduire" t={16} /></button>
      <button className="app-fen" title={grand ? "Restaurer" : "Agrandir"} onClick={() => window.jexaBureau.agrandir()}><Ico n={grand ? "restaurer" : "agrandir"} t={14} /></button>
      <button className="app-fen fermer" title="Fermer" onClick={() => window.jexaBureau.fermer()}><Ico n="fermer" t={15} /></button>
    </div>);
}

/** Une carte qui s'incline vers la souris (profondeur 3D). */
function Incline({ children, force = 8, style, className = "" }) {
  const ref = useRef(null);
  const bouge = (e) => {
    const el = ref.current; if (!el) return;
    const r = el.getBoundingClientRect();
    const x = (e.clientX - r.left) / r.width - 0.5, y = (e.clientY - r.top) / r.height - 0.5;
    el.style.transform = `perspective(900px) rotateX(${(-y * force).toFixed(2)}deg) rotateY(${(x * force).toFixed(2)}deg) translateZ(0)`;
  };
  const repos = () => { if (ref.current) ref.current.style.transform = "perspective(900px) rotateX(0) rotateY(0)"; };
  return <div ref={ref} onPointerMove={bouge} onPointerLeave={repos} className={className}
              style={{ transition: "transform .25s var(--ease)", ...style }}>{children}</div>;
}

function FondProfond() {  // des lueurs qui suivent la souris, a des profondeurs differentes
  const [p, setP] = useState({ x: 0, y: 0 });
  useEffect(() => {
    const f = (e) => setP({ x: e.clientX / innerWidth - 0.5, y: e.clientY / innerHeight - 0.5 });
    addEventListener("pointermove", f); return () => removeEventListener("pointermove", f);
  }, []);
  const couche = (k) => ({ transform: `translate(${p.x * k}px, ${p.y * k}px)`, transition: "transform .6s var(--ease)", position: "absolute", inset: 0 });
  return (
    <div style={{ position: "absolute", inset: 0, overflow: "hidden", pointerEvents: "none" }}>
      <div style={couche(-30)}><div className="app-orbe" style={{ width: 420, height: 420, background: "var(--tomate)", top: "-8%", left: "-6%", opacity: .22 }} /></div>
      <div style={couche(45)}><div className="app-orbe" style={{ width: 380, height: 380, background: "var(--sarcelle)", bottom: "-10%", right: "-4%", opacity: .2, animationDelay: "-5s" }} /></div>
      <div style={couche(-70)}><div className="app-orbe" style={{ width: 260, height: 260, background: "var(--moutarde, #e6b94a)", top: "40%", left: "55%", opacity: .18, animationDelay: "-9s" }} /></div>
      <div style={couche(90)}><div className="app-orbe" style={{ width: 200, height: 200, background: "#8b6cff", top: "8%", right: "18%", opacity: .1, animationDelay: "-3s" }} /></div>
    </div>
  );
}

/* HEXA Link : le petit programme HEXA du PC (installé avec nos logiciels) ; fonctionne dans tous les navigateurs */
const HEXA_LINK = "http://127.0.0.1:47621";
function useHexaLink() {
  const [compteLink, setCompteLink] = useState(null);
  useEffect(() => {
    let fini = false;
    fetch(HEXA_LINK + "/status").then((r) => r.json()).then((s) => { if (!fini && s && s.connected && s.username) setCompteLink(s.username); }).catch(() => {});
    return () => { fini = true; };
  }, []);
  // la popup « c'est bien toi ? » s'ouvre sur le PC ; on reçoit un code à usage unique (60 s)
  const demander = async () => {
    const r = await fetch(HEXA_LINK + "/request", { method: "POST", headers: { "Content-Type": "application/json" }, body: "{}" });
    const d = await r.json().catch(() => ({}));
    if (!r.ok || !d.code) throw Object.assign(new Error(d.error || "refusé"), { raison: d.reason });
    return d.code;
  };
  return { compteLink, demander };
}

function ConnexionApp({ connecter, connecterLien }) {
  const { compteLink, demander } = useHexaLink();
  const [attenteLien, setAttenteLien] = useState(false);
  const viaLien = async () => {
    setErreur(""); setAttenteLien(true);
    try {
      const r = await connecterLien(await demander());
      if (!r.jeton) setErreur(r.erreur || "Connexion HEXA Link impossible.");
    } catch (e) {
      setErreur(e.raison === "denied" ? "Connexion annulée dans HEXA Link." : e.raison === "caller" ? "Ce navigateur n'est pas reconnu par HEXA Link." : "HEXA Link ne répond pas : utilise ton mot de passe.");
    } finally { setAttenteLien(false); }
  };
  const [id, setId] = useState(""), [mdp, setMdp] = useState(""), [code, setCode] = useState("");
  const [besoin2fa, setBesoin2fa] = useState(false), [erreur, setErreur] = useState(""), [attente, setAttente] = useState(false);
  const [voir, setVoir] = useState(false);
  const champ = { width: "100%", border: "1.5px solid var(--ligne)", borderRadius: 16, padding: "13px 16px", fontSize: 15.5, fontFamily: "inherit",
                  outline: "none", background: "var(--surface)", color: "var(--encre)", marginBottom: 10 };
  const envoyer = async (e) => {
    e.preventDefault(); setErreur(""); setAttente(true);
    try {
      const r = await connecter(id, mdp, besoin2fa ? code : null);
      if (r.requires_2fa) setBesoin2fa(true);
      else if (!r.jeton) setErreur(r.erreur || "Connexion impossible.");
    } catch { setErreur("Le site Hexa ne répond pas pour le moment (il est peut-être hors ligne). Réessaie dans un instant."); }
    finally { setAttente(false); }
  };
  return (
    <div style={{ position: "fixed", inset: 0, background: "var(--creme)", display: "grid", placeItems: "center", overflow: "hidden" }}>
      <FondProfond />
      {BUREAU && <div className="app-drag" style={{ position: "absolute", top: 0, left: 0, right: 0, height: 48, display: "flex", justifyContent: "flex-end", alignItems: "center", padding: "0 10px", zIndex: 5 }}><BoutonsFenetre /></div>}
      <div style={{ width: "min(430px, 92vw)", position: "relative" }}>
        <form onSubmit={envoyer} className="profond bord-vivant focus" style={{ background: "var(--papier)", borderRadius: 34, padding: "34px 34px 28px", animation: "pop .6s cubic-bezier(.34,1.56,.64,1) both" }}>
          <div style={{ display: "grid", placeItems: "center", marginBottom: 14, transform: "translateZ(40px)" }}>
            <JexaVivante taille={96} etat={attente ? "reflechit" : id || mdp ? "ecoute" : "repos"} yeuxFermes={voir && !besoin2fa} />
          </div>
          <h1 className="serif" style={{ fontSize: 30, fontWeight: 900, textAlign: "center", transform: "translateZ(30px)" }}>Bienvenue sur Jexa</h1>
          <p style={{ textAlign: "center", color: "var(--doux)", margin: "8px 0 22px", fontSize: 14.5 }}>Connecte-toi avec ton compte Hexa pour continuer.</p>
          {compteLink && connecterLien && !besoin2fa && <>
            <button type="button" className="btn relief" onClick={viaLien} disabled={attenteLien}
                    style={{ width: "100%", display: "flex", alignItems: "center", gap: 12, background: "var(--surface)", color: "var(--encre)", padding: "12px 16px", fontSize: 15, textAlign: "left", border: "1.5px solid var(--ligne)" }}>
              <span style={{ width: 34, height: 34, flex: "0 0 34px", borderRadius: 99, display: "grid", placeItems: "center", background: "var(--tomate)", color: "#fff", fontWeight: 800 }}>{compteLink.charAt(0).toUpperCase()}</span>
              <span style={{ flex: 1, minWidth: 0 }}><b style={{ display: "block" }}>{attenteLien ? "Confirme dans HEXA Link…" : "Continuer en tant que " + compteLink}</b>
                <small style={{ color: "var(--doux)" }}>Connexion rapide avec HEXA Link</small></span>
            </button>
            <div style={{ display: "flex", alignItems: "center", gap: 10, color: "var(--doux)", fontSize: 12.5, margin: "16px 0 14px" }}>
              <span style={{ flex: 1, height: 1, background: "var(--ligne)" }} />ou avec ton mot de passe<span style={{ flex: 1, height: 1, background: "var(--ligne)" }} /></div>
          </>}
          {!besoin2fa ? <>
            <input style={champ} placeholder="Pseudo ou e-mail Hexa" value={id} onChange={(e) => setId(e.target.value)} autoFocus autoComplete="username" />
            <div style={{ position: "relative" }}>
              <input style={{ ...champ, paddingRight: 48 }} type={voir ? "text" : "password"} placeholder="Mot de passe" value={mdp}
                     onChange={(e) => setMdp(e.target.value)} autoComplete="current-password" />
              <button type="button" onClick={() => setVoir(!voir)} title={voir ? "Cacher" : "Afficher"}
                      style={{ position: "absolute", right: 10, top: 9, border: 0, background: "transparent", padding: 4 }}><OeilSimple ferme={voir} /></button>
            </div>
          </> : <input style={champ} placeholder="Code de double authentification" value={code} onChange={(e) => setCode(e.target.value)} autoFocus inputMode="numeric" />}
          {erreur && <div style={{ color: "var(--tomate)", fontSize: 13.5, margin: "2px 0 10px" }}>{erreur}</div>}
          <button className="btn relief" disabled={attente || !id || !mdp} style={{ width: "100%", background: "var(--tomate)", color: "#fff", padding: "14px", fontSize: 15.5, marginTop: 6 }}>
            {attente ? "Connexion…" : besoin2fa ? "Valider" : "Se connecter"}</button>
          <div style={{ textAlign: "center", fontSize: 13, color: "var(--doux)", marginTop: 16 }}>
            Pas de compte ? <a href="https://hexa-mc.fr/register" target="_blank" rel="noreferrer" style={{ color: "var(--tomate)", fontWeight: 700 }}>Crée-le sur Hexa</a></div>
          <div style={{ textAlign: "center", fontSize: 11.5, color: "var(--doux)", marginTop: 10, opacity: .8 }}>Ton mot de passe part directement chez Hexa : Jexa ne le voit jamais.</div>
        </form>
      </div>
    </div>
  );
}

function MarkdownLeger({ texte }) {  // gras, code, listes : juste ce qu'il faut
  const ligne = (t, k) => t.split(/(\*\*[^*]+\*\*|`[^`]+`)/g).map((x, i) =>
    x.startsWith("**") && x.endsWith("**") ? <b key={k + "-" + i}>{x.slice(2, -2)}</b> : x.startsWith("`") && x.endsWith("`") ? <code key={k + "-" + i}>{x.slice(1, -1)}</code> : x);
  const morceaux = String(texte || "").split(/```(\w*)\n([\s\S]*?)\n?```/g);
  if (morceaux.length > 1) {
    const sortie = [];
    for (let i = 0; i < morceaux.length; i += 3) {
      if (morceaux[i].trim()) sortie.push(<MarkdownLeger key={"t" + i} texte={morceaux[i].trim()} />);
      if (i + 2 < morceaux.length) sortie.push(<BlocCode key={"c" + i} langage={morceaux[i + 1]} code={morceaux[i + 2]} />);
    }
    return sortie;
  }
  const blocs = String(texte || "").split(/\n{2,}/);
  return blocs.map((b, i) => {
    const l = b.split("\n");
    if (l.every((x) => /^\s*[-•*]\s+/.test(x))) return <ul key={i}>{l.map((x, j) => <li key={j}>{ligne(x.replace(/^\s*[-•*]\s+/, ""), j)}</li>)}</ul>;
    return <p key={i}>{l.map((x, j) => <React.Fragment key={j}>{j > 0 && <br />}{ligne(x, j)}</React.Fragment>)}</p>;
  });
}

function BlocCode({ langage, code }) {
  const [copie, setCopie] = useState(false);
  const noms = { python: "Python", js: "JavaScript", html: "HTML" };
  const copier = async () => {
    try { await navigator.clipboard.writeText(code); setCopie(true); setTimeout(() => setCopie(false), 1600); } catch {}
  };
  return (
    <div style={{ margin: "6px 0 12px", borderRadius: 14, overflow: "hidden", background: "#1d1a17", color: "#f4ecdc", boxShadow: "0 8px 20px -12px #0008" }}>
      <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", padding: "6px 12px", fontSize: 12, fontFamily: "DM Mono, monospace", background: "#2a2622", color: "#c9bda6" }}>
        <span>{noms[langage] || langage || "code"}</span>
        <button onClick={copier} style={{ background: "none", border: "none", color: "inherit", cursor: "pointer", fontFamily: "inherit", fontSize: 12 }}>{copie ? "Copié !" : "Copier"}</button>
      </div>
      <pre style={{ margin: 0, padding: "12px 14px", overflowX: "auto", fontFamily: "DM Mono, monospace", fontSize: 13, lineHeight: 1.55, whiteSpace: "pre" }}>{code}</pre>
    </div>
  );
}

const DAMIER_APP ="repeating-conic-gradient(#e8dcc3 0 25%, #fcf8f0 0 50%) 0 0 / 12px 12px";

/** En grand : copier ou telecharger un dessin de Jexa. */
function Visionneuse({ images, depart, nom, format, fermer }) {
  const [i, setI] = useState(depart || 0);
  const [msg, setMsg] = useState("");
  useEffect(() => {
    const f = (e) => { if (e.key === "Escape") fermer(); if (e.key === "ArrowRight") setI((k) => (k + 1) % images.length); if (e.key === "ArrowLeft") setI((k) => (k - 1 + images.length) % images.length); };
    addEventListener("keydown", f); return () => removeEventListener("keydown", f);
  }, []);
  const u = images[i];
  const fichier = `jexa-${(nom || "dessin").toLowerCase().replace(/[^a-z0-9àâçéèêëîïôûùüÿ]+/gi, "-").replace(/^-|-$/g, "").slice(0, 40) || "dessin"}-${i + 1}.png`;
  const copier = async () => {
    try {
      const blob = await (await fetch(u)).blob();
      await navigator.clipboard.write([new ClipboardItem({ "image/png": blob })]);
      setMsg("Image copiée !");
    } catch { setMsg("Copie impossible ici : utilise Télécharger."); }
    setTimeout(() => setMsg(""), 2200);
  };
  const bouton = { border: 0, borderRadius: 99, padding: "10px 16px", fontWeight: 700, fontSize: 14, display: "inline-flex", alignItems: "center", gap: 8, cursor: "pointer", fontFamily: "inherit" };
  return ReactDOM.createPortal(  // au niveau de la page : pas coincee dans la bulle (son animation capture « fixed »)
    <div onClick={fermer} style={{ position: "fixed", inset: 0, zIndex: 2000, background: "rgba(20,18,26,.72)", backdropFilter: "blur(6px)", display: "grid", placeItems: "center", animation: "monte .25s ease both" }}>
      <div onClick={(e) => e.stopPropagation()} style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 14, maxWidth: "92vw" }}>
        <img src={u} alt="" style={{ maxWidth: "min(88vw, 720px)", maxHeight: "68vh", minWidth: 220, minHeight: 220, objectFit: "contain", imageRendering: "pixelated", borderRadius: 18,
                                     background: DAMIER_APP, boxShadow: "0 30px 80px -20px #000a", animation: "pop .4s cubic-bezier(.34,1.56,.64,1) both" }} key={u} />
        {format && <div style={{ color: "#fff", opacity: .8, fontSize: 13 }}>{format.largeur}×{format.hauteur} · {format.pourquoi}</div>}
        <div style={{ display: "flex", gap: 8, flexWrap: "wrap", justifyContent: "center" }}>
          {images.length > 1 && <button onClick={() => setI((i - 1 + images.length) % images.length)} style={{ ...bouton, background: "rgba(255,255,255,.14)", color: "#fff" }}>‹</button>}
          <button onClick={copier} style={{ ...bouton, background: "#fff", color: "#24232b" }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><rect x="8" y="8" width="12" height="12" rx="2" /><path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3" /></svg>Copier</button>
          <a href={u} download={fichier} style={{ ...bouton, background: "var(--tomate)", color: "#fff", textDecoration: "none" }}>
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M12 4v11M7 10l5 5 5-5M5 20h14" /></svg>Télécharger</a>
          {images.length > 1 && <button onClick={() => setI((i + 1) % images.length)} style={{ ...bouton, background: "rgba(255,255,255,.14)", color: "#fff" }}>›</button>}
          <button onClick={fermer} style={{ ...bouton, background: "rgba(255,255,255,.14)", color: "#fff" }}>Fermer</button>
        </div>
        <div style={{ color: "#fff", minHeight: 18, fontSize: 13 }}>{msg || (images.length > 1 ? `${i + 1} / ${images.length} · flèches du clavier pour passer` : "")}</div>
      </div>
    </div>, document.body);
}

/** Ses meilleurs dessins, empiles comme des photos : clic = en grand (copier, telecharger) ; les fleches font passer le suivant. */
function PileImages({ images, format, nom }) {
  const [devant, setDevant] = useState(0), [survol, setSurvol] = useState(false), [grand, setGrand] = useState(false);
  const n = images.length;
  const ratio = format ? format.largeur / format.hauteur : 1;
  const W = ratio >= 1 ? 168 : Math.round(168 * ratio), H = ratio >= 1 ? Math.round(168 / ratio) : 168;
  const POSE = [{ x: 0, y: 0, r: 0 }, { x: 9, y: -6, r: 4 }, { x: -8, y: -9, r: -5 }];  // les cartes du dessous depassent a peine
  const fleche = { position: "absolute", top: "50%", transform: "translateY(-50%)", zIndex: 10, width: 26, height: 26, borderRadius: 99, border: 0, cursor: "pointer",
                   background: "var(--surface)", color: "var(--encre)", boxShadow: "var(--ombre-3d)", display: "grid", placeItems: "center", fontWeight: 900, opacity: survol ? 1 : 0, transition: "opacity .25s" };
  return (
    <div>
      <div onPointerEnter={() => setSurvol(true)} onPointerLeave={() => setSurvol(false)} style={{ position: "relative", width: W, height: H, margin: "10px 0 6px 6px" }}>
        {images.map((u, i) => {
          const k = (i - devant + n) % n, p = POSE[k] || POSE[POSE.length - 1], f = survol ? 1.7 : 1;
          return <img key={i} src={u} alt="" onClick={() => (k === 0 ? setGrand(true) : setDevant(i))} title={k === 0 ? "Voir en grand · copier · télécharger" : "Mettre devant"}
            style={{ position: "absolute", inset: 0, width: W, height: H, imageRendering: "pixelated", borderRadius: 22, cursor: "pointer", objectFit: "contain",
            background: DAMIER_APP, border: "3px solid var(--surface)", zIndex: n - k,
            transform: `translate(${p.x * f}px, ${p.y * f}px) rotate(${p.r * f}deg) scale(${1 - k * 0.04})`,
            boxShadow: k === 0 ? "var(--ombre-3d), 0 18px 30px -16px rgba(60,30,10,.45)" : "0 8px 16px -10px rgba(60,30,10,.4)",
            filter: k === 0 ? "none" : "saturate(.85) brightness(.97)", transition: "transform .45s cubic-bezier(.34,1.4,.64,1), box-shadow .3s, filter .3s" }} />;
        })}
        {n > 1 && <>
          <button onClick={() => setDevant((d) => (d - 1 + n) % n)} title="Précédent" style={{ ...fleche, left: -12 }}>‹</button>
          <button onClick={() => setDevant((d) => (d + 1) % n)} title="Suivant" style={{ ...fleche, right: -12 }}>›</button>
        </>}
      </div>
      <div style={{ display: "flex", gap: 5, alignItems: "center", marginLeft: Math.max(6, W / 2 - 14) }}>
        {images.map((_, i) => <span key={i} onClick={() => setDevant(i)} style={{ width: 6, height: 6, borderRadius: 99, cursor: "pointer",
          background: i === devant ? "var(--tomate)" : "var(--ligne)", transition: "background .3s" }} />)}
      </div>
      {format && <div style={{ fontSize: 11.5, color: "var(--doux)", marginTop: 6 }}>{format.largeur}×{format.hauteur} · {format.pourquoi}</div>}
      {grand && <Visionneuse images={images} depart={devant} nom={nom} format={format} fermer={() => setGrand(false)} />}
    </div>
  );
}

function DessinEnCours({ avance = 0 }) {
  const R = 22, C = 2 * Math.PI * R;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 14, margin: "6px 0" }}>
      <div className="profond" style={{ position: "relative", width: 112, height: 112, borderRadius: 20, background: DAMIER_APP, display: "grid", placeItems: "center", overflow: "hidden" }}>
        <div style={{ position: "absolute", inset: 0, background: "linear-gradient(110deg, transparent 30%, rgba(255,255,255,.55) 50%, transparent 70%)", backgroundSize: "300px 100%", animation: "brille 1.6s linear infinite" }} />
        <svg width="56" height="56" viewBox="0 0 56 56" style={{ position: "relative" }}>
          <circle cx="28" cy="28" r={R} fill="none" stroke="var(--creme-fonce)" strokeWidth="5" />
          <circle cx="28" cy="28" r={R} fill="none" stroke="var(--tomate)" strokeWidth="5" strokeLinecap="round" strokeDasharray={C}
                  strokeDashoffset={C * (1 - avance)} transform="rotate(-90 28 28)" style={{ transition: "stroke-dashoffset .3s" }} />
        </svg>
      </div>
      <div><div style={{ fontWeight: 700 }}>Je dessine 6 essais…</div>
        <div style={{ fontSize: 13, color: "var(--doux)" }}>{Math.round(avance * 100)} % · je te garde les 3 meilleurs</div></div>
    </div>
  );
}

function MessageJexa({ m, ouvrirVault }) {
  return (
    <div className="app-jexa-msg" style={{ display: "flex", gap: 14, alignItems: "flex-start" }}>
      <div style={{ flex: "none", marginTop: 2 }}><JexaVivante taille={30} etat={m.attente ? "reflechit" : "repos"} /></div>
      <div style={{ minWidth: 0, flex: 1 }}>
        {m.attente && !m.dessin ? <div className="app-points" style={{ padding: "8px 0" }}><span /><span /><span /></div> : null}
        {m.texte && <div className="profond" style={{ color: m.erreur ? "var(--tomate)" : "inherit", background: "var(--surface)", borderRadius: "6px 22px 22px 22px", padding: "12px 18px", display: "inline-block", maxWidth: "100%" }}><MarkdownLeger texte={m.texte} /></div>}
        {m.demandeNote && <button className="btn relief" onClick={ouvrirVault} style={{ marginTop: 10, background: "var(--encre)", color: "var(--papier)", display: "inline-flex", alignItems: "center", gap: 8 }}>
          <Ico n="bouclier" t={16} /> Choisir une note du Hexa Vault</button>}
        {m.dessin && m.attente && <DessinEnCours avance={m.avance} />}
        {m.dessin && !m.attente && m.images?.length > 0 && <PileImages images={m.images} format={m.format} nom={m.sujet} />}
        {m.dessin && m.mots && !m.attente && <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 6 }}>mots compris : {m.mots.filter((w) => w !== "pixel").join(", ") || "aucun (dessin libre)"}</div>}
        {m.outil?.source && <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 6 }}>Source : {m.outil.source}</div>}
        {m.surligne && <button className="app-mini" onClick={() => window.parent.postMessage(m.pagePdf ? { type: "hexa-jexa-pdf-page", page: m.pagePdf } : { type: "hexa-jexa-surligner", passages: m.passages }, "*")}
                               style={{ marginTop: 8, display: "inline-flex", alignItems: "center", gap: 6, fontSize: 12.5, color: "var(--tomate)" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M9 11l-6 6v3h3l6-6M22 2l-8.5 8.5M15 4l5 5" /></svg>
          {m.pagePdf ? `Page ${m.pagePdf} du PDF` : "Surligné sur la page"}{m.page ? ` « ${m.page.slice(0, 40)} »` : ""} · y retourner</button>}
      </div>
    </div>
  );
}

/** En haut : le mode Discussion, ou le mode Travail (un projet dans un dossier) — le travail arrive bientot. */
function ChoixMode({ ouvrirProjet }) {
  const seg = (actif) => ({ border: 0, borderRadius: 99, padding: "6px 14px", fontSize: 13, fontWeight: 700, cursor: "pointer", fontFamily: "inherit", display: "inline-flex", alignItems: "center", gap: 6,
    background: actif ? "var(--surface)" : "transparent", color: actif ? "var(--encre)" : "var(--doux)", boxShadow: actif ? "var(--ombre-3d)" : "none", transition: "all .25s" });
  return (
    <div className="app-nodrag" style={{ display: "flex", gap: 2, padding: 3, borderRadius: 99, background: "var(--creme-fonce)" }}>
      <button style={seg(true)}>Discussion</button>
      <button style={seg(false)} onClick={ouvrirProjet} title="Bientôt : un projet dans un dossier (images, code, applications…)">
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><rect x="5" y="11" width="14" height="10" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>
        Travail</button>
    </div>
  );
}

function FenetreProjet({ fermer }) {
  const [nom, setNom] = useState("Mon projet"), [ou, setOu] = useState("jexa");
  const carte = (actif) => ({ border: `2px solid ${actif ? "var(--tomate)" : "var(--ligne)"}`, borderRadius: 18, padding: "12px 14px", textAlign: "left", cursor: "pointer",
    background: actif ? "var(--tomate-c)" : "var(--surface)", color: "var(--encre)", fontFamily: "inherit", transition: "all .2s" });
  return (
    <Fenetre titre="Nouveau projet" fermer={fermer}>
      <p style={{ fontSize: 13.5, color: "var(--doux)", margin: "0 0 14px", lineHeight: 1.55 }}>
        Le mode Travail range tout ce que Jexa fait dans un dossier : images générées, code, applications… Chaque projet a le sien.</p>
      <label style={{ fontSize: 13, fontWeight: 700 }}>Nom du projet</label>
      <input value={nom} onChange={(e) => setNom(e.target.value)} style={{ width: "100%", margin: "6px 0 14px", border: "1.5px solid var(--ligne)", borderRadius: 14, padding: "10px 14px",
             fontFamily: "inherit", background: "var(--surface)", color: "var(--encre)", outline: "none" }} />
      <div style={{ display: "grid", gap: 8, marginBottom: 16 }}>
        <button style={carte(ou === "jexa")} onClick={() => setOu("jexa")}><b>Créer un dossier pour moi</b>
          <div className="mono" style={{ fontSize: 12, color: "var(--doux)", marginTop: 4 }}>Documents\Jexa\{nom.trim() || "Mon projet"}</div></button>
        <button style={carte(ou === "dossier")} onClick={() => setOu("dossier")}><b>Choisir un dossier existant</b>
          <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 4 }}>Jexa travaillera dans le dossier que tu choisis.</div></button>
      </div>
      <button className="btn" disabled style={{ width: "100%", background: "var(--creme-fonce)", color: "var(--doux)", cursor: "not-allowed", display: "flex", justifyContent: "center", alignItems: "center", gap: 8 }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><rect x="5" y="11" width="14" height="10" rx="2" /><path d="M8 11V8a4 4 0 0 1 8 0v3" /></svg>
        Le mode Travail arrive bientôt</button>
      <div style={{ fontSize: 12, color: "var(--doux)", marginTop: 10, textAlign: "center" }}>Pour l'instant, tout se passe en mode Discussion.</div>
    </Fenetre>
  );
}

function ChoixModele({ modeles, modele, setModele }) {
  const [ouvert, setOuvert] = useState(false);
  const actuel = modeles.find((x) => x.id === modele) || modeles[0];
  useEffect(() => { if (!ouvert) return; const f = () => setOuvert(false); setTimeout(() => addEventListener("click", f), 0); return () => removeEventListener("click", f); }, [ouvert]);
  return (
    <div style={{ position: "relative" }}>
      <button className="app-mini" onClick={() => setOuvert(!ouvert)} style={{ fontSize: 13.5, fontWeight: 700, padding: "6px 10px", color: "var(--encre)" }}>
        {actuel?.nom || "Jexa"} <svg width="10" height="10" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" style={{ opacity: .6, marginLeft: 2 }}><path d="M6 9l6 6 6-6" /></svg></button>
      {ouvert && <div className="app-menu" style={{ bottom: "calc(100% + 8px)", right: 0 }}>
        {modeles.map((x) => (
          <button key={x.id} className="app-item" onClick={() => { setModele(x.id); setOuvert(false); }} style={{ alignItems: "flex-start" }}>
            <div style={{ flex: 1 }}><div style={{ fontWeight: 700 }}>{x.nom}</div><div style={{ fontSize: 12.5, color: "var(--doux)" }}>{x.detail}</div></div>
            {x.id === modele && <span style={{ color: "var(--tomate)", display: "grid" }}><svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5 9-10" /></svg></span>}
          </button>))}
      </div>}
    </div>
  );
}

/* Le Hexa Vault : toutes les donnees du compte, sur les serveurs Hexa. Les notes (celles de Hexa Browser) y sont
   chiffrees de bout en bout (AES-256-GCM, cle tiree du mot de passe : PBKDF2-SHA256, 210 000 tours, comme Hexa Browser).
   La cle reste sur cet appareil ; Jexa ne lit une note que si tu la choisis. */
const VAULT = {
  async deriver(mdp, pseudo) {
    const base = await crypto.subtle.importKey("raw", new TextEncoder().encode(mdp), "PBKDF2", false, ["deriveBits"]);
    const bits = await crypto.subtle.deriveBits({ name: "PBKDF2", hash: "SHA-256", iterations: 210000,
      salt: new TextEncoder().encode("hexa-browser/sync/v1/" + pseudo.toLowerCase()) }, base, 256);
    return btoa(String.fromCharCode(...new Uint8Array(bits)));
  },
  async garder(pseudo, cle) {  // application de bureau : protegee par Windows (DPAPI) ; web : le temps de la session
    if (BUREAU && window.jexaBureau.garderCle) return window.jexaBureau.garderCle(pseudo, cle);
    try { sessionStorage.setItem("jexa_vault_" + pseudo, cle); } catch {}
  },
  async lire(pseudo) {
    if (BUREAU && window.jexaBureau.lireCle) return (await window.jexaBureau.lireCle(pseudo)) || null;
    try { return sessionStorage.getItem("jexa_vault_" + pseudo); } catch { return null; }
  },
  async oublier(pseudo) {
    if (BUREAU && window.jexaBureau.oublierCle) return window.jexaBureau.oublierCle(pseudo);
    try { sessionStorage.removeItem("jexa_vault_" + pseudo); } catch {}
  },
  async aes(cle, usage) { return crypto.subtle.importKey("raw", Uint8Array.from(atob(cle), (c) => c.charCodeAt(0)), "AES-GCM", false, [usage]); },
  async lireKind(compte, cle, kind) {  // dechiffre ici, sur l'appareil (meme format que Hexa Browser : nonce de 12 octets + donnees)
    const r = await fetch((compte.api || HEXA_API) + "/api/jexa/vault/" + kind, { headers: { Authorization: "Bearer " + compte.jeton } });
    if (!r.ok) throw new Error("Hexa Vault injoignable");
    const { blob } = await r.json();
    if (!blob) return null;
    const brut = Uint8Array.from(atob(blob), (c) => c.charCodeAt(0));
    const clair = await crypto.subtle.decrypt({ name: "AES-GCM", iv: brut.slice(0, 12) }, await VAULT.aes(cle, "decrypt"), brut.slice(12));  // erreur si mauvaise cle
    return JSON.parse(new TextDecoder().decode(clair));
  },
  async ecrireJexa(compte, cle, donnees) {  // chiffre ici, avant l'envoi : le serveur ne recoit qu'un bloc illisible
    const iv = crypto.getRandomValues(new Uint8Array(12));
    const ct = new Uint8Array(await crypto.subtle.encrypt({ name: "AES-GCM", iv }, await VAULT.aes(cle, "encrypt"), new TextEncoder().encode(JSON.stringify(donnees))));
    const tout = new Uint8Array(12 + ct.length); tout.set(iv); tout.set(ct, 12);
    let b = ""; for (let i = 0; i < tout.length; i += 0x8000) b += String.fromCharCode(...tout.subarray(i, i + 0x8000));
    const r = await fetch((compte.api || HEXA_API) + "/api/jexa/vault/jexa", { method: "POST", headers: { "Content-Type": "application/json", Authorization: "Bearer " + compte.jeton }, body: JSON.stringify({ blob: btoa(b) }) });
    if (!r.ok) throw new Error("Hexa Vault injoignable");
  },
  async notes(compte, cle) {
    const data = await VAULT.lireKind(compte, cle, "notes");
    if (!data) return [];
    const texte = (html) => { const d = document.createElement("div"); d.innerHTML = String(html || "").replace(/<(br|\/p|\/div|\/li|\/h\d)>/gi, "\n$&"); d.querySelectorAll("img,script,style").forEach((x) => x.remove()); return d.textContent.replace(/\n{3,}/g, "\n\n").trim(); };
    return (data.items || []).filter((n) => !n.del).map((n) => { const t = texte(n.html); return { id: n.id, t: n.t, texte: t, titre: (t.split("\n")[0] || "Note sans titre").slice(0, 70) }; })
      .sort((a, b) => b.t - a.t);
  },
};
/* Les discussions dans le Hexa Vault, au format de Hexa Browser : [{ id, title, t, messages: [{ role, content }] }].
   Les dessins (trop lourds) restent sur l'appareil ; le texte des discussions se retrouve partout. */
const versFil = (d) => ({ id: d.id, title: d.titre, t: d.date, app: { modele: d.modele || "nexus" },
  messages: d.messages.filter((m) => m.texte && !m.attente).map((m) => ({ role: m.qui === "toi" ? "user" : "assistant", content: m.texte, ...(m.erreur ? { error: true } : {}),
    ...(m.images?.length && !String(m.images[0]).startsWith("data:") ? { images: m.images, format: m.format, sujet: m.sujet } : {}) })) });
const depuisFil = (f) => ({ id: f.id, titre: f.title || "Discussion", date: f.t || Date.now(), modele: f.app?.modele || "nexus", monde: [],
  messages: (f.messages || []).map((m) => ({ qui: m.role === "user" ? "toi" : "jexa", texte: m.content, ...(m.error ? { erreur: true } : {}),
    ...(m.images ? { dessin: true, images: m.images, format: m.format, sujet: m.sujet } : {}) })) });
function fusionner(locales, fils) {
  const parId = {};
  locales.forEach((d) => { parId[d.id] = d; });
  (fils || []).forEach((f) => {
    const d = parId[f.id];
    const plusLong = d && (f.messages || []).length > d.messages.filter((m) => m.texte && !m.attente).length;
    const sansDessin = d && !d.messages.some((m) => m.images && !(f.messages || []).some((x) => x.images));  // on garde la version qui a les dessins
    if (!d || plusLong || ((f.t || 0) > (d.date || 0) && sansDessin)) parId[f.id] = depuisFil(f);
  });
  return Object.values(parId).sort((a, b) => b.date - a.date);
}

const DEMANDE_NOTES = /\b(mes|ma|une|des|tes|la) notes?\b|\bhexa vault\b|\bmon vault\b/i;

function FenetreVault({ fermer, compte, choisir, mode }) {
  const [cle, setCle] = useState(undefined), [notes, setNotes] = useState(null), [mdp, setMdp] = useState(""), [erreur, setErreur] = useState(""), [attente, setAttente] = useState(false), [q, setQ] = useState("");
  const ouvrir = async (k) => {
    setAttente(true); setErreur("");
    try { setNotes(await VAULT.notes(compte, k)); setCle(k); }
    catch (e) { setCle(null); setErreur(e.name === "OperationError" ? "Mot de passe incorrect : je n'arrive pas à ouvrir tes notes." : "Je n'arrive pas à joindre ton Hexa Vault."); }
    finally { setAttente(false); }
  };
  useEffect(() => { VAULT.lire(compte.pseudo).then((k) => (k ? ouvrir(k) : setCle(null))); }, []);
  const deverrouiller = async (e) => {
    e.preventDefault(); setAttente(true);
    const k = await VAULT.deriver(mdp, compte.pseudo);
    await ouvrir(k);
    try { await VAULT.notes(compte, k); await VAULT.garder(compte.pseudo, k); } catch {}
    setMdp("");
  };
  const visibles = (notes || []).filter((n) => !q || (n.titre + " " + n.texte).toLowerCase().includes(q.toLowerCase()));
  return (
    <Fenetre titre="Hexa Vault" fermer={fermer}>
      <p style={{ fontSize: 13.5, color: "var(--doux)", margin: "0 0 14px", lineHeight: 1.55 }}>
        Toutes tes données Hexa (souvenirs de Jexa, notes de Hexa Browser…) sont rangées dans ton <b>Hexa Vault</b>. Tes notes y sont chiffrées :
        {mode === "choisir" ? " choisis celle que Jexa peut lire. Elle ne verra que celle-là." : " Jexa ne les lit jamais, sauf celle que tu lui montres."}</p>
      {cle === undefined || attente ? <div className="chargement" style={{ height: 120, borderRadius: 18 }} /> : cle === null ? (
        <form onSubmit={deverrouiller}>
          <div style={{ fontSize: 13.5, marginBottom: 8 }}>Pour ouvrir tes notes <b>sur cet appareil</b>, entre le mot de passe de ton compte Hexa. Il ne sort pas de ton appareil.</div>
          <input type="password" value={mdp} onChange={(e) => setMdp(e.target.value)} autoFocus placeholder="Mot de passe Hexa"
                 style={{ width: "100%", border: "1.5px solid var(--ligne)", borderRadius: 16, padding: "12px 16px", fontFamily: "inherit", background: "var(--surface)", color: "var(--encre)", outline: "none", marginBottom: 10 }} />
          {erreur && <div style={{ color: "var(--tomate)", fontSize: 13, marginBottom: 8 }}>{erreur}</div>}
          <button className="btn relief" disabled={!mdp} style={{ width: "100%", background: "var(--encre)", color: "var(--papier)" }}>Ouvrir mes notes</button>
        </form>
      ) : <>
        {erreur && <div style={{ color: "var(--tomate)", fontSize: 13, marginBottom: 8 }}>{erreur}</div>}
        <input value={q} onChange={(e) => setQ(e.target.value)} placeholder="Chercher une note…"
               style={{ width: "100%", border: "1.5px solid var(--ligne)", borderRadius: 14, padding: "9px 14px", fontFamily: "inherit", background: "var(--surface)", color: "var(--encre)", outline: "none", marginBottom: 10 }} />
        <div className="app-defile" style={{ maxHeight: "45vh", overflowY: "auto", display: "flex", flexDirection: "column", gap: 6 }}>
          {!visibles.length && <div style={{ color: "var(--doux)", fontSize: 13.5, padding: 10 }}>{notes.length ? "Aucune note trouvée." : "Tu n'as pas encore de notes dans Hexa Browser."}</div>}
          {visibles.map((n) => (
            <button key={n.id} className="app-item" disabled={mode !== "choisir"} onClick={() => { choisir(n); fermer(); }} style={{ display: "block", padding: "10px 12px", cursor: mode === "choisir" ? "pointer" : "default" }}>
              <div style={{ fontWeight: 700, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{n.titre}</div>
              <div style={{ fontSize: 12, color: "var(--doux)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{new Date(n.t).toLocaleDateString("fr-FR")} · {n.texte.slice(n.titre.length, n.titre.length + 90) || "…"}</div>
            </button>))}
        </div>
        <button className="app-mini" onClick={async () => { await VAULT.oublier(compte.pseudo); setCle(null); setNotes(null); }} style={{ marginTop: 10, fontSize: 12.5 }}>Verrouiller sur cet appareil</button>
      </>}
    </Fenetre>
  );
}

const VERSION_APP = "1.2.0";
const JOURNAL = [
  { version: "1.2.0", date: "15 octobre 2026", points: ["Hexa Vault : tes notes de Hexa Browser, chiffrées, que Jexa lit seulement si tu choisis une note",
    "Jexa Atelier : 6 essais en arrière-plan, ses 3 meilleurs en pile"] },
  { version: "1.1.0", date: "15 octobre 2026", points: ["Menu du compte : paramètres, utilisation, langue, aide, journal", "Lucioles et lumière aux couleurs du thème de nuit",
    "Boutons de fenêtre dessinés par Jexa", "Icônes dessinées, plus aucun emoji"] },
  { version: "1.0.0", date: "15 octobre 2026", points: ["Première version de l'application Jexa", "Connexion avec un compte Hexa, offre gratuite et quota du jour",
    "Choix du modèle : Jexa et Jexa Atelier (dessins en pixel art construits en direct)", "Discussions rangées par date, recherche, pièces jointes"] },
];

ICONES.reglages = "M12 9a3 3 0 1 0 0 6 3 3 0 0 0 0-6zM19.4 15a1.7 1.7 0 0 0 .3 1.8l.1.1a2 2 0 1 1-2.8 2.8l-.1-.1a1.7 1.7 0 0 0-1.8-.3 1.7 1.7 0 0 0-1 1.5V21a2 2 0 1 1-4 0v-.1a1.7 1.7 0 0 0-1.1-1.5 1.7 1.7 0 0 0-1.8.3l-.1.1a2 2 0 1 1-2.8-2.8l.1-.1a1.7 1.7 0 0 0 .3-1.8 1.7 1.7 0 0 0-1.5-1H3a2 2 0 1 1 0-4h.1a1.7 1.7 0 0 0 1.5-1.1 1.7 1.7 0 0 0-.3-1.8l-.1-.1a2 2 0 1 1 2.8-2.8l.1.1a1.7 1.7 0 0 0 1.8.3H9a1.7 1.7 0 0 0 1-1.5V3a2 2 0 1 1 4 0v.1a1.7 1.7 0 0 0 1 1.5 1.7 1.7 0 0 0 1.8-.3l.1-.1a2 2 0 1 1 2.8 2.8l-.1.1a1.7 1.7 0 0 0-.3 1.8V9a1.7 1.7 0 0 0 1.5 1H21a2 2 0 1 1 0 4h-.1a1.7 1.7 0 0 0-1.5 1z";
ICONES.jauge = "M12 21a9 9 0 1 1 9-9M12 12l4-4M3 12h2M12 3v2";
ICONES.aide = "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM9.5 9.5a2.5 2.5 0 1 1 3.5 2.3c-.6.3-1 .9-1 1.6V14M12 17h.01";
ICONES.fusee = "M12 15l-3-3a12 12 0 0 1 9-8 12 12 0 0 1-8 9zM9 12H5l2-4h5M12 15v4l4-2v-5M5 19c0-2 1-3 3-3";
ICONES.journal = "M5 4h11l3 3v13H5zM9 10h6M9 14h6M9 18h4";
ICONES.info = "M12 3a9 9 0 1 0 0 18 9 9 0 0 0 0-18zM12 11v6M12 7.5h.01";
ICONES.suivant = "M9 6l6 6-6 6";
ICONES.bouclier = "M12 3l8 3v6c0 5-3.5 8-8 9-4.5-1-8-4-8-9V6z";

function LigneMenu({ ico, texte, droite, onClick, danger, href }) {
  const contenu = <>
    <span style={{ display: "grid", color: danger ? "var(--tomate)" : "var(--doux)" }}><Ico n={ico} t={17} /></span>
    <span style={{ flex: 1 }}>{texte}</span>
    {droite && <span style={{ fontSize: 12, color: "var(--doux)", display: "flex", alignItems: "center" }}>{droite}</span>}
  </>;
  const st = { color: danger ? "var(--tomate)" : "var(--encre)", textDecoration: "none", gap: 12, padding: "9px 12px" };
  return href ? <a className="app-item" href={href} target="_blank" rel="noreferrer" style={st}>{contenu}</a>
              : <button className="app-item" onClick={onClick} style={st}>{contenu}</button>;
}

function CarteCompte({ session, deconnecter, ouvrir }) {
  const [ouvert, setOuvert] = useState(false), [plus, setPlus] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    if (!ouvert) { setPlus(false); return; }
    const f = (e) => { if (!ref.current?.contains(e.target)) setOuvert(false); };
    setTimeout(() => addEventListener("pointerdown", f), 0); return () => removeEventListener("pointerdown", f);
  }, [ouvert]);
  if (!session) return null;
  const reste = session.limite == null ? null : Math.max(0, session.limite - session.utilise);
  const aller = (nom) => { setOuvert(false); ouvrir(nom); };
  const trait = <div style={{ height: 1, background: "var(--ligne)", margin: "5px 8px" }} />;
  return (
    <div ref={ref} style={{ position: "relative", padding: 10 }}>
      {ouvert && <div className="app-menu" style={{ bottom: "calc(100% - 2px)", left: 10, right: 10, minWidth: 0, width: 280, padding: 6 }}>
        <div style={{ fontSize: 12.5, color: "var(--doux)", padding: "8px 12px 6px", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{session.pseudo} · compte Hexa</div>
        <LigneMenu ico="reglages" texte="Paramètres" droite="Ctrl+," onClick={() => aller("parametres")} />
        <LigneMenu ico="jauge" texte="Utilisation" onClick={() => aller("utilisation")} />
        <LigneMenu ico="globe" texte="Langue" droite="Français" onClick={() => aller("langue")} />
        <LigneMenu ico="aide" texte="Obtenir de l'aide" onClick={() => aller("aide")} />
        {trait}
        {!session.admin && <LigneMenu ico="fusee" texte="Mettre l'offre à niveau" onClick={() => aller("forfait")} />}
        <LigneMenu ico="bouclier" texte="Hexa Vault" droite="Mes données" onClick={() => aller("vault")} />
        <LigneMenu ico="souvenir" texte="Ce dont je me souviens" onClick={() => aller("souvenirs")} />
        <LigneMenu ico="journal" texte="Journal des modifications" onClick={() => aller("journal")} />
        <div style={{ position: "relative" }} onPointerEnter={() => setPlus(true)} onPointerLeave={() => setPlus(false)}>
          <LigneMenu ico="info" texte="En savoir plus" droite={<Ico n="suivant" t={14} />} onClick={() => setPlus(!plus)} />
          {plus && <div className="app-menu" style={{ left: "calc(100% + 4px)", bottom: -6, minWidth: 230, padding: 6 }}>
            <LigneMenu ico="info" texte="À propos de Jexa" onClick={() => aller("apropos")} />
            <LigneMenu ico="bouclier" texte="Confidentialité" onClick={() => aller("confidentialite")} />
            <LigneMenu ico="lien" texte="Le site jexa.fr" href="https://jexa.fr" />
            <LigneMenu ico="lien" texte="Mon compte Hexa" href="https://hexa-mc.fr" />
          </div>}
        </div>
        {trait}
        <LigneMenu ico="sortie" texte="Se déconnecter" danger onClick={() => { setOuvert(false); deconnecter(); }} />
      </div>}
      <button className="relief" onClick={() => setOuvert(!ouvert)} style={{ width: "100%", border: 0, background: "var(--surface)", borderRadius: 18, padding: "10px 12px", textAlign: "left", color: "var(--encre)", display: "flex", gap: 10, alignItems: "center" }}>
        <div style={{ width: 36, height: 36, borderRadius: 12, display: "grid", placeItems: "center", fontWeight: 900, color: "#fff", flex: "none",
                      background: "linear-gradient(135deg, var(--tomate), var(--moutarde, #e6b94a))" }}>{session.pseudo.slice(0, 1).toUpperCase()}</div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ display: "flex", gap: 6, alignItems: "center" }}>
            <b style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{session.pseudo}</b>
            <span style={{ fontSize: 10.5, fontWeight: 800, padding: "2px 7px", borderRadius: 99, letterSpacing: ".04em",
                           background: session.admin ? "var(--moutarde-c, #f6ebc8)" : "var(--sarcelle-c)", color: session.admin ? "#9a6b00" : "var(--sarcelle)" }}>{session.offre}</span>
          </div>
          {reste == null ? <div style={{ fontSize: 12, color: "var(--doux)" }}>Messages illimités</div> : <>
            <div style={{ fontSize: 12, color: "var(--doux)" }}>{reste} message{reste > 1 ? "s" : ""} restant{reste > 1 ? "s" : ""} aujourd'hui</div>
            <div style={{ height: 4, borderRadius: 99, background: "var(--creme-fonce)", marginTop: 4, overflow: "hidden" }}>
              <div style={{ width: `${100 * session.utilise / session.limite}%`, height: "100%", background: reste < 10 ? "var(--tomate)" : "var(--sarcelle)", transition: "width .5s var(--ease)" }} /></div>
          </>}
        </div>
      </button>
    </div>
  );
}

function Interrupteur({ oui, changer }) {
  return <button onClick={() => changer(!oui)} style={{ width: 44, height: 26, borderRadius: 99, border: 0, padding: 3, background: oui ? "var(--tomate)" : "var(--creme-fonce)", transition: "background .25s" }}>
    <span style={{ display: "block", width: 20, height: 20, borderRadius: 99, background: "#fff", boxShadow: "0 2px 4px #0003", transform: `translateX(${oui ? 18 : 0}px)`, transition: "transform .25s var(--ease)" }} /></button>;
}

function LigneReglage({ titre, detail, children }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 14, padding: "12px 0", borderBottom: "1px solid var(--ligne)" }}>
    <div style={{ flex: 1 }}><div style={{ fontWeight: 700, fontSize: 14.5 }}>{titre}</div>{detail && <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 2 }}>{detail}</div>}</div>
    {children}</div>;
}

function FenetresApp({ quoi, fermer, compte, choisirNote, session, theme, setTheme, modele, setModele, envoiEntree, setEnvoiEntree, effacerTout, souvenirs, oublier, nbDiscussions }) {
  if (!quoi) return null;
  if (quoi === "souvenirs") return <FenetreSouvenirs fermer={fermer} souvenirs={souvenirs} oublier={oublier} />;
  if (quoi === "projet") return <FenetreProjet fermer={fermer} />;
  if (quoi === "vault" || quoi === "vault-choisir") return <FenetreVault fermer={fermer} compte={compte} choisir={choisirNote} mode={quoi === "vault-choisir" ? "choisir" : "voir"} />;
  const choix = (actif) => ({ border: 0, borderRadius: 99, padding: "7px 14px", fontWeight: 700, fontSize: 13, background: actif ? "var(--encre)" : "var(--creme-fonce)", color: actif ? "var(--papier)" : "var(--encre)" });
  const reste = session.limite == null ? null : Math.max(0, session.limite - session.utilise);
  const minuit = new Date(); minuit.setHours(24, 0, 0, 0);
  const contenu = {
    parametres: ["Paramètres", <>
      <LigneReglage titre="Thème" detail="Le jour crème, ou la nuit violette.">
        <div style={{ display: "flex", gap: 6 }}><button style={choix(theme === "jour")} onClick={() => setTheme("jour")}>Jour</button><button style={choix(theme === "nuit")} onClick={() => setTheme("nuit")}>Nuit</button></div>
      </LigneReglage>
      <LigneReglage titre="Modèle par défaut" detail="Celui qui est choisi quand tu ouvres une discussion.">
        <select value={modele} onChange={(e) => setModele(e.target.value)} style={{ borderRadius: 12, padding: "7px 10px", fontFamily: "inherit", background: "var(--surface)", color: "var(--encre)", border: "1.5px solid var(--ligne)" }}>
          {session.modeles.map((m) => <option key={m.id} value={m.id}>{m.nom}</option>)}</select>
      </LigneReglage>
      <LigneReglage titre="Envoyer avec Entrée" detail="Sinon : Ctrl+Entrée pour envoyer, Entrée pour aller à la ligne."><Interrupteur oui={envoiEntree} changer={setEnvoiEntree} /></LigneReglage>
      <LigneReglage titre="Effacer toutes mes discussions" detail={`${nbDiscussions} discussion${nbDiscussions > 1 ? "s" : ""}, gardée${nbDiscussions > 1 ? "s" : ""} seulement sur cet appareil.`}>
        <button className="btn relief" onClick={() => { if (confirm("Effacer toutes tes discussions ? C'est définitif.")) { effacerTout(); fermer(); } }}
                style={{ background: "var(--tomate-c)", color: "var(--tomate)" }}>Effacer</button>
      </LigneReglage>
    </>],
    utilisation: ["Utilisation", <>
      <div className="profond" style={{ background: "var(--surface)", borderRadius: 20, padding: 18, marginBottom: 14 }}>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}><b>Messages aujourd'hui</b>
          <span className="mono" style={{ fontSize: 14 }}>{session.utilise}{session.limite != null ? ` / ${session.limite}` : ""}</span></div>
        {session.limite != null ? <>
          <div style={{ height: 10, borderRadius: 99, background: "var(--creme-fonce)", marginTop: 10, overflow: "hidden" }}>
            <div style={{ width: `${100 * session.utilise / session.limite}%`, height: "100%", background: reste < 10 ? "var(--tomate)" : "var(--sarcelle)" }} /></div>
          <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 8 }}>{reste} restant{reste > 1 ? "s" : ""} · remis à zéro à minuit (dans {Math.ceil((minuit - Date.now()) / 36e5)} h)</div>
        </> : <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 8 }}>Compte admin : aucune limite.</div>}
      </div>
      <LigneReglage titre="Offre" detail={session.admin ? "Admin de Hexa Labs" : "Gratuite, pour tout le monde avec un compte Hexa"}><b>{session.offre}</b></LigneReglage>
      <LigneReglage titre="Modèles disponibles" detail={session.modeles.map((m) => m.nom).join(" · ")} />
      <div style={{ fontSize: 12.5, color: "var(--doux)", marginTop: 12 }}>Un dessin de Jexa Atelier compte comme un message.</div>
    </>],
    langue: ["Langue", <>
      <LigneReglage titre="Français" detail="Jexa a appris le français de zéro."><span style={{ color: "var(--tomate)", display: "grid" }}><svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.6" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12l5 5 9-10" /></svg></span></LigneReglage>
      <LigneReglage titre="English" detail="Pas encore : Jexa ne parle que français pour l'instant."><span style={{ fontSize: 12, color: "var(--doux)" }}>Bientôt</span></LigneReglage>
    </>],
    aide: ["Obtenir de l'aide", <>
      <div style={{ fontWeight: 700, marginBottom: 6 }}>Raccourcis clavier</div>
      {[["Nouvelle discussion", "Ctrl+N"], ["Rechercher", "Ctrl+K"], ["Afficher / masquer la barre", "Ctrl+B"], ["Paramètres", "Ctrl+,"], ["Aller à la ligne", "Maj+Entrée"]].map(([a, b]) => (
        <div key={a} style={{ display: "flex", justifyContent: "space-between", padding: "7px 0", borderBottom: "1px solid var(--ligne)", fontSize: 14 }}><span>{a}</span><span className="mono" style={{ color: "var(--doux)" }}>{b}</span></div>))}
      <div style={{ fontSize: 13.5, color: "var(--doux)", margin: "14px 0 12px" }}>Un souci, une idée ? Écris à l'équipe Hexa Labs depuis le site Hexa.</div>
      <a className="btn relief" href="https://hexa-mc.fr" target="_blank" rel="noreferrer" style={{ display: "inline-block", textDecoration: "none", background: "var(--encre)", color: "var(--papier)" }}>Ouvrir le site Hexa</a>
    </>],
    forfait: ["Ton offre", <>
      <div className="profond bord-vivant focus" style={{ background: "var(--surface)", borderRadius: 22, padding: 18, marginBottom: 12 }}>
        <div style={{ display: "flex", justifyContent: "space-between" }}><b style={{ fontSize: 17 }}>Gratuit</b><span style={{ fontSize: 12, fontWeight: 800, color: "var(--sarcelle)" }}>TON OFFRE</span></div>
        <div style={{ fontSize: 13.5, color: "var(--doux)", marginTop: 6 }}>{session.limite} messages par jour · Jexa et Jexa Atelier · discussions sur ton appareil</div>
      </div>
      <div style={{ fontSize: 13.5, color: "var(--doux)" }}>Pour l'instant, Jexa est entièrement gratuite. D'autres offres arriveront plus tard : rien à payer aujourd'hui.</div>
    </>],
    journal: ["Journal des modifications", <div className="app-defile" style={{ maxHeight: "55vh", overflowY: "auto", paddingRight: 6 }}>
      {JOURNAL.map((j) => <div key={j.version} style={{ marginBottom: 16 }}>
        <div style={{ display: "flex", gap: 8, alignItems: "baseline" }}><b className="serif" style={{ fontSize: 18 }}>Version {j.version}</b><span style={{ fontSize: 12.5, color: "var(--doux)" }}>{j.date}</span></div>
        <ul style={{ margin: "6px 0 0", paddingLeft: 20, fontSize: 14, lineHeight: 1.6 }}>{j.points.map((x) => <li key={x}>{x}</li>)}</ul>
      </div>)}
    </div>],
    apropos: ["À propos de Jexa", <>
      <p style={{ fontSize: 14.5, lineHeight: 1.6, margin: "0 0 12px" }}>Jexa est une intelligence artificielle créée <b>de zéro</b> par Hexa Labs : pas de modèle déjà entraîné par quelqu'un d'autre. Elle apprend toute seule, cours après cours, et s'améliore chaque nuit.</p>
      <LigneReglage titre="Version de l'application" detail={BUREAU ? "Application de bureau" : "Version web"}><span className="mono">{VERSION_APP}</span></LigneReglage>
    </>],
    confidentialite: ["Confidentialité", <ul style={{ margin: 0, paddingLeft: 20, fontSize: 14, lineHeight: 1.7 }}>
      <li>Ton <b>mot de passe</b> part directement chez Hexa : Jexa ne le voit jamais.</li>
      <li>Tes <b>discussions</b> restent sur cet appareil : le serveur de Jexa ne les enregistre pas.</li>
      <li>Ce dont Jexa <b>se souvient</b> (ton prénom, ce que tu aimes…) est rangé dans ton <b>Hexa Vault</b>, et tu peux tout effacer.</li>
      <li>Tes <b>notes</b> du Hexa Vault sont chiffrées de bout en bout : ni Hexa ni Jexa ne peuvent les lire. Jexa ne voit <b>que la note que tu choisis</b> de lui montrer, quand tu le demandes.</li>
      <li>Pour répondre à certaines questions, Jexa cherche <b>seulement le sujet</b> (un mot, une ville) sur des sources fiables, jamais ta conversation.</li>
      <li>Rien n'est revendu.</li>
    </ul>],
  }[quoi];
  if (!contenu) return null;
  return <Fenetre titre={contenu[0]} fermer={fermer}><div style={{ maxHeight: "70vh", overflowY: "auto" }}>{contenu[1]}</div></Fenetre>;
}

const IDEES_APP = [
  { icone: "globe", couleur: "var(--sarcelle)", texte: "qui est Marie Curie ?", label: "Qui est Marie Curie ?" },
  { icone: "lettre", couleur: "var(--tomate)", texte: "tu peux m'aider à écrire un message ?", label: "M'aider à écrire un message" },
  { icone: "livre", couleur: "#b08a1e", texte: "raconte Il était une fois un petit dragon qui", label: "Raconte-moi une histoire" },
  { icone: "pinceau", couleur: "#8b6cff", texte: "une épée en diamant", label: "Dessine une épée en diamant", modele: "atelier" },
];

const IDEES_PAGE = [
  { icone: "livre", couleur: "var(--sarcelle)", texte: "résume cette page", label: "Résume cette page" },
  { icone: "globe", couleur: "var(--tomate)", texte: "quelle est l'idée principale de cette page ?", label: "L'idée principale ?" },
];

function groupeDate(t) {
  const j = new Date(); j.setHours(0, 0, 0, 0);
  const d = (j - new Date(t).setHours(0, 0, 0, 0)) / 864e5;
  return d <= 0 ? "Aujourd'hui" : d <= 1 ? "Hier" : d <= 7 ? "Cette semaine" : "Plus ancien";
}

function AppJexa() {
  const { compte, souvenirs, connecter, connecterLien, deconnecter, retenir, oublier, adopter } = useCompteHexa();
  const [session, setSession] = useState(null);
  const [synchro, setSynchro] = useState(null);
  const [attendreNavigateur, setAttendreNavigateur] = useState(INTEGRE);
  const [onglet, setOnglet] = useState(null);       // la page web ouverte dans le navigateur (panneau)
  const [avecPage, setAvecPage] = useState(true);    // Jexa lit-elle la page pour repondre ?
  useEffect(() => {
    if (!COMPACT) return;
    const f = (e) => { if (e.source === window.parent && e.data && e.data.type === "hexa-jexa-onglet") setOnglet(e.data.titre ? { titre: e.data.titre, url: e.data.url } : null); };
    addEventListener("message", f); return () => removeEventListener("message", f);
  }, []);
  useEffect(() => { if (INTEGRE) { const t = setTimeout(() => setAttendreNavigateur(false), 4000); return () => clearTimeout(t); } }, []);  // null | "en cours" | "ok" | "pause" | "erreur"
  const derniereSynchro = useRef(0), envoiSynchro = useRef(null);
  const discRef = useRef([]);
  const [verif, setVerif] = useState(!!compte);
  const cle = compte ? "jexa_app_" + compte.pseudo : null;
  const [discussions, setDiscussions] = useState([]);
  const [courante, setCourante] = useState(null);
  const [texte, setTexte] = useState("");
  const [attente, setAttente] = useState(false);
  const [focus, setFocus] = useState(false);
  const [recherche, setRecherche] = useState("");
  const [barre, setBarre] = useState(() => typeof innerWidth === "undefined" || innerWidth > 760);  // etroit (panneau du navigateur) : barre repliee
  const [modele, setModele] = useState(() => lireJson("jexa_app_modele", "nexus"));
  const [fenetre, setFenetre] = useState(null);
  const [theme, setTheme] = useState(() => lireJson("jexa_app_theme", "jour"));
  const [envoiEntree, setEnvoiEntree] = useState(() => lireJson("jexa_app_entree", true));
  useEffect(() => { ecrireJson("jexa_app_entree", envoiEntree); }, [envoiEntree]);
  const zone = useRef(null), champ = useRef(null), fichierRef = useRef(null), chercheRef = useRef(null);

  useEffect(() => { ecrireJson("jexa_app_modele", modele); }, [modele]);
  useEffect(() => {  // dans Hexa Browser : on recoit le compte du navigateur (et la cle du Vault), sans redemander le mot de passe
    if (!INTEGRE) return;
    const f = async (e) => {
      if (e.source !== window.parent || !e.data) return;
      if (e.data.type === "hexa-jexa-sans-compte") { setAttendreNavigateur(false); return; }  // pas connecte dans le navigateur : connexion ici
      if (e.data.type !== "hexa-jexa-compte") return;
      const { jeton, pseudo, api, cle } = e.data;
      if (!/^[a-f0-9]{64}$/i.test(jeton || "") || !pseudo) return;
      if (cle) await VAULT.garder(pseudo, cle);
      if (!compte || compte.jeton !== jeton) adopter({ jeton, pseudo, api });
    };
    addEventListener("message", f);
    window.parent.postMessage({ type: "hexa-jexa-pret" }, "*");
    return () => removeEventListener("message", f);
  }, []);
  useEffect(() => {
    ecrireJson("jexa_app_theme", theme);
    if (theme === "nuit") document.documentElement.dataset.theme = "nexus"; else delete document.documentElement.dataset.theme;
    if (window.jexaBureau?.couleurs) window.jexaBureau.couleurs(theme === "nuit");
  }, [theme]);
  useEffect(() => {  // le serveur de Jexa verifie le jeton aupres d'Hexa (et donne le quota)
    if (!compte) { setSession(null); setVerif(false); return; }
    setVerif(true);
    fetch("/api/app/session", { method: "POST", body: JSON.stringify({ jeton: compte.jeton, api: compte.api }) })
      .then(async (r) => {
        if (r.status === 401) { if (INTEGRE) window.parent.postMessage({ type: "hexa-jexa-renouveler" }, "*"); else deconnecter(); return null; }
        return r.json();
      })
      .then((s) => s && setSession(s)).catch(() => {}).finally(() => setVerif(false));
  }, [compte?.jeton]);
  useEffect(() => { if (cle) { setDiscussions(lireJson(cle, [])); setCourante(null); } }, [cle]);
  useEffect(() => { if (cle) ecrireJson(cle, discussions.slice(0, 200).map((d) => ({ ...d, messages: d.messages.map(({ attente, ...m }) => m) }))); }, [discussions]);
  discRef.current = discussions;
  // la synchronisation avec Hexa Browser : on lit le Vault, on fusionne (le plus recent gagne), puis on renvoie le tout
  const synchroniser = async (envoyerAussi = true) => {
    if (!compte || !session) return;
    const k = await VAULT.lire(compte.pseudo);
    if (!k) { setSynchro("pause"); return; }
    setSynchro("en cours");
    try {
      const fils = await VAULT.lireKind(compte, k, "jexa");
      const locales = fusionner(lireJson(cle, []).map((d) => d), discRef.current.map(versFil));  // l'appareil + ce qui est a l'ecran
      const fusion = fusionner(locales, Array.isArray(fils) ? fils : []);
      discRef.current = fusion;
      setDiscussions(fusion);
      if (envoyerAussi) await VAULT.ecrireJexa(compte, k, fusion.filter((d) => d.messages.length).slice(0, 50).map(versFil));
      derniereSynchro.current = Date.now();
      setSynchro("ok");
    } catch { setSynchro("erreur"); }
  };
  useEffect(() => {  // a la connexion, puis toutes les minutes et quand on revient sur la fenetre
    if (!session) return;
    synchroniser();
    const t = setInterval(() => synchroniser(), 60000);
    const f = () => { if (Date.now() - derniereSynchro.current > 15000) synchroniser(); };
    addEventListener("focus", f);
    return () => { clearInterval(t); removeEventListener("focus", f); };
  }, [session?.pseudo]);
  useEffect(() => {  // apres une modification : envoi groupe, 3 s plus tard
    if (!session || attente) return;
    clearTimeout(envoiSynchro.current);
    envoiSynchro.current = setTimeout(() => synchroniser(), 3000);
    return () => clearTimeout(envoiSynchro.current);
  }, [discussions, attente]);
  useEffect(() => { zone.current && zone.current.scrollTo({ top: zone.current.scrollHeight, behavior: "smooth" }); });
  useEffect(() => {
    const f = (e) => {
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "n") { e.preventDefault(); setCourante(null); setTexte(""); }
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setBarre(true); setTimeout(() => chercheRef.current?.focus(), 50); }
      if ((e.ctrlKey || e.metaKey) && e.key.toLowerCase() === "b") { e.preventDefault(); setBarre((b) => !b); }
      if ((e.ctrlKey || e.metaKey) && e.key === ",") { e.preventDefault(); setFenetre("parametres"); }
    };
    addEventListener("keydown", f); return () => removeEventListener("keydown", f);
  }, []);
  useEffect(() => {  // la zone de saisie grandit avec le texte
    const c = champ.current; if (!c) return; c.style.height = "auto"; c.style.height = Math.min(c.scrollHeight, 240) + "px";
  }, [texte]);

  const connecterAvecVault = async (id, mdp, code) => {
    const r = await connecter(id, mdp, code);
    if (r.jeton && r.pseudo) VAULT.deriver(mdp, r.pseudo).then((k) => VAULT.garder(r.pseudo, k)).catch(() => {});
    return r;
  };
  const deconnecterTout = () => {
    if (INTEGRE) { window.parent.postMessage({ type: "hexa-jexa-deconnexion" }, "*"); return; }  // le compte est celui du navigateur
    if (compte) VAULT.oublier(compte.pseudo); deconnecter();
  };
  if (!compte && INTEGRE && attendreNavigateur) return (
    <div style={{ position: "fixed", inset: 0, display: "grid", placeItems: "center", background: "var(--creme)" }}>
      <style>{STYLE_APP}</style><div style={{ textAlign: "center" }}><JexaVivante taille={80} etat="reflechit" /><div style={{ color: "var(--doux)", marginTop: 14 }}>Connexion avec Hexa Browser…</div></div></div>);
  if (!compte) return <><style>{STYLE_APP}</style><ConnexionApp connecter={connecterAvecVault} connecterLien={connecterLien} /></>;
  if (!session) return (
    <div style={{ position: "fixed", inset: 0, display: "grid", placeItems: "center", background: "var(--creme)" }}>
      <style>{STYLE_APP}</style>
      <div style={{ textAlign: "center" }}><JexaVivante taille={80} etat="reflechit" />
        <div style={{ color: "var(--doux)", marginTop: 14 }}>{verif ? "Je vérifie ton compte Hexa…" : "Jexa est momentanément indisponible. Réessaie dans un instant."}</div>
        {!verif && <button className="btn relief" onClick={() => location.reload()} style={{ marginTop: 14, background: "var(--encre)", color: "var(--papier)" }}>Réessayer</button>}</div>
    </div>);

  const conv = discussions.find((d) => d.id === courante);
  const majMsg = (id, f) => setDiscussions((ds) => ds.map((x) => (x.id === id ? { ...x, messages: f(x.messages) } : x)));
  const nouvelle = () => { setCourante(null); setTexte(""); setTimeout(() => champ.current?.focus(), 50); };
  const heure = new Date().getHours();
  const salut = heure < 5 || heure >= 18 ? "Bonsoir" : "Bonjour";
  const prenom = souvenirs.find((s) => s.cle === "prenom")?.valeur || session.pseudo;

  const demarrer = async (t, mod) => {
    let d = conv;
    if (!d) {
      const monde = await fetch("/api/monde").then((r) => r.json()).catch(() => []);
      d = { id: Date.now().toString(36), titre: t.slice(0, 48), monde, messages: [], date: Date.now(), modele: mod };
    }
    return d;
  };

  const dessiner = async (t, d) => {
    const id = d.id;
    majMsg(id, (ms) => [...ms, { qui: "jexa", attente: true, dessin: true, avance: 0, texte: "" }]);
    const r = await fetch("/api/app/dessin", { method: "POST", body: JSON.stringify({ jeton: compte.jeton, texte: t }) });
    if (!r.ok) { const e = await r.json().catch(() => ({})); if (e.session) setSession(e.session);
      majMsg(id, (ms) => [...ms.slice(0, -1), { qui: "jexa", texte: e.erreur || "Je n'ai pas pu dessiner.", erreur: true }]); return; }
    const lecteur = r.body.getReader(), dec = new TextDecoder();
    let tampon = "";
    for (;;) {
      const { done, value } = await lecteur.read();
      if (done) break;
      tampon += dec.decode(value, { stream: true });
      const parts = tampon.split("\n\n"); tampon = parts.pop();
      for (const p of parts) {
        if (!p.startsWith("data: ")) continue;
        const x = JSON.parse(p.slice(6));
        if (x.session) setSession(x.session);
        majMsg(id, (ms) => { const m = { ...ms[ms.length - 1] };
          if (x.erreur) { m.texte = x.erreur; m.erreur = true; m.dessin = false; m.attente = false; }
          if (x.mots) m.mots = x.mots;
          if (x.format) m.format = x.format;
          if (x.avance != null) m.avance = x.avance;
          if (x.images) { m.images = x.images; m.essais = x.essais; m.sujet = t; }
          if (x.fini && !m.erreur) {
            m.attente = false;
            const f = m.format, agrandi = f && (f.largeur !== 16 || f.hauteur !== 16);
            m.texte = `Voilà mes ${m.images?.length || 0} meilleurs essais sur ${m.essais || 6}, en ${f ? f.largeur + "×" + f.hauteur : "16×16"} (${f ? f.pourquoi : "carré"}).`
              + (agrandi ? " Pour l'instant je dessine en 16×16 : je l'ai agrandi au format sans flou." : "") + " Clique sur l'image pour la voir en grand, la copier ou la télécharger.";
          }
          return [...ms.slice(0, -1), m]; });
      }
    }
    majMsg(id, (ms) => ms.map((m, i) => (i === ms.length - 1 ? { ...m, attente: false } : m)));
  };

  const banni = session?.ban && session.ban.jusqua * 1000 > Date.now() ? session.ban : null;
  const envoyer = async (t = texte, mod = modele) => {
    if (!t.trim() || attente || banni) return;
    if (mod !== "atelier" && DEMANDE_NOTES.test(t) && !conv?.fichier) {  // elle demande d'abord : jamais de lecture sans ton choix
      setTexte("");
      let d0 = await demarrer(t, mod);
      d0 = { ...d0, date: Date.now(), messages: [...d0.messages, { qui: "toi", texte: t }, { qui: "jexa", demandeNote: true,
        texte: "Je ne lis jamais tes notes sans ton accord. Choisis celle que je peux lire dans ton Hexa Vault, et je ne verrai que celle-là." }] };
      setDiscussions((ds) => [d0, ...ds.filter((x) => x.id !== d0.id)]); setCourante(d0.id);
      return;
    }
    setAttente(true); setTexte("");
    let d = await demarrer(t, mod);
    const historique = d.messages.filter((m) => !m.erreur && m.texte).map((m) => ({ qui: m.qui, texte: m.texte }));
    d = { ...d, date: Date.now(), messages: [...d.messages, { qui: "toi", texte: t }] };
    setDiscussions((ds) => [d, ...ds.filter((x) => x.id !== d.id)]);
    setCourante(d.id);
    try {
      if (mod === "atelier") { await dessiner(t, d); return; }
      majMsg(d.id, (ms) => [...ms, { qui: "jexa", attente: true }]);
      let fichier = d.fichier, page = null;
      if (COMPACT && avecPage && onglet) {  // la page ouverte devient le texte de reference
        page = await lirePageOuverte();
        if (page?.pdf) {  // un PDF : son texte page par page (pour sauter ensuite a la bonne page)
          const rp = await fetch("/api/app/pdf", { method: "POST", body: JSON.stringify({ jeton: compte.jeton, donnees: page.pdf }) }).then((x) => x.json()).catch(() => ({}));
          page = rp.pages ? { ...page, pdf: null, pages: rp.pages, texte: rp.pages.join("\n\n") } : null;
        }
        if (page) fichier = { nom: page.titre, texte: page.texte.slice(0, 60000) };
      }
      const r = await fetch("/api/app/parler", { method: "POST", body: JSON.stringify({ jeton: compte.jeton, texte: t, monde: d.monde, historique, souvenirs, fichier }) });
      const x = await r.json();
      if (page && x.passages?.length && !x.erreur) {  // le navigateur defile jusqu'au passage et le surligne
        if (page.pages) {  // PDF : le lecteur ne se laisse pas surligner, on saute a la page du passage
          const sans = (z) => z.toLowerCase().replace(/\s+/g, "");
          const cle = sans(x.passages[0]).slice(0, 40);
          const n = page.pages.findIndex((pg) => sans(pg).includes(cle));
          if (n >= 0) { x.pagePdf = n + 1; window.parent.postMessage({ type: "hexa-jexa-pdf-page", page: n + 1 }, "*"); }
        } else window.parent.postMessage({ type: "hexa-jexa-surligner", passages: x.passages }, "*");
        x.surligne = !page.pages || !!x.pagePdf;
      }
      if (x.session) setSession(x.session);
      if (x.ban) setSession((s0) => ({ ...(x.session || s0), ban: x.ban }));
      if (r.status === 401) { deconnecter(); return; }
      if (x.retenir?.length) x.retenir.forEach((s) => retenir(s.cle, s.valeur));
      majMsg(d.id, (ms) => [...ms.slice(0, -1), { qui: "jexa", texte: x.reponse || x.erreur, erreur: !!x.erreur, outil: page ? null : x.outil,
                                                    surligne: x.surligne, passages: x.surligne ? x.passages : null, page: page ? page.titre : null, pagePdf: x.pagePdf }]);
    } catch {
      majMsg(d.id, (ms) => [...ms.filter((m) => !m.attente), { qui: "jexa", texte: "Je n'arrive pas à réfléchir pour le moment. Réessaie dans un instant.", erreur: true }]);
    } finally { setAttente(false); setTimeout(() => champ.current?.focus(), 50); }
  };

  const joindre = async (f) => {
    if (!f || attente) return;
    setAttente(true);
    let d = await demarrer("Fichier : " + f.name, "nexus");
    d = { ...d, date: Date.now(), messages: [...d.messages, { qui: "toi", texte: "Fichier joint : " + f.name }] };
    setDiscussions((ds) => [d, ...ds.filter((x) => x.id !== d.id)]); setCourante(d.id);
    try {
      const b64 = await new Promise((ok, ko) => { const r = new FileReader(); r.onload = () => ok(String(r.result).split(",")[1]); r.onerror = ko; r.readAsDataURL(f); });
      const r = await (await fetch("/api/fichier", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify({ nom: f.name, donnees: b64 }) })).json();
      setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, fichier: r.texte ? { nom: f.name, texte: r.texte } : x.fichier,
        messages: [...x.messages, { qui: "jexa", texte: r.reponse || r.erreur, erreur: !!r.erreur }] } : x)));
    } catch { majMsg(d.id, (ms) => [...ms, { qui: "jexa", texte: "Je n'ai pas réussi à lire ce fichier.", erreur: true }]); }
    finally { setAttente(false); }
  };

  const montrerNote = async (n) => {  // la SEULE note que Jexa peut lire : celle que tu viens de choisir
    let d = conv || await demarrer("Note : " + n.titre, "nexus");
    d = { ...d, date: Date.now(), fichier: { nom: n.titre, texte: n.texte.slice(0, 60000) },
          messages: [...d.messages, { qui: "toi", texte: "Note du Hexa Vault : " + n.titre },
                     { qui: "jexa", texte: `J'ai ouvert ta note « ${n.titre} » (et seulement celle-là). Pose-moi une question dessus, ou demande-moi de la résumer.` }] };
    setDiscussions((ds) => [d, ...ds.filter((x) => x.id !== d.id)]); setCourante(d.id);
    setTimeout(() => champ.current?.focus(), 50);
  };

  const visibles = discussions.filter((d) => !recherche || (d.titre + " " + d.messages.map((m) => m.texte).join(" ")).toLowerCase().includes(recherche.toLowerCase()));
  const groupes = {};
  visibles.forEach((d) => { (groupes[groupeDate(d.date)] ||= []).push(d); });
  const reste = session.limite == null ? null : Math.max(0, session.limite - session.utilise);

  const saisie = (
    <div style={{ width: "100%", maxWidth: 780, margin: "0 auto" }}>
      {COMPACT && onglet && modele !== "atelier" && (
        <button onClick={() => setAvecPage(!avecPage)} title={avecPage ? "Jexa lit cette page pour te répondre (clic : ne plus la lire)" : "Clic : laisser Jexa lire cette page"}
                className="profond" style={{ display: "flex", alignItems: "center", gap: 8, maxWidth: "100%", margin: "0 0 8px", border: 0, borderRadius: 99, padding: "6px 12px",
                  fontSize: 12.5, background: avecPage ? "var(--tomate-c)" : "var(--surface)", color: avecPage ? "var(--tomate)" : "var(--doux)", transition: "background .25s, color .25s" }}>
          <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="M4 4h16v16H4zM4 9h16" /></svg>
          <span style={{ overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{avecPage ? "Je lis : " : "Page ignorée : "}{onglet.titre}</span>
        </button>)}
      <Incline force={2.5}>
        <div className={"bord-vivant profond" + (focus ? " focus" : "") + (attente ? " pense" : "")} style={{ background: "var(--surface)", padding: "14px 14px 10px 20px" }}>
          {banni && <div style={{ background: "var(--tomate-c)", color: "var(--tomate)", borderRadius: 14, padding: "10px 14px", marginBottom: 10, fontSize: 13.5, fontWeight: 600 }}>
            Jexa a mis fin à la conversation après des propos inacceptables. Tu pourras lui reparler le {new Date(banni.jusqua * 1000).toLocaleString("fr-FR", { day: "2-digit", month: "2-digit", hour: "2-digit", minute: "2-digit" })}.</div>}
          <textarea ref={champ} value={texte} rows={1} disabled={!!banni} onChange={(e) => setTexte(e.target.value)} onFocus={() => setFocus(true)} onBlur={() => setFocus(false)}
                    onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey && (envoiEntree || e.ctrlKey || e.metaKey)) { e.preventDefault(); envoyer(); } }}
                    placeholder={modele === "atelier" ? "Que veux-tu que je dessine ? (ex. une pomme, une épée en diamant…)" : "Écris à Jexa…"}
                    style={{ width: "100%", border: 0, outline: "none", resize: "none", background: "transparent", fontFamily: "inherit", fontSize: 16, lineHeight: 1.5, color: "var(--encre)", maxHeight: 240 }} />
          <div style={{ display: "flex", alignItems: "center", gap: 6, marginTop: 6 }}>
            <input ref={fichierRef} type="file" style={{ display: "none" }} onChange={(e) => { joindre(e.target.files[0]); e.target.value = ""; }} />
            <button className="app-mini" title="Joindre un fichier (PDF, Word, texte, image…)" onClick={() => fichierRef.current?.click()} style={{ padding: "6px 8px" }}><Ico n="trombone" t={18} /></button>
            <button className="app-mini" title="Montrer une note du Hexa Vault à Jexa" onClick={() => setFenetre("vault-choisir")} style={{ padding: "6px 8px", display: "flex", alignItems: "center", gap: 6, fontSize: 12.5 }}><Ico n="bouclier" t={17} /> Hexa Vault</button>
            <div style={{ flex: 1 }} />
            <ChoixModele modeles={session.modeles} modele={modele} setModele={setModele} />
            <button className="relief" onClick={() => envoyer()} disabled={!texte.trim() || attente} title="Envoyer (Entrée)"
                    style={{ width: 38, height: 38, borderRadius: 14, border: 0, display: "grid", placeItems: "center", fontSize: 18, fontWeight: 900,
                             background: texte.trim() && !attente ? "var(--tomate)" : "var(--creme-fonce)", color: texte.trim() && !attente ? "#fff" : "var(--doux)", transition: "background .2s" }}><Ico n="fleche" t={18} e={2.2} /></button>
          </div>
        </div>
      </Incline>
      <div style={{ textAlign: "center", fontSize: 11.5, color: "var(--doux)", marginTop: 8 }}>
        Jexa peut se tromper : vérifie ce qui compte.{reste != null && ` · ${reste} message${reste > 1 ? "s" : ""} restant${reste > 1 ? "s" : ""} aujourd'hui`}</div>
    </div>
  );

  return (
    <div className={"app-jexa" + (barre ? " ouvert-mobile" : " sans-barre")}>
      <style>{STYLE_APP}</style>
      {BUREAU && <div className="app-drag" style={{ position: "fixed", top: 0, left: 0, right: 0, height: 12, zIndex: 100 }} />}
      <aside className="app-cote">
        <div className={BUREAU ? "app-drag" : ""} style={{ display: "flex", alignItems: "center", gap: 12, padding: "20px 14px 16px 20px" }}>
          <JexaVivante taille={40} etat={attente ? "reflechit" : "repos"} />
          <span className="serif" style={{ fontSize: 28, fontWeight: 900, flex: 1 }}>Jexa</span>
          <button className="app-rond relief" data-force="3" title={theme === "nuit" ? "Thème de jour" : "Thème de nuit"} onClick={() => setTheme(theme === "nuit" ? "jour" : "nuit")}>
            <Ico n={theme === "nuit" ? "soleil" : "lune"} t={17} /></button>
          <button className="app-rond relief" data-force="3" title="Masquer la barre (Ctrl+B)" onClick={() => setBarre(false)}><Ico n="panneau" t={17} /></button>
        </div>
        <div style={{ padding: "4px 12px 8px", display: "flex", flexDirection: "column", gap: 8 }}>
          <button className="btn rebond relief" onClick={nouvelle} style={{ background: "var(--tomate)", color: "#fff", display: "flex", alignItems: "center", gap: 8, padding: "12px 18px", fontSize: 15,
                  boxShadow: "0 10px 20px -12px rgba(214,95,55,.9)" }}><Ico n="plus" t={17} e={2.4} /> Nouvelle discussion</button>
          <label className="profond" style={{ display: "flex", alignItems: "center", gap: 8, borderRadius: 14, padding: "8px 12px", background: "var(--surface)", color: "var(--doux)" }}>
            <Ico n="loupe" t={16} />
            <input ref={chercheRef} value={recherche} onChange={(e) => setRecherche(e.target.value)} placeholder="Rechercher (Ctrl+K)"
                   style={{ flex: 1, minWidth: 0, border: 0, fontFamily: "inherit", fontSize: 13.5, background: "transparent", color: "var(--encre)", outline: "none" }} /></label>
        </div>
        {synchro && <div style={{ fontSize: 11.5, color: synchro === "erreur" ? "var(--tomate)" : "var(--doux)", padding: "0 20px 6px", display: "flex", alignItems: "center", gap: 6 }}>
          <span style={{ width: 7, height: 7, borderRadius: 99, background: synchro === "ok" ? "var(--sarcelle)" : synchro === "erreur" ? "var(--tomate)" : "var(--moutarde, #e6b94a)" }} />
          {synchro === "ok" ? (INTEGRE ? "Synchronisé avec l'application Jexa" : "Synchronisé avec Hexa Browser") : synchro === "en cours" ? "Synchronisation…" :
           synchro === "pause" ? <span>Synchro en pause : <a href="#" onClick={(e) => { e.preventDefault(); setFenetre("vault"); }} style={{ color: "inherit" }}>ouvre ton Hexa Vault</a></span> : "Synchronisation impossible pour l'instant"}
        </div>}
        <div className="app-defile" style={{ flex: 1, overflowY: "auto", padding: "0 10px" }}>
          {!visibles.length && <div style={{ color: "var(--doux)", fontSize: 13, padding: "14px 6px" }}>{recherche ? "Rien trouvé." : "Tes discussions apparaîtront ici."}</div>}
          {["Aujourd'hui", "Hier", "Cette semaine", "Plus ancien"].filter((g) => groupes[g]).map((g) => (
            <div key={g} style={{ marginBottom: 10 }}>
              <div style={{ fontSize: 11, fontWeight: 800, letterSpacing: ".1em", textTransform: "uppercase", color: "var(--doux)", padding: "8px 12px 4px" }}>{g}</div>
              {groupes[g].map((d) => (
                <div key={d.id} className={"app-item" + (d.id === courante ? " actif" : "")} onClick={() => setCourante(d.id)} style={{ cursor: "pointer" }}>
                  {d.modele === "atelier" && <span style={{ color: "var(--doux)", display: "grid" }}><Ico n="pinceau" t={14} /></span>}
                  <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{d.titre}</span>
                  <span className="app-actions">
                    <button className="app-mini" title="Renommer" onClick={(e) => { e.stopPropagation(); const t = prompt("Nouveau nom", d.titre); if (t) setDiscussions((ds) => ds.map((x) => (x.id === d.id ? { ...x, titre: t.slice(0, 60) } : x))); }}><Ico n="crayon" t={14} /></button>
                    <button className="app-mini" title="Supprimer" onClick={(e) => { e.stopPropagation(); if (confirm("Supprimer cette discussion ?")) { setDiscussions((ds) => ds.filter((x) => x.id !== d.id)); if (courante === d.id) setCourante(null); } }}><Ico n="poubelle" t={14} /></button>
                  </span>
                </div>))}
            </div>))}
        </div>
        <CarteCompte session={session} deconnecter={deconnecterTout} ouvrir={setFenetre} />
      </aside>

      <main className="app-panneau">
        <FondProfond />
        <Lucioles agite={attente} />
        <Projecteur />
        <div className={BUREAU ? "app-drag" : ""} style={{ position: "relative", zIndex: 3, height: 52, flex: "none", display: "flex", alignItems: "center", gap: 8, padding: "0 10px 0 16px" }}>
          {!barre && <button className="app-rond relief" data-force="3" title="Afficher la barre (Ctrl+B)" onClick={() => setBarre(true)}><Ico n="panneau" t={17} /></button>}
          {!barre && <button className="app-rond relief" data-force="3" title="Nouvelle discussion (Ctrl+N)" onClick={nouvelle}><Ico n="plus" t={17} e={2.2} /></button>}
          <div style={{ flex: 1, fontWeight: 700, fontSize: 14.5, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", color: conv ? "var(--encre)" : "var(--doux)", paddingLeft: 4 }}>{conv ? conv.titre : ""}</div>
          {!COMPACT && <ChoixMode ouvrirProjet={() => setFenetre("projet")} />}
          <div style={{ flex: 1 }} />
          <BoutonsFenetre />
        </div>
        {!conv ? (
          <div style={{ flex: 1, position: "relative", zIndex: 2, display: "flex", flexDirection: "column", justifyContent: "center", padding: "0 22px 60px" }}>
            <div style={{ position: "relative", textAlign: "center", marginBottom: 26 }}>
              <Incline force={16} style={{ display: "inline-block" }}><JexaVivante taille={COMPACT ? 76 : 110} etat={attente ? "reflechit" : texte ? "ecoute" : "repos"} /></Incline>
              <h1 className="serif" style={{ fontSize: "clamp(30px, 4vw, 44px)", fontWeight: 900, marginTop: 14, animation: "monte .6s var(--ease) both" }}>{salut}, {prenom}</h1>
              <div style={{ color: "var(--doux)", marginTop: 6, animation: "monte .6s .1s var(--ease) both" }}>Qu'est-ce qu'on fait aujourd'hui ?</div>
            </div>
            <div style={{ position: "relative" }}>{saisie}</div>
            <div style={{ position: "relative", display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(170px, 1fr))", gap: 10, maxWidth: 780, width: "100%", margin: "18px auto 0" }}>
              {(COMPACT && onglet ? IDEES_PAGE : IDEES_APP).map((x, i) => (
                <Incline key={x.label} force={10}>
                  <button className="relief" onClick={() => { const m = x.modele || "nexus"; setModele(m); envoyer(x.texte, m); }}
                          style={{ width: "100%", border: 0, background: "var(--surface)", borderRadius: 18, padding: "14px 14px", textAlign: "left", color: "var(--encre)", fontSize: 13.5,
                                   animation: `monte .5s ${0.15 + i * 0.06}s var(--ease) both` }}>
                    <div style={{ width: 34, height: 34, borderRadius: 11, display: "grid", placeItems: "center", marginBottom: 10, color: x.couleur,
                                  background: `color-mix(in srgb, ${x.couleur} 14%, transparent)`, boxShadow: "inset 0 1px 0 rgba(255,255,255,.6)" }}><Ico n={x.icone} t={18} /></div>{x.label}</button>
                </Incline>))}
            </div>
          </div>
        ) : (<>
          <div ref={zone} className="app-defile" style={{ position: "relative", zIndex: 2, flex: 1, overflowY: "auto", padding: "10px 22px 20px" }}>
            <div style={{ maxWidth: 780, margin: "0 auto", display: "flex", flexDirection: "column", gap: 22 }}>
              {conv.messages.map((m, i) => m.qui === "toi"
                ? <div key={i} style={{ display: "flex", justifyContent: "flex-end" }}><div className="app-bulle-toi">{m.texte}</div></div>
                : <MessageJexa key={i} m={m} ouvrirVault={() => setFenetre("vault-choisir")} />)}
            </div>
          </div>
          <div style={{ position: "relative", zIndex: 2, flex: "none", padding: "6px 22px 16px" }}>{saisie}</div>
        </>)}
      </main>
      <FenetresApp quoi={fenetre} fermer={() => setFenetre(null)} compte={compte} choisirNote={montrerNote} session={session} theme={theme} setTheme={setTheme} modele={modele} setModele={setModele}
                   envoiEntree={envoiEntree} setEnvoiEntree={setEnvoiEntree} effacerTout={() => { setDiscussions([]); setCourante(null); }}
                   souvenirs={souvenirs} oublier={oublier} nbDiscussions={discussions.length} />
    </div>
  );
}

function JexaDort({ taille = 190 }) {
  return (
    <div style={{ position: "relative", width: taille, height: taille * 1.25 }}>
      {[["Z", 0, 34], ["z", 1.3, 24], ["Z", 2.6, 30]].map(([l, d, t], i) => (
        <span key={i} className="serif" style={{ position: "absolute", left: "62%", top: "18%", fontWeight: 900, fontSize: t, color: "#d8ccff",
                                                  textShadow: "0 0 18px rgba(139,108,255,.7)", opacity: 0, animation: `zzz 3.9s ${d}s ease-in-out infinite` }}>{l}</span>))}
      <svg viewBox="0 0 200 200" width={taille} height={taille} style={{ position: "absolute", bottom: 0, left: 0, animation: "dort 3.9s ease-in-out infinite", transformOrigin: "50% 90%",
                                                                         filter: "drop-shadow(0 30px 40px rgba(0,0,0,.55))" }}>
        <defs>
          <radialGradient id="dort-corps" cx="38%" cy="30%" r="75%">
            <stop offset="0" stopColor="#f6a07a" /><stop offset=".45" stopColor="#e9714a" /><stop offset=".85" stopColor="#bb4a27" /><stop offset="1" stopColor="#8f3318" />
          </radialGradient>
          <radialGradient id="dort-reflet" cx="50%" cy="50%" r="50%"><stop offset="0" stopColor="#fff" stopOpacity=".55" /><stop offset="1" stopColor="#fff" stopOpacity="0" /></radialGradient>
          <radialGradient id="dort-joue" cx="50%" cy="50%" r="50%"><stop offset="0" stopColor="#ffb3a0" stopOpacity=".55" /><stop offset="1" stopColor="#ffb3a0" stopOpacity="0" /></radialGradient>
        </defs>
        <circle cx="100" cy="100" r="90" fill="url(#dort-corps)" />
        <ellipse cx="78" cy="48" rx="34" ry="20" fill="url(#dort-reflet)" />
        <path d="M70 96 Q80 106 90 96" stroke="#fff6ea" strokeWidth="7" strokeLinecap="round" fill="none" />
        <path d="M110 96 Q120 106 130 96" stroke="#fff6ea" strokeWidth="7" strokeLinecap="round" fill="none" />
        <ellipse cx="58" cy="128" rx="16" ry="9" fill="url(#dort-joue)" />
        <ellipse cx="142" cy="128" rx="16" ry="9" fill="url(#dort-joue)" />
      </svg>
    </div>
  );
}

function EcranDort() {
  const b = window.jexaBureau;
  const bouton = { width: 34, height: 28, border: 0, borderRadius: 8, background: "transparent", color: "#cfc8e8", fontSize: 15, WebkitAppRegion: "no-drag" };
  return (
    <div style={{ position: "fixed", inset: 0, zIndex: 9999, display: "grid", placeItems: "center", overflow: "hidden", WebkitAppRegion: "drag",
                  background: "radial-gradient(ellipse at 50% 35%, #231c3d 0%, #0f0e16 65%)", color: "#efeaff", animation: "monte .6s var(--ease) both" }}>
      <style>{`@keyframes zzz { 0% { opacity: 0; transform: translate(0, 10px) scale(.6) rotate(-8deg); } 25% { opacity: 1; } 80% { opacity: .9; }
               100% { opacity: 0; transform: translate(46px, -90px) scale(1.15) rotate(12deg); } }
               @keyframes dort { 0%, 100% { transform: scale(1, 1); } 50% { transform: scale(1.04, .97); } }
               @keyframes etoile { 0%, 100% { opacity: .15; } 50% { opacity: .8; } }`}</style>
      {Array.from({ length: 40 }, (_, i) => (
        <span key={i} style={{ position: "absolute", left: `${(i * 37) % 100}%`, top: `${(i * 53) % 100}%`, width: 2 + (i % 3), height: 2 + (i % 3), borderRadius: 9,
                               background: "#cfc4ff", animation: `etoile ${3 + (i % 5)}s ${(i % 7) * 0.4}s ease-in-out infinite` }} />))}
      {b && <div style={{ position: "absolute", top: 8, right: 10, display: "flex", gap: 4 }}>
        <button style={bouton} onClick={b.reduire} aria-label="Réduire">–</button>
        <button style={bouton} onClick={b.fermer} aria-label="Fermer">✕</button>
      </div>}
      <div style={{ display: "flex", flexDirection: "column", alignItems: "center", gap: 20, textAlign: "center", padding: 16 }}>
        <JexaDort />
        <h1 className="serif" style={{ fontSize: "clamp(28px, 5vw, 42px)", fontWeight: 900 }}>Jexa est indisponible</h1>
        <p style={{ margin: 0, maxWidth: 420, color: "#b9b1d6", lineHeight: 1.6 }}>Jexa n'est pas joignable pour le moment. Cette page se rouvrira automatiquement dès qu'elle sera de nouveau disponible.</p>
      </div>
    </div>
  );
}

function Veille({ children }) {
  const [dort, setDort] = useState(false);
  useEffect(() => {
    let rates = 0, arret = false, minuteur;
    const verifier = async () => {
      let ok = false;
      try {
        const r = await fetch("/api/principal", { cache: "no-store" });
        ok = r.ok;
      } catch {}
      if (arret) return;
      rates = ok ? 0 : rates + 1;
      setDort(rates >= 2 || (!ok && rates >= 1 && !document.body.dataset.vu));
      if (ok) document.body.dataset.vu = "1";
      minuteur = setTimeout(verifier, ok ? 15000 : 5000);
    };
    verifier();
    return () => { arret = true; clearTimeout(minuteur); };
  }, []);
  useEffect(() => {
    if (!dort) return;
    const avant = document.documentElement.dataset.theme;
    document.documentElement.dataset.theme = "nexus";
    window.jexaBureau?.couleurs?.(true);
    return () => {
      if (avant) document.documentElement.dataset.theme = avant; else delete document.documentElement.dataset.theme;
      window.jexaBureau?.couleurs?.(avant === "nexus");
    };
  }, [dort]);
  return <>{children}{dort && <EcranDort />}</>;
}

const PAGES = { "/app": AppJexa, "/atelier": Atelier, "/coeur": Coeur, "/": Discuter, "/discuter": Discuter, "/cerveau": App, "/vitrine": Vitrine, "/affiche": AfficheNuit, "/film": Film };
const Page = PAGES[location.pathname.replace(/\/+$/, "") || "/"] || Discuter;
ReactDOM.createRoot(document.getElementById("root")).render(<Veille><Page /></Veille>);
