/* GUIDKO App — shared school modules: Students (CRUD), Instructors, Analytics, Finance, Settings */

// ---------- STUDENTS (CRUD) ----------
function StudentsModule({ role }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const toast = useToast();
  const [q, setQ] = React.useState("");
  const [detail, setDetail] = React.useState(null);
  const [addOpen, setAddOpen] = React.useState(false);
  const [phaseF, setPhaseF] = React.useState("all");

  let list = store.state.students.filter(s => s.name.toLowerCase().includes(q.toLowerCase()));
  if (phaseF !== "all") list = list.filter(s => s.phase === phaseF);

  return (
    <>
      <Topbar subtitle={t("GESTION ÉLÈVES","STUDENT MANAGEMENT")} title={t("Élèves","Students")} search={false}
        actions={<Button kind="primary" onClick={() => setAddOpen(true)}>+ {t("Nouvel élève","New student")}</Button>}/>
      <PageBody>
        <div style={{ display: "flex", gap: 10, marginBottom: 16, alignItems: "center" }}>
          <div style={{ flex: 1, maxWidth: 320 }}>
            <Input value={q} onChange={setQ} placeholder={t("Rechercher un élève…","Search a student…")} style={{ marginBottom: 0 }} right={<span style={{ color: C.slate }}>⌕</span>}/>
          </div>
          <Segmented value={phaseF} onChange={setPhaseF} options={[
            { value: "all", label: t("Tous","All") }, { value: "Code", label: "Code" },
            { value: "Conduite", label: t("Conduite","Driving") }, { value: "Examen", label: t("Examen","Exam") },
          ]}/>
          <span style={{ marginLeft: "auto", fontFamily: "'Geist Mono', monospace", fontSize: 12, color: C.slate }}>{list.length} {t("élèves","students")}</span>
        </div>

        <Card style={{ padding: 0, overflow: "hidden" }}>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <thead>
              <tr style={{ background: "#FBF8EE" }}>
                {[t("ÉLÈVE","STUDENT"), t("PHASE","PHASE"), "CODE", t("CONDUITE","DRIVING"), t("PROGRESSION","PROGRESS"), t("SOLDE","BALANCE"), ""].map(h => (
                  <th key={h} style={{ textAlign: "left", padding: "12px 20px", fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.12em", color: C.slate, fontWeight: 500 }}>{h}</th>
                ))}
              </tr>
            </thead>
            <tbody>
              {list.map((s, i) => {
                const m = instructorById(store.state, s.instructorId);
                return (
                  <tr key={s.id} onClick={() => setDetail(s)} style={{ borderTop: `1px solid ${C.softLine}`, cursor: "pointer" }}
                    onMouseEnter={e => e.currentTarget.style.background = "#FBF8EE"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
                    <td style={{ padding: "12px 20px" }}>
                      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
                        <Avatar name={s.name} size={32} tone={s.tone}/>
                        <div><div style={{ fontWeight: 600 }}>{s.name}</div><div style={{ fontSize: 11, color: C.slate }}>{s.age} ans · {m ? m.name : "—"}</div></div>
                      </div>
                    </td>
                    <td style={{ padding: "12px 20px" }}><Pill tone={s.phase === "Examen" ? "flame" : s.phase === "Conduite" ? "sky" : "signal"}>{s.phase}</Pill></td>
                    <td style={{ padding: "12px 20px", fontFamily: "'Geist Mono', monospace" }}>{s.code}/40</td>
                    <td style={{ padding: "12px 20px", fontFamily: "'Geist Mono', monospace" }}>{s.hours}/{s.hoursTotal}h</td>
                    <td style={{ padding: "12px 20px", width: 140 }}><div style={{ display: "flex", alignItems: "center", gap: 8 }}><Bar pct={s.progress} h={6}/><span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 11 }}>{s.progress}%</span></div></td>
                    <td style={{ padding: "12px 20px", fontFamily: "'Geist Mono', monospace", fontWeight: 600, color: s.balance > 0 ? C.flame : C.signal }}>{s.balance} €</td>
                    <td style={{ padding: "12px 20px", color: C.slate }}>›</td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </Card>
      </PageBody>

      <StudentDetail student={detail} onClose={() => setDetail(null)}
        onDelete={(id) => { store.removeStudent(id); setDetail(null); toast.push(t("Élève supprimé","Student removed"), "danger"); }}/>
      <AddStudentModal open={addOpen} onClose={() => setAddOpen(false)}
        onAdd={(st) => { store.addStudent(st); setAddOpen(false); toast.push(t("Élève ajouté !","Student added!"), "signal"); }}/>
    </>
  );
}

function StudentDetail({ student, onClose, onDelete }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  if (!student) return null;
  const m = instructorById(store.state, student.instructorId);
  const skills = [[t("Connaissance véhicule","Vehicle knowledge"), 95], [t("Manœuvres","Maneuvers"), 78], [t("Circulation","Traffic"), 88], [t("Autonomie","Autonomy"), Math.round(student.progress * 0.8)]];
  return (
    <Modal open onClose={onClose} title={student.name} width={500}>
      <div style={{ display: "flex", alignItems: "center", gap: 14, marginBottom: 18 }}>
        <Avatar name={student.name} size={56} tone={student.tone}/>
        <div style={{ flex: 1 }}>
          <div style={{ fontSize: 13, color: C.slate }}>{student.age} ans · {t("inscrit","since")} {student.enrolled}</div>
          <div style={{ display: "flex", gap: 6, marginTop: 6 }}><Pill tone={student.phase === "Examen" ? "flame" : "sky"}>{student.phase}</Pill>{m && <Pill tone="neutral">{m.name}</Pill>}</div>
        </div>
        <div style={{ textAlign: "right" }}><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 36, lineHeight: 1 }}>{student.progress}%</div><Label style={{ fontSize: 9 }}>{t("PROGRESSION","PROGRESS")}</Label></div>
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginBottom: 18 }}>
        {[["CODE", `${student.code}/40`], [t("CONDUITE","DRIVING"), `${student.hours}/${student.hoursTotal}h`], [t("SOLDE","BALANCE"), `${student.balance} €`]].map(([k, v]) => (
          <div key={k} style={{ padding: 12, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 9 }}><Label style={{ fontSize: 9 }}>{k}</Label><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, marginTop: 4 }}>{v}</div></div>
        ))}
      </div>
      <Label style={{ marginBottom: 10 }}>{t("COMPÉTENCES","SKILLS")}</Label>
      {skills.map(([n, v]) => (
        <div key={n} style={{ marginBottom: 10 }}>
          <div style={{ display: "flex", justifyContent: "space-between", fontSize: 12, marginBottom: 4 }}><span>{n}</span><span style={{ fontFamily: "'Geist Mono', monospace", fontWeight: 600 }}>{v}</span></div>
          <Bar pct={v} color={v > 80 ? C.signal : v > 60 ? C.flame : C.sky} h={5}/>
        </div>
      ))}
      <div style={{ display: "flex", gap: 8, marginTop: 18 }}>
        <Button kind="danger" onClick={() => onDelete(student.id)}>{t("Supprimer","Delete")}</Button>
        <Button kind="primary" full onClick={onClose}>{t("Fermer","Close")}</Button>
      </div>
    </Modal>
  );
}

