/* GUIDKO App — Élève (Student) screens. Interactive: booking, playable code quiz, messages. */

function EleveApp({ section, navigate }) {
  switch (section) {
    case "overview": return <EleveOverview navigate={navigate}/>;
    case "book": return <EleveBook navigate={navigate}/>;
    case "code": return <CodeQuiz/>;
    case "vehicles": return <AutoModule role="eleve" navigate={navigate}/>;
    case "messages": return <EleveMessages/>;
    case "profile": return <EleveProfile/>;
    default: return <EleveOverview navigate={navigate}/>;
  }
}

function me(store) { return studentById(store.state, "s1"); }

function EleveOverview({ navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const s = me(store);
  const myLessons = store.state.lessons.filter(l => l.studentId === "s1").sort((a,b) => a.day - b.day || a.hour - b.hour);
  const next = myLessons.find(l => l.status !== "done") || myLessons[0];
  const m = next && instructorById(store.state, next.instructorId);

  return (
    <>
      <Topbar subtitle={t("LÉA MERCIER · 23 ANS","LÉA MERCIER · AGE 23")} title={t("Tu y es presque, Léa.","Almost there, Léa.")}
        actions={<Button kind="flame" onClick={() => navigate("/eleve/book")}>+ {t("Réserver un cours","Book a lesson")}</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "1.4fr 1fr", gap: 14 }}>
          <Card dark style={{ padding: 28 }}>
            <Label color="#7A82A8" style={{ marginBottom: 8 }}>{t("MA PROGRESSION","MY PROGRESS")}</Label>
            <div style={{ display: "flex", alignItems: "flex-end", gap: 24 }}>
              <div style={{ flex: 1 }}>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 80, lineHeight: 0.95, letterSpacing: "-0.02em" }}>{s.progress}<span style={{ fontSize: 36, color: C.flame }}>%</span></div>
                <div style={{ fontSize: 14, color: "#C9CEE3", marginTop: 8 }}>{t("Tu es prête pour l'examen blanc.","Ready for the mock exam.")}</div>
              </div>
              <div style={{ position: "relative", width: 130, height: 130 }}>
                <Donut segments={[{v:s.progress,c:C.flame},{v:100-s.progress,c:"#1F2542"}]} size={130} thickness={16} track="#1F2542"/>
                <div style={{ position: "absolute", inset: 0, display: "grid", placeItems: "center", fontFamily: "'Geist Mono', monospace", fontSize: 10, color: "#9098B5" }}>{t("PRÊT","READY")}</div>
              </div>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 8, marginTop: 24 }}>
              {[[t("Code","Code"),"✓",true,false],[t("Conduite","Drive"),`${s.hours}/${s.hoursTotal}h`,false,true],[t("Examen blanc","Mock"),"—",false,false],[t("Permis","License"),"—",false,false]].map(([n,d,ok,active],i) => (
                <div key={i} style={{ padding: 14, background: "#1F2542", borderRadius: 8, border: active ? `1px solid ${C.flame}` : "1px solid transparent" }}>
                  <div style={{ display: "flex", justifyContent: "space-between", marginBottom: 8 }}>
                    <span style={{ width: 20, height: 20, borderRadius: 10, background: ok ? C.signal : active ? C.flame : "#3A4068", display: "grid", placeItems: "center", fontSize: 11, color: "#fff" }}>{ok ? "✓" : i+1}</span>
                    {active && <Pill tone="flame">{t("EN COURS","NOW")}</Pill>}
                  </div>
                  <div style={{ fontSize: 13, fontWeight: 600, color: "#fff" }}>{n}</div>
                  <div style={{ fontSize: 11, color: "#9098B5", fontFamily: "'Geist Mono', monospace", marginTop: 2 }}>{d}</div>
                </div>
              ))}
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <Label color={C.flame} style={{ marginBottom: 4 }}>{t("PROCHAIN COURS","NEXT LESSON")}</Label>
            {next ? (
              <>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 44, lineHeight: 1, marginTop: 4 }}>{(GK_lang() === "fr" ? DAYS_FR : DAYS_EN)[next.day]} {DATES[next.day]}</div>
                <div style={{ fontSize: 14, color: C.slate, marginTop: 4 }}>{String(next.hour).padStart(2,"0")}:00 — {String(next.hour+1).padStart(2,"0")}:00 · {store.state.types[next.type].l}</div>
                <div style={{ display: "flex", gap: 12, alignItems: "center", padding: 14, background: "#FBF8EE", borderRadius: 10, border: `1px solid ${C.softLine}`, marginTop: 18 }}>
                  <Avatar name={m.name} size={42} tone={m.tone}/>
                  <div style={{ flex: 1 }}><div style={{ fontSize: 14, fontWeight: 600 }}>{m.name}</div><div style={{ fontSize: 12, color: C.slate }}>{t("Ton moniteur","Your instructor")}</div></div>
                </div>
                <div style={{ display: "flex", gap: 8, marginTop: 16 }}>
                  <Button kind="primary" full onClick={() => navigate("/eleve/messages")}>{t("Contacter","Message")}</Button>
                  <Button kind="ghost" onClick={() => navigate("/eleve/book")}>{t("Décaler","Reschedule")}</Button>
                </div>
              </>
            ) : <div style={{ padding: 30, textAlign: "center", color: C.slate }}>{t("Aucun cours prévu.","No lesson booked.")}</div>}
          </Card>
        </div>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14, marginTop: 14 }}>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 8 }}>{t("HEURES DE CONDUITE","DRIVING HOURS")}</Label>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}><span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 46, lineHeight: 1 }}>{s.hours}</span><span style={{ fontSize: 16, color: C.slate }}>/ {s.hoursTotal}h</span></div>
            <div style={{ marginTop: 14 }}><Bar pct={s.hours/s.hoursTotal*100}/></div>
          </Card>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 8 }}>{t("ENTRAÎNEMENT CODE","CODE PRACTICE")}</Label>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}><span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 46, lineHeight: 1 }}>{s.code}</span><span style={{ fontSize: 16, color: C.slate }}>/ 40</span></div>
            <div style={{ marginTop: 14, display: "grid", gridTemplateColumns: "repeat(10,1fr)", gap: 3 }}>
              {Array.from({length:40}).map((_,i) => <div key={i} style={{ height: 14, background: i < s.code ? C.signal : "#F0EBDC", borderRadius: 2 }}/>)}
            </div>
          </Card>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 8 }}>{t("SOLDE","BALANCE")}</Label>
            <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 46, lineHeight: 1 }}>{s.balance} €</div>
            <div style={{ fontSize: 12, color: C.slate, marginTop: 4 }}>{t("2/4 mensualités","2/4 installments")}</div>
            <Button kind="primary" size="sm" full style={{ marginTop: 14 }} onClick={() => navigate("/eleve/profile")}>{t("Payer maintenant","Pay now")}</Button>
          </Card>
        </div>
        {/* Cross-service: après le cours → covoiturage ou livraison */}
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 14, marginTop: 14 }}>
          <Card style={{ padding: 18, background: "#FBF8EE", display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}><span style={{ fontSize: 22 }}>⇅</span><div style={{ fontWeight: 600, fontSize: 14 }}>{t("Après ton cours : covoiturage","After your lesson: carpool")}</div></div>
            <div style={{ fontSize: 12.5, color: C.slate, lineHeight: 1.5 }}>{t("Ton moniteur rentre aussi ? Partage le trajet retour.","Your instructor heading home too? Share the ride back.")}</div>
            <Button size="sm" kind="ink" onClick={() => navigate("/covoit/overview")}>{t("Voir les trajets","See rides")} →</Button>
          </Card>
          <Card style={{ padding: 18, display: "flex", flexDirection: "column", gap: 10 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 10 }}><span style={{ fontSize: 22 }}>🚴</span><div style={{ fontWeight: 600, fontSize: 14 }}>{t("Gagne de l'argent entre tes cours","Earn between lessons")}</div></div>
            <div style={{ fontSize: 12.5, color: C.slate, lineHeight: 1.5 }}>{t("Livre des repas ou colis avec ton vélo ou ta voiture.","Deliver food or packages with your bike or car.")}</div>
            <Button size="sm" kind="ghost" onClick={() => navigate("/livraison/overview")}>{t("GUIDKO Livraison","GUIDKO Delivery")} →</Button>
          </Card>
        </div>
      </PageBody>
    </>
  );
}

