/* Topbar with breadcrumb, search, session, theme toggle */

const TITLES = {
  dashboard:    ["Pilotage", "Dashboard"],
  "daily-picks":["Sourcing", "Picks du jour · 10 produits + 10 fournisseurs"],
  research:    ["Sourcing", "Recherche de produits"],
  asin:        ["Sourcing", "Bibliothèque ASIN"],
  "profit-calc":["Sourcing", "ProfitCalcPro"],
  opportunity: ["Sourcing", "OpportunityFinder"],
  "team-board":["Sourcing", "TeamBoard"],
  alerts:      ["Sourcing", "Alertes"],
  jarvis:      ["Intelligence", "JARVIS"],
  messages:    ["Intelligence", "Messages \u00e9quipe"],
  supplier:    ["Fournisseurs", "Annuaire"],
  catalogs:    ["Fournisseurs", "Catalogues"],
  "open-acct": ["Fournisseurs", "Comptes ouverts"],
  finance:     ["Finance & Ops", "Finances"],
  expenses:    ["Finance & Ops", "Dépenses & Impôts"],
  shipments:   ["Finance & Ops", "Expéditions FBA"],
  returns:     ["Finance & Ops", "Retours"],
  prep:        ["Finance & Ops", "Prep Center"],
  import:      ["Finance & Ops", "Import"],
  calendar:    ["Système", "Calendrier"],
  resources:   ["Système", "Ressources"],
  workshop:    ["Système", "Atelier SQL"],
  email:       ["Système", "Daily Digest"],
  settings:    ["Système", "Paramètres"],
};

