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

function IconCitrus()    { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><path d="M8 1.5l1.2 3.3L12.5 6 9.2 7.2 8 10.5 6.8 7.2 3.5 6l3.3-1.2L8 1.5z"/><path d="M3 10.5l.6 1.6 1.6.6-1.6.6L3 15l-.6-1.7-1.7-.6 1.7-.6L3 10.5z"/></svg>; }
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 IconLeads()     { 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="6"/><circle cx="8" cy="8" r="3"/><circle cx="8" cy="8" r="1" fill="currentColor"/></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 IconMeasure()   { return <svg width="16" height="16" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.4" strokeLinecap="round" strokeLinejoin="round"><rect x="2" y="3" width="12" height="10" rx="1"/><line x1="2" y1="6.5" x2="14" y2="6.5"/><line x1="5" y1="3" x2="5" y2="13"/><line x1="8" y1="3" x2="8" y2="13"/><line x1="11" y1="3" x2="11" y2="13"/></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, authUser, enabledSections, allowAgentCreation = true }) {
  // Filter helper: a nav item is visible when the allowlist is null/undefined
  // (backwards-compat — show everything) OR when its id is in the array.
  // "settings" is ALWAYS visible regardless — tenants must keep access to
  // their own account management even when the master-admin disables it.
  const isSectionEnabled = (id) => {
    if (id === "settings" || id === "home") return true;
    if (!Array.isArray(enabledSections)) return true;
    return enabledSections.includes(id);
  };
  // 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");
        }
        // Patch window.CITRUS_BRANDING with the authenticated per-tenant
        // branding. On first sign-in the page loaded before any token existed,
        // so .config.js served Citrus defaults. Syncing from the authenticated
        // /config response fixes the sidebar name without a full page reload.
        if (data.branding && typeof data.branding === "object" && window.CITRUS_BRANDING) {
          Object.assign(window.CITRUS_BRANDING, data.branding);
        }
        // Broadcast so already-mounted sections (e.g. Agents welcome card)
        // can pick up the new tenant profile/name without a page refresh.
        try { window.dispatchEvent(new Event("citrus-brand")); } catch {}
        setBrand(readBrand());
      })
      .catch(() => {});
    return () => { cancelled = true; };
  }, []);
  const groupA = [
    { id: "home",      label: "CITRUS",    icon: <IconCitrus /> },
    { id: "agents",    label: "Agents",    icon: <IconAgents /> },
    { id: "inbox",     label: "Inbox",     icon: <IconInbox />,    badge: inboxBadge },
    { id: "leads",     label: "Leads",     icon: <IconLeads /> },
    { 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) => {
    const visible = g.filter((it) => isSectionEnabled(it.id));
    const filtered = visible;
    // Hide the group header entirely when the whole group was filtered out —
    // otherwise we'd render a section label with no items underneath it.
    if (filtered.length === 0) return null;
    return (
      <>
        {label ? <div className="ds-nav-group">{label}</div> : null}
        {filtered.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 || (authUser && authUser.businessSlug && authUser.businessSlug !== "self" ? authUser.businessSlug.replace(/-/g, " ") : "") || ""}</span>
      </a>
      {allowAgentCreation ? (
        <button className="ds-new" onClick={onNew}>
          <span className="ds-new-plus">+</span>
          New agent
        </button>
      ) : null}
      <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 || (authUser && authUser.businessSlug && authUser.businessSlug !== "self" ? authUser.businessSlug : "") || "").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;