function GK_lang() { return window.__guidkoLang || "fr"; }
function EleveBook({ navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const days = lang === "fr" ? DAYS_FR : DAYS_EN;
  const [type, setType] = React.useState("broute");
  const [day, setDay] = React.useState(2);
  const [hour, setHour] = React.useState(null);

  const taken = (d, h) => store.state.lessons.some(l => l.day === d && l.hour === h);

  async function confirm() {
    const now = new Date();
    const target = new Date(now);
    target.setDate(now.getDate() + day + 1);
    target.setHours(hour, 0, 0, 0);

    try {
      if (window.GuidkoAPI && window.GuidkoAPI.lessons && typeof window.GuidkoAPI.lessons.book === "function") {
        await window.GuidkoAPI.lessons.book({
          schoolId: "guidko-school-demo",
          instructorId: "m1",
          type,
          duration: 60,
          scheduledAt: target.toISOString(),
          price: 50,
        });
      }
    } catch (e) {}

    store.addLesson({ day, hour, studentId: "s1", instructorId: "m1", type });
    toast.push(t("Cours réservé ! Marc a été notifié.","Lesson booked! Marc was notified."), "signal");
    navigate("/eleve/overview");
  }

  return (
    <>
      <Topbar subtitle={t("RÉSERVATION","BOOKING")} title={t("Réserver un cours","Book a lesson")} search={false}/>
      <PageBody>
        <div style={{ maxWidth: 720 }}>
          <Label style={{ marginBottom: 10 }}>{t("1 · TYPE DE COURS","1 · LESSON TYPE")}</Label>
          <div style={{ display: "flex", gap: 8, marginBottom: 24, flexWrap: "wrap" }}>
            {Object.entries(store.state.types).map(([k, ty]) => {
              const on = type === k;
              return <span key={k} onClick={() => setType(k)} style={{ padding: "10px 16px", borderRadius: 999, fontSize: 14, cursor: "pointer", background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, border: `1px solid ${on ? C.ink : C.softLine}`, fontWeight: 600, display: "inline-flex", alignItems: "center", gap: 8 }}><span style={{ width: 9, height: 9, background: ty.color, borderRadius: 999 }}/>{ty.l}</span>;
            })}
          </div>

          <Label style={{ marginBottom: 10 }}>{t("2 · JOUR","2 · DAY")}</Label>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(6, 1fr)", gap: 8, marginBottom: 24 }}>
            {days.map((d, i) => (
              <div key={i} onClick={() => { setDay(i); setHour(null); }} style={{ padding: "14px 0", textAlign: "center", borderRadius: 10, cursor: "pointer", background: day === i ? C.flame : "#fff", color: day === i ? "#fff" : C.ink, border: `1px solid ${day === i ? C.flame : C.softLine}` }}>
                <Label color={day === i ? "#fff" : C.slate} style={{ fontSize: 9, opacity: 0.8 }}>{d}</Label>
                <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, lineHeight: 1, marginTop: 2 }}>{DATES[i]}</div>
              </div>
            ))}
          </div>

          <Label style={{ marginBottom: 10 }}>{t("3 · CRÉNEAU","3 · TIME SLOT")}</Label>
          <div style={{ display: "grid", gridTemplateColumns: "repeat(5, 1fr)", gap: 8 }}>
            {HOURS.filter(h => h !== 12).map(h => {
              const isTaken = taken(day, h);
              const on = hour === h;
              return <div key={h} onClick={() => !isTaken && setHour(h)} style={{ padding: "12px 0", textAlign: "center", borderRadius: 9, fontSize: 14, fontWeight: 600, cursor: isTaken ? "not-allowed" : "pointer", background: on ? C.ink : isTaken ? "#F0EBDC" : "#fff", color: on ? "#fff" : isTaken ? C.slate : C.ink, border: `1px solid ${on ? C.ink : C.softLine}`, opacity: isTaken ? 0.45 : 1, textDecoration: isTaken ? "line-through" : "none" }}>{String(h).padStart(2,"0")}:00</div>;
            })}
          </div>

          {hour !== null && (
            <Card style={{ padding: 18, marginTop: 24, display: "flex", alignItems: "center", justifyContent: "space-between", background: C.ink, borderColor: C.ink }}>
              <div>
                <Label color="#7A82A8" style={{ fontSize: 9 }}>{days[day]} {DATES[day]} · {String(hour).padStart(2,"0")}:00</Label>
                <div style={{ fontSize: 16, fontWeight: 600, color: "#fff", marginTop: 2 }}>{store.state.types[type].l} · Marc Lefèvre</div>
              </div>
              <Button kind="flame" onClick={confirm}>{t("Confirmer la réservation","Confirm booking")} →</Button>
            </Card>
          )}
        </div>
      </PageBody>
    </>
  );
}

