/* GUIDKO App — transversal layer: ⌘K command palette + notifications center.
   Mounted globally in AppShell so every role gets it. */

// ---------- Notifications (per-role, some derived from store) ----------
function notificationsFor(role, state, t) {
  const base = {
    gerant: [
      { icon: "€", tone: "signal", title: t("Paiement reçu — Léa Mercier","Payment received — Léa Mercier"), sub: "210 € · " + t("il y a 12 min","12 min ago"), to: "/gerant/finance" },
      { icon: "⇄", tone: "flame", title: t("3 leads sur ta marketplace","3 leads on your marketplace"), sub: t("Peugeot 208 · il y a 1 h","Peugeot 208 · 1 h ago"), to: "/gerant/vehicles" },
      { icon: "★", tone: "sky", title: t("Nouvel élève inscrit","New student enrolled"), sub: "Manon Girard · " + t("aujourd'hui","today"), to: "/gerant/students" },
      { icon: "▼", tone: "danger", title: t("19 créneaux vides cette semaine","19 empty slots this week"), sub: t("Manque à gagner estimé 1 240 €","Est. lost revenue €1,240"), to: "/gerant/planning" },
    ],
    accueil: [
      { icon: "✎", tone: "flame", title: t("2 dossiers à valider","2 files to validate"), sub: t("Manon Girard, Julien Pré","Manon Girard, Julien Pré"), to: "/accueil/enroll" },
      { icon: "◎", tone: "sky", title: t("Manon Girard arrive à 09:30","Manon Girard arriving 09:30"), sub: t("Signature contrat","Contract signing"), to: "/accueil/overview" },
      { icon: "✆", tone: "neutral", title: t("3 appels à rappeler","3 calls to return"), sub: t("File d'attente","Queue"), to: "/accueil/overview" },
    ],
    moniteur: [
      { icon: "◎", tone: "flame", title: t("Prochain cours dans 32 min","Next lesson in 32 min"), sub: "Tom Vasseur · Manœuvres", to: "/moniteur/overview" },
      { icon: "✉", tone: "sky", title: t("Message de Léa Mercier","Message from Léa Mercier"), sub: t("« Je suis sur place ! »","\"I'm here!\""), to: "/moniteur/overview" },
      { icon: "€", tone: "signal", title: t("Virement prévu le 31 mars","Payout on Mar 31"), sub: "2 840 €", to: "/moniteur/earnings" },
    ],
    eleve: [
      { icon: "▤", tone: "flame", title: t("Cours demain à 10:00","Lesson tomorrow at 10:00"), sub: t("B-route avec Marc","B-road with Marc"), to: "/eleve/overview" },
      { icon: "✉", tone: "sky", title: t("Marc t'a envoyé un message","Marc sent you a message"), sub: t("« À tout de suite ! »","\"See you soon!\""), to: "/eleve/messages" },
      { icon: "★", tone: "signal", title: t("Score code : 36/40","Code score: 36/40"), sub: t("Continue comme ça !","Keep it up!"), to: "/eleve/code" },
      { icon: "€", tone: "neutral", title: t("Mensualité due le 5","Installment due on 5th"), sub: "210 €", to: "/eleve/profile" },
    ],
  };
  return base[role] || [];
}

