// Shell components for Perdura Capital
// Sidebar nav, topbar, AI copilot drawer

const { useState: useStateS, useEffect: useEffectS, useMemo: useMemoS, useRef: useRefS } = React;

// ─── Logo mark ────────────────────────────────────────────────────────────
function PerduraMark({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 24 24" fill="none">
      <defs>
        <linearGradient id="pmg" x1="0" y1="0" x2="1" y2="1">
          <stop offset="0%" stopColor="var(--accent)" />
          <stop offset="100%" stopColor="var(--accent-2)" />
        </linearGradient>
      </defs>
      <path d="M4 20V4h7c3.3 0 6 2.5 6 5.8 0 3.4-2.7 5.9-6 5.9H8" stroke="url(#pmg)" strokeWidth="2.2" strokeLinecap="round" strokeLinejoin="round" />
      <circle cx="18" cy="19" r="2" fill="var(--accent)" />
    </svg>
  );
}

// ─── Icons ────────────────────────────────────────────────────────────────
const Icon = ({ d, size = 16, fill = "none", stroke = "currentColor", strokeWidth = 1.6 }) => (
  <svg width={size} height={size} viewBox="0 0 24 24" fill={fill} stroke={stroke} strokeWidth={strokeWidth} strokeLinecap="round" strokeLinejoin="round">
    {typeof d === "string" ? <path d={d} /> : d}
  </svg>
);

const icons = {
  overview: "M3 12h4l3-8 4 16 3-8h4",
  sales: "M3 17l6-6 4 4 8-8 M21 7v6h-6",
  inventory: "M3 7l9-4 9 4-9 4-9-4z M3 7v10l9 4 9-4V7 M12 11v10",
  supply: "M3 7h13l3 3v7H3z M3 11h16 M7 7V4h7v3",
  manufacturing: "M2 21h20 M4 21v-8l5 4v-4l5 4v-4l5 4 M14 13V8a2 2 0 00-2-2H8a2 2 0 00-2 2v5",
  cash: "M3 7h18v10H3z M3 11h18 M7 15h2 M11 15h2",
  arap: "M5 4h10l4 4v12H5z M5 14h14 M9 18h6",
  service: "M12 2a10 10 0 100 20 10 10 0 000-20z M12 7v5l3 2",
  customer: "M12 12a4 4 0 100-8 4 4 0 000 8z M4 21a8 8 0 0116 0",
  margin: "M3 3l4 18 4-12 4 8 6-14",
  forecast: "M3 17V7 M9 17V11 M15 17V9 M21 17V5 M3 21h18",
  exceptions: "M12 2L2 21h20L12 2z M12 9v5 M12 17v.1",
  config: "M9 3l3 4 3-4 M3 9l4 3-4 3 M21 9l-4 3 4 3 M9 21l3-4 3 4 M12 12m-3 0a3 3 0 106 0 3 3 0 10-6 0",
  users: "M9 11a4 4 0 100-8 4 4 0 000 8z M3 21a6 6 0 0112 0 M16 11l4-4 M16 11l4 4",
  calendar: "M5 5h14v14H5z M5 9h14 M9 3v4 M15 3v4",
  customize: "M3 5h8 M13 19h8 M16 3v6 M8 15v6 M5 11h14 M5 19h6",
  decisions: "M12 2v6 M12 14v8 M5 8l7-6 7 6 M5 8h14 M9 14l3 4 3-4",
  settings: "M12 8a4 4 0 100 8 4 4 0 000-8z M19 12l2-1 -2-3-2 1-1-2h-4l-1 2-2-1-2 3 2 1-2 1 2 3 2-1 1 2h4l1-2 2 1 2-3z",
  search: "M11 19a8 8 0 100-16 8 8 0 000 16z M21 21l-4.3-4.3",
  bell: "M6 8a6 6 0 0112 0c0 7 3 9 3 9H3s3-2 3-9 M10 21h4",
  ai: "M12 3v3 M12 18v3 M3 12h3 M18 12h3 M5.6 5.6l2.1 2.1 M16.3 16.3l2.1 2.1 M5.6 18.4l2.1-2.1 M16.3 7.7l2.1-2.1",
  chevron: "M9 18l6-6-6-6",
  caret: "M6 9l6 6 6-6",
  filter: "M3 6h18 M7 12h10 M11 18h2",
  download: "M12 3v14 M5 12l7 7 7-7 M3 21h18",
  drill: "M5 5l14 14 M5 19l14-14",
  refresh: "M21 12a9 9 0 11-3.5-7 M21 3v6h-6",
  plus: "M12 5v14 M5 12h14",
  check: "M5 12l5 5L20 7",
  x: "M6 6l12 12 M6 18L18 6",
  building: "M3 21h18 M5 21V7l7-4 7 4v14 M9 9h.01 M13 9h.01 M9 13h.01 M13 13h.01 M9 17h.01 M13 17h.01",
  upload: "M12 21V7 M5 12l7-7 7 7 M3 3h18",
  link: "M10 14a5 5 0 007 0l3-3a5 5 0 00-7-7l-1 1 M14 10a5 5 0 00-7 0l-3 3a5 5 0 007 7l1-1",
};

