/* Messages — real-time team chat (DM + channels) with deep-link mentions.

   Storage model:
     - localStorage["kcc:current_user"]      = "clarens" | "kevin" | "carly"
     - localStorage["kcc:messages"]          = JSON [{ id, channel, from, text, ts }]
     - localStorage["kcc:typing"]            = JSON { channel, who, ts }

   Cross-tab "live" is handled via the `storage` event — open the app in two
   tabs and switch user in each, and messages flow between them in real time. */

const NAV_LINKS = {
  // canonical → { label, page }
  "annuaire":      { label: "Annuaire fournisseurs", page: "supplier" },
  "fournisseurs":  { label: "Annuaire fournisseurs", page: "supplier" },
  "fournisseur":   { label: "Annuaire fournisseurs", page: "supplier" },
  "dashboard":     { label: "Dashboard",             page: "dashboard" },
  "tableau":       { label: "Dashboard",             page: "dashboard" },
  "recherche":     { label: "Recherche produits",    page: "research" },
  "produits":      { label: "Recherche produits",    page: "research" },
  "catalogue":     { label: "Recherche produits",    page: "research" },
  "profitcalc":    { label: "ProfitCalcPro",         page: "profit-calc" },
  "calc":          { label: "ProfitCalcPro",         page: "profit-calc" },
  "marges":        { label: "ProfitCalcPro",         page: "profit-calc" },
  "finance":       { label: "Finances",              page: "finance" },
  "finances":      { label: "Finances",              page: "finance" },
  "calendrier":    { label: "Calendrier",            page: "calendar" },
  "agenda":        { label: "Calendrier",            page: "calendar" },
  "alertes":       { label: "Alertes sourcing",      page: "alerts" },
  "jarvis":        { label: "JARVIS",                page: "jarvis" },
  "paramètres":    { label: "Paramètres",            page: "settings" },
  "settings":      { label: "Paramètres",            page: "settings" },
  "messages":      { label: "Messages",              page: "messages" },
  "digest":        { label: "Daily Digest",          page: "email" },
  "email":         { label: "Daily Digest",          page: "email" },
};

const SEED_MESSAGES = [
  { id: "m1", channel: "team",         from: "kevin",   text: "Bonjour l'équipe — petit point sourcing : [fournisseurs] Foshan Auto Trim accumule 14j de retard sur la dernière PO. On évalue les options.", ts: Date.now() - 1000*60*60*5 },
  { id: "m2", channel: "team",         from: "carly",   text: "OK noté. J'ai 3 candidats remplaçants validés sur la [recherche] — catégorie Auto, marges 26-31%.", ts: Date.now() - 1000*60*60*4 },
  { id: "m3", channel: "team",         from: "clarens", text: "Parfait. Carly, peux-tu drop les ASIN ici ? Je veux faire tourner le [calc] avant d'engager une RFQ.", ts: Date.now() - 1000*60*60*3 },
  { id: "m4", channel: "team",         from: "carly",   text: "B07KQ4F2L9 · B08NMR2X3D · B09L8YHT2P · tous BSR < 4k.", ts: Date.now() - 1000*60*60*3 + 60000 },
  { id: "m5", channel: "dm:clarens-kevin", from: "clarens", text: "Kevin, on parle de Hangzhou BambooLine demain matin ? Je veux pousser pour MOQ 150 avant de signer.", ts: Date.now() - 1000*60*60*2 },
  { id: "m6", channel: "dm:clarens-kevin", from: "kevin",   text: "Yes 9h. J'ai déjà sondé Lin Mei, elle est ouverte à 175 si on commit Q3.", ts: Date.now() - 1000*60*60*2 + 120000 },
  { id: "m7", channel: "dm:clarens-carly", from: "carly",   text: "Le [digest] de demain devrait inclure le résultat de l'audit lot 240429-AROM. Je l'ai posté dans le [dashboard].", ts: Date.now() - 1000*60*30 },
  { id: "m8", channel: "team",         from: "kevin",   text: "PS : check le [calendrier] — j'ai déplacé la review Q2 au mardi 18.", ts: Date.now() - 1000*60*8 },
];

