// ============ DASHBOARD · TOPBAR ============
// The sticky header above the section pane. Shows the current tab title
// (or the focused agent's name + role), search, and the "+ New agent" CTA.

function UserMenu({ authUser, onLogout }) {
  const [open, setOpen] = React.useState(false);
  const ref = React.useRef(null);
  const initials = (authUser.name || authUser.email || "?")
    .split(" ").slice(0, 2).map((w) => w[0]).join("").toUpperCase();

  React.useEffect(() => {
    if (!open) return;
    const handler = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", handler);
    return () => document.removeEventListener("mousedown", handler);
  }, [open]);

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        onClick={() => setOpen((v) => !v)}
        title={authUser.name || authUser.email}
        style={{
          width: 32, height: 32, borderRadius: "50%",
          background: "var(--accent)", color: "#fff",
          border: "none", cursor: "pointer",
          fontSize: 12, fontWeight: 700,
          display: "flex", alignItems: "center", justifyContent: "center",
          flexShrink: 0,
        }}
      >
        {initials}
      </button>
      {open && (
        <div style={{
          position: "absolute", right: 0, top: "calc(100% + 8px)",
          background: "var(--paper)", border: "1px solid var(--border)",
          borderRadius: 10, boxShadow: "0 8px 24px rgba(0,0,0,.12)",
          minWidth: 200, zIndex: 1000, overflow: "hidden",
        }}>
          <div style={{ padding: "12px 16px", borderBottom: "1px solid var(--border)" }}>
            <div style={{ fontWeight: 600, fontSize: 13, color: "var(--ink)" }}>{authUser.name || "—"}</div>
            <div style={{ fontSize: 12, color: "var(--ink-2)", marginTop: 2 }}>{authUser.email}</div>
            <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 4, textTransform: "capitalize" }}>{authUser.role}</div>
          </div>
          <button
            onClick={() => { setOpen(false); onLogout && onLogout(); }}
            style={{
              display: "flex", alignItems: "center", gap: 8,
              width: "100%", padding: "10px 16px",
              background: "none", border: "none", cursor: "pointer",
              fontSize: 13, color: "var(--ink)", textAlign: "left",
            }}
            onMouseEnter={(e) => e.currentTarget.style.background = "var(--hover)"}
            onMouseLeave={(e) => e.currentTarget.style.background = "none"}
          >
            <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="M10 3h3a1 1 0 0 1 1 1v8a1 1 0 0 1-1 1h-3M7 11l-4-3 4-3M3 8h8"/>
            </svg>
            Sign out
          </button>
        </div>
      )}
    </div>
  );
}