function NotificationsPanel({ role, navigate, onClose }) {
  const C = GK.colors;
  const { t } = useI18n();
  const store = useStore();
  const [read, setRead] = React.useState({});
  const items = notificationsFor(role, store.state, t);
  const toneColor = { signal: C.signal, flame: C.flame, sky: C.sky, danger: C.danger, neutral: C.slate };

  return (
    <div style={{ position: "fixed", top: 56, right: 18, width: 360, maxHeight: "80vh", overflow: "hidden", background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 14, boxShadow: "0 20px 60px rgba(11,15,31,0.22)", zIndex: 600, display: "flex", flexDirection: "column", animation: "gkModalIn .18s ease" }}>
      <div style={{ padding: "16px 18px", borderBottom: `1px solid ${C.softLine}`, display: "flex", justifyContent: "space-between", alignItems: "center" }}>
        <div style={{ fontFamily: "'Instrument Serif', serif", fontSize: 22 }}>{t("Notifications","Notifications")}</div>
        <button onClick={() => setRead(Object.fromEntries(items.map((_, i) => [i, true])))} style={{ background: "none", border: "none", color: C.flame, fontSize: 12, cursor: "pointer" }}>{t("Tout marquer lu","Mark all read")}</button>
      </div>
      <div className="gk-scroll" style={{ overflowY: "auto" }}>
        {items.map((n, i) => (
          <div key={i} onClick={() => { setRead(r => ({ ...r, [i]: true })); navigate(n.to); onClose(); }} style={{ display: "flex", gap: 12, padding: "13px 18px", borderBottom: `1px solid ${C.softLine}`, cursor: "pointer", background: read[i] ? "transparent" : "#FFFBF5" }}
            onMouseEnter={e => e.currentTarget.style.background = "#FBF8EE"} onMouseLeave={e => e.currentTarget.style.background = read[i] ? "transparent" : "#FFFBF5"}>
            <div style={{ width: 34, height: 34, borderRadius: 9, background: toneColor[n.tone] + "1A", color: toneColor[n.tone], display: "grid", placeItems: "center", fontSize: 15, flexShrink: 0 }}>{n.icon}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 13.5, fontWeight: 600, lineHeight: 1.3 }}>{n.title}</div>
              <div style={{ fontSize: 12, color: C.slate, marginTop: 2 }}>{n.sub}</div>
            </div>
            {!read[i] && <span style={{ width: 8, height: 8, borderRadius: 999, background: C.flame, flexShrink: 0, marginTop: 6 }}/>}
          </div>
        ))}
      </div>
      <div style={{ padding: "10px 18px", borderTop: `1px solid ${C.softLine}`, textAlign: "center" }}>
        <span style={{ fontSize: 12, color: C.slate }}>{t("Tu es à jour ✓","You're all caught up ✓")}</span>
      </div>
    </div>
  );
}

// ---------- Command Palette (⌘K) ----------
function CommandPalette({ role, navigate, onClose }) {
  const C = GK.colors;
  const { t, lang } = useI18n();
  const store = useStore();
  const [q, setQ] = React.useState("");
  const inputRef = React.useRef(null);
  React.useEffect(() => { inputRef.current?.focus(); }, []);

  // Build command set: role nav + entities + cross-app jumps
  const cfg = ROLES[role];
  const navCmds = (cfg ? cfg.nav : []).map(n => ({ type: t("Aller à","Go to"), label: n[lang], icon: n.g, to: `/${role}/${n.k}` }));
  const studentCmds = store.state.students.map(s => ({ type: t("Élève","Student"), label: s.name, icon: "★", to: role === "eleve" ? "/eleve/overview" : `/${role === "moniteur" ? "moniteur" : role === "accueil" ? "accueil" : "gerant"}/students` }));
  const vehicleCmds = store.state.vehicles.slice(0, 6).map(v => ({ type: t("Véhicule","Vehicle"), label: `${v.brand} ${v.model}`, icon: "⇄", to: `/${role}/vehicles` }));
  const appCmds = [
    { type: t("Application","App"), label: t("Marché Mobilité","Mobility Market"), icon: "⇄", to: "/auto/market" },
    { type: t("Application","App"), label: t("Changer d'application","Switch app"), icon: "⇆", to: "/login" },
  ];
  const all = [...navCmds, ...appCmds, ...studentCmds, ...vehicleCmds];
  const filtered = q.trim() ? all.filter(c => (c.label + " " + c.type).toLowerCase().includes(q.toLowerCase())) : all.slice(0, 8);

  return (
    <div onClick={onClose} style={{ position: "fixed", inset: 0, background: "rgba(11,15,31,0.4)", backdropFilter: "blur(3px)", zIndex: 8000, display: "flex", justifyContent: "center", alignItems: "flex-start", paddingTop: "12vh", animation: "gkFadeIn .12s ease" }}>
      <div onClick={e => e.stopPropagation()} style={{ width: 560, maxWidth: "92%", background: C.paper, borderRadius: 14, border: `1px solid ${C.softLine}`, boxShadow: "0 30px 80px rgba(0,0,0,0.35)", overflow: "hidden", animation: "gkModalIn .16s ease" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "16px 18px", borderBottom: `1px solid ${C.softLine}` }}>
          <span style={{ color: C.slate, fontSize: 18 }}>⌕</span>
          <input ref={inputRef} value={q} onChange={e => setQ(e.target.value)} placeholder={t("Rechercher une page, un élève, un véhicule…","Search a page, student, vehicle…")}
            onKeyDown={e => { if (e.key === "Escape") onClose(); if (e.key === "Enter" && filtered[0]) { navigate(filtered[0].to); onClose(); } }}
            style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontSize: 16, fontFamily: "'Geist', sans-serif", color: C.ink }}/>
          <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, padding: "3px 7px", background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 5, color: C.slate }}>ESC</span>
        </div>
        <div className="gk-scroll" style={{ maxHeight: 380, overflowY: "auto", padding: 8 }}>
          {filtered.length === 0 && <div style={{ padding: 30, textAlign: "center", color: C.slate, fontSize: 14 }}>{t("Aucun résultat","No results")}</div>}
          {filtered.map((c, i) => (
            <div key={i} onClick={() => { navigate(c.to); onClose(); }} style={{ display: "flex", alignItems: "center", gap: 12, padding: "11px 12px", borderRadius: 9, cursor: "pointer" }}
              onMouseEnter={e => e.currentTarget.style.background = "#fff"} onMouseLeave={e => e.currentTarget.style.background = "transparent"}>
              <div style={{ width: 30, height: 30, borderRadius: 8, background: "#fff", border: `1px solid ${C.softLine}`, display: "grid", placeItems: "center", fontSize: 14, color: C.ink }}>{c.icon}</div>
              <span style={{ flex: 1, fontSize: 14, fontWeight: 500 }}>{c.label}</span>
              <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, letterSpacing: "0.1em", color: C.slate, textTransform: "uppercase" }}>{c.type}</span>
            </div>
          ))}
        </div>
        <div style={{ padding: "10px 18px", borderTop: `1px solid ${C.softLine}`, display: "flex", gap: 16, fontSize: 11, color: C.slate, fontFamily: "'Geist Mono', monospace" }}>
          <span>↵ {t("OUVRIR","OPEN")}</span><span>ESC {t("FERMER","CLOSE")}</span><span style={{ marginLeft: "auto" }}>GUIDKO ⌘K</span>
        </div>
      </div>
    </div>
  );
}

