// Conversations · Inscriptions · Agenda · Paramètres · AnnoncesPage · ParentChildView

// ============================================================ CONVERSATIONS

const CONVS = [
  { id: "c1", who: "Camille Lefranc",  role: "Parent · PS",       time: "09:14", unread: 2, online: true, type: "parent",
    linked: { name: "Joachim Lefranc", sub: "Inscription PS · à valider" },
    files:  [{ n: "Certificat médical.pdf", s: "245 Ko" }, { n: "Photo identité.jpg", s: "1.2 Mo" }] },
  { id: "c2", who: "Marie Lambert",    role: "Enseignante · CE1",  time: "08:42", unread: 0, online: true, type: "equipe",
    linked: { name: "CE1 Camélia", sub: "4 absents aujourd'hui" },
    files:  [{ n: "Bilan P4 CE1.pdf", s: "180 Ko" }] },
  { id: "c3", who: "Yasmine Benkacem", role: "Parent · CP",        time: "Hier",  unread: 0, type: "parent",
    linked: { name: "Sami Benkacem", sub: "Élève CP · dossier en cours" },
    files:  [{ n: "Justificatif absence.pdf", s: "95 Ko" }] },
  { id: "c4", who: "Équipe pédago",    role: "Groupe · 4 membres", time: "Hier",  unread: 1, type: "equipe",
    linked: { name: "Réunion jeudi 12h", sub: "Ordre du jour à valider" },
    files:  [{ n: "Ordre du jour.docx", s: "42 Ko" }] },
  { id: "c5", who: "Julien Wagner",    role: "Parent · CE1",       time: "Lun",   unread: 0, type: "parent",
    linked: { name: "Emma Wagner", sub: "Dossier CE1 · en cours de revue" },
    files:  [{ n: "Avis d'imposition.pdf", s: "310 Ko" }] },
];

const MSGS_BY_CONV = {
  c1: [
    { side: "them", text: "Bonjour Sophie, j'espère que vous allez bien.", time: "09:12" },
    { side: "them", text: "Est-ce que la cantine sera ouverte vendredi pour la sortie ?", time: "09:13" },
    { side: "me",   text: "Bonjour Camille ! Oui la cantine sera ouverte normalement. Le pique-nique sortie n'est que pour ceux qui le souhaitent.", time: "09:14" },
    { side: "them", text: "Parfait, merci ! Joachim prendra à la cantine alors.", time: "09:14" },
  ],
  c2: [
    { side: "them", text: "Bonjour Sophie, j'ai ajouté l'observation pour Adam.", time: "08:38" },
    { side: "them", text: "Ça serait bien qu'on en parle, il est un peu agité ces derniers temps.", time: "08:40" },
    { side: "me",   text: "Tout à fait Marie. Je te propose qu'on se voit jeudi à 12h ?", time: "08:42" },
  ],
  c3: [
    { side: "me",   text: "Bonjour Yasmine, je voulais vous donner des nouvelles de Sami.", time: "Hier" },
    { side: "me",   text: "Il progresse très bien en lecture, on est vraiment contents de lui !", time: "Hier" },
    { side: "them", text: "Merci pour le retour, ça nous fait vraiment plaisir. À demain.", time: "Hier" },
  ],
  c4: [
    { side: "them", text: "Équipe pédago : quelqu'un peut valider l'ordre du jour pour jeudi ?", time: "Hier" },
    { side: "me",   text: "Oui, j'ai envoyé le doc partagé par email hier soir.", time: "Hier" },
    { side: "them", text: "Sophie : on valide l'ordre du jour ?", time: "Hier" },
  ],
  c5: [
    { side: "them", text: "Bonjour, veuillez trouver ci-joint le certificat médical pour Emma.", time: "Lun" },
    { side: "me",   text: "Merci Julien, je mets à jour le dossier immédiatement.", time: "Lun" },
  ],
};