function Topbar({ tab, focused, onBack, onNew, onStartTour, agents, onOpenAgent, onSwitchTab, onMenu, activeEnvName, envs = [], activeEnvId = "", authUser, onLogout }) {
  const titles = {
    agents:    "Your agents",
    inbox:     "Inbox",
    activity:  "Activity",
    approvals: "Approvals",
    insights:  "Insights",
    templates: "Templates",
    knowledge: "Knowledge",
    tools:     "Tools & integrations",
    team:      "Team",
    billing:   "Billing & usage",
    settings:  "Settings",
  };
  const inputRef = useRef(null);
  const [q, setQ] = useState("");
  const [focusOn, setFocusOn] = useState(false);

  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        inputRef.current && inputRef.current.focus();
      }
      if (e.key === "Escape" && document.activeElement === inputRef.current) {
        setQ(""); inputRef.current.blur();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const switchEnv = (id) => {
    if (id === activeEnvId) return;
    if (!id) {
      localStorage.removeItem("citrus_active_env");
      localStorage.removeItem("citrus_active_env_data");
    } else {
      const env = envs.find((e) => e.id === id);
      if (!env) return;
      localStorage.setItem("citrus_active_env", id);
      localStorage.setItem("citrus_active_env_data", JSON.stringify(env));
    }
    window.location.reload();
  };

  const envDotColor = (name = "") => {
    const n = name.toLowerCase();
    if (n.includes("prod")) return "#22a06b";
    if (n.includes("sandbox") || n.includes("dev")) return "var(--accent)";
    if (n.includes("uat") || n.includes("staging")) return "#d97706";
    if (n.includes("qa") || n.includes("test")) return "#0ea5e9";
    return "#888";
  };

  const TAB_HITS = [
    ["inbox", "Inbox"], ["activity", "Activity"], ["approvals", "Approvals"],
    ["insights", "Insights"], ["templates", "Templates"], ["knowledge", "Knowledge"],
    ["tools", "Tools & integrations"], ["team", "Team"], ["billing", "Billing & usage"],
    ["settings", "Settings"],
  ];
  const ql = q.trim().toLowerCase();
  const agentHits = ql && agents ? agents.filter((a) =>
    a.name.toLowerCase().includes(ql) || a.role.toLowerCase().includes(ql)
  ) : [];
  const tabHits = ql ? TAB_HITS.filter(([, l]) => l.toLowerCase().includes(ql)) : [];
  const showResults = focusOn && ql.length > 0;

  return (
    <header className="ds-top">
      <div className="ds-top-left">
        {onMenu ? (
          <button className="ds-menu-btn" onClick={onMenu} aria-label="Toggle navigation">
            <svg width="20" height="20" viewBox="0 0 20 20" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round">
              <path d="M3 6h14M3 10h14M3 14h14" />
            </svg>
          </button>
        ) : null}
        {focused ? (
          <button className="ds-back" onClick={onBack}>
            <svg width="14" height="14" viewBox="0 0 14 14"><path d="M11 7H3M5 3 1 7l4 4" stroke="currentColor" strokeWidth="1.5" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>
            Back
          </button>
        ) : null}
        <h1 className="ds-top-title">
          {focused ? focused.name : titles[tab]}
          {focused ? <span className="ds-top-sub"> · {focused.role}</span> : null}
        </h1>
        {activeEnvName && activeEnvName !== "Production" && (
          <span style={{
            background: "#F59E0B",
            color: "#fff",
            fontSize: 11,
            fontWeight: 700,
            padding: "2px 8px",
            borderRadius: 4,
            letterSpacing: "0.05em",
            textTransform: "uppercase",
            marginLeft: 8,
          }}>
            {activeEnvName}
          </span>
        )}
      </div>
      <div className="ds-top-right">
        <div className="ds-search">
          <svg width="14" height="14" viewBox="0 0 14 14"><circle cx="6" cy="6" r="4" stroke="currentColor" strokeWidth="1.5" fill="none"/><path d="M9 9l4 4" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round"/></svg>
          <input
            ref={inputRef}
            placeholder="Search agents, sections…"
            value={q}
            onChange={(e) => setQ(e.target.value)}
            onFocus={() => setFocusOn(true)}
            onBlur={() => setTimeout(() => setFocusOn(false), 120)}
          />
          <kbd>⌘K</kbd>
          {showResults ? (
            <div className="ds-search-results">
              {agentHits.length === 0 && tabHits.length === 0 ? (
                <div className="ds-search-empty">No matches</div>
              ) : null}
              {agentHits.length > 0 ? (
                <div className="ds-search-group">
                  <div className="ds-search-group-h">Agents</div>
                  {agentHits.map((a) => (
                    <button
                      key={a.id}
                      className="ds-search-row"
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => { onOpenAgent && onOpenAgent(a.id); setQ(""); }}
                    >
                      <span className="ds-search-mark" style={{ background: a.palette.skin }}>{a.name[0]}</span>
                      <span className="ds-search-n">{a.name}</span>
                      <span className="ds-search-d">{a.role}</span>
                    </button>
                  ))}
                </div>
              ) : null}
              {tabHits.length > 0 ? (
                <div className="ds-search-group">
                  <div className="ds-search-group-h">Sections</div>
                  {tabHits.map(([id, label]) => (
                    <button
                      key={id}
                      className="ds-search-row"
                      onMouseDown={(e) => e.preventDefault()}
                      onClick={() => { onSwitchTab && onSwitchTab(id); setQ(""); }}
                    >
                      <span className="ds-search-d">{label}</span>
                    </button>
                  ))}
                </div>
              ) : null}
            </div>
          ) : null}
        </div>
        {envs.length > 0 && (
          <div style={{ position: "relative", display: "flex", alignItems: "center" }}>
            <div style={{ position: "absolute", left: 10, width: 8, height: 8, borderRadius: "50%", background: envDotColor(activeEnvId ? (envs.find(e => e.id === activeEnvId)?.name || "") : "prod"), pointerEvents: "none", zIndex: 1 }} />
            <select
              value={activeEnvId || ""}
              onChange={(e) => switchEnv(e.target.value)}
              style={{ paddingLeft: 24, paddingRight: 24, paddingTop: 6, paddingBottom: 6, border: "1px solid var(--border)", borderRadius: 8, background: "var(--paper)", color: "var(--ink)", font: "inherit", fontSize: 13, fontWeight: 500, cursor: "pointer", outline: "none", appearance: "none", WebkitAppearance: "none" }}
            >
              <option value="">Default</option>
              {envs.map((env) => (
                <option key={env.id} value={env.id}>{env.name}</option>
              ))}
            </select>
            <svg style={{ position: "absolute", right: 8, pointerEvents: "none", color: "var(--ink-2)" }} width="10" height="10" viewBox="0 0 10 10" fill="none">
              <path d="M2 3.5l3 3 3-3" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
            </svg>
          </div>
        )}
        {!focused ? (
          <>
            <button className="btn btn-ghost btn-sm" onClick={onStartTour} title="Take a tour of the dashboard">
              <svg width="14" height="14" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <circle cx="8" cy="8" r="6.5"/>
                <path d="M5.8 6c.2-1 1-1.7 2.2-1.7 1.3 0 2.2.8 2.2 1.9 0 .9-.5 1.4-1.4 1.9-.6.4-.9.7-.9 1.3"/>
                <circle cx="8" cy="11.4" r=".6" fill="currentColor"/>
              </svg>
              Take a tour
            </button>
            <button className="btn btn-primary btn-sm" onClick={onNew}>
              <span className="ds-new-plus">+</span>
              New agent
            </button>
          </>
        ) : null}
        {authUser ? (
          <UserMenu authUser={authUser} onLogout={onLogout} />
        ) : null}
      </div>
    </header>
  );
}

window.Topbar = Topbar;