// ---------- CODE QUIZ (playable) ----------
const QUIZ = [
  { q: { fr: "À cette intersection sans signalisation, qui a la priorité ?", en: "At this unmarked intersection, who has right of way?" }, opts: { fr: ["Le véhicule venant de droite","Le véhicule le plus rapide","Moi, je continue","Le véhicule de gauche"], en: ["Vehicle coming from the right","The fastest vehicle","Me, I continue","Vehicle from the left"] }, a: 0 },
  { q: { fr: "Quelle est la distance de sécurité sur autoroute à 130 km/h ?", en: "Safe following distance on highway at 130 km/h?" }, opts: { fr: ["Environ 2 secondes","Environ 1 seconde","50 mètres","Environ 5 secondes"], en: ["About 2 seconds","About 1 second","50 meters","About 5 seconds"] }, a: 0 },
  { q: { fr: "Un feu orange clignotant signifie :", en: "A flashing amber light means:" }, opts: { fr: ["Ralentir et passer avec prudence","Arrêt obligatoire","Accélérer","Stationnement autorisé"], en: ["Slow down, proceed with caution","Mandatory stop","Speed up","Parking allowed"] }, a: 0 },
  { q: { fr: "En ville, la vitesse maximale par défaut est :", en: "Default max speed in a city is:" }, opts: { fr: ["50 km/h","30 km/h","70 km/h","90 km/h"], en: ["50 km/h","30 km/h","70 km/h","90 km/h"] }, a: 0 },
  { q: { fr: "Le taux d'alcoolémie légal pour un jeune permis est :", en: "Legal blood alcohol limit for a new driver is:" }, opts: { fr: ["0,2 g/L","0,5 g/L","0,8 g/L","0 g/L"], en: ["0.2 g/L","0.5 g/L","0.8 g/L","0 g/L"] }, a: 0 },
];