function AddStudentModal({ open, onClose, onAdd }) {
  const { t } = useI18n();
  const store = useStore();
  const [f, setF] = React.useState({ name: "", age: "20", instructorId: "m1", hoursTotal: "20" });
  const up = (k, v) => setF(s => ({ ...s, [k]: v }));
  return (
    <Modal open={open} onClose={onClose} title={t("Nouvel élève","New student")}>
      <Input label={t("Nom complet","Full name")} value={f.name} onChange={v => up("name", v)} placeholder="Prénom Nom"/>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 12 }}>
        <Input label={t("Âge","Age")} value={f.age} onChange={v => up("age", v)} type="number"/>
        <Select label={t("Forfait","Package")} value={f.hoursTotal} onChange={v => up("hoursTotal", v)} options={[{value:"20",label:"20h"},{value:"30",label:"30h"},{value:"40",label:"40h"}]}/>
      </div>
      <Select label={t("Moniteur attribué","Assigned instructor")} value={f.instructorId} onChange={v => up("instructorId", v)} options={store.state.instructors.map(m => ({ value: m.id, label: m.name }))}/>
      <div style={{ display: "flex", gap: 8, marginTop: 8 }}>
        <Button kind="ghost" onClick={onClose}>{t("Annuler","Cancel")}</Button>
        <Button kind="flame" full onClick={() => f.name && onAdd({ name: f.name, age: +f.age, tone: Math.floor(Math.random()*5), code: 0, hours: 0, hoursTotal: +f.hoursTotal, progress: 5, instructorId: f.instructorId, balance: +f.hoursTotal * 42, status: "new", phase: "Code", enrolled: "Mar 2026" })}>{t("Ajouter l'élève","Add student")} →</Button>
      </div>
    </Modal>
  );
}

// ---------- INSTRUCTORS ----------
function InstructorsModule() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  return (
    <>
      <Topbar subtitle={t("ÉQUIPE PÉDAGOGIQUE","TEACHING TEAM")} title={t("Moniteurs","Instructors")}
        actions={<Button kind="primary">+ {t("Ajouter","Add")}</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(280px, 1fr))", gap: 14 }}>
          {store.state.instructors.map(m => {
            const count = store.state.lessons.filter(l => l.instructorId === m.id).length;
            const students = store.state.students.filter(s => s.instructorId === m.id);
            return (
              <Card key={m.id} style={{ padding: 20 }}>
                <div style={{ display: "flex", alignItems: "center", gap: 12 }}>
                  <Avatar name={m.name} size={48} tone={m.tone}/>
                  <div><div style={{ fontSize: 16, fontWeight: 600 }}>{m.name}</div><div style={{ fontSize: 12, color: C.slate }}>{m.vehicle}</div></div>
                </div>
                <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginTop: 16 }}>
                  {[[count, t("COURS/SEM","LESSONS/WK")], [students.length, t("ÉLÈVES","STUDENTS")], [(count*280)+"€", "CA"]].map(([v, l]) => (
                    <div key={l} style={{ padding: "10px 8px", background: "#FBF8EE", borderRadius: 8, textAlign: "center" }}><div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22, lineHeight: 1 }}>{v}</div><Label style={{ fontSize: 8, marginTop: 4 }}>{l}</Label></div>
                  ))}
                </div>
                <div style={{ marginTop: 14, display: "flex", marginLeft: 4 }}>
                  {students.slice(0, 5).map((s, i) => <div key={s.id} style={{ marginLeft: -8 }}><Avatar name={s.name} size={26} tone={s.tone} style={{ border: "2px solid #fff" }}/></div>)}
                  {students.length > 5 && <div style={{ marginLeft: -8, width: 26, height: 26, borderRadius: 6, background: C.ink, color: "#fff", display: "grid", placeItems: "center", fontSize: 10, border: "2px solid #fff" }}>+{students.length-5}</div>}
                </div>
              </Card>
            );
          })}
        </div>
      </PageBody>
    </>
  );
}