const CHANNELS = [
  { id: "team",                    name: "#équipe-kcc",       members: ["clarens", "kevin", "carly"], kind: "channel" },
  { id: "alerts",                  name: "#alertes",          members: ["clarens", "kevin", "carly"], kind: "channel", desc: "Auto · JARVIS poste les alertes critiques ici" },
  { id: "dm:clarens-kevin",        name: "Kevin",             members: ["clarens", "kevin"],          kind: "dm" },
  { id: "dm:clarens-carly",        name: "Carly",             members: ["clarens", "carly"],          kind: "dm" },
  { id: "dm:kevin-carly",          name: "Kevin · Carly",     members: ["kevin", "carly"],            kind: "dm" },
];

const userColor = (u) => ({ clarens: "var(--user-clarens)", kevin: "var(--user-kevin)", carly: "var(--user-carly)" }[u]);
const userName = (u) => ({ clarens: "Clarens", kevin: "Kevin", carly: "Carly" }[u] || u);

// Parse text with [token] and @page mentions → tokens we can render as buttons
const parseMessage = (text) => {
  const parts = [];
  let last = 0;
  const re = /\[([^\]\n]+)\]|@(\w+)/g;
  let m;
  while ((m = re.exec(text)) !== null) {
    if (m.index > last) parts.push({ type: "text", value: text.slice(last, m.index) });
    const raw = (m[1] || m[2]).trim().toLowerCase();
    const link = NAV_LINKS[raw];
    if (link) parts.push({ type: "link", value: m[1] || m[2], page: link.page, label: link.label });
    else parts.push({ type: "text", value: m[0] });
    last = re.lastIndex;
  }
  if (last < text.length) parts.push({ type: "text", value: text.slice(last) });
  return parts;
};

// ── Local store helpers (with cross-tab sync) ────────────────────────
const KCC_USER_KEY = "kcc:current_user";
const KCC_MSGS_KEY = "kcc:messages";

const getCurrentUser = () => localStorage.getItem(KCC_USER_KEY) || "clarens";
const setCurrentUser = (u) => { localStorage.setItem(KCC_USER_KEY, u); window.dispatchEvent(new Event("kcc:user-change")); };

const loadMessages = () => {
  try {
    const raw = localStorage.getItem(KCC_MSGS_KEY);
    if (!raw) {
      localStorage.setItem(KCC_MSGS_KEY, JSON.stringify(SEED_MESSAGES));
      return SEED_MESSAGES;
    }
    return JSON.parse(raw);
  } catch { return SEED_MESSAGES; }
};

const saveMessages = (arr) => localStorage.setItem(KCC_MSGS_KEY, JSON.stringify(arr));

// ── Hook: subscribe to messages with live cross-tab sync ─────────────
const useMessages = () => {
  const [messages, setMessages] = useState(loadMessages);
  useEffect(() => {
    const onStorage = (e) => {
      if (e.key === KCC_MSGS_KEY) setMessages(loadMessages());
    };
    window.addEventListener("storage", onStorage);
    return () => window.removeEventListener("storage", onStorage);
  }, []);
  const send = (channel, from, text) => {
    const msg = { id: "m-" + Date.now() + Math.random().toString(36).slice(2, 6), channel, from, text, ts: Date.now() };
    const next = [...loadMessages(), msg];
    saveMessages(next);
    setMessages(next);
  };
  return [messages, send];
};

// Use the global useCurrentUser from data.jsx (returns user object).
// Wrap to return [stringId, setter] for messages.jsx internals.
const useCurrentUserMsgs = () => {
  const globalHook = window.__kccUseCurrentUserObj;
  if (globalHook) {
    const [u, setU] = globalHook();
    return [typeof u === "string" ? u : u?.id || "clarens", (uid) => setU(uid)];
  }
  // Fallback if data.jsx hook unavailable
  const [user, setUser] = useState(getCurrentUser);
  useEffect(() => {
    const onChange = () => setUser(getCurrentUser());
    window.addEventListener("kcc:user-change", onChange);
    window.addEventListener("storage", (e) => { if (e.key === KCC_USER_KEY) onChange(); });
    return () => window.removeEventListener("kcc:user-change", onChange);
  }, []);
  return [user, (u) => { setCurrentUser(u); setUser(u); }];
};