function CodeQuiz() {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [i, setI] = React.useState(0);
  const [sel, setSel] = React.useState(null);
  const [checked, setChecked] = React.useState(false);
  const [score, setScore] = React.useState(0);
  const [done, setDone] = React.useState(false);
  const [exp, setExp] = React.useState(null);
  const [expBusy, setExpBusy] = React.useState(false);

  const item = QUIZ[i];

  function validate() {
    if (sel === null) return;
    setChecked(true);
    if (sel === item.a) setScore(s => s + 1);
  }
  function next() {
    setExp(null);
    if (i + 1 >= QUIZ.length) { setDone(true); return; }
    setI(i + 1); setSel(null); setChecked(false);
  }
  function restart() { setI(0); setSel(null); setChecked(false); setScore(0); setDone(false); setExp(null); }

  async function askLia() {
    if (expBusy) return;
    setExpBusy(true);
    const correct = item.opts[lang][item.a];
    const prompt = `Tu es Lia, monitrice d'auto-école. Explique en ${lang === "fr" ? "français" : "anglais"}, en 2-3 phrases simples et pédagogiques, pourquoi la bonne réponse à cette question de code de la route est « ${correct} ». Question : « ${item.q[lang]} ».`;
    const fb = lang === "fr" ? "La bonne réponse est « " + correct + " ». Retiens la règle et applique-la à chaque situation similaire." : "The correct answer is “" + correct + "”. Remember the rule and apply it to similar situations.";
    const ans = await liaComplete(prompt, fb);
    setExp(ans); setExpBusy(false);
  }

  if (done) {
    const pct = Math.round(score / QUIZ.length * 100);
    const pass = pct >= 60;
    return (
      <>
        <Topbar subtitle={t("ENTRAÎNEMENT CODE","CODE PRACTICE")} title={t("Résultat","Result")} search={false}/>
        <PageBody>
          <div style={{ maxWidth: 480, margin: "40px auto", textAlign: "center" }}>
            <Donut segments={[{v:score,c:pass?C.signal:C.flame},{v:QUIZ.length-score,c:"#F0EBDC"}]} size={180} thickness={22}/>
            <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 64, lineHeight: 1, marginTop: -120, marginBottom: 80 }}>{score}<span style={{ fontSize: 28, color: C.slate }}>/{QUIZ.length}</span></div>
            <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 36, fontWeight: 400, margin: "0 0 8px" }}>{pass ? t("Bravo, Léa !","Well done, Léa!") : t("Encore un effort.","Almost there.")}</h2>
            <p style={{ fontSize: 15, color: C.slate, marginBottom: 24 }}>{pass ? t("Tu es au-dessus du seuil de réussite (60%).","You're above the 60% pass threshold.") : t("Il te faut 60% pour valider. Réessaie !","You need 60% to pass. Try again!")}</p>
            <Button kind="flame" size="lg" onClick={restart}>{t("Recommencer","Try again")} ↻</Button>
          </div>
        </PageBody>
      </>
    );
  }

  return (
    <>
      <Topbar subtitle={t("ENTRAÎNEMENT CODE","CODE PRACTICE")} title={t("Série de code","Code series")} search={false}
        actions={<Pill tone="flame">{i+1} / {QUIZ.length}</Pill>}/>
      <PageBody>
        <div style={{ maxWidth: 680, margin: "0 auto" }}>
          <Bar pct={(i)/QUIZ.length*100} h={5}/>
          <div style={{ marginTop: 24 }}>
            <CarImg width="100%" height={200} label={t("Situation routière","Road situation")}/>
          </div>
          <h2 style={{ fontFamily: "'Instrument Serif', serif", fontSize: 30, fontWeight: 400, lineHeight: 1.15, margin: "22px 0 18px", letterSpacing: "-0.01em" }}>{item.q[lang]}</h2>
          <div style={{ display: "flex", flexDirection: "column", gap: 10 }}>
            {item.opts[lang].map((opt, oi) => {
              const isSel = sel === oi;
              const isCorrect = oi === item.a;
              let bg = "#fff", bd = C.softLine, badge = String.fromCharCode(65 + oi), badgeBg = "#fff", badgeFg = C.slate;
              if (checked) {
                if (isCorrect) { bg = "#0FB76B11"; bd = C.signal; badgeBg = C.signal; badgeFg = "#fff"; }
                else if (isSel) { bg = "#E11D4811"; bd = C.danger; badgeBg = C.danger; badgeFg = "#fff"; }
              } else if (isSel) { bg = "#FF5A1F0D"; bd = C.flame; badgeBg = C.flame; badgeFg = "#fff"; }
              return (
                <div key={oi} onClick={() => !checked && setSel(oi)} style={{ padding: "14px 16px", borderRadius: 11, display: "flex", alignItems: "center", gap: 12, background: bg, border: `1.5px solid ${bd}`, cursor: checked ? "default" : "pointer" }}>
                  <span style={{ width: 26, height: 26, borderRadius: 13, background: badgeBg, color: badgeFg, display: "grid", placeItems: "center", fontSize: 12, fontWeight: 700, fontFamily: "'Geist Mono', monospace", border: badgeBg === "#fff" ? `1.5px solid ${C.softLine}` : "none" }}>{badge}</span>
                  <span style={{ fontSize: 14, fontWeight: 500, flex: 1 }}>{opt}</span>
                  {checked && isCorrect && <span style={{ color: C.signal }}>✓</span>}
                  {checked && isSel && !isCorrect && <span style={{ color: C.danger }}>✗</span>}
                </div>
              );
            })}
          </div>
          {checked && (
            <div style={{ marginTop: 16, padding: 16, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 12 }}>
              <div style={{ display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                  <span style={{ width: 24, height: 24, borderRadius: 7, background: C.ink, color: C.flame, display: "grid", placeItems: "center", fontSize: 12 }}>✦</span>
                  <span style={{ fontSize: 13, fontWeight: 600 }}>{t("Lia, ta monitrice IA","Lia, your AI instructor")}</span>
                </div>
                {!exp && <Button kind="light" size="sm" onClick={askLia} style={{ opacity: expBusy ? 0.5 : 1 }}>{expBusy ? t("Lia réfléchit…","Lia thinking…") : t("Explique-moi pourquoi","Explain why")}</Button>}
              </div>
              {exp && <div style={{ fontSize: 13.5, lineHeight: 1.5, color: C.ink, marginTop: 10, whiteSpace: "pre-wrap" }}>{exp}</div>}
            </div>
          )}
          <div style={{ display: "flex", justifyContent: "flex-end", marginTop: 16 }}>
            {!checked ? <Button kind="primary" size="lg" onClick={validate} style={{ opacity: sel === null ? 0.5 : 1 }}>{t("Valider","Check")} →</Button>
              : <Button kind="flame" size="lg" onClick={next}>{i+1 >= QUIZ.length ? t("Voir le résultat","See result") : t("Question suivante","Next question")} →</Button>}
          </div>
        </div>
      </PageBody>
    </>
  );
}

// ---------- MESSAGES ----------
function EleveMessages() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const [text, setText] = React.useState("");
  const msgs = store.state.messages.filter(m => (m.from === "s1" && m.to === "m1") || (m.from === "m1" && m.to === "s1"));
  const endRef = React.useRef(null);
  React.useEffect(() => { endRef.current?.scrollTo(0, endRef.current.scrollHeight); }, [msgs.length]);

  function send() {
    if (!text.trim()) return;
    store.sendMessage("s1", "m1", text.trim());
    setText("");
  }

  return (
    <>
      <Topbar subtitle={t("MESSAGERIE","MESSAGING")} title="Marc Lefèvre" search={false}
        actions={<Pill tone="signal">{t("En ligne","Online")}</Pill>}/>
      <div style={{ flex: 1, display: "flex", flexDirection: "column", overflow: "hidden", background: C.paper }}>
        <div ref={endRef} className="gk-scroll" style={{ flex: 1, overflowY: "auto", padding: 26, display: "flex", flexDirection: "column", gap: 10 }}>
          {msgs.map(m => {
            const mine = m.from === "s1";
            return (
              <div key={m.id} style={{ alignSelf: mine ? "flex-end" : "flex-start", maxWidth: "60%" }}>
                <div style={{ padding: "11px 14px", background: mine ? C.ink : "#fff", color: mine ? "#fff" : C.ink, borderRadius: 14, borderTopRightRadius: mine ? 4 : 14, borderTopLeftRadius: mine ? 14 : 4, fontSize: 14, lineHeight: 1.45, border: mine ? "none" : `1px solid ${C.softLine}` }}>{m.text}</div>
                <div style={{ fontSize: 10, color: C.slate, fontFamily: "'Geist Mono', monospace", marginTop: 4, textAlign: mine ? "right" : "left" }}>{m.at}</div>
              </div>
            );
          })}
        </div>
        <div style={{ padding: 20, borderTop: `1px solid ${C.softLine}`, display: "flex", gap: 10, background: C.paper }}>
          <input value={text} onChange={e => setText(e.target.value)} onKeyDown={e => e.key === "Enter" && send()} placeholder={t("Écris un message…","Write a message…")}
            style={{ flex: 1, padding: "13px 16px", border: `1px solid ${C.softLine}`, borderRadius: 24, fontSize: 14, fontFamily: "'Geist', sans-serif", outline: "none" }}/>
          <Button kind="flame" onClick={send}>{t("Envoyer","Send")} →</Button>
        </div>
      </div>
    </>
  );
}