// ---------- ANALYTICS ----------
function AnalyticsModule() {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const [range, setRange] = React.useState("12m");
  return (
    <>
      <Topbar subtitle={t("ANALYTICS · BUSINESS INTELLIGENCE","ANALYTICS · BI")} title={t("Analytics","Analytics")}
        actions={<Button kind="light">{t("Exporter PDF","Export PDF")} ↓</Button>}/>
      <PageBody>
        <Card style={{ padding: 26, marginBottom: 14 }}>
          <div style={{ display: "flex", justifyContent: "space-between" }}>
            <Label style={{ marginBottom: 8 }}>{t("CHIFFRE D'AFFAIRES","REVENUE")}</Label>
            <Segmented value={range} onChange={setRange} options={[{value:"7d",label:"7j"},{value:"12s",label:"12s"},{value:"12m",label:"12m"}]}/>
          </div>
          <div style={{ display: "flex", alignItems: "flex-end", gap: 36 }}>
            <div>
              <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 80, lineHeight: 0.95, letterSpacing: "-0.025em" }}>216 480 €</div>
              <div style={{ display: "flex", gap: 10, marginTop: 12, alignItems: "center" }}><Pill tone="signal">+24,8%</Pill><span style={{ fontSize: 13, color: C.slate }}>{t("vs année dernière","vs last year")}</span></div>
            </div>
            <div style={{ flex: 1 }}>
              <BarChart data={[{l:"A",v:14},{l:"M",v:16},{l:"J",v:18},{l:"J",v:15},{l:"A",v:12},{l:"S",v:19},{l:"O",v:21},{l:"N",v:22},{l:"D",v:18},{l:"J",v:20},{l:"F",v:23},{l:"M",v:26}]} width={680} height={120} accentIndex={11}/>
            </div>
          </div>
        </Card>

        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 14 }}>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 8 }}>{t("RÉPARTITION DES COURS","LESSON MIX")}</Label>
            <div style={{ display: "flex", alignItems: "center", gap: 18 }}>
              <Donut segments={[{v:42,c:C.flame},{v:28,c:C.signal},{v:18,c:C.sky},{v:12,c:C.ink}]} size={130} thickness={18}/>
              <div style={{ flex: 1, fontSize: 12 }}>
                {[["Conduite","42%",C.flame],["Code","28%",C.signal],["Manœuvres","18%",C.sky],["Examen","12%",C.ink]].map(([n,v,c]) => (
                  <div key={n} style={{ display: "flex", justifyContent: "space-between", padding: "5px 0" }}><span style={{ display: "inline-flex", alignItems: "center", gap: 8 }}><span style={{ width: 10, height: 10, background: c }}/>{n}</span><span style={{ fontFamily: "'Geist Mono', monospace", fontWeight: 600 }}>{v}</span></div>
                ))}
              </div>
            </div>
          </Card>
          <Card style={{ padding: 22 }}>
            <Label style={{ marginBottom: 8 }}>{t("TAUX DE RÉUSSITE","PASS RATE")}</Label>
            <div style={{ display: "flex", alignItems: "baseline", gap: 8 }}><span style={{ fontFamily: "'Instrument Serif', serif", fontSize: 54, lineHeight: 1 }}>74<span style={{ fontSize: 22, color: C.flame }}>%</span></span><Pill tone="signal">+9pt</Pill></div>
            <div style={{ fontSize: 12, color: C.slate, marginTop: 6 }}>{t("Moyenne nationale : 58%","National avg: 58%")}</div>
            <div style={{ marginTop: 16 }}><SparkLine data={[58,62,60,65,68,70,72,74]} color={C.flame} width={280} height={56}/></div>
          </Card>
          <Card dark style={{ padding: 22 }}>
            <Label color="#7A82A8" style={{ marginBottom: 8 }}>{t("MANQUE À GAGNER","REVENUE LEAK")}</Label>
            <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 54, lineHeight: 1, color: "#FF8854" }}>–4 280 €</div>
            <div style={{ fontSize: 12, color: "#9098B5", marginTop: 6 }}>{t("12 mois · 87 créneaux vides","12 months · 87 empty slots")}</div>
            <div style={{ marginTop: 16, padding: 12, background: "#1F2542", borderRadius: 8, fontSize: 12, lineHeight: 1.5, color: "#C9CEE3" }}>💡 {t("Ouvre 3 créneaux le samedi matin : +1 200 €/mois potentiel.","Open 3 Saturday morning slots: +€1,200/mo.")}</div>
          </Card>
        </div>
      </PageBody>
    </>
  );
}