const Topbar = ({ page, theme, onToggleTheme, onOpenCmdK, onOpenAuth, onNavigate, onOpenChangelog, onOpenJarvis }) => {
  const crumbs = TITLES[page] || ["—", "—"];
  const [me, setMe] = useCurrentUser();
  const [notifOpen, setNotifOpen] = useState(false);
  const [tick, setTick] = useState(0);
  // Re-render every 30s so notification counts stay fresh
  useEffect(() => {
    const id = setInterval(() => setTick(t => t + 1), 30000);
    return () => clearInterval(id);
  }, []);
  const alerts = Array.isArray(window.ALERTS) ? window.ALERTS : [];
  const tasks = Array.isArray(window.TASKS) ? window.TASKS : [];
  const messages = Array.isArray(window.KCC_MESSAGES) ? window.KCC_MESSAGES : [];
  const recentMsgs = messages.slice(-3).reverse();
  const myId = typeof me === "string" ? me : me?.id;
  const myTasks = tasks.filter(t => t.assignee === myId && t.status !== "fait").slice(0, 5);
  const notifCount = alerts.length + myTasks.length + (recentMsgs.length > 0 ? 1 : 0);
  const toggleMobileNav = () => {
    const app = document.querySelector('.app');
    if (!app) return;
    const open = app.getAttribute('data-mobile-nav') === 'open';
    app.setAttribute('data-mobile-nav', open ? 'closed' : 'open');
  };

  return (
    <header className="topbar">
      <button className="mobile-menu-toggle icon-btn" onClick={toggleMobileNav} title="Menu" aria-label="Menu">
        <Icon name="menu" />
      </button>
      <div className="breadcrumb">
        <span className="crumb">KCC</span>
        <span className="sep"><Icon name="chevronRight" size={12} /></span>
        <span className="crumb">{crumbs[0]}</span>
        <span className="sep"><Icon name="chevronRight" size={12} /></span>
        <span className="crumb last">{crumbs[1]}</span>
      </div>

      <div className="topbar-spacer" />

      <div className="session-pill" title="Synchronisation multi-utilisateurs · D1 + KV temps réel">
        <span className="live-dot" />
        <span>Sync · D1 · KV</span>
      </div>

      <div className="team-switcher" title="Changer d'utilisateur actif (sync entre les 3 cofondateurs)">
        {USERS.map((u) => (
          <button
            key={u.id}
            className="team-pick"
            data-active={u.id === myId}
            onClick={() => setMe(u.id)}
            title={`${u.name} · ${u.role}`}
          >
            <Avatar user={u.id} size="sm" />
          </button>
        ))}
      </div>

      <div className="topbar-actions">
        <button className="icon-btn" onClick={onOpenCmdK} title="Recherche globale (⌘K)">
          <Icon name="search" />
        </button>
        {onOpenJarvis && (
          <button className="icon-btn" onClick={onOpenJarvis} title="JARVIS (⌘+J)" style={{ position: "relative" }}>
            <Icon name="sparkles" />
            <span className="dot" style={{ background: "var(--green)" }} />
          </button>
        )}
        {onOpenChangelog && (
          <button className="icon-btn" onClick={onOpenChangelog} title={`Changelog v${window.KCC_VERSION || "3.4"}`}>
            <Icon name="layers" />
            {window.KCC_HAS_UPDATE && <span className="dot" style={{ background: "var(--accent)" }} />}
          </button>
        )}
        <div style={{ position: "relative" }}>
          <button className="icon-btn" title={`${notifCount} notification${notifCount > 1 ? "s" : ""}`} onClick={() => setNotifOpen(o => !o)}>
            <Icon name="bell" />
            {notifCount > 0 && <span className="dot" style={{ background: "var(--red)" }} />}
          </button>
          {notifOpen && (
            <div
              role="dialog"
              style={{
                position: "absolute", top: "calc(100% + 8px)", right: 0, zIndex: 1000,
                width: 340, maxHeight: 480, overflow: "auto",
                background: "var(--bg-1)", border: "1px solid var(--border)",
                borderRadius: 10, boxShadow: "0 12px 32px rgba(0,0,0,0.25)",
              }}
              onMouseLeave={() => setNotifOpen(false)}
            >
              <div className="between" style={{ padding: "10px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
                <span style={{ fontSize: 12, fontWeight: 600 }}>Notifications</span>
                <button className="icon-btn" style={{ width: 22, height: 22 }} onClick={() => setNotifOpen(false)} title="Fermer">
                  <Icon name="x" size={12} />
                </button>
              </div>

              {/* Alerts */}
              {alerts.length > 0 && (
                <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>
                    Alertes · {alerts.length}
                  </div>
                  {alerts.slice(0, 5).map((a, i) => (
                    <div key={i} className="row" style={{ gap: 8, padding: "6px 0", cursor: "pointer" }}
                         onClick={() => { setNotifOpen(false); onNavigate && onNavigate("alerts"); }}>
                      <Icon name={a.level === "danger" ? "alert" : a.level === "warn" ? "warning" : "info"} size={12}
                            style={{ color: a.level === "danger" ? "var(--red)" : a.level === "warn" ? "var(--amber)" : "var(--accent)" }} />
                      <div style={{ flex: 1, fontSize: 12 }}>
                        <div style={{ fontWeight: 500 }}>{a.title || a.message || "Alerte"}</div>
                        {a.description && <div style={{ fontSize: 11, color: "var(--text-faint)" }}>{a.description}</div>}
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {/* My tasks */}
              {myTasks.length > 0 && (
                <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>
                    Mes tâches · {myTasks.length}
                  </div>
                  {myTasks.map((t, i) => (
                    <div key={i} className="row" style={{ gap: 8, padding: "6px 0", cursor: "pointer" }}
                         onClick={() => { setNotifOpen(false); onNavigate && onNavigate("team-board"); }}>
                      <Icon name="check" size={12} style={{ color: "var(--accent)" }} />
                      <div style={{ flex: 1, fontSize: 12 }}>{t.title || t.task}</div>
                    </div>
                  ))}
                </div>
              )}

              {/* Recent messages */}
              {recentMsgs.length > 0 && (
                <div style={{ padding: "8px 12px", borderBottom: "1px solid var(--border-subtle)" }}>
                  <div style={{ fontSize: 10.5, color: "var(--text-faint)", textTransform: "uppercase", letterSpacing: "0.06em", marginBottom: 6 }}>
                    Messages récents
                  </div>
                  {recentMsgs.map((m, i) => (
                    <div key={i} className="row" style={{ gap: 8, padding: "6px 0", cursor: "pointer" }}
                         onClick={() => { setNotifOpen(false); onNavigate && onNavigate("messages"); }}>
                      <Avatar user={m.from || m.author || "clarens"} size="sm" />
                      <div style={{ flex: 1, fontSize: 12 }}>
                        <div style={{ fontWeight: 500, textTransform: "capitalize" }}>{m.from || m.author}</div>
                        <div style={{ fontSize: 11, color: "var(--text-faint)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap", maxWidth: 240 }}>
                          {m.body || m.text}
                        </div>
                      </div>
                    </div>
                  ))}
                </div>
              )}

              {notifCount === 0 && (
                <div style={{ padding: 24, textAlign: "center", color: "var(--text-faint)", fontSize: 12 }}>
                  Tout est sous contrôle. Aucune notification.
                </div>
              )}

              <div style={{ padding: "8px 12px", borderTop: "1px solid var(--border-subtle)" }}>
                <button className="btn" data-variant="ghost" data-size="sm"
                        onClick={() => { setNotifOpen(false); onNavigate && onNavigate("alerts"); }}
                        style={{ width: "100%" }}>
                  Voir toutes les alertes
                </button>
              </div>
            </div>
          )}
        </div>
        <button className="icon-btn" onClick={onToggleTheme} title={theme === "dark" ? "Thème clair" : "Thème sombre"}>
          <Icon name={theme === "dark" ? "sun" : "moon"} />
        </button>
        <button className="icon-btn" onClick={onOpenAuth} title="Session / 2FA">
          <Avatar user={myId} size="sm" />
        </button>
      </div>
    </header>
  );
};

window.Topbar = Topbar;