// ---------- PROFILE ----------
function EleveProfile() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const toast = useToast();
  const s = me(store);
  return (
    <>
      <Topbar subtitle={t("MON COMPTE","MY ACCOUNT")} title={t("Profil","Profile")} search={false}/>
      <PageBody>
        <div style={{ maxWidth: 620, display: "flex", flexDirection: "column", gap: 14 }}>
          <Card dark style={{ padding: 24 }}>
            <div style={{ display: "flex", alignItems: "center", gap: 14 }}>
              <Avatar name={s.name} size={56} tone={s.tone}/>
              <div style={{ flex: 1 }}><div style={{ fontSize: 18, fontWeight: 600 }}>{s.name}</div><div style={{ fontSize: 12, color: "#9098B5" }}>lea.mercier@gmail.com</div></div>
              <Pill tone="flame">Auto-École Lubasa</Pill>
            </div>
            <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 18, paddingTop: 18, borderTop: "1px solid #1F2542" }}>
              {[[s.progress+"%",t("PROGRESSION","PROGRESS")],[s.hours+"h",t("CONDUITES","DRIVES")],[s.code+"/40","CODE"]].map(([v,l]) => (
                <div key={l} style={{ textAlign: "center" }}><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 26, lineHeight: 1 }}>{v}</div><Label color="#9098B5" style={{ fontSize: 8, marginTop: 4 }}>{l}</Label></div>
              ))}
            </div>
          </Card>

          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 12 }}>{t("FORFAIT EN COURS","CURRENT PACKAGE")}</Label>
            <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline" }}>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 28 }}>{t("Forfait","Package")} {s.hoursTotal}h</div>
              <div style={{ fontFamily: "'Geist Mono', monospace", fontSize: 15, color: C.flame, fontWeight: 600 }}>{s.balance} € {t("restant","left")}</div>
            </div>
            <div style={{ marginTop: 12, display: "flex", gap: 4 }}>
              {[1,2,3,4].map(n => <div key={n} style={{ flex: 1, height: 8, borderRadius: 4, background: n <= 2 ? C.signal : "#F0EBDC" }}/>)}
            </div>
            <div style={{ fontSize: 12, color: C.slate, marginTop: 8 }}>{t("2/4 mensualités payées","2/4 installments paid")}</div>
            <Button kind="primary" full style={{ marginTop: 16 }} onClick={() => toast.push(t("Paiement de 210 € effectué !","€210 payment done!"), "signal")}>{t("Payer la prochaine mensualité · 210 €","Pay next installment · €210")}</Button>
          </Card>
        </div>
      </PageBody>
    </>
  );
}

window.EleveApp = EleveApp;
window.GK_lang = GK_lang;