// ─── Navigation config ────────────────────────────────────────────────────
const navItems = (bizType) => [
  { key: "health",      label: "Daily Health View",  icon: icons.overview, group: "Today" },
  { key: "weekly",      label: "Weekly Review",      icon: icons.calendar, group: "Today" },
  { key: "overview",    label: "Financial Overview", icon: icons.overview, group: "Finance" },
  { key: "cash",        label: "Cash Flow & Runway", icon: icons.cash, group: "Finance" },
  { key: "arap",        label: "AR / AP Aging",      icon: icons.arap, group: "Finance" },
  { key: "expenses",    label: "Expense Intelligence", icon: icons.config, group: "Finance" },
  { key: "forecast",    label: "Forecast",           icon: icons.forecast, group: "Finance" },
  { key: "capital",     label: "Capital Allocation", icon: icons.cash, group: "Finance" },
  { key: "sales",       label: "Sales Analysis",     icon: icons.sales, group: "Revenue" },
  { key: "patterns",    label: "Sales Patterns",     icon: icons.customer, group: "Revenue" },
  { key: "pricing",     label: "Pricing Intelligence", icon: icons.margin, group: "Revenue" },
  { key: "acquisition", label: "Acquisition & Cohorts", icon: icons.users, group: "Revenue" },
  { key: "customer",    label: "Customer Profitability", icon: icons.customer, group: "Revenue" },
  { key: "margin",      label: "Margin Analytics",   icon: icons.margin, group: "Revenue" },
  ...(bizType === "retail" ? [
    { key: "stores",    label: "Stores",             icon: icons.building, group: "Operations" },
  ] : []),
  ...(bizType === "product" || bizType === "manufacturing" || bizType === "retail" ? [
    { key: "inventory", label: "Inventory",          icon: icons.inventory, group: "Operations" },
    { key: "supply",    label: "Supply Chain",       icon: icons.supply, group: "Operations" },
  ] : []),
  ...(bizType === "manufacturing" ? [
    { key: "manufacturing", label: "Production & OEE", icon: icons.manufacturing, group: "Operations" },
  ] : []),
  ...(bizType === "subscription" ? [
    { key: "subscription", label: "Subscription Analytics", icon: icons.forecast, group: "Operations" },
  ] : []),
  ...(bizType === "service" ? [
    { key: "service",   label: "Resource Productivity", icon: icons.service, group: "Operations" },
  ] : []),
  { key: "exceptions",  label: "Exceptions Inbox",   icon: icons.exceptions, group: "Insights" },
  { key: "decisions",   label: "Strategic Decisions", icon: icons.decisions, group: "Insights" },
  { key: "ratios",      label: "Financial Ratios",   icon: icons.margin, group: "Insights" },
  { key: "goals",       label: "Goals & Targets",    icon: icons.check, group: "Insights" },
  { key: "risk",        label: "Risk Dashboard",      icon: icons.exceptions, group: "Insights" },
  { key: "settings_config",    label: "Configuration",     icon: icons.config,    group: "Settings" },
  { key: "settings_period",    label: "Period & Calendar", icon: icons.calendar,  group: "Settings" },
  { key: "settings_users",     label: "Users & Roles",     icon: icons.users,     group: "Settings" },
  { key: "settings_custom",    label: "Customization",     icon: icons.customize, group: "Settings" },
  { key: "documents",          label: "Documents",         icon: `M14 2H6a2 2 0 0 0-2 2v16a2 2 0 0 0 2 2h12a2 2 0 0 0 2-2V8z M14 2v6h6 M16 13H8 M16 17H8`,  group: "Settings" },
];