function Conversations({ role }) {
  const { toast, t } = useApp();
  const [selId, setSel] = React.useState("c1");
  const [draft, setDraft] = React.useState("");
  const [messages, setMessages] = React.useState(MSGS_BY_CONV);
  const [unreads, setUnreads] = React.useState(
    Object.fromEntries(CONVS.map(c => [c.id, c.unread || 0]))
  );
  const [filter, setFilter] = React.useState("all");
  const [convOrder, setConvOrder] = React.useState(CONVS.map(c => c.id));
  const sel = CONVS.find(c => c.id === selId);
  const threadRef = React.useRef(null);

  const now = () => new Date().toLocaleTimeString("fr-FR", {hour: "2-digit", minute: "2-digit"});

  const openConv = (id) => {
    setSel(id);
    setUnreads(u => ({...u, [id]: 0}));
  };

  const bumpConv = (id) => setConvOrder(o => [id, ...o.filter(x => x !== id)]);

  const send = () => {
    if (!draft.trim()) return;
    const msg = { side: "me", text: draft.trim(), time: now() };
    setMessages(m => ({...m, [selId]: [...(m[selId] || []), msg]}));
    setDraft("");
    bumpConv(selId);
  };

  React.useEffect(() => {
    if (threadRef.current) threadRef.current.scrollTop = threadRef.current.scrollHeight;
  }, [messages, selId]);

  const totalUnread = Object.values(unreads).reduce((a, b) => a + b, 0);

  const FILTERS = [
    { k: "all",    l: t("filter_all_conv") },
    { k: "unread", l: `${t("filter_unread")} · ${totalUnread}` },
    { k: "parent", l: t("filter_parents_conv") },
    { k: "equipe", l: t("filter_equipe_conv") },
  ];

  const visibleConvs = CONVS
    .filter(c => {
      if (filter === "unread") return unreads[c.id] > 0;
      if (filter === "parent") return c.type === "parent";
      if (filter === "equipe") return c.type === "equipe";
      return true;
    })
    .sort((a, b) => convOrder.indexOf(a.id) - convOrder.indexOf(b.id));

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("conv_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{t("conv_title")}</h1></div>}
        right={
          <>
            <button className="btn btn-primary" onClick={() => toast("Nouvelle conversation créée")}><Icons.Plus size={16}/>{t("new_conv")}</button>
          </>
        }
      />

      <div className="card" style={{display: "grid", gridTemplateColumns: "340px 1fr 280px", minHeight: 720, overflow: "hidden"}}>
        {/* Liste des conversations */}
        <div style={{borderRight: "1px solid var(--border)", display: "flex", flexDirection: "column"}}>
          <div style={{padding: 14, borderBottom: "1px solid var(--border)"}}>
            <div className="search">
              <Icons.Search size={16}/>
              <input placeholder={t("search")}/>
            </div>
            <div className="row gap-2" style={{marginTop: 10, flexWrap: "wrap"}}>
              {FILTERS.map(f => (
                <button key={f.k}
                        onClick={() => setFilter(f.k)}
                        className={filter === f.k ? "chip brand" : "chip"}
                        style={{cursor: "pointer"}}>
                  {f.l}
                </button>
              ))}
            </div>
          </div>
          <div style={{flex: 1, overflowY: "auto"}}>
            {visibleConvs.length === 0 && (
              <div style={{padding: 32, textAlign: "center"}}>
                <div className="meta">{t("no_conv")}</div>
              </div>
            )}
            {visibleConvs.map(c => {
              const active = c.id === selId;
              const unread = unreads[c.id] || 0;
              return (
                <button key={c.id} onClick={() => openConv(c.id)}
                        className="row gap-3"
                        style={{
                          width: "100%", textAlign: "left", padding: "14px 16px",
                          alignItems: "center",
                          background: active ? "var(--brand-soft)" : "transparent",
                          borderLeft: `3px solid ${active ? "var(--brand)" : "transparent"}`,
                          borderBottom: "1px solid var(--border)",
                        }}>
                  <div style={{position: "relative", flexShrink: 0}}>
                    <Initials name={c.who} size={42}/>
                    {c.online && <span style={{
                      position: "absolute", bottom: 0, right: 0, width: 12, height: 12,
                      borderRadius: 99, background: "var(--brand)", border: "2px solid var(--surface)",
                    }}/>}
                  </div>
                  <div style={{flex: 1, minWidth: 0}}>
                    <div className="row" style={{justifyContent: "space-between", alignItems: "center", marginBottom: 2}}>
                      <div style={{fontWeight: unread > 0 ? 800 : 700, color: "var(--ink)", fontSize: 14}}>{c.who}</div>
                      <div className="meta tnum" style={{fontSize: 11.5}}>{c.time}</div>
                    </div>
                    <div className="meta" style={{whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis", fontSize: 12.5}}>
                      {(messages[c.id] || []).slice(-1)[0]?.text || ""}
                    </div>
                  </div>
                  {unread > 0 && (
                    <span style={{
                      minWidth: 18, height: 18, borderRadius: 99, padding: "0 5px",
                      background: "var(--brand)", color: "white", fontSize: 11, fontWeight: 700,
                      display: "grid", placeItems: "center", flexShrink: 0,
                    }}>{unread}</span>
                  )}
                </button>
              );
            })}
          </div>
        </div>

        {/* Thread */}
        <div style={{display: "flex", flexDirection: "column"}}>
          <div className="row" style={{padding: "16px 22px", borderBottom: "1px solid var(--border)", alignItems: "center", justifyContent: "space-between"}}>
            <div className="row gap-3" style={{alignItems: "center"}}>
              <Initials name={sel.who} size={40}/>
              <div>
                <div style={{fontWeight: 700, color: "var(--ink)", fontSize: 15}}>{sel.who}</div>
                <div className="meta">{sel.role}{sel.online && <span style={{color: "var(--brand)"}}> · {t("online_label")}</span>}</div>
              </div>
            </div>
            <div className="row gap-2">
              <button className="icon-btn" onClick={() => toast("Appel vidéo lancé")}><Icons.Eye size={16}/></button>
              <button className="icon-btn" onClick={() => toast("Conversation archivée")}><Icons.Doc size={16}/></button>
              <DropMenu
                trigger={<button className="icon-btn"><Icons.Dots size={16}/></button>}
                items={[
                  {icon: Icons.Pin,  label: t("pin_conv"),   onClick: () => toast("Conversation épinglée")},
                  {icon: Icons.Bell, label: t("mute_conv"),  onClick: () => toast("Notifications coupées")},
                  "-",
                  {icon: Icons.X,    label: t("delete_conv"), danger: true, onClick: () => toast("Conversation supprimée")},
                ]}
              />
            </div>
          </div>

          <div ref={threadRef} style={{flex: 1, padding: "24px 22px", overflowY: "auto", display: "flex", flexDirection: "column", gap: 10}}>
            <div style={{textAlign: "center", margin: "4px 0 12px"}}>
              <span className="chip">{t("today")}</span>
            </div>
            {(messages[selId] || []).map((m, i) => (
              <div key={i} className="row" style={{justifyContent: m.side === "me" ? "flex-end" : "flex-start"}}>
                <div style={{
                  maxWidth: "70%", padding: "10px 14px",
                  background: m.side === "me" ? "var(--brand)" : "var(--surface-2)",
                  color: m.side === "me" ? "white" : "var(--ink)",
                  borderRadius: 14,
                  borderBottomRightRadius: m.side === "me" ? 4 : 14,
                  borderBottomLeftRadius:  m.side === "me" ? 14 : 4,
                  fontSize: 14, lineHeight: 1.5,
                }}>
                  {m.text}
                  <div style={{fontSize: 10.5, opacity: .65, marginTop: 4, textAlign: "right"}}>{m.time}</div>
                </div>
              </div>
            ))}
          </div>

          <div style={{padding: 14, borderTop: "1px solid var(--border)"}}>
            <div className="row gap-2" style={{
              padding: "10px 12px", border: "1px solid var(--border)",
              borderRadius: 14, background: "var(--surface-2)", alignItems: "flex-end",
            }}>
              <button className="icon-btn" style={{background: "transparent", border: "none"}} onClick={() => toast("Pièce jointe")}><Icons.Plus size={18}/></button>
              <textarea value={draft} onChange={e => setDraft(e.target.value)}
                        onKeyDown={e => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); send(); }}}
                        placeholder={t("write_msg_ph")}
                        rows={1}
                        style={{
                          flex: 1, border: "none", outline: "none", background: "transparent",
                          font: "inherit", fontSize: 14, resize: "none", padding: "8px 0",
                        }}/>
              <button className="icon-btn" style={{background: "transparent", border: "none"}} onClick={() => toast("Micro")}><Icons.Mic size={18}/></button>
              <button className="btn btn-primary" onClick={send}><Icons.Send size={14}/>{t("send_btn")}</button>
            </div>
          </div>
        </div>

        {/* Rail détails */}
        <div style={{borderLeft: "1px solid var(--border)", padding: 20, overflowY: "auto"}}>
          <div className="col" style={{alignItems: "center", textAlign: "center", marginBottom: 16}}>
            <Initials name={sel.who} size={64}/>
            <div className="h3" style={{marginTop: 10}}>{sel.who}</div>
            <div className="meta" style={{marginTop: 2}}>{sel.role}</div>
          </div>
          <div className="row gap-2" style={{marginBottom: 20}}>
            <button className="btn" style={{flex: 1}} onClick={() => toast("Profil ouvert")}><Icons.Eye size={14}/>{t("profile_btn")}</button>
            <button className="btn" style={{flex: 1}} onClick={() => toast("RDV proposé")}><Icons.Cal size={14}/>{t("rdv_btn")}</button>
          </div>

          <div className="eyebrow" style={{marginBottom: 8}}>{t("linked_to")}</div>
          <div className="row gap-3" style={{padding: "12px", background: "var(--surface-2)", borderRadius: 12, marginBottom: 16, alignItems: "center"}}>
            <Initials name={sel.linked.name} size={36}/>
            <div style={{flex: 1, minWidth: 0}}>
              <div style={{fontWeight: 700, color: "var(--ink)", fontSize: 13.5, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{sel.linked.name}</div>
              <div className="meta">{sel.linked.sub}</div>
            </div>
            <button className="btn btn-ghost" style={{flexShrink: 0, padding: "6px 8px"}}><Icons.ChevR size={14}/></button>
          </div>

          <div className="eyebrow" style={{marginBottom: 8}}>{t("shared_files")}</div>
          <div className="col gap-2">
            {sel.files.map((f, i) => (
              <button key={i} className="row gap-3" style={{
                padding: 10, borderRadius: 10, border: "1px solid var(--border)",
                alignItems: "center", textAlign: "left", background: "var(--surface)",
              }} onClick={() => toast("Téléchargement : " + f.n)}>
                <Icons.Doc size={18} style={{color: "var(--ink-3)", flexShrink: 0}}/>
                <div style={{flex: 1, minWidth: 0}}>
                  <div style={{fontWeight: 600, color: "var(--ink)", fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis"}}>{f.n}</div>
                  <div className="meta">{f.s}</div>
                </div>
              </button>
            ))}
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================ INSCRIPTIONS
const INSC_FULL = [
  { id: 1, name: "Joachim Lefranc",   level: "PS",  parent: "Camille Lefranc",   tel: "06 11 22 33 44", status: "new",       since: "il y a 2h",  email: "c.lefranc@gmail.com" },
  { id: 2, name: "Emma Wagner",       level: "CE1", parent: "Julien Wagner",     tel: "06 22 33 44 55", status: "review",    since: "Hier",       email: "j.wagner@protonmail.com" },
  { id: 3, name: "Sami Benkacem",     level: "CP",  parent: "Yasmine Benkacem",  tel: "06 33 44 55 66", status: "review",    since: "Hier",       email: "y.benkacem@orange.fr" },
  { id: 4, name: "Lou Vanier",        level: "CE2", parent: "Mathieu Vanier",    tel: "06 44 55 66 77", status: "wait",      since: "Lun",        email: "m.vanier@gmail.com" },
  { id: 5, name: "Aïcha Diop",        level: "MS",  parent: "Aminata Diop",      tel: "06 55 66 77 88", status: "wait",      since: "Lun",        email: "a.diop@gmail.com" },
  { id: 6, name: "Noé Carmel",        level: "PS",  parent: "Élise Carmel",      tel: "06 66 77 88 99", status: "validated", since: "Ven",        email: "elise@carmel.fr" },
  { id: 7, name: "Tess Riou",         level: "CE2", parent: "Marion Riou",       tel: "06 77 88 99 00", status: "validated", since: "Jeu",        email: "m.riou@hotmail.fr" },
];

function Inscriptions() {
  const { toast, confirm, t } = useApp();
  const [filter, setFilter] = React.useState("all");
  const [selId, setSelId] = React.useState(1);

  const STATUS_META = {
    new:       { l: t("insc_status_new"),       cls: "brand" },
    review:    { l: t("insc_status_review"),    cls: "warn"  },
    wait:      { l: t("insc_status_wait"),      cls: ""      },
    validated: { l: t("insc_status_validated"), cls: "brand" },
  };

  const list = INSC_FULL.filter(i => filter === "all" || i.status === filter);
  const sel = INSC_FULL.find(i => i.id === selId);

  const TABS = [
    { k: "all",       l: t("tab_all_insc")       },
    { k: "new",       l: t("tab_new_insc")       },
    { k: "review",    l: t("tab_review_insc")    },
    { k: "wait",      l: t("tab_wait_insc")      },
    { k: "validated", l: t("tab_validated_insc") },
  ];

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("insc_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{t("insc_title")}</h1></div>}
        right={
          <>
            <button className="btn" onClick={() => toast("Export CSV démarré")}><Icons.Doc size={16}/>{t("export")}</button>
            <button className="btn btn-primary" onClick={() => toast("Nouveau dossier créé")}><Icons.Plus size={16}/>{t("new_file")}</button>
          </>
        }
      />

      <div className="row gap-4" style={{marginBottom: 20}}>
        <Stat label={t("insc_received")} value="12" sub="↑ 3 cette semaine"/>
        <Stat label={t("insc_to_process")} value="5" valueColor="var(--warn)" sub="3 nouveaux"/>
        <Stat label={t("insc_validated_count")} value="6" sub="dont 2 cette semaine"/>
        <Stat label={t("insc_rate")} value="86%" sub="moyenne année"/>
      </div>

      <div className="row gap-5" style={{alignItems: "flex-start"}}>
        <div className="card" style={{flex: 1.4, minWidth: 0}}>
          <div className="row" style={{padding: "16px 20px", borderBottom: "1px solid var(--border)", justifyContent: "space-between", alignItems: "center"}}>
            <div className="tabs">
              {TABS.map(tb => (
                <button key={tb.k} className={filter===tb.k?"active":""} onClick={() => setFilter(tb.k)}>{tb.l}</button>
              ))}
            </div>
            <button className="btn"><Icons.Filter size={14}/></button>
          </div>
          <div>
            {list.map(i => {
              const active = i.id === selId;
              const s = STATUS_META[i.status];
              return (
                <button key={i.id} onClick={() => setSelId(i.id)}
                        className="lrow"
                        style={{
                          gridTemplateColumns: "auto 1.4fr 70px auto auto",
                          padding: "14px 20px", textAlign: "left", width: "100%",
                          background: active ? "var(--brand-soft)" : "transparent",
                          borderLeft: `3px solid ${active ? "var(--brand)" : "transparent"}`,
                        }}>
                  <Initials name={i.name} size={38}/>
                  <div style={{minWidth: 0}}>
                    <div style={{fontWeight: 700, color: active ? "var(--brand-ink)" : "var(--ink)", fontSize: 14}}>{i.name}</div>
                    <div className="meta">{i.parent} · {i.since}</div>
                  </div>
                  <span className="chip">{i.level}</span>
                  <span className={`chip ${s.cls}`}>{s.l}</span>
                  <Icons.ChevR size={16} style={{color: "var(--ink-5)"}}/>
                </button>
              );
            })}
          </div>
        </div>

        <div className="card" style={{flex: 1, position: "sticky", top: 20}}>
          <div className="row" style={{padding: "20px 22px 14px", justifyContent: "space-between", alignItems: "center"}}>
            <div className="row gap-3" style={{alignItems: "center"}}>
              <Initials name={sel.name} size={56}/>
              <div>
                <div className="h2">{sel.name}</div>
                <div className="meta">Niveau {sel.level} · {sel.since}</div>
              </div>
            </div>
            <span className={`chip ${STATUS_META[sel.status].cls}`}>{STATUS_META[sel.status].l}</span>
          </div>

          <div style={{padding: "8px 22px 22px"}}>
            <div className="eyebrow" style={{marginBottom: 8}}>{t("family_label")}</div>
            <div style={{padding: "14px", background: "var(--surface-2)", borderRadius: 12, marginBottom: 18}}>
              <div style={{fontWeight: 700, color: "var(--ink)"}}>{sel.parent}</div>
              <div className="meta tnum" style={{marginTop: 4}}>{sel.tel}</div>
              <div className="meta" style={{marginTop: 2}}>{sel.email}</div>
            </div>

            <div className="eyebrow" style={{marginBottom: 8}}>{t("file_label")}</div>
            <div className="col gap-2" style={{marginBottom: 18}}>
              {[
                {n: "Acte de naissance",     ok: true},
                {n: "Justificatif domicile",  ok: true},
                {n: "Carnet de santé",        ok: sel.status !== "wait"},
                {n: "Avis d'imposition",      ok: sel.status === "validated"},
              ].map((f, i) => (
                <div key={i} className="row gap-3" style={{padding: "10px 14px", border: "1px solid var(--border)", borderRadius: 10, alignItems: "center"}}>
                  <Icons.Doc size={16} style={{color: f.ok ? "var(--brand)" : "var(--ink-5)"}}/>
                  <div style={{flex: 1, fontSize: 13.5, color: "var(--ink)", fontWeight: 500}}>{f.n}</div>
                  {f.ok ? <span className="chip brand">{t("doc_received")}</span> : <span className="chip warn">{t("doc_missing")}</span>}
                </div>
              ))}
            </div>

            <div className="row gap-2">
              <button className="btn" style={{flex: 1}} onClick={() => toast("Message envoyé à la famille")}>
                <Icons.Msg size={14}/>{t("message_btn")}
              </button>
              <button className="btn" style={{flex: 1}} onClick={() => toast("RDV proposé")}>
                <Icons.Cal size={14}/>{t("propose_rdv")}
              </button>
            </div>
            <div className="row gap-2" style={{marginTop: 8}}>
              <button className="btn" style={{flex: 1}}
                      onClick={() => confirm({title:"Refuser ce dossier ?", body:"La famille recevra un email automatique. L'action est réversible pendant 7 jours.", confirmLabel:t("refuse_btn"), danger:true, onConfirm:()=>toast("Dossier refusé")})}>
                <Icons.X size={14}/>{t("refuse_btn")}
              </button>
              <button className="btn btn-primary" style={{flex: 2}}
                      onClick={() => confirm({title:"Valider l'inscription ?", body:`${sel.name} sera ajouté·e à la classe de ${sel.level} pour septembre 2026.`, confirmLabel:t("validate_insc"), onConfirm:()=>toast(sel.name + " — inscription validée")})}>
                <Icons.Check size={14}/>{t("validate_insc")}
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ============================================================ AGENDA

const EVENTS_BASE = [
  { id: 1, day: 1, h: 9,  dur: 1,   title: "Conseil d'école",     who: "Salle direction",    color: "brand", desc: "Ordre du jour : bilans P4, organisation kermesse, effectifs 2027.",                          classes: "all" },
  { id: 2, day: 1, h: 14, dur: 1,   title: "RDV famille Wagner",  who: "Sophie",              color: "warn",  desc: "Discussion sur le dossier d'inscription CE1 pour Emma Wagner. Document manquant : avis d'imposition.", classes: "all" },
  { id: 3, day: 2, h: 10, dur: 2,   title: "Sortie médiathèque",  who: "CE1 Camélia",         color: "brand", desc: "Médiathèque du 8ème. Départ 09h45, retour 11h45. Autorisation de sortie signée obligatoire.", classes: "ce1" },
  { id: 4, day: 3, h: 9,  dur: 3,   title: "Photo de classe",     who: "Toutes les classes",  color: "brand", desc: "Photographe à 09h00. Prévoir une tenue soignée. Séances par classe de 09h à 12h.",             classes: "all" },
  { id: 5, day: 4, h: 12, dur: 1,   title: "Réunion équipe",      who: "Salle des maîtres",   color: "warn",  desc: "Bilans P4 et organisation de la kermesse. Présence de toute l'équipe souhaitée.",              classes: "all" },
  { id: 6, day: 4, h: 15, dur: 1.5, title: "Bilans P4",           who: "Équipe pédago",        color: "brand", desc: "Présentation et échanges sur les bilans de la période 4 par classe.",                          classes: "all" },
  { id: 7, day: 5, h: 9,  dur: 4,   title: "Kermesse",            who: "Tout le monde",        color: "brand", desc: "Kermesse annuelle de l'école. Jeux, buvette, vente de gâteaux. Bienvenue à tous !",            classes: "all" },
];

const DATES = [18, 19, 20, 21, 22];
const cap = s => s.charAt(0).toUpperCase() + s.slice(1);

function AgendaWeek({ events, onEventClick }) {
  const { lang } = useApp();
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const DAYS = DATES.map(d => cap(new Date(2026, 4, d).toLocaleDateString(loc, {weekday: "long"})));
  const hours = Array.from({length: 9}, (_, i) => i + 8);
  return (
    <div className="card" style={{overflow: "hidden"}}>
      <div style={{display: "grid", gridTemplateColumns: "70px repeat(5, 1fr)", borderBottom: "1px solid var(--border)"}}>
        <div/>
        {DAYS.map((d, i) => (
          <div key={i} style={{padding: "16px 12px", textAlign: "center", borderLeft: "1px solid var(--border)"}}>
            <div className="eyebrow">{d}</div>
            <div className="tnum" style={{
              marginTop: 4, fontSize: 22, fontWeight: 800,
              color: i === 2 ? "var(--brand)" : "var(--ink)",
              display: "inline-grid", placeItems: "center",
              width: 36, height: 36, borderRadius: 99,
              background: i === 2 ? "var(--brand-soft)" : "transparent",
            }}>{DATES[i]}</div>
          </div>
        ))}
      </div>
      <div style={{display: "grid", gridTemplateColumns: "70px repeat(5, 1fr)", position: "relative"}}>
        <div>
          {hours.map(h => (
            <div key={h} style={{height: 64, borderBottom: "1px solid var(--border)", padding: "6px 10px", textAlign: "right"}}>
              <span className="meta tnum" style={{fontSize: 11}}>{h}h00</span>
            </div>
          ))}
        </div>
        {DAYS.map((_, day) => (
          <div key={day} style={{borderLeft: "1px solid var(--border)", position: "relative"}}>
            {hours.map(h => (
              <div key={h} style={{height: 64, borderBottom: "1px solid var(--border)"}}/>
            ))}
            {events.filter(e => e.day - 1 === day).map((e, i) => {
              const top = (e.h - 8) * 64;
              const height = e.dur * 64 - 4;
              const isBrand = e.color === "brand";
              return (
                <button key={i} onClick={() => onEventClick(e)}
                        style={{
                          position: "absolute", left: 6, right: 6, top: top + 2, height,
                          borderRadius: 10, padding: "8px 10px", textAlign: "left",
                          background: isBrand ? "var(--brand-soft)" : "#FBEFD7",
                          border: `1px solid ${isBrand ? "var(--brand-soft-2)" : "#F1D9A5"}`,
                          borderLeft: `4px solid ${isBrand ? "var(--brand)" : "var(--warn)"}`,
                          cursor: "pointer",
                        }}>
                  <div style={{fontWeight: 700, fontSize: 12.5, color: isBrand ? "var(--brand-ink)" : "#7A4A0E", lineHeight: 1.25}}>
                    {e.title}
                  </div>
                  <div className="meta" style={{fontSize: 11, color: isBrand ? "var(--brand-ink)" : "#8A5410", opacity: .85, marginTop: 2}}>
                    {e.who}
                  </div>
                </button>
              );
            })}
          </div>
        ))}
      </div>
    </div>
  );
}

function AgendaMonth({ events, onEventClick }) {
  const { lang } = useApp();
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const weekDays = Array.from({length: 7}, (_, i) =>
    cap(new Date(2026, 4, 4 + i).toLocaleDateString(loc, {weekday: "short"})).replace(".", "")
  );
  const offset = 4;
  const daysInMonth = 31;

  const dayEvents = {};
  events.forEach(e => {
    const d = 17 + e.day;
    if (!dayEvents[d]) dayEvents[d] = [];
    dayEvents[d].push(e);
  });

  const cells = [];
  for (let i = 0; i < offset; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  const remaining = (7 - (cells.length % 7)) % 7;
  for (let i = 0; i < remaining; i++) cells.push(null);

  return (
    <div className="card" style={{overflow: "hidden"}}>
      <div style={{display: "grid", gridTemplateColumns: "repeat(7, 1fr)", borderBottom: "1px solid var(--border)"}}>
        {weekDays.map(d => (
          <div key={d} style={{padding: "12px 8px", textAlign: "center", borderLeft: "1px solid var(--border)"}}>
            <span className="eyebrow">{d}</span>
          </div>
        ))}
      </div>
      <div style={{display: "grid", gridTemplateColumns: "repeat(7, 1fr)"}}>
        {cells.map((day, idx) => {
          const evts = day ? (dayEvents[day] || []) : [];
          const isToday = day === 20;
          return (
            <div key={idx} style={{
              minHeight: 90, borderRight: "1px solid var(--border)", borderBottom: "1px solid var(--border)",
              padding: "8px 6px",
              background: !day ? "var(--surface-2)" : isToday ? "var(--brand-soft)" : "var(--surface)",
            }}>
              {day && (
                <>
                  <div style={{
                    fontWeight: isToday ? 800 : 600, fontSize: 13,
                    color: isToday ? "var(--brand-ink)" : "var(--ink)", marginBottom: 4,
                  }}>{day}</div>
                  <div style={{display: "flex", flexDirection: "column", gap: 2}}>
                    {evts.slice(0, 2).map((e, i) => (
                      <button key={i} onClick={() => onEventClick(e)} style={{
                        fontSize: 10.5, fontWeight: 600, padding: "2px 5px", borderRadius: 5,
                        background: e.color === "brand" ? "var(--brand-soft)" : "var(--warn-soft)",
                        color: e.color === "brand" ? "var(--brand-ink)" : "#8A5410",
                        border: "none", textAlign: "left", width: "100%",
                        overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis",
                        cursor: "pointer",
                      }}>{e.title}</button>
                    ))}
                    {evts.length > 2 && <div className="meta" style={{fontSize: 10}}>+{evts.length - 2}</div>}
                  </div>
                </>
              )}
            </div>
          );
        })}
      </div>
    </div>
  );
}

function AgendaYear({ events, onEventClick }) {
  const { lang, t } = useApp();
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const months = Array.from({length: 12}, (_, i) =>
    cap(new Date(2026, i, 1).toLocaleDateString(loc, {month: "long"}))
  );
  return (
    <div style={{display: "grid", gridTemplateColumns: "repeat(4, 1fr)", gap: 16}}>
      {months.map((month, mi) => {
        const isCurrent = mi === 4;
        return (
          <div key={mi} className="card" style={{padding: 16, border: isCurrent ? "2px solid var(--brand)" : undefined}}>
            <div style={{fontWeight: 700, color: isCurrent ? "var(--brand-ink)" : "var(--ink)", fontSize: 14, marginBottom: 10}}>
              {month} 2026
            </div>
            {isCurrent ? (
              <div style={{display: "flex", flexDirection: "column", gap: 4}}>
                {events.slice(0, 4).map((e, i) => (
                  <button key={i} onClick={() => onEventClick(e)} style={{
                    fontSize: 11, padding: "3px 7px", borderRadius: 6,
                    background: e.color === "brand" ? "var(--brand-soft)" : "var(--warn-soft)",
                    color: e.color === "brand" ? "var(--brand-ink)" : "#8A5410",
                    border: "none", textAlign: "left", width: "100%",
                    overflow: "hidden", whiteSpace: "nowrap", textOverflow: "ellipsis",
                    cursor: "pointer",
                  }}>{DATES[e.day-1]} — {e.title}</button>
                ))}
                {events.length > 4 && <div className="meta" style={{fontSize: 10.5}}>+{events.length - 4} événements</div>}
              </div>
            ) : (
              <div className="meta" style={{fontSize: 12}}>
                {mi < 4 ? t("cal_past") : mi === 8 ? t("cal_back_to_school") : mi === 11 ? t("cal_xmas") : t("no_event")}
              </div>
            )}
          </div>
        );
      })}
    </div>
  );
}

function AgendaDay({ events, onEventClick }) {
  const { lang } = useApp();
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const todayStr = cap(new Date(2026, 4, 20).toLocaleDateString(loc, {weekday: "long", day: "numeric", month: "long", year: "numeric"}));
  const hours = Array.from({length: 9}, (_, i) => i + 8);
  const todayEvents = events.filter(e => e.day === 3);
  return (
    <div className="card" style={{overflow: "hidden"}}>
      <div style={{padding: "16px 24px", borderBottom: "1px solid var(--border)"}}>
        <div className="h2">{todayStr}</div>
      </div>
      <div style={{display: "grid", gridTemplateColumns: "70px 1fr", position: "relative"}}>
        <div>
          {hours.map(h => (
            <div key={h} style={{height: 64, borderBottom: "1px solid var(--border)", padding: "6px 10px", textAlign: "right"}}>
              <span className="meta tnum" style={{fontSize: 11}}>{h}h00</span>
            </div>
          ))}
        </div>
        <div style={{borderLeft: "1px solid var(--border)", position: "relative"}}>
          {hours.map(h => <div key={h} style={{height: 64, borderBottom: "1px solid var(--border)"}}/>)}
          {todayEvents.map((e, i) => {
            const top = (e.h - 8) * 64;
            const height = e.dur * 64 - 4;
            const isBrand = e.color === "brand";
            return (
              <button key={i} onClick={() => onEventClick(e)} style={{
                position: "absolute", left: 6, right: 6, top: top + 2, height,
                borderRadius: 10, padding: "8px 10px", textAlign: "left",
                background: isBrand ? "var(--brand-soft)" : "#FBEFD7",
                border: `1px solid ${isBrand ? "var(--brand-soft-2)" : "#F1D9A5"}`,
                borderLeft: `4px solid ${isBrand ? "var(--brand)" : "var(--warn)"}`,
                cursor: "pointer",
              }}>
                <div style={{fontWeight: 700, fontSize: 13, color: isBrand ? "var(--brand-ink)" : "#7A4A0E"}}>{e.title}</div>
                <div className="meta" style={{fontSize: 11.5, color: isBrand ? "var(--brand-ink)" : "#8A5410", opacity: .85, marginTop: 2}}>
                  {e.h}h00 · {e.who}
                </div>
              </button>
            );
          })}
        </div>
      </div>
    </div>
  );
}

function EventDetailModal({ event, onClose, canEdit }) {
  const { toast, t, lang } = useApp();
  const isBrand = event.color === "brand";
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const dayStr = cap(new Date(2026, 4, DATES[event.day - 1]).toLocaleDateString(loc, {weekday: "long", day: "numeric", month: "long"}));
  const endH = event.h + event.dur;
  const endStr = Number.isInteger(endH) ? `${endH}h00` : `${Math.floor(endH)}h30`;

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" style={{width: 500}} onClick={e => e.stopPropagation()}>
        <div style={{
          padding: "20px 24px 18px",
          borderLeft: `6px solid ${isBrand ? "var(--brand)" : "var(--warn)"}`,
          borderBottom: "1px solid var(--border)",
          background: isBrand ? "var(--brand-soft)" : "#FFF7EA",
          display: "flex", alignItems: "flex-start", justifyContent: "space-between",
        }}>
          <div>
            <div style={{fontWeight: 800, fontSize: 20, color: isBrand ? "var(--brand-ink)" : "#7A4A0E", marginBottom: 6}}>
              {event.title}
            </div>
            <div className="meta" style={{color: isBrand ? "var(--brand-ink)" : "#8A5410", opacity: .85}}>
              {dayStr} · {event.h}h00 → {endStr} · {event.who}
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}
                  style={{background: "transparent", border: "none", color: isBrand ? "var(--brand-ink)" : "#7A4A0E"}}>
            <Icons.X size={16}/>
          </button>
        </div>

        {event.desc && (
          <div style={{padding: "20px 24px"}}>
            <div className="eyebrow" style={{marginBottom: 8}}>{t("description_label")}</div>
            <div style={{fontSize: 14, color: "var(--ink-2)", lineHeight: 1.65}}>{event.desc}</div>
          </div>
        )}

        <div className="row" style={{padding: "14px 20px", borderTop: "1px solid var(--border)", justifyContent: "space-between", background: "var(--surface-2)"}}>
          <button className="btn btn-ghost" onClick={onClose}>{t("close")}</button>
          {canEdit && (
            <div className="row gap-2">
              <button className="btn" style={{color: "var(--danger)"}} onClick={() => { toast("Événement supprimé"); onClose(); }}>
                <Icons.X size={14}/>{t("delete_event")}
              </button>
              <button className="btn btn-primary" onClick={() => { toast("Édition de l'événement"); onClose(); }}>
                <Icons.Settings size={14}/>{t("edit_event")}
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function AddEventModal({ onClose, onSave }) {
  const { t, lang } = useApp();
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const daysOpts = DATES.map(d => cap(new Date(2026, 4, d).toLocaleDateString(loc, {weekday: "long", day: "numeric", month: "long"})));
  const [title, setTitle] = React.useState("");
  const [day,   setDay]   = React.useState(1);
  const [hour,  setHour]  = React.useState(9);
  const [dur,   setDur]   = React.useState(1);
  const [desc,  setDesc]  = React.useState("");
  const [color, setColor] = React.useState("brand");
  const [who,   setWho]   = React.useState("");

  return (
    <div className="scrim" onClick={onClose}>
      <div className="modal" style={{width: 560}} onClick={e => e.stopPropagation()}>
        <div className="row" style={{padding: "16px 20px", justifyContent: "space-between", alignItems: "center", borderBottom: "1px solid var(--border)"}}>
          <div className="row gap-3" style={{alignItems: "center"}}>
            <div style={{width: 36, height: 36, borderRadius: 10, background: "var(--brand-soft)", display: "grid", placeItems: "center", color: "var(--brand)"}}>
              <Icons.Cal size={18}/>
            </div>
            <div>
              <div className="eyebrow">{t("agenda_title")}</div>
              <div className="h3">{t("agenda_new")}</div>
            </div>
          </div>
          <button className="icon-btn" onClick={onClose}><Icons.X size={16}/></button>
        </div>

        <div style={{padding: "20px 24px"}}>
          <div style={{marginBottom: 14}}>
            <div className="eyebrow" style={{marginBottom: 6}}>{t("event_title_label")}</div>
            <input autoFocus value={title} onChange={e => setTitle(e.target.value)}
                   onKeyDown={e => e.key === "Enter" && save()}
                   placeholder="Ex: Réunion équipe, Sortie médiathèque…"
                   style={{...inputStyle(), width: "100%"}}/>
          </div>

          <div className="row gap-3" style={{marginBottom: 14}}>
            <div style={{flex: 2}}>
              <div className="eyebrow" style={{marginBottom: 6}}>{t("event_day_label")}</div>
              <select value={day} onChange={e => setDay(+e.target.value)}
                      style={{...inputStyle(), width: "100%", appearance: "auto"}}>
                {daysOpts.map((d, i) => <option key={i} value={i+1}>{d}</option>)}
              </select>
            </div>
            <div style={{flex: 1}}>
              <div className="eyebrow" style={{marginBottom: 6}}>{t("event_hour_label")}</div>
              <select value={hour} onChange={e => setHour(+e.target.value)}
                      style={{...inputStyle(), width: "100%", appearance: "auto"}}>
                {[8,9,10,11,12,13,14,15,16,17].map(h => <option key={h} value={h}>{h}h00</option>)}
              </select>
            </div>
            <div style={{flex: 1}}>
              <div className="eyebrow" style={{marginBottom: 6}}>{t("event_dur_label")}</div>
              <select value={dur} onChange={e => setDur(+e.target.value)}
                      style={{...inputStyle(), width: "100%", appearance: "auto"}}>
                {[0.5,1,1.5,2,2.5,3,4].map(d => <option key={d} value={d}>{d}h</option>)}
              </select>
            </div>
          </div>

          <div style={{marginBottom: 14}}>
            <div className="eyebrow" style={{marginBottom: 6}}>{t("event_who_label")}</div>
            <input value={who} onChange={e => setWho(e.target.value)}
                   placeholder="Ex: Toute l'équipe, Salle de réunion…"
                   style={{...inputStyle(), width: "100%"}}/>
          </div>

          <div style={{marginBottom: 14}}>
            <div className="eyebrow" style={{marginBottom: 6}}>{t("event_desc_label")}</div>
            <textarea value={desc} onChange={e => setDesc(e.target.value)} rows={3}
                      placeholder="Détails, ordre du jour, matériel nécessaire…"
                      style={{...inputStyle({textarea: true}), width: "100%"}}/>
          </div>

          <div>
            <div className="eyebrow" style={{marginBottom: 6}}>{t("event_type_label")}</div>
            <div className="row gap-2">
              <button onClick={() => setColor("brand")}
                      className={color === "brand" ? "chip brand" : "chip"}
                      style={{padding: "8px 14px"}}>{t("event_general")}</button>
              <button onClick={() => setColor("warn")}
                      className={color === "warn" ? "chip warn" : "chip"}
                      style={{padding: "8px 14px"}}>{t("event_important")}</button>
            </div>
          </div>
        </div>

        <div className="row" style={{padding: "14px 20px", borderTop: "1px solid var(--border)", justifyContent: "space-between", background: "var(--surface-2)"}}>
          <button className="btn btn-ghost" onClick={onClose}>{t("cancel")}</button>
          <button className="btn btn-primary" onClick={save}>
            <Icons.Check size={14}/>{t("add_to_cal")}
          </button>
        </div>
      </div>
    </div>
  );
}

function Agenda({ role }) {
  const { toast, t } = useApp();
  const [view, setView] = React.useState("week");
  const [selectedEvent, setSelectedEvent] = React.useState(null);
  const [addingEvent, setAddingEvent] = React.useState(false);
  const [events, setEvents] = React.useState(EVENTS_BASE);

  const isProf = role === "professeur";
  const isPar  = role === "parent";

  const visibleEvents = events.filter(e => {
    if (isProf) return e.classes === "all" || e.classes === "ce1";
    if (isPar)  return e.classes === "all" || e.classes === "ce1";
    return true;
  });

  const VIEWS = [
    { k: "day",   l: t("view_day")   },
    { k: "week",  l: t("view_week")  },
    { k: "month", l: t("view_month") },
    { k: "year",  l: t("view_year")  },
  ];

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("agenda_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{t("agenda_title")}</h1></div>}
        right={
          <>
            <div className="row gap-2 card" style={{padding: 4, borderRadius: 10}}>
              <button className="icon-btn" style={{border: "none", background: "transparent"}}><Icons.ChevL size={16}/></button>
              <button className="btn btn-ghost">{t("agenda_today")}</button>
              <button className="icon-btn" style={{border: "none", background: "transparent"}}><Icons.ChevR size={16}/></button>
            </div>
            <div className="tabs">
              {VIEWS.map(v => (
                <button key={v.k} className={view===v.k?"active":""} onClick={() => setView(v.k)}>{v.l}</button>
              ))}
            </div>
            {!isPar && (
              <button className="btn btn-primary" onClick={() => setAddingEvent(true)}>
                <Icons.Plus size={16}/>{t("agenda_new")}
              </button>
            )}
          </>
        }
      />

      {view === "day"   && <AgendaDay   events={visibleEvents} onEventClick={setSelectedEvent}/>}
      {view === "week"  && <AgendaWeek  events={visibleEvents} onEventClick={setSelectedEvent}/>}
      {view === "month" && <AgendaMonth events={visibleEvents} onEventClick={setSelectedEvent}/>}
      {view === "year"  && <AgendaYear  events={visibleEvents} onEventClick={setSelectedEvent}/>}

      {selectedEvent && (
        <EventDetailModal
          event={selectedEvent}
          onClose={() => setSelectedEvent(null)}
          canEdit={!isPar}
        />
      )}
      {addingEvent && (
        <AddEventModal
          onClose={() => setAddingEvent(false)}
          onSave={(evt) => {
            setEvents(es => [...es, evt]);
            toast("Événement ajouté : " + evt.title);
            setAddingEvent(false);
          }}
        />
      )}
    </div>
  );
}

// ============================================================ PARAMÈTRES
function Parametres() {
  const { toast, lang, setLang, t } = useApp();
  const [section, setSection] = React.useState("compte");
  const sections = [
    { k: "compte",  l: t("param_compte"),  icon: Icons.Settings },
    { k: "notifs",  l: t("param_notifs"),  icon: Icons.Bell },
    { k: "secu",    l: t("param_secu"),    icon: Icons.Check },
    { k: "billing", l: t("param_billing"), icon: Icons.Doc },
    { k: "team",    l: t("param_team"),    icon: Icons.Team },
    { k: "ia",      l: t("param_ia"),      icon: Icons.Sparkle },
  ];

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("settings_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{t("settings_title")}</h1></div>}
        right={<button className="btn btn-primary" onClick={() => toast("Modifications enregistrées")}><Icons.Check size={16}/>{t("save")}</button>}
      />

      <div className="row gap-5" style={{alignItems: "flex-start"}}>
        <div className="card" style={{width: 240, padding: 8, flexShrink: 0}}>
          {sections.map(s => (
            <button key={s.k} onClick={() => setSection(s.k)}
                    className="nav-item"
                    style={{
                      width: "100%",
                      background: section===s.k ? "var(--brand-soft)" : "transparent",
                      color: section===s.k ? "var(--brand-ink)" : "var(--ink-3)",
                      fontWeight: section===s.k ? 600 : 500,
                    }}>
              <s.icon size={16}/>{s.l}
            </button>
          ))}
        </div>

        <div className="col gap-5" style={{flex: 1, minWidth: 0}}>
          {section === "compte" && (
            <div className="card card-pad">
              <div className="h2" style={{marginBottom: 18}}>{t("account_title")}</div>
              <div className="row gap-4" style={{alignItems: "center", marginBottom: 20}}>
                <Photo src="https://i.pravatar.cc/120?img=48" size={72}/>
                <div className="col gap-2">
                  <button className="btn">{t("change_photo_btn")}</button>
                  <span className="meta">{t("photo_hint")}</span>
                </div>
              </div>
              <div className="row gap-4">
                <div style={{flex: 1}}><Input label={t("firstname_label")} value="Sophie"/></div>
                <div style={{flex: 1}}><Input label={t("lastname_label")} value="Marchand"/></div>
              </div>
              <div className="row gap-4">
                <div style={{flex: 1}}><Input label={t("email_pro_label")} value="sophie@tournesol.fr"/></div>
                <div style={{flex: 1}}><Input label={t("phone_pro_label")} value="06 12 34 56 78"/></div>
              </div>
              <Input label={t("title_input_label")} value="Directrice"/>
              <Field2 label={t("lang_label")}>
                <div className="row gap-2">
                  {[{code:"fr",label:"Français"},{code:"en",label:"English"},{code:"es",label:"Español"}].map(l => (
                    <button key={l.code}
                            onClick={() => setLang(l.code)}
                            className={lang===l.code ? "chip brand" : "chip"}
                            style={{padding: "8px 12px"}}>
                      {l.label}
                    </button>
                  ))}
                </div>
              </Field2>
            </div>
          )}

          {section === "notifs" && (
            <div className="card card-pad">
              <div className="h2" style={{marginBottom: 6}}>{t("notifs_title")}</div>
              <div className="meta" style={{marginBottom: 18}}>{t("notifs_sub")}</div>
              {[
                {l:"Nouvelles observations",     d:"Quand un enseignant ajoute une obs."},
                {l:"Inscriptions reçues",         d:"Nouveaux dossiers à traiter"},
                {l:"Messages parents",           d:"Réception immédiate"},
                {l:"Récap quotidien · 18h",       d:"Une seule notif par jour avec le résumé"},
                {l:"Récap hebdo IA · vendredi",   d:"Synthèse + brouillon d'annonce"},
              ].map((n, i) => (
                <div key={i} className="row gap-3" style={{padding:"14px 0", borderBottom:i<4?"1px solid var(--border)":"none", alignItems:"center"}}>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:600,color:"var(--ink)"}}>{n.l}</div>
                    <div className="meta">{n.d}</div>
                  </div>
                  <Toggle on={i!==2} onClick={() => toast("Préférence mise à jour")}/>
                </div>
              ))}
            </div>
          )}

          {section === "secu" && (
            <div className="card card-pad">
              <div className="h2" style={{marginBottom: 18}}>{t("secu_title")}</div>
              <div className="row" style={{padding:"16px 18px", border:"1px solid var(--border)", borderRadius:12, alignItems:"center", marginBottom:14}}>
                <div style={{flex:1}}>
                  <div style={{fontWeight:700,color:"var(--ink)"}}>{t("two_factor_label")}</div>
                  <div className="meta" style={{marginTop:2}}>{t("two_factor_sub")}</div>
                </div>
                <span className="chip brand"><span className="chip-dot"/>{t("active_chip_secu")}</span>
              </div>
              <div className="row gap-2" style={{marginBottom:18}}>
                <button className="btn" onClick={() => toast("Lien de réinitialisation envoyé")}>{t("change_pw")}</button>
                <button className="btn" onClick={() => toast("Sessions déconnectées")}>{t("disconnect_others")}</button>
              </div>
              <div className="eyebrow" style={{marginBottom:8}}>{t("active_sessions")}</div>
              <div className="col gap-2">
                {[
                  {d:"MacBook Pro · Safari",p:"Paris",t:"Maintenant",current:true},
                  {d:"iPhone 15 · App",p:"Paris",t:"il y a 2h"},
                  {d:"Windows · Chrome",p:"Lyon",t:"Hier"},
                ].map((s, i) => (
                  <div key={i} className="row gap-3" style={{padding:"12px 14px", border:"1px solid var(--border)", borderRadius:10, alignItems:"center"}}>
                    <div style={{flex:1}}>
                      <div style={{fontWeight:600,color:"var(--ink)"}}>{s.d}</div>
                      <div className="meta">{s.p} · {s.t}</div>
                    </div>
                    {s.current
                      ? <span className="chip brand">{t("this_session")}</span>
                      : <button className="btn btn-ghost" onClick={() => toast("Session déconnectée")}>{t("disconnect_btn")}</button>}
                  </div>
                ))}
              </div>
            </div>
          )}

          {section === "billing" && (
            <div className="card card-pad">
              <div className="h2" style={{marginBottom:18}}>{t("billing_title")}</div>
              <div style={{padding:20,background:"var(--brand-soft)",borderRadius:14,border:"1px solid var(--brand-soft-2)",marginBottom:18}}>
                <div className="row" style={{justifyContent:"space-between",alignItems:"flex-start"}}>
                  <div>
                    <div className="eyebrow" style={{color:"var(--brand-ink)"}}>{t("current_plan")}</div>
                    <div className="display" style={{fontSize:30,color:"var(--brand-ink)",marginTop:4}}>Scolia · École</div>
                    <div className="meta" style={{color:"var(--brand-ink)",opacity:.8,marginTop:4}}>4 classes · 26 élèves · facturation mensuelle</div>
                  </div>
                  <div style={{textAlign:"right"}}>
                    <div className="display" style={{fontSize:32,color:"var(--brand-ink)"}}>89€</div>
                    <div className="meta" style={{color:"var(--brand-ink)",opacity:.8}}>{t("per_month")}</div>
                  </div>
                </div>
                <div className="row gap-2" style={{marginTop:16}}>
                  <button className="btn" style={{background:"white",borderColor:"transparent"}}>{t("change_plan")}</button>
                  <button className="btn btn-ghost" style={{color:"var(--brand-ink)"}}>{t("see_usage")}</button>
                </div>
              </div>
              <div className="eyebrow" style={{marginBottom:8}}>{t("last_invoices")}</div>
              {[{m:"Mai 2026",a:"89,00 €"},{m:"Avril 2026",a:"89,00 €"},{m:"Mars 2026",a:"89,00 €"}].map((f,i) => (
                <div key={i} className="row gap-3" style={{padding:"12px 0",borderBottom:i<2?"1px solid var(--border)":"none",alignItems:"center"}}>
                  <Icons.Doc size={18} style={{color:"var(--ink-3)"}}/>
                  <div style={{flex:1,fontWeight:600,color:"var(--ink)"}}>{f.m}</div>
                  <div className="tnum" style={{fontWeight:700,color:"var(--ink)"}}>{f.a}</div>
                  <span className="chip brand">{t("paid_status")}</span>
                  <button className="btn btn-ghost" onClick={() => toast("PDF téléchargé")}>{t("download_btn")}</button>
                </div>
              ))}
            </div>
          )}

          {section === "team" && (
            <div className="card card-pad">
              <div className="row" style={{justifyContent:"space-between",alignItems:"center",marginBottom:14}}>
                <div className="h2">{t("team_title_param")}</div>
                <button className="btn btn-primary" onClick={() => toast("Invitation envoyée")}><Icons.Plus size={14}/>{t("invite_btn")}</button>
              </div>
              {window.SCOLIA.TEACHERS.map(tc => (
                <div key={tc.id} className="row gap-3" style={{padding:"14px 0",borderBottom:"1px solid var(--border)",alignItems:"center"}}>
                  <Photo src={tc.img} size={40}/>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:700,color:"var(--ink)"}}>{tc.name}</div>
                    <div className="meta">{tc.first.toLowerCase()}@tournesol.fr</div>
                  </div>
                  <span className="chip">{t("teacher_role_chip")}</span>
                  <button className="btn btn-ghost" onClick={() => toast("Permissions ouvertes")}>{t("permissions_btn_param")}</button>
                </div>
              ))}
              <div className="row gap-3" style={{padding:"14px 0",alignItems:"center"}}>
                <Photo src="https://i.pravatar.cc/120?img=48" size={40}/>
                <div style={{flex:1}}>
                  <div style={{fontWeight:700,color:"var(--ink)"}}>Sophie Marchand <span style={{color:"var(--brand)"}}>· toi</span></div>
                  <div className="meta">sophie@tournesol.fr</div>
                </div>
                <span className="chip brand">{t("direction_chip")}</span>
              </div>
            </div>
          )}

          {section === "ia" && (
            <div className="card card-pad">
              <div className="h2" style={{marginBottom:18}}>{t("ia_param_title")}</div>
              {[
                {l:"Brouillon d'annonces",         d:"Suggère un texte à partir d'un contexte court."},
                {l:"Synthèse hebdo automatique",   d:"Récap chaque vendredi : présence, paiements, alertes."},
                {l:"Pré-remplissage observations", d:"Suggère un texte d'obs. à partir de mots-clés."},
                {l:"Détection retards de paiement",d:"Brouillon de relance à un clic."},
              ].map((it, i) => (
                <div key={i} className="row gap-3" style={{padding:"14px 0",borderBottom:i<3?"1px solid var(--border)":"none",alignItems:"center"}}>
                  <div style={{flex:1}}>
                    <div style={{fontWeight:600,color:"var(--ink)"}}>{it.l}</div>
                    <div className="meta">{it.d}</div>
                  </div>
                  <Toggle on={i!==2} onClick={() => toast("Préférence IA mise à jour")}/>
                </div>
              ))}
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

// ============================================================ ANNONCES PAGE

function AnnoncesPage({ onNewAnnonce }) {
  const { toast, t } = useApp();
  const [annonces, setAnnonces] = React.useState(window.SCOLIA.ANNONCES);
  const [filter, setFilter] = React.useState("all");

  const visible = filter === "pinned" ? annonces.filter(a => a.pinned) : annonces;

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("annonces_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{t("annonces_title")}</h1></div>}
        right={
          <>
            <div className="tabs">
              <button className={filter==="all"?"active":""} onClick={() => setFilter("all")}>{t("tab_all_ann")} · {annonces.length}</button>
              <button className={filter==="pinned"?"active":""} onClick={() => setFilter("pinned")}>{t("tab_pinned_ann")}</button>
            </div>
            <button className="btn btn-primary" onClick={onNewAnnonce}>
              <Icons.Plus size={16}/>{t("new_annonce_btn")}
            </button>
          </>
        }
      />

      <div className="col gap-4">
        {visible.map(a => (
          <div key={a.id} className="card card-pad">
            <div className="row" style={{justifyContent: "space-between", alignItems: "flex-start", gap: 16}}>
              <div style={{flex: 1, minWidth: 0}}>
                {a.pinned && (
                  <div className="row gap-2" style={{alignItems: "center", marginBottom: 10}}>
                    <Icons.Pin size={13} style={{color: "var(--brand-ink)"}}/>
                    <span style={{fontSize: 11, fontWeight: 700, letterSpacing: ".08em", textTransform: "uppercase", color: "var(--brand-ink)"}}>{t("pinned_chip")}</span>
                  </div>
                )}
                <div style={{fontWeight: 700, color: "var(--ink)", fontSize: 18, marginBottom: 8}}>{a.title}</div>
                <div style={{color: "var(--ink-3)", fontSize: 14, lineHeight: 1.6, marginBottom: 16}}>{a.body}</div>
                <div className="row gap-3" style={{alignItems: "center"}}>
                  <span className="meta">{a.by}</span>
                  <span className="meta">·</span>
                  <span className="meta">{a.time}</span>
                  <span className="chip brand"><Icons.Eye size={12}/>{a.reads}/{a.total} lus</span>
                </div>
              </div>
              <DropMenu align="right"
                trigger={<button className="icon-btn"><Icons.Dots size={16}/></button>}
                items={[
                  {icon: Icons.Pin, label: a.pinned ? t("desepingler") : t("epingler"), onClick: () => toast(a.pinned ? "Désépinglée" : "Épinglée")},
                  {icon: Icons.Doc, label: t("export_ann"), onClick: () => toast("Annonce exportée")},
                  "-",
                  {icon: Icons.X, label: t("delete_ann"), danger: true,
                   onClick: () => setAnnonces(as => as.filter(x => x.id !== a.id))},
                ]}/>
            </div>
          </div>
        ))}
        {visible.length === 0 && (
          <div className="card card-pad" style={{textAlign: "center", padding: 56}}>
            <Icons.Megaphone size={32} style={{color: "var(--ink-5)", margin: "0 auto 14px", display: "block"}}/>
            <div className="h3" style={{marginBottom: 6}}>{t("no_annonce")}</div>
            <div className="meta">{t("no_annonce_sub")}</div>
            <button className="btn btn-primary" style={{margin: "18px auto 0", display: "inline-flex"}} onClick={onNewAnnonce}>
              <Icons.Plus size={14}/>{t("new_annonce_btn")}
            </button>
          </div>
        )}
      </div>
    </div>
  );
}

// ============================================================ VUE PARENT

function ParentChildView() {
  const { toast, t, lang } = useApp();
  const { TEACHERS, ANNONCES } = window.SCOLIA;
  const teacher = TEACHERS.find(tc => tc.id === "marie");
  const [tab, setTab] = React.useState("suivi");
  const loc = lang === "en" ? "en-US" : lang === "es" ? "es-ES" : "fr-FR";
  const agendaWeek = [
    {evts:[]},
    {evts:[{title:"Sortie médiathèque", h:"10h00", desc:"Départ 09h45, retour 11h45. Autorisation nécessaire."}]},
    {evts:[{title:"Photo de classe",    h:"09h00", desc:"Prévoir une tenue soignée."}]},
    {evts:[]},
    {evts:[{title:"Kermesse",           h:"09h00", desc:"Bienvenue à toutes les familles !"}]},
  ].map((d, i) => ({
    day: cap(new Date(2026, 4, DATES[i]).toLocaleDateString(loc, {weekday: "long", day: "numeric", month: "long"})),
    evts: d.evts,
  }));

  const child = { name: "Léo Martin", age: 7, classe: "CE1 Camélia", since: "sept. 2023" };

  const TABS = [
    { k: "suivi",    l: t("tab_suivi_parent")    },
    { k: "annonces", l: t("tab_annonces_parent") },
    { k: "agenda",   l: t("tab_agenda_parent")   },
  ];

  return (
    <div>
      <Topbar
        left={<div><div className="eyebrow">{t("parent_eyebrow")}</div><h1 className="h1" style={{marginTop:6}}>{child.name}</h1></div>}
        right={
          <button className="btn btn-primary" onClick={() => toast("Message envoyé à l'école")}>
            <Icons.Msg size={16}/>{t("parent_contact_btn")}
          </button>
        }
      />

      <div className="row gap-5" style={{alignItems: "flex-start"}}>
        {/* Carte enfant */}
        <div className="card card-pad" style={{width: 290, flexShrink: 0}}>
          <div style={{textAlign: "center", marginBottom: 20}}>
            <div style={{display: "flex", justifyContent: "center"}}>
              <Sketch id="leo" size={72}/>
            </div>
            <div className="h2" style={{marginTop: 14}}>{child.name}</div>
            <div className="meta" style={{marginTop: 4}}>{child.age} ans · {child.classe}</div>
            <div className="meta" style={{marginTop: 2}}>Scolarisé depuis {child.since}</div>
          </div>

          <div className="divider" style={{marginBottom: 16}}/>

          <div className="col gap-3" style={{marginBottom: 16}}>
            <div className="row" style={{justifyContent: "space-between", alignItems: "center"}}>
              <span className="meta">{t("present_today_label")}</span>
              <span className="status ok"><span className="dot"/>{t("present_status")}</span>
            </div>
            <div className="row" style={{justifyContent: "space-between", alignItems: "center"}}>
              <span className="meta">{t("teacher_role")}</span>
              <div className="row gap-2" style={{alignItems: "center"}}>
                <Photo src={teacher.img} size={22}/>
                <span style={{fontSize: 13, fontWeight: 600, color: "var(--ink)"}}>{teacher.first}</span>
              </div>
            </div>
            <div className="row" style={{justifyContent: "space-between", alignItems: "center"}}>
              <span className="meta">Classe</span>
              <span className="chip">{child.classe}</span>
            </div>
          </div>

          <div className="col gap-2">
            <button className="btn" style={{width: "100%", justifyContent: "center"}}
                    onClick={() => toast("Conversation ouverte avec l'école")}>
              <Icons.Msg size={14}/>{t("send_msg_btn")}
            </button>
            <button className="btn" style={{width: "100%", justifyContent: "center"}}
                    onClick={() => toast("Demande de RDV envoyée")}>
              <Icons.Cal size={14}/>{t("request_rdv_btn")}
            </button>
          </div>
        </div>

        {/* Panel onglets */}
        <div className="card" style={{flex: 1}}>
          <div style={{padding: "0 22px", borderBottom: "1px solid var(--border)", display: "flex", gap: 0}}>
            <div className="tabs" style={{marginTop: 16, marginBottom: -1}}>
              {TABS.map(tb => (
                <button key={tb.k} className={tab===tb.k?"active":""} onClick={() => setTab(tb.k)}>{tb.l}</button>
              ))}
            </div>
          </div>

          <div style={{padding: 24}}>
            {tab === "suivi" && (
              <div className="col gap-5">
                <div>
                  <div className="h3" style={{marginBottom: 14}}>{t("last_obs_parent")}</div>
                  <div className="col gap-3">
                    {[
                      { date: "Aujourd'hui · 14h30", by: "Marie Lambert", text: "Léo a pris la parole spontanément en regroupement. Vocabulaire précis, belle progression à l'oral." },
                      { date: "Hier · 10h15",        by: "Marie Lambert", text: "Excellente journée ! Léo a aidé un camarade en lecture — très belle initiative." },
                      { date: "15 mai",              by: "Marie Lambert", text: "Souhaite lire à voix haute — progrès notable en fluidité de lecture." },
                    ].map((e, i) => (
                      <div key={i} style={{padding:"14px 16px", borderLeft:"3px solid var(--brand)", background:"var(--surface-2)", borderRadius:"0 10px 10px 0"}}>
                        <div style={{fontSize:13.5,color:"var(--ink-2)",lineHeight:1.55,marginBottom:6}}>{e.text}</div>
                        <div className="meta">{e.date} · {e.by}</div>
                      </div>
                    ))}
                  </div>
                </div>

                <div>
                  <div className="h3" style={{marginBottom: 14}}>{t("skills_title")}</div>
                  <div className="col gap-3">
                    {[
                      {dom:"Lecture · décoder",   pct:80, lvl:"Acquis"},
                      {dom:"Maths · numération",  pct:65, lvl:"En cours"},
                      {dom:"Écriture · cursive",  pct:40, lvl:"À renforcer"},
                    ].map((comp, i) => (
                      <div key={i}>
                        <div className="row" style={{justifyContent:"space-between",alignItems:"baseline",marginBottom:6}}>
                          <div style={{fontSize:13.5,fontWeight:600,color:"var(--ink)"}}>{comp.dom}</div>
                          <div className="meta">{comp.lvl}</div>
                        </div>
                        <div className="pbar" style={{height:6}}>
                          <div className="ok" style={{
                            width:`${comp.pct}%`,
                            background:comp.pct>=70?"var(--brand)":comp.pct>=50?"var(--warn)":"var(--danger)",
                          }}/>
                        </div>
                      </div>
                    ))}
                  </div>
                </div>
              </div>
            )}

            {tab === "annonces" && (
              <div className="col gap-4">
                <div className="h3" style={{marginBottom: 6}}>{t("school_annonces_parent")}</div>
                {ANNONCES.map(a => (
                  <div key={a.id} style={{
                    padding: 16,
                    background: a.pinned ? "var(--brand-soft)" : "var(--surface-2)",
                    border: `1px solid ${a.pinned ? "var(--brand-soft-2)" : "var(--border)"}`,
                    borderRadius: 14,
                  }}>
                    {a.pinned && (
                      <div className="row gap-2" style={{alignItems:"center",marginBottom:8}}>
                        <Icons.Pin size={12} style={{color:"var(--brand-ink)"}}/>
                        <span style={{fontSize:10.5,fontWeight:700,letterSpacing:".08em",textTransform:"uppercase",color:"var(--brand-ink)"}}>{t("pinned")}</span>
                      </div>
                    )}
                    <div style={{fontWeight:700,color:"var(--ink)",marginBottom:6}}>{a.title}</div>
                    <div style={{fontSize:13.5,color:"var(--ink-3)",lineHeight:1.55,marginBottom:10}}>{a.body}</div>
                    <div className="meta">{a.by} · {a.time}</div>
                  </div>
                ))}
              </div>
            )}

            {tab === "agenda" && (
              <div className="col gap-3">
                <div className="h3" style={{marginBottom: 6}}>{t("week_agenda_parent")} — {child.classe}</div>
                {agendaWeek.map((d, i) => (
                  <div key={i} style={{padding:"12px 14px", border:"1px solid var(--border)", borderRadius:10}}>
                    <div style={{fontWeight:600,color:"var(--ink)",marginBottom:d.evts.length?8:0}}>{d.day}</div>
                    {d.evts.length === 0
                      ? <div className="meta">{t("no_event")}</div>
                      : d.evts.map((e, j) => (
                          <div key={j} style={{
                            padding:"8px 12px",
                            background:"var(--brand-soft)", borderRadius:8,
                            borderLeft:"3px solid var(--brand)",
                          }}>
                            <div style={{fontWeight:700,color:"var(--brand-ink)",fontSize:13}}>{e.title}</div>
                            <div className="meta" style={{marginTop:2}}>{e.h} · {e.desc}</div>
                          </div>
                        ))
                    }
                  </div>
                ))}
              </div>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.Conversations   = Conversations;
window.Inscriptions    = Inscriptions;
window.Agenda          = Agenda;
window.Parametres      = Parametres;
window.AnnoncesPage    = AnnoncesPage;
window.ParentChildView = ParentChildView;