const fmtTs = (ts) => {
  const d = new Date(ts);
  const today = new Date(); today.setHours(0,0,0,0);
  const msgDay = new Date(ts); msgDay.setHours(0,0,0,0);
  const diffDays = Math.round((today - msgDay) / (1000 * 60 * 60 * 24));
  const time = d.toLocaleTimeString("fr-CA", { hour: "2-digit", minute: "2-digit" });
  if (diffDays === 0) return time;
  if (diffDays === 1) return "Hier · " + time;
  if (diffDays < 7) return d.toLocaleDateString("fr-CA", { weekday: "short" }) + " · " + time;
  return d.toLocaleDateString("fr-CA", { day: "numeric", month: "short" }) + " · " + time;
};

const fmtRelative = (ts) => {
  const sec = Math.round((Date.now() - ts) / 1000);
  if (sec < 60) return "à l'instant";
  if (sec < 3600) return Math.round(sec/60) + "min";
  if (sec < 86400) return Math.round(sec/3600) + "h";
  return Math.round(sec/86400) + "j";
};

// ─────────────────────────────────────────────────────────────────────
const Messages = ({ onNavigate }) => {
  const toast = useToast();
  const [user, setUser] = useCurrentUserMsgs();
  const [messages, send] = useMessages();
  const [channelId, setChannelId] = useState("team");
  const [input, setInput] = useState("");
  const [showHint, setShowHint] = useState(false);
  const scrollRef = useRef(null);
  const inputRef = useRef(null);

  const visibleChannels = CHANNELS.filter((c) => c.members.includes(user));
  const channel = visibleChannels.find((c) => c.id === channelId) || visibleChannels[0];
  const thread = messages.filter((m) => m.channel === channel.id).sort((a, b) => a.ts - b.ts);

  // Online presence — random but stable
  const presence = { clarens: "online", kevin: "online", carly: "away" };

  useEffect(() => {
    scrollRef.current?.scrollTo({ top: scrollRef.current.scrollHeight });
  }, [thread.length, channelId]);

  const submit = () => {
    const text = input.trim();
    if (!text) return;
    send(channel.id, user, text);
    setInput("");
    setTimeout(() => inputRef.current?.focus(), 0);
  };

  // Detect open [ to surface hint dropdown
  useEffect(() => {
    const open = /\[[\w\sàâçéèêëîïôûùüÿ]*$/i.test(input);
    setShowHint(open);
  }, [input]);

  const linkSuggestions = Object.entries(NAV_LINKS)
    .map(([k, v]) => ({ token: k, label: v.label }))
    .filter((s, i, arr) => arr.findIndex(x => x.label === s.label) === i)
    .slice(0, 8);

  const insertToken = (tok) => {
    const stripped = input.replace(/\[[\w\sàâçéèêëîïôûùüÿ]*$/i, "");
    setInput(stripped + "[" + tok + "] ");
    inputRef.current?.focus();
  };

  const renderText = (m) => {
    const parts = parseMessage(m.text);
    return parts.map((p, i) => {
      if (p.type === "link") {
        return (
          <button key={i} onClick={() => { onNavigate(p.page); toast({ message: `→ ${p.label}`, tone: "blue" }); }}
            style={{
              display: "inline-flex", alignItems: "center", gap: 4,
              padding: "1px 7px", margin: "0 1px",
              background: "var(--accent-soft)",
              color: "var(--accent)",
              border: "1px solid color-mix(in oklch, var(--accent) 30%, transparent)",
              borderRadius: 999, fontSize: "0.92em", fontWeight: 500,
              cursor: "pointer", verticalAlign: "baseline",
            }}>
            <Icon name="link" size={10}/> {p.label}
          </button>
        );
      }
      return <span key={i}>{p.value}</span>;
    });
  };

  // Unread counter (simple: messages from someone else within last 24h)
  const unreadFor = (chId) => {
    const last24 = Date.now() - 24*60*60*1000;
    return messages.filter(m => m.channel === chId && m.from !== user && m.ts > last24).length;
  };

  return (
    <div style={{ display: "grid", gridTemplateColumns: "260px 1fr", height: "100%", minHeight: 0 }}>
      {/* Channels list */}
      <div style={{ borderRight: "1px solid var(--border-subtle)", display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <div style={{ padding: "14px 16px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ fontSize: 15, fontWeight: 600 }}>Messages</div>
          <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>3 partenaires · live sync</div>
        </div>

        {/* Account switcher */}
        <div style={{ padding: "10px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
          <div style={{ fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 500, marginBottom: 6 }}>Connecté en tant que</div>
          <div style={{ display: "flex", gap: 4, background: "var(--bg-2)", borderRadius: 6, padding: 3 }}>
            {USERS.map((u) => (
              <button key={u.id} onClick={() => { setUser(u.id); toast({ message: `Compte → ${u.name}`, tone: "blue" }); }} style={{
                flex: 1, padding: "5px 0", borderRadius: 4, fontSize: 11.5,
                background: user === u.id ? "var(--bg-4)" : "transparent",
                color: user === u.id ? "var(--text)" : "var(--text-dim)",
                fontWeight: user === u.id ? 600 : 400,
                border: "none", cursor: "pointer",
                display: "inline-flex", alignItems: "center", justifyContent: "center", gap: 5,
              }}>
                <Avatar user={u.id} size="sm"/>
                {u.name}
              </button>
            ))}
          </div>
          <div className="mono" style={{ marginTop: 8, fontSize: 10, color: "var(--text-faint)" }}>
            Astuce : ouvrez le portail dans 2 onglets, changez de compte → sync temps réel.
          </div>
        </div>

        <div style={{ flex: 1, overflow: "auto", padding: "8px 6px" }}>
          {(() => {
            const sections = [
              ["Canaux",     visibleChannels.filter(c => c.kind === "channel")],
              ["Messages directs", visibleChannels.filter(c => c.kind === "dm")],
            ];
            return sections.map(([title, items]) => (
              <div key={title} style={{ marginBottom: 10 }}>
                <div style={{ padding: "6px 10px 4px", fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 500 }}>{title}</div>
                {items.map((c) => {
                  const isActive = c.id === channelId;
                  const other = c.members.find((u) => u !== user);
                  const unread = unreadFor(c.id);
                  return (
                    <div key={c.id} onClick={() => setChannelId(c.id)} style={{
                      display: "flex", alignItems: "center", gap: 8,
                      padding: "6px 10px", margin: "1px 0", borderRadius: 6,
                      background: isActive ? "var(--bg-3)" : "transparent",
                      color: isActive ? "var(--text)" : "var(--text-muted)",
                      cursor: "pointer", fontSize: 12.5,
                    }}>
                      {c.kind === "channel"
                        ? <span style={{ width: 18, textAlign: "center", color: "var(--text-faint)", fontSize: 13 }}>#</span>
                        : <span style={{ position: "relative" }}>
                            <Avatar user={other} size="sm"/>
                            <span style={{ position: "absolute", bottom: -1, right: -1, width: 7, height: 7, borderRadius: 999, background: presence[other] === "online" ? "var(--green)" : "var(--amber)", border: "1.5px solid var(--bg-1)" }}/>
                          </span>}
                      <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", fontWeight: isActive ? 600 : 450 }}>{c.kind === "channel" ? c.name.replace("#", "") : userName(other)}</span>
                      {unread > 0 && <span style={{
                        minWidth: 18, height: 16, padding: "0 5px", borderRadius: 999,
                        background: "var(--accent)", color: "#0a0d12",
                        fontSize: 10, fontWeight: 700, textAlign: "center",
                        display: "inline-flex", alignItems: "center", justifyContent: "center",
                      }}>{unread}</span>}
                    </div>
                  );
                })}
              </div>
            ));
          })()}
        </div>
      </div>

      {/* Thread */}
      <div style={{ display: "flex", flexDirection: "column", minHeight: 0 }}>
        {/* Header */}
        <div style={{ padding: "12px 18px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
          <div style={{ flex: 1, minWidth: 0 }}>
            <div className="row" style={{ gap: 8 }}>
              <span style={{ fontSize: 14, fontWeight: 600 }}>
                {channel.kind === "channel" ? channel.name : userName(channel.members.find((u) => u !== user))}
              </span>
              {channel.kind === "channel"
                ? <Badge tone="muted">{channel.members.length} membres</Badge>
                : <Badge tone={presence[channel.members.find((u) => u !== user)] === "online" ? "green" : "amber"} dot>{presence[channel.members.find((u) => u !== user)] === "online" ? "en ligne" : "absent"}</Badge>}
            </div>
            {channel.desc && <div style={{ fontSize: 11.5, color: "var(--text-dim)", marginTop: 2 }}>{channel.desc}</div>}
          </div>
          <button className="icon-btn" title="Recherche"><Icon name="search" size={14}/></button>
          <button className="icon-btn" title="Plus"><Icon name="moreH" size={14}/></button>
        </div>

        {/* Messages */}
        <div ref={scrollRef} style={{ flex: 1, overflow: "auto", padding: "16px 0" }}>
          <div style={{ maxWidth: 820, margin: "0 auto", padding: "0 18px" }}>
            {thread.length === 0 && (
              <div style={{ textAlign: "center", padding: 40, color: "var(--text-dim)", fontSize: 13 }}>
                Aucun message · soyez le premier à écrire.
              </div>
            )}
            {thread.map((m, i) => {
              const prev = thread[i - 1];
              const showHead = !prev || prev.from !== m.from || (m.ts - prev.ts) > 5 * 60 * 1000;
              const isSelf = m.from === user;
              return (
                <div key={m.id} style={{ display: "flex", gap: 10, marginTop: showHead ? 12 : 2 }}>
                  <div style={{ width: 28, flexShrink: 0 }}>
                    {showHead && <Avatar user={m.from} size="sm"/>}
                  </div>
                  <div style={{ flex: 1, minWidth: 0 }}>
                    {showHead && (
                      <div className="row" style={{ gap: 8, marginBottom: 2 }}>
                        <span style={{ fontSize: 12.5, fontWeight: 600, color: userColor(m.from) }}>{userName(m.from)}</span>
                        <span className="mono" style={{ fontSize: 10.5, color: "var(--text-faint)" }}>{fmtTs(m.ts)}</span>
                        {isSelf && <span style={{ fontSize: 10, color: "var(--text-faint)" }}>(vous)</span>}
                      </div>
                    )}
                    <div style={{ fontSize: 13, lineHeight: 1.55, wordBreak: "break-word" }}>
                      {renderText(m)}
                    </div>
                  </div>
                </div>
              );
            })}
          </div>
        </div>

        {/* Input */}
        <div style={{ padding: "10px 18px 14px", borderTop: "1px solid var(--border-subtle)" }}>
          <div style={{ maxWidth: 820, margin: "0 auto" }}>
            <div style={{ position: "relative" }}>
              {showHint && (
                <div style={{
                  position: "absolute", bottom: "calc(100% + 6px)", left: 0,
                  background: "var(--bg-2)", border: "1px solid var(--border)",
                  borderRadius: 8, padding: 4, minWidth: 240,
                  boxShadow: "var(--shadow-pop)", zIndex: 5,
                }}>
                  <div style={{ padding: "6px 8px", fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".08em" }}>
                    Insérer un lien · navigue automatiquement
                  </div>
                  {linkSuggestions.map((s) => (
                    <button key={s.token} onClick={() => insertToken(s.token)} style={{
                      display: "flex", alignItems: "center", gap: 8, width: "100%",
                      padding: "6px 8px", borderRadius: 4,
                      background: "transparent", border: "none",
                      color: "var(--text)", fontSize: 12, cursor: "pointer", textAlign: "left",
                    }}
                    onMouseEnter={(e) => e.currentTarget.style.background = "var(--bg-3)"}
                    onMouseLeave={(e) => e.currentTarget.style.background = "transparent"}>
                      <Icon name="link" size={11} style={{ color: "var(--accent)" }}/>
                      <span className="mono" style={{ fontSize: 11, color: "var(--text-dim)" }}>[{s.token}]</span>
                      <span style={{ marginLeft: "auto", color: "var(--text-faint)", fontSize: 11 }}>{s.label}</span>
                    </button>
                  ))}
                </div>
              )}
              <div style={{
                display: "flex", alignItems: "flex-end", gap: 8,
                background: "var(--bg-2)", border: "1px solid var(--border)",
                borderRadius: 12, padding: "8px 8px 8px 14px",
              }}>
                <textarea
                  ref={inputRef}
                  value={input}
                  onChange={(e) => setInput(e.target.value)}
                  onKeyDown={(e) => { if (e.key === "Enter" && !e.shiftKey) { e.preventDefault(); submit(); } }}
                  placeholder={`Message à ${channel.kind === "channel" ? channel.name : userName(channel.members.find((u) => u !== user))} · tapez [annuaire] pour lier une page`}
                  rows={1}
                  style={{ flex: 1, resize: "none", background: "transparent", border: "none", outline: "none", color: "var(--text)", fontSize: 13, lineHeight: 1.45, fontFamily: "inherit", maxHeight: 160, padding: "6px 0" }}
                />
                <button className="btn" data-variant="ghost" data-size="sm" title="Insérer un lien" onClick={() => setInput(input + "[")} style={{ height: 28 }}>
                  <Icon name="link" size={12}/>
                </button>
                <button className="btn" data-variant="primary" data-size="sm" disabled={!input.trim()} onClick={submit} style={{ height: 28, padding: "0 12px" }}>
                  <Icon name="zap" size={12}/> Envoyer
                </button>
              </div>
              <div style={{ marginTop: 6, fontSize: 10.5, color: "var(--text-faint)" }}>
                Entrée pour envoyer · Shift+Entrée pour saut de ligne · <span className="mono">[annuaire]</span>, <span className="mono">[finance]</span>, <span className="mono">[calendrier]</span>… deviennent des liens cliquables.
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
};

// Topbar mini account switcher — drops down to switch user
const AccountSwitcher = () => {
  const [user, setUser] = useCurrentUserMsgs();
  const [open, setOpen] = useState(false);
  const ref = useRef(null);
  useEffect(() => {
    const close = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", close);
    return () => document.removeEventListener("mousedown", close);
  }, []);
  const u = USERS.find((x) => x.id === user) || USERS[0];
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen(o => !o)} title={`${u.name} · cliquez pour changer de compte`}
        style={{
          display: "inline-flex", alignItems: "center", gap: 7,
          height: 30, padding: "0 10px 0 5px", borderRadius: 999,
          background: "var(--bg-2)",
          border: "1px solid var(--border)",
          color: "var(--text)", fontSize: 12, fontWeight: 550, cursor: "pointer",
          transition: "border-color 120ms",
        }}
        onMouseEnter={(e) => e.currentTarget.style.borderColor = "var(--accent)"}
        onMouseLeave={(e) => e.currentTarget.style.borderColor = "var(--border)"}>
        <Avatar user={u.id} size="sm"/>
        <span>{u.name}</span>
        <Icon name="chevronDown" size={11} style={{ color: "var(--text-dim)" }}/>
      </button>
      {open && (
        <div style={{
          position: "absolute", top: "100%", right: 0, marginTop: 6,
          background: "var(--bg-1)", border: "1px solid var(--border)",
          borderRadius: 10, padding: 6, minWidth: 240, zIndex: 60,
          boxShadow: "var(--shadow-pop)",
        }}>
          <div style={{ padding: "8px 10px 6px", fontSize: 10, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: ".08em", fontWeight: 600 }}>Changer de compte</div>
          {USERS.map((x) => (
            <button key={x.id} onClick={() => { setUser(x.id); setOpen(false); }}
              style={{
                display: "flex", alignItems: "center", gap: 10, width: "100%",
                padding: "8px 10px", borderRadius: 6,
                background: x.id === user ? "var(--bg-3)" : "transparent",
                border: "none", color: "var(--text)", fontSize: 12.5, cursor: "pointer", textAlign: "left",
              }}
              onMouseEnter={(e) => { if (x.id !== user) e.currentTarget.style.background = "var(--bg-2)"; }}
              onMouseLeave={(e) => { if (x.id !== user) e.currentTarget.style.background = "transparent"; }}>
              <Avatar user={x.id}/>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ fontWeight: 600 }}>{x.name}</div>
                <div style={{ fontSize: 10.5, color: "var(--text-dim)" }}>{x.role}</div>
              </div>
              {x.id === user && <Icon name="check" size={13} style={{ color: "var(--accent)" }}/>}
            </button>
          ))}
          <div style={{ borderTop: "1px solid var(--border-subtle)", marginTop: 6, paddingTop: 6 }}>
            <button onClick={() => setOpen(false)} style={{
              display: "flex", alignItems: "center", gap: 8, width: "100%",
              padding: "7px 10px", borderRadius: 6, border: "none",
              background: "transparent", color: "var(--text-muted)",
              fontSize: 12, cursor: "pointer", textAlign: "left",
            }}>
              <Icon name="users" size={12}/>
              <span>Gérer l'équipe…</span>
            </button>
          </div>
        </div>
      )}
    </div>
  );
};

window.Messages = Messages;
window.AccountSwitcher = AccountSwitcher;
// Don't override window.useCurrentUser — data.jsx version returns user object (used by sidebar/topbar/team-board)
window.useMessages = useMessages;