// ─── Integration status helpers ──────────────────────────────────────────────
const PROVIDER_LABELS = { qbo: 'QuickBooks', xero: 'Xero', netsuite: 'NetSuite', stripe: 'Stripe', shopify: 'Shopify', plaid: 'Plaid' };

function IntegrationFooter({ integrations }) {
  const connected = (integrations || []).filter(i => i.status === 'connected' || i.status === 'syncing');
  if (!connected.length) {
    return (
      <div style={{ fontSize: 10.5, color: "var(--text-4)", padding: "0 2px 8px" }}>
        No integrations connected
      </div>
    );
  }
  // Show the first connected integration (primary)
  const primary = connected[0];
  const label   = PROVIDER_LABELS[primary.provider] || primary.provider;
  const isSyncing = primary.status === 'syncing';

  let syncLabel = 'Connected';
  if (primary.last_sync_at) {
    const mins = Math.floor((Date.now() - new Date(primary.last_sync_at)) / 60000);
    syncLabel = mins < 60 ? `Synced ${mins}m` : mins < 1440 ? `Synced ${Math.floor(mins/60)}h` : `Synced ${Math.floor(mins/1440)}d`;
  }

  return (
    <div style={{ fontSize: 10.5, color: "var(--text-3)", display: "flex", justifyContent: "space-between", padding: "0 2px 8px" }}>
      <span>Connected · {label}{connected.length > 1 ? ` +${connected.length - 1}` : ''}</span>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 4 }}>
        <span style={{
          width: 5, height: 5, borderRadius: "50%",
          background: isSyncing ? "var(--warning)" : "var(--positive)",
          boxShadow: isSyncing ? "0 0 6px var(--warning)" : "0 0 6px var(--positive)",
        }} />
        {syncLabel}
      </span>
    </div>
  );
}