// ---------- FINANCE ----------
function FinanceModule() {
  const C = GK.colors;
  const { t } = useI18n();
  return (
    <>
      <Topbar subtitle={t("FINANCES · MARS 2026","FINANCE · MAR 2026")} title={t("Finances","Finance")}
        actions={<Button kind="light">{t("Export comptable","Accounting export")} ↓</Button>}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 14 }}>
          <KPI label={t("REVENUS","REVENUE")} value="18 420 €" delta="+12%" icon="€"/>
          <KPI label={t("CHARGES","COSTS")} value="11 240 €" delta="-3%" deltaTone="signal" icon="▼"/>
          <KPI label={t("BÉNÉFICE NET","NET PROFIT")} value="7 180 €" delta="+22%" icon="▲"/>
          <KPI label={t("IMPAYÉS","UNPAID")} value="2 340 €" delta="6 élèves" deltaTone="flame" icon="!"/>
        </div>
        <Card style={{ padding: 22, marginTop: 14 }}>
          <Label style={{ marginBottom: 14 }}>{t("FACTURES RÉCENTES","RECENT INVOICES")}</Label>
          <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
            <tbody>
              {[
                ["Léa Mercier", "Forfait 20h", "840 €", "payée"],
                ["Aïcha Bakouri", "Mensualité 2/4", "210 €", "payée"],
                ["Hugo Bélanger", "Forfait 20h", "840 €", "attente"],
                ["Camille Roy", "Forfait 30h", "1 260 €", "attente"],
                ["Adama Diallo", "Heures sup. ×4", "180 €", "payée"],
              ].map(([n, d, a, st], i) => (
                <tr key={i} style={{ borderTop: i === 0 ? "none" : `1px solid ${C.softLine}` }}>
                  <td style={{ padding: "12px 0", fontWeight: 600 }}>{n}</td>
                  <td style={{ padding: "12px 0", color: C.slate }}>{d}</td>
                  <td style={{ padding: "12px 0", fontFamily: "'Geist Mono', monospace", fontWeight: 600 }}>{a}</td>
                  <td style={{ padding: "12px 0", textAlign: "right" }}><Pill tone={st === "payée" ? "signal" : "flame"}>{st === "payée" ? t("Payée","Paid") : t("En attente","Pending")}</Pill></td>
                </tr>
              ))}
            </tbody>
          </table>
        </Card>
      </PageBody>
    </>
  );
}

// ---------- SETTINGS (centre de contrôle complet, role-aware) ----------
const SETTINGS_SECTIONS = [
  { k: "profil",   g: "◆", fr: "Profil & compte", en: "Profile & account" },
  { k: "notif",    g: "🔔", fr: "Notifications", en: "Notifications" },
  { k: "privacy",  g: "🛡", fr: "Confidentialité", en: "Privacy" },
  { k: "prefs",    g: "🌍", fr: "Langue & région", en: "Language & region" },
  { k: "linked",   g: "⇄", fr: "Services liés", en: "Linked services" },
  { k: "metier",   g: "♛", fr: "Préférences métier", en: "Role preferences" },
  { k: "data",     g: "⟲", fr: "Données", en: "Data" },
];