// ---------- Toolbar mounted in AppShell (bell + ⌘K trigger) ----------
function TransversalToolbar({ role, navigate }) {
  const C = GK.colors;
  const { t } = useI18n();
  const [cmd, setCmd] = React.useState(false);
  const [notif, setNotif] = React.useState(false);
  const unread = notificationsFor(role, {}, t).length;

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setCmd(true); }
    };
    const onCmd = () => setCmd(true);
    window.addEventListener("keydown", onKey);
    window.addEventListener("gk-cmdk", onCmd);
    return () => { window.removeEventListener("keydown", onKey); window.removeEventListener("gk-cmdk", onCmd); };
  }, []);

  return (
    <>
      <div style={{ position: "fixed", top: 14, right: 92, zIndex: 600, display: "flex", gap: 8 }}>
        <button onClick={() => window.dispatchEvent(new CustomEvent("gk-cmdk"))} title="⌘K" style={{ display: "flex", alignItems: "center", gap: 8, height: 34, padding: "0 12px", background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 999, cursor: "pointer", color: C.slate, fontSize: 13, boxShadow: "0 2px 12px rgba(0,0,0,0.06)" }}>
          ⌕ <span style={{ fontFamily: "'Geist Mono', monospace", fontSize: 10, padding: "2px 6px", background: C.paper, borderRadius: 4 }}>⌘K</span>
        </button>
        <button onClick={() => setNotif(n => !n)} style={{ position: "relative", width: 34, height: 34, background: "#fff", border: `1px solid ${C.softLine}`, borderRadius: 999, cursor: "pointer", fontSize: 14, boxShadow: "0 2px 12px rgba(0,0,0,0.06)" }}>
          🔔
          {unread > 0 && <span style={{ position: "absolute", top: -3, right: -3, minWidth: 16, height: 16, padding: "0 4px", background: C.flame, color: "#fff", borderRadius: 999, fontSize: 10, fontWeight: 700, display: "grid", placeItems: "center", border: "2px solid " + C.paper }}>{unread}</span>}
        </button>
      </div>
      {cmd && <CommandPalette role={role} navigate={navigate} onClose={() => setCmd(false)}/>}
      {notif && <NotificationsPanel role={role} navigate={navigate} onClose={() => setNotif(false)}/>}
    </>
  );
}

window.TransversalToolbar = TransversalToolbar;
