// ============ DASHBOARD · SIDEBAR ============
// Left rail: brand, "New agent" CTA, three nav groups, user pill.
// Icons live here because nothing else uses them.

function IconAgents()    { return <svg width="16" height="16" viewBox="0 0 16 16"><circle cx="8" cy="6" r="3" stroke="currentColor" strokeWidth="1.4" fill="none"/><path d="M2 14c0-3 3-5 6-5s6 2 6 5" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round"/></svg>; }
function IconActivity()  { return <svg width="16" height="16" viewBox="0 0 16 16"><path d="M1 8h3l2-5 4 10 2-5h3" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>; }
function IconApproval()  { return <svg width="16" height="16" viewBox="0 0 16 16"><rect x="2" y="3" width="12" height="10" rx="1.5" stroke="currentColor" strokeWidth="1.4" fill="none"/><path d="M5 8l2 2 4-4" stroke="currentColor" strokeWidth="1.4" fill="none" strokeLinecap="round" strokeLinejoin="round"/></svg>; }
function IconBilling()   { return <svg width="16" height="16" viewBox="0 0 16 16"><rect x="2" y="4" width="12" height="9" rx="1.5" stroke="currentColor" strokeWidth="1.4" fill="none"/><line x1="2" y1="7" x2="14" y2="7" stroke="currentColor" strokeWidth="1.4"/><rect x="4" y="9.5" width="3" height="1.5" fill="currentColor"/></svg>; }
function IconInbox()     { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 9h3l1 2h4l1-2h3M2 9l2-6h8l2 6v4a1 1 0 0 1-1 1H3a1 1 0 0 1-1-1V9z"/></svg>; }
function IconInsights()  { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M2 13V3M2 13h12M5 11V7M8 11V5M11 11V8"/></svg>; }
function IconTemplates() { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><rect x="2" y="2" width="5" height="5" rx="1"/><rect x="9" y="2" width="5" height="5" rx="1"/><rect x="2" y="9" width="5" height="5" rx="1"/><rect x="9" y="9" width="5" height="5" rx="1"/></svg>; }
function IconKnow()      { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M3 2h7l3 3v9H3z"/><path d="M10 2v3h3"/></svg>; }
function IconTools()     { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><circle cx="8" cy="8" r="2"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M3 3l1.5 1.5M11.5 11.5L13 13M3 13l1.5-1.5M11.5 4.5L13 3"/></svg>; }
function IconTeam()      { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="6" cy="6" r="2.5"/><circle cx="12" cy="6.5" r="2"/><path d="M2 13c0-2 2-3.5 4-3.5s4 1.5 4 3.5M10 12c0-1.5 1-2.5 2.5-2.5S15 10.5 15 12"/></svg>; }
function IconSettings()  { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4"><circle cx="8" cy="8" r="2"/><path d="M8 1v2M8 13v2M1 8h2M13 8h2M2.5 2.5l1.5 1.5M12 12l1.5 1.5M2.5 13.5L4 12M12 4l1.5-1.5"/></svg>; }
function IconPersonas()  { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><circle cx="5" cy="6" r="2"/><circle cx="11" cy="6" r="2"/><path d="M2 13c0-1.5 1.5-3 3-3M14 13c0-1.5-1.5-3-3-3M5.5 13c0-1.5 1-2.5 2.5-2.5s2.5 1 2.5 2.5"/></svg>; }

function Sidebar({ tab, setTab, onNew, inboxBadge = 0, approvalsBadge = 0 }) {
  // Local "brand" is the user-configured profile (citrus_profile in
  // localStorage). Per-tenant branding (window.CITRUS_BRANDING) wins when
  // present — it's server-driven and overrides anything the tenant set in
  // their own dashboard profile. Defensive: both sources are optional.
  const readBrand = () => {
    let local = {};
    try { local = JSON.parse(localStorage.getItem("citrus_profile") || "{}"); }
    catch { local = {}; }
    const server = (typeof window !== "undefined" && window.CITRUS_BRANDING) || {};
    return {
      color: (server.accentColor && /^#[0-9a-fA-F]{6}$/.test(server.accentColor) ? server.accentColor : null) || local.color || null,
      logo:  server.logoUrl || local.logo || null,
      name:  server.displayName || local.name || null,
    };
  };
  const [brand, setBrand] = useState(readBrand());
  useEffect(() => {
    const handler = () => setBrand(readBrand());
    window.addEventListener("citrus-brand", handler);
    return () => window.removeEventListener("citrus-brand", handler);
  }, []);
  // Self-sync: fetch /config on mount so the rail picks up the current
  // tenant's saved profile.name without waiting for the user to visit
  // Settings. The server's response REPLACES localStorage — we do NOT
  // merge with whatever was there. Merging caused a nasty bug: after
  // viewing /t/bahr/ then signing in as Gabtic, localStorage still had
  // {name: "Bahr"}; Gabtic's /config returned a profile that had `desc`
  // set but no `name`, so the merge kept "Bahr" and the dashboard header
  // displayed "Bahr" for a Gabtic-authed user. Treat localStorage as a
  // disposable rendering cache, not a persistent merge target.
  useEffect(() => {
    const cfg = (typeof window !== "undefined" && window.CITRUS_CONFIG) || {};
    const url = cfg.SERVER_URL || "";
    if (!url) return;
    let cancelled = false;
    fetch(`${url}/config`)
      .then((r) => (r.ok ? r.json() : null))
      .then((data) => {
        if (cancelled || !data) return;
        if (data.profile && typeof data.profile === "object") {
          localStorage.setItem("citrus_profile", JSON.stringify(data.profile));
        } else {
          // Server returned no profile for this tenant (brand-new tenant);
          // wipe the cached one so the rail falls back to defaults instead
          // of showing the previous tenant's name.
          localStorage.removeItem("citrus_profile");
        }
        setBrand(readBrand());
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);
  const groupA = [
    { id: "agents",    label: "Agents",    icon: <IconAgents /> },
    { id: "inbox",     label: "Inbox",     icon: <IconInbox />,    badge: inboxBadge },
    { id: "activity",  label: "Activity",  icon: <IconActivity /> },
    { id: "approvals", label: "Approvals", icon: <IconApproval />, badge: approvalsBadge },
    { id: "insights",  label: "Insights",  icon: <IconInsights /> },
  ];
  const groupB = [
    { id: "templates", label: "Templates", icon: <IconTemplates /> },
    { id: "personas",  label: "Personas",  icon: <IconPersonas /> },
    { id: "knowledge", label: "Knowledge", icon: <IconKnow /> },
    { id: "tools",     label: "Tools",     icon: <IconTools /> },
    { id: "team",      label: "Team",      icon: <IconTeam /> },
  ];
  const groupC = [
    { id: "billing",  label: "Billing",  icon: <IconBilling /> },
    { id: "settings", label: "Settings", icon: <IconSettings /> },
  ];
  const renderGroup = (g, label) => (
    <>
      {label ? <div className="ds-nav-group">{label}</div> : null}
      {g.map((it) => (
        <button
          key={it.id}
          className={`ds-nav-item ${tab === it.id ? "is-active" : ""}`}
          onClick={() => setTab(it.id)}
        >
          <span className="ds-nav-icon">{it.icon}</span>
          <span className="ds-nav-label">{it.label}</span>
          {it.badge ? <span className="ds-nav-badge">{it.badge}</span> : null}
        </button>
      ))}
    </>
  );
  return (
    <aside className="ds-side">
      <a className="ds-brand" href="/landing/">
        <span className="ds-brand-mark" style={brand.color ? { background: brand.color } : null}>
          {brand.logo
            ? <img src={brand.logo} alt="logo" style={{ width: "100%", height: "100%", objectFit: "contain" }} />
            : "◍"}
        </span>
        <span className="ds-brand-word">{brand.name || "citrus"}</span>
      </a>
      <button className="ds-new" onClick={onNew}>
        <span className="ds-new-plus">+</span>
        New agent
      </button>
      <nav className="ds-nav">
        {renderGroup(groupA, "Day to day")}
        {renderGroup(groupB, "Build")}
        {renderGroup(groupC, "Account")}
      </nav>
      <div className="ds-side-foot">
        <div className="ds-user">
          <div className="ds-user-avatar" style={brand.color ? { background: brand.color } : null}>
            {(brand.name || "Citrus").trim().slice(0, 2).toUpperCase()}
          </div>
          <div className="ds-user-meta">
            <div className="ds-user-name">{brand.name || "Set up your company"}</div>
            <div className="ds-user-org">Owner</div>
          </div>
        </div>
        <a href="/landing/" className="ds-side-signout">Sign out</a>
      </div>
    </aside>
  );
}

window.Sidebar = Sidebar;