// Préférences métier par espace (la "réalité concrète" de chaque rôle).
// Contrôles : text · select(options) · toggles. Clé = rôle, ou rôle:côté pour les apps à double entrée.
const METIER_PREFS = {
  gerant: { title: { fr: "Auto-école", en: "School" }, fields: [
    { k: "school", type: "text", label: { fr: "Nom de l'auto-école", en: "School name" }, val: "Auto-École Lubasa" },
    { k: "addr",   type: "text", label: { fr: "Adresse", en: "Address" }, val: "18 rue de Lyon, 75011 Paris" },
    { k: "agr",    type: "text", label: { fr: "N° agrément préfecture", en: "Prefecture licence n°" }, val: "E 02 075 0042 0" },
    { k: "comm",   type: "select", label: { fr: "Commission moniteurs affiliés", en: "Affiliated instructor fee" }, val: "15%", options: ["0%", "10%", "15%", "20%"] },
    { k: "cancel", type: "select", label: { fr: "Délai d'annulation sans frais", en: "Free cancellation window" }, val: "48 h", options: ["24 h", "48 h", "72 h"] },
  ], toggles: [
    { k: "autorel", label: { fr: "Relances automatiques élèves (Lia)", en: "Auto student follow-ups (Lia)" }, on: true },
    { k: "onlinebook", label: { fr: "Réservation en ligne des leçons", en: "Online lesson booking" }, on: true },
    { k: "fleetshare", label: { fr: "Proposer ma flotte à la location/covoit", en: "Offer my fleet to rental/carpool" }, on: false },
    { k: "recruit", label: { fr: "Recrutement de moniteurs ouvert", en: "Instructor recruitment open" }, on: false },
  ]},
  accueil: { title: { fr: "Accueil", en: "Front desk" }, fields: [
    { k: "hours", type: "text", label: { fr: "Horaires d'ouverture", en: "Opening hours" }, val: "Lun–Sam · 9h–19h" },
  ], toggles: [
    { k: "autoenroll", label: { fr: "Pré-remplissage des dossiers (Lia)", en: "Auto-fill enrollment files (Lia)" }, on: true },
    { k: "welcome", label: { fr: "Email de bienvenue automatique", en: "Automatic welcome email" }, on: true },
    { k: "deskpay", label: { fr: "Encaissement au comptoir → Wallet", en: "Counter payment → Wallet" }, on: true },
  ]},
  moniteur: { title: { fr: "Moniteur — mode double", en: "Instructor — dual mode" }, fields: [
    { k: "rate", type: "text", label: { fr: "Tarif horaire indépendant", en: "Independent hourly rate" }, val: "49 €/h" },
    { k: "zone", type: "text", label: { fr: "Zone d'intervention", en: "Coverage area" }, val: "Paris 11e–12e–20e" },
    { k: "avail", type: "select", label: { fr: "Disponibilité par semaine", en: "Weekly availability" }, val: "24 h", options: ["12 h", "24 h", "35 h", "40 h+"] },
    { k: "perm", type: "select", label: { fr: "Catégories enseignées", en: "Taught categories" }, val: "B", options: ["B", "B + A", "B + A + C", "Tous permis"] },
  ], toggles: [
    { k: "indep", label: { fr: "Mode indépendant actif", en: "Independent mode on" }, on: true },
    { k: "crossearn", label: { fr: "Proposer covoit/livraison entre cours", en: "Offer carpool/delivery between lessons" }, on: true },
    { k: "liaprep", label: { fr: "Plans de leçon générés par Lia", en: "Lia-generated lesson plans" }, on: true },
    { k: "privacy", label: { fr: "Espace privé invisible des gérants", en: "Private space hidden from managers" }, on: true },
  ]},
  eleve: { title: { fr: "Apprentissage", en: "Learning" }, fields: [
    { k: "goal", type: "select", label: { fr: "Permis visé", en: "Target licence" }, val: "Permis B", options: ["Permis B", "Permis A/A2", "Permis AM", "Permis C"] },
    { k: "exam", type: "text", label: { fr: "Date d'examen visée", en: "Target exam date" }, val: "Juin 2026" },
    { k: "pace", type: "select", label: { fr: "Rythme d'apprentissage", en: "Learning pace" }, val: "Standard", options: ["Tranquille", "Standard", "Accéléré"] },
  ], toggles: [
    { k: "liacode", label: { fr: "Code adaptatif par Lia", en: "Lia adaptive code" }, on: true },
    { k: "carpoolhome", label: { fr: "Covoiturage retour après cours", en: "Carpool home after lessons" }, on: true },
    { k: "accomp", label: { fr: "Suivi conduite accompagnée (km)", en: "Supervised driving tracking (km)" }, on: false },
  ]},
  // — Covoiturage : côté conducteur (prestataire) vs passager (client)
  "covoit:conducteur": { title: { fr: "Covoiturage — Conducteur", en: "Carpool — Driver" }, fields: [
    { k: "veh", type: "text", label: { fr: "Véhicule déclaré", en: "Declared vehicle" }, val: "Renault Clio · AB-123-CD" },
    { k: "price", type: "text", label: { fr: "Prix par place", en: "Price per seat" }, val: "6 €" },
    { k: "plan", type: "select", label: { fr: "Formule de commission", en: "Commission plan" }, val: "Free · 12%", options: ["Free · 12%", "Pro · 6%"] },
    { k: "valid", type: "select", label: { fr: "Validation des passagers", en: "Passenger approval" }, val: "Automatique", options: ["Automatique", "Manuelle"] },
  ], toggles: [
    { k: "recurring", label: { fr: "Trajets récurrents", en: "Recurring rides" }, on: false },
    { k: "deliveralso", label: { fr: "Accepter aussi des livraisons", en: "Also accept deliveries" }, on: false },
    { k: "autogps", label: { fr: "Ouvrir le GUIDAROUTE au départ", en: "Open GUIDAROUTE at departure" }, on: true },
  ]},
  "covoit:passager": { title: { fr: "Covoiturage — Passager", en: "Carpool — Passenger" }, fields: [
    { k: "home", type: "text", label: { fr: "Trajet domicile-travail", en: "Home-work commute" }, val: "Paris → La Défense" },
    { k: "seats", type: "select", label: { fr: "Places habituelles", en: "Usual seats" }, val: "1", options: ["1", "2", "3"] },
  ], toggles: [
    { k: "recurring", label: { fr: "Alertes trajets récurrents", en: "Recurring ride alerts" }, on: true },
    { k: "share", label: { fr: "Partager mon trajet (proches)", en: "Share my trip (relatives)" }, on: true },
    { k: "nonsmoke", label: { fr: "Conducteurs non-fumeurs", en: "Non-smoking drivers" }, on: false },
  ]},
  // — Livraison : côté livreur (prestataire) vs client
  "livraison:livreur": { title: { fr: "Livraison — Livreur", en: "Delivery — Courier" }, fields: [
    { k: "vehicle", type: "select", label: { fr: "Véhicule principal", en: "Main vehicle" }, val: "Scooter (A1)", options: ["Vélo", "Trottinette", "Scooter (A1)", "Moto (A2)", "Voiture (B)", "Camionnette"] },
    { k: "zone", type: "text", label: { fr: "Zone de livraison", en: "Delivery area" }, val: "Paris 11e–12e" },
    { k: "cats", type: "select", label: { fr: "Catégories acceptées", en: "Accepted categories" }, val: "Repas + Colis", options: ["Repas", "Repas + Colis", "Tout + Médical", "Tout + B2B"] },
  ], toggles: [
    { k: "online", label: { fr: "En ligne (recevoir des missions)", en: "Online (receive missions)" }, on: true },
    { k: "boost", label: { fr: "Missions boost week-end", en: "Weekend boost missions" }, on: true },
    { k: "b2b", label: { fr: "Accepter la logistique B2B", en: "Accept B2B logistics" }, on: false },
  ]},
  "livraison:client": { title: { fr: "Livraison — Client", en: "Delivery — Client" }, fields: [
    { k: "addr", type: "text", label: { fr: "Adresse principale", en: "Main address" }, val: "7 rue du Commerce, 75015" },
    { k: "drop", type: "select", label: { fr: "Mode de remise", en: "Drop-off mode" }, val: "Sans contact", options: ["En main propre", "Sans contact", "À l'accueil"] },
  ], toggles: [
    { k: "track", label: { fr: "Suivi temps réel", en: "Real-time tracking" }, on: true },
    { k: "tip", label: { fr: "Pourboire proposé à la livraison", en: "Tip suggested at delivery" }, on: true },
  ]},
};
// Résout la clé métier selon le rôle et le côté (passager/conducteur, client/livreur).
function metierKey(role, user) {
  if (role === "covoit") return "covoit:" + ((user && user.covoitSide) || "passager");
  if (role === "livraison") return "livraison:" + ((user && user.livrSide) || "client");
  return role;
}