// ─── Super-admin company switcher dropdown ────────────────────────────────
function AdminCompanySwitcher({ allCompanies, scopedCompanyId, onSwitchCompany, onSwitchToAdmin }) {
  const [open, setOpen] = useStateS(false);
  const ref = useRefS();

  useEffectS(() => {
    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]);

  const current = allCompanies.find(c => c.id === scopedCompanyId);
  const displayName = current?.name || (scopedCompanyId ? "Unknown" : "Demo dashboard");

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <div className="pc-sb-org-row" style={{ cursor: "pointer" }} onClick={() => setOpen(o => !o)}>
        <div style={{ width: 24, height: 24, borderRadius: 4, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 600, color: "var(--on-accent)" }}>
          {current?.name ? current.name.split(/\s+/).slice(0,2).map(w => w[0]).join("").toUpperCase() : "D"}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
            {displayName}
          </div>
          <div style={{ fontSize: 10, color: "var(--accent)", fontWeight: 600, letterSpacing: 0.3 }}>ADMIN VIEW</div>
        </div>
        <Icon d={icons.caret} size={12} />
      </div>

      {open && (
        <div style={{
          position: "absolute", top: "calc(100% + 6px)", left: 0, right: 0, zIndex: 200,
          background: "var(--bg-card)", border: "1px solid var(--border-strong)",
          borderRadius: 8, boxShadow: "0 8px 24px rgba(0,0,0,0.18)", overflow: "hidden",
          minWidth: 200,
        }}>
          <div style={{ padding: "8px 10px 4px", fontSize: 10, color: "var(--text-4)", textTransform: "uppercase", letterSpacing: 0.5 }}>
            Client companies
          </div>
          <div style={{ maxHeight: 220, overflowY: "auto" }}>
            <button
              onClick={() => { onSwitchCompany(null); setOpen(false); }}
              style={{
                display: "flex", alignItems: "center", gap: 8, width: "100%",
                padding: "7px 12px", background: !scopedCompanyId ? "var(--bg-hover)" : "none",
                border: "none", cursor: "pointer", textAlign: "left",
                color: "var(--text-1)", fontSize: 12.5,
              }}
            >
              <div style={{ width: 20, height: 20, borderRadius: 3, background: "var(--bg-elev-2)", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 9, fontWeight: 700, color: "var(--text-3)" }}>
                D
              </div>
              <span style={{ flex: 1 }}>Demo dashboard</span>
              {!scopedCompanyId && <Icon d={icons.check} size={12} />}
            </button>
            {allCompanies.length > 0 && (
              <div style={{ borderTop: "1px solid var(--border)", margin: "2px 0" }} />
            )}
            {allCompanies.map(c => (
              <button
                key={c.id}
                onClick={() => { onSwitchCompany(c.id); setOpen(false); }}
                style={{
                  display: "flex", alignItems: "center", gap: 8, width: "100%",
                  padding: "7px 12px", background: c.id === scopedCompanyId ? "var(--bg-hover)" : "none",
                  border: "none", cursor: "pointer", textAlign: "left",
                  color: "var(--text-1)", fontSize: 12.5,
                }}
              >
                <div style={{ width: 20, height: 20, borderRadius: 3, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", flexShrink: 0, display: "flex", alignItems: "center", justifyContent: "center", fontSize: 9, fontWeight: 700, color: "var(--on-accent)" }}>
                  {c.name.split(/\s+/).slice(0,2).map(w => w[0]).join("").toUpperCase()}
                </div>
                <span style={{ flex: 1, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{c.name}</span>
                {c.id === scopedCompanyId && <Icon d={icons.check} size={12} />}
              </button>
            ))}
          </div>
          <div style={{ borderTop: "1px solid var(--border)", padding: "4px 0" }}>
            <button
              onClick={() => { onSwitchToAdmin(); setOpen(false); }}
              style={{
                display: "flex", alignItems: "center", gap: 8, width: "100%",
                padding: "7px 12px", background: "none", border: "none",
                cursor: "pointer", color: "var(--accent)", fontSize: 12, fontWeight: 600,
              }}
            >
              <Icon d={icons.building} size={13} />
              Admin Console
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Sidebar ──────────────────────────────────────────────────────────────
function Sidebar({ page, setPage, bizType, persona, exceptionsCount, density, integrations, companyProfile, isSuperAdmin, allCompanies, scopedCompanyId, onSwitchToAdmin, onSwitchCompany }) {
  const items = navItems(bizType);
  const groups = items.reduce((acc, it) => {
    acc[it.group] = acc[it.group] || [];
    acc[it.group].push(it);
    return acc;
  }, {});

  const rowH = density === "compact" ? 28 : density === "comfy" ? 38 : 32;

  return (
    <aside className="pc-sidebar">
      <div className="pc-sb-brand">
        <PerduraMark size={22} />
        <div>
          <div style={{ fontSize: 13.5, fontWeight: 600, letterSpacing: -0.1 }}>Perdura Capital</div>
          <div style={{ fontSize: 10.5, color: "var(--text-3)", letterSpacing: 0.4, textTransform: "uppercase" }}>Operating intelligence</div>
        </div>
      </div>

      <div className="pc-sb-org">
        {isSuperAdmin ? (
          <AdminCompanySwitcher
            allCompanies={allCompanies}
            scopedCompanyId={scopedCompanyId}
            onSwitchCompany={onSwitchCompany}
            onSwitchToAdmin={onSwitchToAdmin}
          />
        ) : (
          <div className="pc-sb-org-row">
            <div style={{ width: 24, height: 24, borderRadius: 4, background: "linear-gradient(135deg, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center", fontSize: 11, fontWeight: 600, color: "var(--on-accent)" }}>
              {companyProfile?.name ? companyProfile.name.split(/\s+/).slice(0,2).map(w => w[0]).join("").toUpperCase() : "—"}
            </div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontSize: 12, fontWeight: 500, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{companyProfile?.name || "Your Company"}</div>
              <div style={{ fontSize: 10, color: "var(--text-3)" }}>{bizType === "service" ? "Services" : bizType === "product" ? "Product / DTC" : bizType === "retail" ? "Retail / Stores" : "Manufacturing"} · {companyProfile?.fiscal_year_end ? "FY" + (() => { const m = ["January","February","March","April","May","June","July","August","September","October","November","December"].indexOf(companyProfile.fiscal_year_end); const now = new Date(); return String(now.getMonth() <= m ? now.getFullYear() : now.getFullYear() + 1).slice(-2); })() : "FY26"}</div>
            </div>
            <Icon d={icons.caret} size={12} />
          </div>
        )}
      </div>

      <nav className="pc-sb-nav">
        {Object.entries(groups).map(([g, gItems]) => (
          <div key={g} className="pc-sb-group">
            <div className="pc-sb-group-label">{g}</div>
            {gItems.map(it => (
              <button key={it.key}
                className={"pc-sb-item " + (page === it.key ? "active" : "")}
                style={{ height: rowH }}
                onClick={() => setPage(it.key)}>
                <Icon d={it.icon} size={15} />
                <span>{it.label}</span>
                {it.key === "exceptions" && exceptionsCount > 0 && (
                  <span className="pc-badge-warning">{exceptionsCount}</span>
                )}
              </button>
            ))}
          </div>
        ))}
      </nav>

      <div className="pc-sb-foot">
        <IntegrationFooter integrations={integrations} />
        {isSuperAdmin && (
          <button
            onClick={onSwitchToAdmin}
            style={{
              display: "flex", alignItems: "center", gap: 7, width: "100%",
              padding: "7px 8px", marginBottom: 6, background: "rgba(110,231,183,0.08)",
              border: "1px solid rgba(110,231,183,0.2)", borderRadius: 6,
              cursor: "pointer", color: "var(--accent)", fontSize: 11.5, fontWeight: 600,
            }}
          >
            <Icon d={icons.building} size={13} />
            Admin Console
          </button>
        )}
        <button
          onClick={() => window.__perduraSetPage && window.__perduraSetPage("contact")}
          style={{
            display: "flex", alignItems: "center", gap: 7, width: "100%",
            padding: "7px 8px", marginBottom: 6, background: "none",
            border: "1px solid var(--border)", borderRadius: 6,
            cursor: "pointer", color: "var(--text-3)", fontSize: 11.5, fontWeight: 500,
            transition: "background 0.1s, color 0.1s",
          }}
          onMouseEnter={e => { e.currentTarget.style.background = "var(--hover)"; e.currentTarget.style.color = "var(--text-2)"; }}
          onMouseLeave={e => { e.currentTarget.style.background = "none"; e.currentTarget.style.color = "var(--text-3)"; }}
        >
          <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
          Contact support
        </button>
        <UserMenu companyProfile={companyProfile} persona={persona} />
      </div>
    </aside>
  );
}

// ─── UserMenu — avatar + dropdown with logout ─────────────────────────────
function UserMenu({ companyProfile, persona }) {
  const [open, setOpen] = useStateS(false);
  const [userEmail, setUserEmail] = useStateS("");
  const [userName, setUserName] = useStateS("");
  const ref = useRefS(null);

  useEffectS(() => {
    const db = window.supabaseClient;
    if (!db) return;
    (async () => {
      const { data: { session } } = await db.auth.getSession();
      if (session?.user) {
        setUserEmail(session.user.email || "");
        setUserName(session.user.user_metadata?.full_name || session.user.email?.split("@")[0] || "Account");
      }
    })();
  }, []);

  useEffectS(() => {
    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]);

  const handleLogout = async () => {
    const db = window.supabaseClient;
    if (db) await db.auth.signOut();
    window.location.reload();
  };

  const displayName = companyProfile?.owner_name || userName || "Account";
  const initials = displayName.split(/\s+/).slice(0, 2).map(w => w[0]).join("").toUpperCase() || "PC";

  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button
        className="pc-sb-user"
        style={{ cursor: "pointer", width: "100%", border: "1px solid var(--border)", borderRadius: 8, background: "none", textAlign: "left" }}
        onClick={() => setOpen(o => !o)}
        title="Account settings & sign out"
      >
        <div style={{
          width: 30, height: 30, borderRadius: "50%",
          background: "linear-gradient(135deg, #0284c7, #0891b2)",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 11, fontWeight: 700, color: "white", flexShrink: 0,
        }}>
          {initials}
        </div>
        <div style={{ flex: 1, minWidth: 0 }}>
          <div style={{ fontSize: 12, fontWeight: 600, overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{displayName}</div>
          <div style={{ fontSize: 10, color: "var(--text-3)", overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{userEmail || "Account"}</div>
        </div>
        <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke="var(--text-3)" strokeWidth="2.2" strokeLinecap="round"><polyline points="6 9 12 15 18 9"/></svg>
      </button>

      {open && (
        <div style={{
          position: "absolute", bottom: "calc(100% + 6px)", left: 0, right: 0, zIndex: 500,
          background: "var(--bg-card-solid)", border: "1px solid var(--border)",
          borderRadius: 10, boxShadow: "0 -4px 24px rgba(0,0,0,0.14)", overflow: "hidden",
        }}>
          <div style={{ padding: "12px 14px 8px", borderBottom: "1px solid var(--border)" }}>
            <div style={{ fontSize: 12.5, fontWeight: 600 }}>{displayName}</div>
            {userEmail && <div style={{ fontSize: 11, color: "var(--text-3)", marginTop: 2 }}>{userEmail}</div>}
          </div>
          <div style={{ padding: "4px 0" }}>
            <button
              onClick={() => { setOpen(false); window.__perduraSetPage && window.__perduraSetPage("settings_users"); }}
              style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "8px 14px", background: "none", border: "none", cursor: "pointer", color: "var(--text)", fontSize: 12.5, 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 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M20 21v-2a4 4 0 0 0-4-4H8a4 4 0 0 0-4 4v2"/><circle cx="12" cy="7" r="4"/></svg>
              Manage users
            </button>
            <button
              onClick={() => { setOpen(false); window.__perduraSetPage && window.__perduraSetPage("settings_custom"); }}
              style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "8px 14px", background: "none", border: "none", cursor: "pointer", color: "var(--text)", fontSize: 12.5, 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 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><circle cx="12" cy="12" r="3"/><path d="M19.07 4.93l-1.41 1.41M4.93 4.93l1.41 1.41M19.07 19.07l-1.41-1.41M4.93 19.07l1.41-1.41M2 12h2M20 12h2M12 2v2M12 20v2"/></svg>
              Customize
            </button>
            <button
              onClick={() => { setOpen(false); window.__perduraSetPage && window.__perduraSetPage("contact"); }}
              style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "8px 14px", background: "none", border: "none", cursor: "pointer", color: "var(--text)", fontSize: 12.5, 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 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"><path d="M4 4h16c1.1 0 2 .9 2 2v12c0 1.1-.9 2-2 2H4c-1.1 0-2-.9-2-2V6c0-1.1.9-2 2-2z"/><polyline points="22,6 12,13 2,6"/></svg>
              Contact support
            </button>
          </div>
          <div style={{ borderTop: "1px solid var(--border)", padding: "4px 0" }}>
            <button
              onClick={handleLogout}
              style={{ display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "8px 14px", background: "none", border: "none", cursor: "pointer", color: "var(--danger)", fontSize: 12.5, fontWeight: 500, textAlign: "left" }}
              onMouseEnter={e => e.currentTarget.style.background = "rgba(239,68,68,0.06)"}
              onMouseLeave={e => e.currentTarget.style.background = "none"}
            >
              <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.9" strokeLinecap="round" strokeLinejoin="round"><path d="M9 21H5a2 2 0 0 1-2-2V5a2 2 0 0 1 2-2h4"/><polyline points="16 17 21 12 16 7"/><line x1="21" y1="12" x2="9" y2="12"/></svg>
              Sign out
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

// ─── Topbar ───────────────────────────────────────────────────────────────
function Topbar({ period, setPeriod, fiscalYear, setFiscalYear, persona, setPersona, bizType, setBizType, onOpenAI, exceptionsCount, page, density, companyProfile }) {
  const periods = ["MTD", "QTD", "YTD", "TTM"];
  const personas = ["CEO", "CFO", "Ops"];
  const years = ["FY24", "FY25", "FY26", "FY27 (Plan)"];
  const pageLabel = (navItems(bizType).find(n => n.key === page) || {}).label || "Dashboard";

  return (
    <header className="pc-topbar">
      <div style={{ display: "flex", alignItems: "center", gap: 14, flex: 1, minWidth: 0 }}>
        <div>
          <div style={{ fontSize: 10.5, color: "var(--text-3)", letterSpacing: 0.4, textTransform: "uppercase" }}>{companyProfile?.name || "Your Company"} · {bizType === "service" ? "Services" : bizType === "product" ? "Product" : bizType === "retail" ? "Retail" : "Manufacturing"}</div>
          <h1 style={{ fontSize: 18, fontWeight: 600, letterSpacing: -0.3, margin: 0 }}>{pageLabel}</h1>
        </div>
      </div>

      <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
        {/* Search */}
        <div className="pc-search">
          <Icon d={icons.search} size={13} />
          <input placeholder="Ask anything · search invoices, SKUs, customers" />
          <kbd>⌘K</kbd>
        </div>

        {/* Year selector */}
        <select className="pc-year-select" value={fiscalYear} onChange={(e) => setFiscalYear(e.target.value)} title="Fiscal year">
          {years.map(y => <option key={y} value={y}>{y}</option>)}
        </select>

        {/* Persona switcher */}
        <div className="pc-seg">
          {personas.map(p => (
            <button key={p} className={persona === p ? "active" : ""} onClick={() => setPersona(p)}>{p}</button>
          ))}
        </div>

        {/* Period */}
        <div className="pc-seg">
          {periods.map(p => (
            <button key={p} className={period === p ? "active" : ""} onClick={() => setPeriod(p)}>{p}</button>
          ))}
        </div>

        <button className="pc-icon-btn" title="Refresh"><Icon d={icons.refresh} size={14} /></button>
        <button className="pc-icon-btn" title="Export"><Icon d={icons.download} size={14} /></button>
        <button className="pc-ai-btn" onClick={onOpenAI} title="Open AI Copilot">
          <Icon d={icons.ai} size={14} />
          Ask Perdura
        </button>
      </div>
    </header>
  );
}

// ─── AI Copilot Drawer ────────────────────────────────────────────────────
const aiSuggestionsByPage = {
  overview: [
    "Why did EBITDA dip 3.2 pts last month?",
    "Compare gross margin trend by product line",
    "Which expense categories grew faster than revenue?",
  ],
  sales: [
    "Top 10 customers by revenue growth YTD",
    "Which products are losing momentum in the South region?",
    "Show me deals at risk based on 30-day patterns",
  ],
  inventory: [
    "Which SKUs are tying up the most working capital?",
    "Recommend reorder quantities for fast-movers",
    "Flag slow stock with no movement in 90 days",
  ],
  supply: [
    "Which vendors are slipping on lead time?",
    "If V-205 lead time slips 2 weeks, what stocks out?",
    "Compare landed cost: air vs sea for AUR-100",
  ],
  cash: [
    "Project cash position if AR > 60d collects 50%",
    "Best week to make CapEx purchase next quarter",
    "Sensitivity: 5% AR delay vs. baseline",
  ],
  arap: [
    "Which customers have changed payment behavior?",
    "Draft collections priorities for the next week",
    "Which vendors offer payment discounts I'm missing?",
  ],
  service: [
    "Resources below utilization target last 4 weeks",
    "Project Halcyon — where is the budget overrun coming from?",
    "Forecast bench cost over next 6 weeks",
  ],
  customer: [
    "Most profitable customer segment by net margin",
    "Customers where support cost exceeds gross profit",
    "Cross-sell candidates based on segment patterns",
  ],
  margin: [
    "Walk me through GM bridge from Q1 to Q2",
    "Margin attribution: mix vs. price vs. cost",
    "Top 5 margin compressions over 90 days",
  ],
  forecast: [
    "Show downside scenario with -10% revenue",
    "What if churn doubles? When does cash run out?",
    "Compare base vs upside on hiring assumptions",
  ],
  exceptions: [
    "Group recent exceptions by root cause",
    "Show me only exceptions tied to top-10 customers",
    "Trend of margin exceptions over 6 months",
  ],
};

const aiCannedAnswer = (q) => {
  // Hardcoded plausible response
  if (/ebitda/i.test(q)) return "EBITDA fell 3.2 pts MoM ($87.4K). Driver decomposition:\n• Gross margin -1.8 pts ($52.1K) — primarily Aurelius Pro Kit lots received post-Apr 18 carrying 9% higher unit cost.\n• Opex +1.4 pts ($35.3K) — software subscriptions ($18K, mostly auto-renewals) and travel ($11K, conference).\n• Volume neutral.\n\nIf vendor V-201 cost normalizes next month, ~$32K of margin returns automatically. The auto-renewals are the more actionable lever.";
  if (/top.*customers/i.test(q)) return "YTD top growth (revenue, % vs same period prior year):\n1. Northwind Holdings   +$184K   +41%\n2. Aperture Labs       +$98K    +112% (new logo Mar '25)\n3. Halcyon Group       +$76K    +14%\n4. Ironwood Partners   +$58K    +22%\n5. Quorum Bio          +$51K    +new\n\n2 of 5 are accounts where ACV expanded post-implementation. Suggested action: replicate playbook with Brightside (currently at original ACV).";
  if (/cash|runway/i.test(q)) return "Current cash: $1.82M. Baseline 90-day projection ends at $1.71M. Burn = $1.1K/day net.\n\nIf AR > 60d collects only 50% (vs baseline 80%), endpoint drops to $1.64M and runway compresses by ~14 days. The bigger lever is the $48.2K Atlas Logistics invoice — solo collection would extend runway by 26 days.";
  return "Working on that. (Connect a real model to see live answers.) Suggested next: filter by period, drill into the top contributing line, or compare against the prior 3 months.";
};

function AICopilot({ open, onClose, page }) {
  const [messages, setMessages] = useStateS([
    { role: "system", content: "Perdura AI is reading your live GL, invoices, and operational data. Ask anything." },
  ]);
  const [input, setInput] = useStateS("");
  const [thinking, setThinking] = useStateS(false);
  const endRef = useRefS();

  useEffectS(() => {
    if (endRef.current) endRef.current.scrollIntoView({ behavior: "smooth" });
  }, [messages, thinking]);

  const send = (text) => {
    if (!text.trim()) return;
    const userMsg = { role: "user", content: text };
    setMessages(m => [...m, userMsg]);
    setInput("");
    setThinking(true);
    setTimeout(() => {
      setMessages(m => [...m, { role: "assistant", content: aiCannedAnswer(text) }]);
      setThinking(false);
    }, 900);
  };

  const suggestions = aiSuggestionsByPage[page] || aiSuggestionsByPage.overview;

  return (
    <>
      <div className={"pc-ai-backdrop " + (open ? "open" : "")} onClick={onClose} />
      <aside className={"pc-ai-drawer " + (open ? "open" : "")}>
        <div className="pc-ai-hd">
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <div style={{ width: 26, height: 26, borderRadius: 6, background: "radial-gradient(circle at 30% 30%, var(--accent), var(--accent-2))", display: "flex", alignItems: "center", justifyContent: "center" }}>
              <Icon d={icons.ai} size={14} stroke="var(--on-accent)" strokeWidth={2.2} />
            </div>
            <div>
              <div style={{ fontSize: 13, fontWeight: 600 }}>Perdura Copilot</div>
              <div style={{ fontSize: 10.5, color: "var(--text-3)" }}>Reading your live data · QuickBooks · Last sync 2m</div>
            </div>
          </div>
          <button className="pc-icon-btn" onClick={onClose}><Icon d={icons.x} size={14} /></button>
        </div>

        <div className="pc-ai-body">
          {messages.map((m, i) => (
            <div key={i} className={"pc-ai-msg " + m.role}>
              {m.role === "system" ? (
                <div className="pc-ai-system">{m.content}</div>
              ) : m.role === "user" ? (
                <div className="pc-ai-user">{m.content}</div>
              ) : (
                <div className="pc-ai-assistant">
                  {m.content.split("\n").map((ln, j) => <div key={j}>{ln || <br />}</div>)}
                </div>
              )}
            </div>
          ))}
          {thinking && (
            <div className="pc-ai-msg assistant">
              <div className="pc-ai-assistant pc-ai-thinking">
                <span></span><span></span><span></span>
              </div>
            </div>
          )}
          <div ref={endRef} />
        </div>

        <div className="pc-ai-foot">
          <div style={{ fontSize: 10, color: "var(--text-3)", textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 8 }}>Suggested for this page</div>
          <div style={{ display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 12 }}>
            {suggestions.map((s, i) => (
              <button key={i} className="pc-ai-suggest" onClick={() => send(s)}>{s}</button>
            ))}
          </div>
          <div className="pc-ai-input-wrap">
            <input value={input} onChange={(e) => setInput(e.target.value)}
              onKeyDown={(e) => e.key === "Enter" && send(input)}
              placeholder="Ask about your business…" />
            <button onClick={() => send(input)} className="pc-ai-send">
              <Icon d="M5 12h14 M13 6l6 6-6 6" size={14} />
            </button>
          </div>
        </div>
      </aside>
    </>
  );
}

Object.assign(window, { PerduraMark, Sidebar, Topbar, AICopilot, Icon, icons, navItems });