// Services liés — le hub d'interconnexion (cœur de l'écosystème)
const LINKED_SERVICES = [
  { k: "wallet", g: "▣", color: "#0FB76B", fr: "Wallet GUIDKO", en: "GUIDKO Wallet", desc: { fr: "Solde unique, gains de tous les services", en: "Single balance, all-service earnings" }, on: true, route: "wallet" },
  { k: "gps",    g: "🛰", color: "#FF5A1F", fr: "GUIDAROUTE", en: "GUIDAROUTE", desc: { fr: "Navigation + carte des ressources", en: "Navigation + resource map" }, on: true, route: "gps" },
  { k: "auto",   g: "⇄", color: "#A78BFA", fr: "Marché Mobilité", en: "Mobility Market", desc: { fr: "Acheter, vendre, louer toute mobilité", en: "Buy, sell, rent any mobility" }, on: true, route: "vehicles" },
  { k: "covoit", g: "⇅", color: "#3B6FF8", fr: "Covoiturage", en: "Carpool", desc: { fr: "Revenus complémentaires sur tes trajets", en: "Extra income on your rides" }, on: false, route: null },
  { k: "livraison", g: "📦", color: "#FF5A1F", fr: "Livraison", en: "Delivery", desc: { fr: "Missions entre tes activités", en: "Missions between your activities" }, on: false, route: null },
  { k: "trust",  g: "🛡", color: "#0FB76B", fr: "Confiance & KYC", en: "Trust & KYC", desc: { fr: "Identité vérifiée valable partout", en: "Verified identity valid everywhere" }, on: true, route: "trust" },
];

function SettingsModule({ role, navigate }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const toast = useToast();
  const me = store.state.user || { name: "Léa Mercier", email: "lea@gmail.com" };
  const [tab, setTab] = React.useState("profil");
  const [notif, setNotif] = React.useState({ push: true, email: true, sms: false, lia: true, promo: false });
  const [priv, setPriv] = React.useState({ profile: true, location: true, reviews: true, data: false });
  const [linked, setLinked] = React.useState(() => Object.fromEntries(LINKED_SERVICES.map(s => [s.k, s.on])));
  const metier = METIER_PREFS[metierKey(role, store.state.user)] || METIER_PREFS.eleve;
  const [mTog, setMTog] = React.useState(() => Object.fromEntries(metier.toggles.map(x => [x.k, x.on])));
  const [mSel, setMSel] = React.useState(() => Object.fromEntries((metier.fields || []).filter(f => f.type === "select").map(f => [f.k, f.val])));
  const curName = window.GKcurrency ? window.GKcurrency() : "EUR";

  const Row = ({ label, sub, children, first }) => (
    <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, padding: "13px 0", borderTop: first ? "none" : `1px solid ${C.softLine}` }}>
      <div style={{ minWidth: 0 }}>
        <div style={{ fontSize: 14, fontWeight: 500 }}>{label}</div>
        {sub && <div style={{ fontSize: 12, color: C.slate, marginTop: 2 }}>{sub}</div>}
      </div>
      <div style={{ flexShrink: 0 }}>{children}</div>
    </div>
  );

  return (
    <>
      <Topbar subtitle={t("CONFIGURATION","CONFIGURATION")} title={t("Paramètres","Settings")} search={false}/>
      <PageBody>
        <div style={{ display: "grid", gridTemplateColumns: "210px 1fr", gap: 20, alignItems: "start" }}>
          {/* Section rail */}
          <div style={{ display: "flex", flexDirection: "column", gap: 3, position: "sticky", top: 0 }}>
            {SETTINGS_SECTIONS.map(s => {
              const on = s.k === tab;
              return (
                <button key={s.k} onClick={() => setTab(s.k)} style={{ display: "flex", alignItems: "center", gap: 10, padding: "10px 12px", borderRadius: 9, border: "none", cursor: "pointer", background: on ? C.ink : "transparent", color: on ? "#fff" : C.ink, fontSize: 13.5, fontWeight: on ? 600 : 500, fontFamily: "inherit", textAlign: "left" }}>
                  <span style={{ width: 20, display: "grid", placeItems: "center", color: on ? C.flame : C.slate }}>{window.hasGKIcon && window.hasGKIcon(s.k) ? <GKIcon name={s.k} size={17}/> : <span>{s.g}</span>}</span>
                  <span style={{ flex: 1 }}>{t(s.fr, s.en)}</span>
                </button>
              );
            })}
          </div>

          {/* Section content */}
          <div style={{ maxWidth: 620, display: "flex", flexDirection: "column", gap: 14 }}>
            {tab === "profil" && (
              <>
                <Card style={{ padding: 22 }}>
                  <div style={{ display: "flex", alignItems: "center", gap: 16, marginBottom: 18 }}>
                    <Avatar name={me.name} size={56} tone={me.tone || 3}/>
                    <div>
                      <div style={{ fontSize: 18, fontWeight: 600 }}>{me.name}</div>
                      <div style={{ fontSize: 13, color: C.slate }}>{me.email || t("Compte GUIDKO","GUIDKO account")}</div>
                    </div>
                    <Button kind="light" size="sm" style={{ marginLeft: "auto" }} onClick={() => toast.push(t("Photo mise à jour","Photo updated"), "signal")}>{t("Changer","Change")}</Button>
                  </div>
                  <Input label={t("Nom complet","Full name")} value={me.name} onChange={() => {}}/>
                  <Input label="Email" value={me.email || ""} onChange={() => {}}/>
                  <Input label={t("Téléphone","Phone")} value="+33 6 ·· ·· ··45" onChange={() => {}}/>
                </Card>
                <Card style={{ padding: 22, display: "flex", gap: 14, alignItems: "center", background: "#FBF8EE" }}>
                  <span style={{ fontSize: 22 }}>🔒</span>
                  <div style={{ flex: 1, fontSize: 13, color: C.slate, lineHeight: 1.45 }}>{t("Mot de passe, 2FA et appareils connectés se gèrent dans Sécurité.","Password, 2FA and devices are managed in Security.")}</div>
                  {navigate && <Button kind="ink" size="sm" onClick={() => navigate(`/${role}/security`)}>{t("Sécurité","Security")} →</Button>}
                </Card>
              </>
            )}

            {tab === "notif" && (
              <Card style={{ padding: 22 }}>
                <Label style={{ marginBottom: 8 }}>{t("CANAUX DE NOTIFICATION","NOTIFICATION CHANNELS")}</Label>
                <Row first label={t("Notifications push","Push notifications")} sub={t("Sur cet appareil","On this device")}><Toggle on={notif.push} onChange={v => setNotif(n => ({ ...n, push: v }))}/></Row>
                <Row label="Email" sub={t("Récap & reçus","Digests & receipts")}><Toggle on={notif.email} onChange={v => setNotif(n => ({ ...n, email: v }))}/></Row>
                <Row label="SMS" sub={t("Alertes urgentes uniquement","Urgent alerts only")}><Toggle on={notif.sms} onChange={v => setNotif(n => ({ ...n, sms: v }))}/></Row>
                <div style={{ height: 12 }}/>
                <Label style={{ marginBottom: 8 }}>{t("CONTENU","CONTENT")}</Label>
                <Row first label={t("Conseils & actions de Lia","Lia tips & actions")}><Toggle on={notif.lia} onChange={v => setNotif(n => ({ ...n, lia: v }))}/></Row>
                <Row label={t("Offres & promotions croisées","Cross offers & promos")} sub={t("Entre les services GUIDKO","Across GUIDKO services")}><Toggle on={notif.promo} onChange={v => setNotif(n => ({ ...n, promo: v }))}/></Row>
              </Card>
            )}

            {tab === "privacy" && (
              <Card style={{ padding: 22 }}>
                <Label style={{ marginBottom: 8 }}>{t("CONFIDENTIALITÉ","PRIVACY")}</Label>
                <Row first label={t("Profil visible","Visible profile")} sub={t("Nom & note visibles des autres membres","Name & rating visible to other members")}><Toggle on={priv.profile} onChange={v => setPriv(p => ({ ...p, profile: v }))}/></Row>
                <Row label={t("Partager ma position","Share my location")} sub={t("Pendant trajets & missions uniquement","During rides & missions only")}><Toggle on={priv.location} onChange={v => setPriv(p => ({ ...p, location: v }))}/></Row>
                <Row label={t("Avis croisés publics","Public cross-reviews")}><Toggle on={priv.reviews} onChange={v => setPriv(p => ({ ...p, reviews: v }))}/></Row>
                <Row label={t("Données pour améliorer l'IA","Data to improve AI")} sub={t("Anonymisées · révocable","Anonymized · revocable")}><Toggle on={priv.data} onChange={v => setPriv(p => ({ ...p, data: v }))}/></Row>
                <div style={{ marginTop: 14, padding: 13, background: C.paper, borderRadius: 9, fontSize: 12, color: C.slate, lineHeight: 1.5 }}>🌍 {t("Conforme RGPD et aux lois du pays sélectionné dans Langue & région.","GDPR-compliant and aligned with the country selected in Language & region.")}</div>
              </Card>
            )}

            {tab === "prefs" && (
              <>
                <Card style={{ padding: 22 }}>
                  <Label style={{ marginBottom: 8 }}>{t("LANGUE & DEVISE","LANGUAGE & CURRENCY")}</Label>
                  <Row first label={t("Langue de l'interface","Interface language")} sub={t("Adapte toute la plateforme","Adapts the whole platform")}><LangSelector/></Row>
                  <Row label={t("Devise active","Active currency")} sub={t("Suit ta langue/pays","Follows your language/country")}><span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 14, fontWeight: 600, padding: "6px 12px", background: C.cream, borderRadius: 8 }}>{curName}</span></Row>
                </Card>
                <Card style={{ padding: 22, display: "flex", gap: 14, alignItems: "center" }}>
                  <span style={{ fontSize: 22 }}>🌍</span>
                  <div style={{ flex: 1, fontSize: 13, color: C.slate, lineHeight: 1.45 }}>{t("Règles, permis et taxes locales se gèrent dans Région & conformité.","Local rules, licences and taxes are managed in Region & compliance.")}</div>
                  {navigate && <Button kind="ink" size="sm" onClick={() => navigate(`/${role}/region`)}>{t("Région","Region")} →</Button>}
                </Card>
              </>
            )}

            {tab === "linked" && (
              <>
                <p style={{ fontSize: 13.5, color: C.slate, lineHeight: 1.55, margin: "0 0 4px" }}>{t("Le cœur de GUIDKO : tes services se parlent. Active un pont pour qu'une activité en enrichisse une autre.","GUIDKO's core: your services talk to each other. Turn on a bridge so one activity feeds another.")}</p>
                {LINKED_SERVICES.map(s => (
                  <Card key={s.k} style={{ padding: 16, display: "flex", alignItems: "center", gap: 14 }}>
                    <div style={{ width: 42, height: 42, borderRadius: 11, background: s.color + "22", color: s.color, display: "grid", placeItems: "center", fontSize: 19, flexShrink: 0 }}>{s.g}</div>
                    <div style={{ flex: 1, minWidth: 0 }}>
                      <div style={{ fontSize: 14.5, fontWeight: 600 }}>{t(s.fr, s.en)}</div>
                      <div style={{ fontSize: 12.5, color: C.slate, marginTop: 1 }}>{s.desc[lang] || s.desc.fr}</div>
                    </div>
                    {linked[s.k] && s.route && navigate && <Button kind="ghost" size="sm" onClick={() => navigate(`/${role}/${s.route}`)}>{t("Ouvrir","Open")}</Button>}
                    <Toggle on={linked[s.k]} onChange={v => { setLinked(l => ({ ...l, [s.k]: v })); toast.push(v ? t("Pont activé","Bridge on") : t("Pont coupé","Bridge off"), v ? "signal" : "neutral"); }}/>
                  </Card>
                ))}
              </>
            )}

            {tab === "metier" && (
              <Card style={{ padding: 22 }}>
                <Label style={{ marginBottom: 14 }}>{(metier.title[lang] || metier.title.fr).toUpperCase()}</Label>
                {metier.fields.map(f => f.type === "select" ? (
                  <div key={f.k} style={{ marginBottom: 12 }}>
                    <Label style={{ marginBottom: 6 }}>{f.label[lang] || f.label.fr}</Label>
                    <div style={{ display: "flex", gap: 6, flexWrap: "wrap" }}>
                      {f.options.map(opt => {
                        const on = (mSel[f.k] || f.val) === opt;
                        return <button key={opt} onClick={() => setMSel(s => ({ ...s, [f.k]: opt }))} style={{ padding: "7px 13px", borderRadius: 999, border: `1px solid ${on ? C.ink : C.softLine}`, background: on ? C.ink : "#fff", color: on ? "#fff" : C.ink, fontSize: 12.5, fontWeight: 600, cursor: "pointer", fontFamily: "inherit" }}>{opt}</button>;
                      })}
                    </div>
                  </div>
                ) : <Input key={f.k} label={f.label[lang] || f.label.fr} value={f.val} onChange={() => {}}/>)}
                <div style={{ height: 6 }}/>
                {metier.toggles.map((tg, i) => (
                  <Row key={tg.k} first={i === 0} label={tg.label[lang] || tg.label.fr}><Toggle on={mTog[tg.k]} onChange={v => setMTog(m => ({ ...m, [tg.k]: v }))}/></Row>
                ))}
              </Card>
            )}

            {tab === "data" && (
              <Card style={{ padding: 22 }}>
                <Label style={{ marginBottom: 12 }}>{t("DONNÉES DE DÉMO","DEMO DATA")}</Label>
                <p style={{ fontSize: 13, color: C.slate, margin: "0 0 14px", lineHeight: 1.5 }}>{t("Réinitialise toutes les données (élèves, planning, marketplace) à leur état initial.","Reset all data (students, schedule, marketplace) to initial state.")}</p>
                <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>
                  <Button kind="light" onClick={() => toast.push(t("Export envoyé par email","Export emailed"), "signal")}>↓ {t("Exporter mes données","Export my data")}</Button>
                  <Button kind="danger" onClick={() => { store.resetAll(); toast.push(t("Données réinitialisées","Data reset"), "signal"); }}>{t("Réinitialiser les données","Reset all data")}</Button>
                </div>
              </Card>
            )}
          </div>
        </div>
      </PageBody>
    </>
  );
}

Object.assign(window, { StudentsModule, InstructorsModule, AnalyticsModule, FinanceModule, SettingsModule });
