/* VCP shell: Brand, Sidebar (3 states), TopBar, CompanySwitcher, PeriodSelector, UserMenu. */

function Brand({ collapsed }) {
  return <div style={{ display: "flex", alignItems: "center", gap: 10, padding: collapsed ? "0" : "2px 2px" }}>
    <span style={{ width: 30, height: 30, borderRadius: 8, background: "var(--accent)", color: "#fff", display: "inline-flex", alignItems: "center", justifyContent: "center", fontWeight: 800, fontSize: 13, letterSpacing: "-0.02em", flexShrink: 0 }}>NB</span>
    {!collapsed && <div style={{ lineHeight: 1.15 }}>
      <div style={{ fontWeight: 700, fontSize: 13.5, letterSpacing: "-0.01em" }}>Northbridge</div>
      <div style={{ fontSize: 10, color: "var(--ink-soft)", textTransform: "uppercase", letterSpacing: "0.06em", fontWeight: 600 }}>Value Creation Platform</div>
    </div>}
  </div>;
}

function NavItem({ icon, label, active, onClick, indent, sub }) {
  const [h, setH] = useState(false);
  return <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)} style={{
    display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "left",
    padding: indent ? "7px 10px 7px 34px" : "8px 10px", borderRadius: 8, border: "none",
    background: active ? "var(--accent-soft)" : (h ? "rgba(0,0,0,0.03)" : "transparent"),
    color: active ? "var(--accent)" : "var(--ink-muted)", fontWeight: active ? 600 : 500,
    fontSize: sub ? 12.5 : 13, transition: "color 120ms ease", position: "relative",
  }}>
    {active && !indent && <span style={{ position: "absolute", left: -8, top: 8, bottom: 8, width: 3, borderRadius: 3, background: "var(--accent)" }} />}
    {icon && <Icon name={icon} size={17} color={active ? "var(--accent)" : "var(--ink-soft)"} />}
    <span style={{ flex: 1 }}>{label}</span>
  </button>;
}

const FIRM_NAV = [
  { key: "portfolio", icon: "layers", label: "Investments" },
  { key: "value-creation", icon: "trendingUp", label: "Value Creation" },
  { key: "collaboration", icon: "columns", label: "Collaboration" },
];
const CO_NAV = [
  { key: "co-overview", icon: "building", label: "Overview" },
  { key: "co-oversight", icon: "layers", label: "Investment" },
  { key: "co-valuecreation", icon: "trendingUp", label: "Value Creation" },
  { key: "co-collaboration", icon: "columns", label: "Collaboration" },
];
const PORTCO_NAV = [
  { key: "pc-company", icon: "building", label: "My Company" },
  { key: "pc-assessment", icon: "list", label: "Assessment" },
  { key: "pc-playbooks", icon: "book", label: "Playbooks" },
];

function Sidebar({ state, go, openCompany }) {
  const inCompany = state.door === "firm" && state.companyId;
  const company = state.companyId ? VCP.companyById(state.companyId) : null;
  return <aside style={{
    width: "var(--sidebar-w)", flexShrink: 0, background: "var(--surface-warm)",
    borderRight: "1px solid var(--line)", display: "flex", flexDirection: "column", height: "100%",
  }}>
    <div style={{ padding: "16px 16px 12px" }}><Brand /></div>

    <nav className="scroll-y" style={{ flex: 1, padding: "4px 12px 12px", display: "flex", flexDirection: "column", gap: 2 }}>
      {state.door === "portco" && <>
        <div className="micro" style={{ padding: "8px 8px 6px" }}>{VCP.companyById("helios").name}</div>
        {PORTCO_NAV.map(n => <NavItem key={n.key} {...n} active={state.route === n.key} onClick={() => go({ route: n.key })} />)}
      </>}

      {state.door === "firm" && !inCompany && <>
        <div className="micro" style={{ padding: "8px 8px 6px" }}>Portfolio</div>
        {FIRM_NAV.map(n => <NavItem key={n.key} {...n} active={state.route === n.key} onClick={() => go({ route: n.key })} />)}
      </>}

      {state.door === "firm" && inCompany && <>
        <button onClick={() => go({ route: "portfolio", companyId: null })} style={{
          display: "flex", alignItems: "center", gap: 7, background: "none", border: "none",
          color: "var(--ink-soft)", fontSize: 12, fontWeight: 600, padding: "6px 8px", marginBottom: 2,
        }}><Icon name="arrowLeft" size={14} /> Back to portfolio</button>
        <div style={{ display: "flex", alignItems: "center", gap: 9, padding: "8px", background: "var(--surface-card)", border: "1px solid var(--line)", borderRadius: 9, marginBottom: 8 }}>
          <CompanyMark company={company} size={28} />
          <div style={{ lineHeight: 1.2, overflow: "hidden" }}>
            <div style={{ fontWeight: 700, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{company.name}</div>
            <div style={{ fontSize: 11, color: "var(--ink-soft)" }}>{company.sector}</div>
          </div>
        </div>
        {CO_NAV.map(n => <NavItem key={n.key} {...n} active={state.route === n.key} onClick={() => go({ route: n.key })} />)}
      </>}
    </nav>

    {state.door === "firm" && !inCompany && <div style={{ padding: "8px 12px 12px", borderTop: "1px solid var(--line)" }}>
      <NavItem icon="sliders" label="Admin" active={state.route === "admin"} onClick={() => go({ route: "admin" })} />
    </div>}

    <div style={{ padding: "10px 14px", borderTop: "1px solid var(--line)", fontSize: 10.5, color: "var(--ink-faint)", display: "flex", alignItems: "center", gap: 6 }}>
      <Icon name="shield" size={12} /> Microsoft EntraID SSO
    </div>
  </aside>;
}

function CompanySwitcher({ state, go }) {
  const current = state.companyId ? VCP.companyById(state.companyId) : null;
  return <Dropdown width={300} trigger={(open) => <button style={{
    display: "flex", alignItems: "center", gap: 9, padding: "5px 9px 5px 6px", borderRadius: 9,
    border: "1px solid var(--line)", background: "var(--surface-card)", color: "var(--ink)", maxWidth: 240,
  }}>
    {current ? <CompanyMark company={current} size={22} /> : <span style={{ width: 22, height: 22, borderRadius: 6, background: "var(--surface-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="layers" size={13} color="var(--ink-soft)" /></span>}
    <span style={{ fontWeight: 600, fontSize: 13, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{current ? current.name : "All companies"}</span>
    <Icon name="chevronD" size={14} color="var(--ink-soft)" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" }} />
  </button>}>
    {(close) => <div>
      <div className="micro" style={{ padding: "6px 8px 4px" }}>Jump to company</div>
      <button onClick={() => { go({ route: "portfolio", companyId: null }); close(); }} style={menuRowStyle(!current)}>
        <span style={{ width: 22, height: 22, borderRadius: 6, background: "var(--surface-deep)", display: "inline-flex", alignItems: "center", justifyContent: "center" }}><Icon name="layers" size={13} color="var(--ink-soft)" /></span>
        <span style={{ fontWeight: 600 }}>All companies</span>
        <span style={{ marginLeft: "auto", fontSize: 11, color: "var(--ink-faint)" }}>Portfolio</span>
      </button>
      <div style={{ height: 1, background: "var(--line-soft)", margin: "4px 0" }} />
      <div className="scroll-y" style={{ maxHeight: 320 }}>
        {VCP.companies.map(c => <button key={c.id} onClick={() => { go({ route: "co-overview", companyId: c.id }); close(); }} style={menuRowStyle(current && current.id === c.id)}>
          <CompanyMark company={c} size={22} />
          <span style={{ display: "flex", flexDirection: "column", lineHeight: 1.2, alignItems: "flex-start", overflow: "hidden" }}>
            <span style={{ fontWeight: 600, fontSize: 12.5 }}>{c.name}</span>
            <span style={{ fontSize: 11, color: "var(--ink-soft)" }}>{c.fundLabel}</span>
          </span>
          <span style={{ marginLeft: "auto" }}><ScoreBadge score={c.maturity} size="sm" /></span>
        </button>)}
      </div>
    </div>}
  </Dropdown>;
}
function menuRowStyle(active) {
  return { display: "flex", alignItems: "center", gap: 9, width: "100%", padding: "7px 8px", borderRadius: 8, border: "none", background: active ? "var(--accent-soft)" : "transparent", color: "var(--ink)", textAlign: "left", cursor: "pointer" };
}

function PeriodSelector({ state, go }) {
  return <Dropdown width={150} align="right" trigger={(open) => <button style={{
    display: "flex", alignItems: "center", gap: 7, padding: "6px 10px", borderRadius: 9,
    border: "1px solid var(--line)", background: "var(--surface-card)", color: "var(--ink)",
  }}>
    <Icon name="calendar" size={14} color="var(--ink-soft)" />
    <span className="tabular" style={{ fontWeight: 600, fontSize: 13 }}>{state.period}</span>
    <Icon name="chevronD" size={13} color="var(--ink-soft)" style={{ transform: open ? "rotate(180deg)" : "none", transition: "transform 150ms" }} />
  </button>}>
    {(close) => <div>
      <div className="micro" style={{ padding: "6px 8px 4px" }}>Review period</div>
      {[...VCP.QUARTERS].reverse().map(q => <button key={q} onClick={() => { go({ period: q }); close(); }} style={menuRowStyle(state.period === q)}>
        <span className="tabular" style={{ fontWeight: 600 }}>{q}</span>
        {q === "25Q2" && <span style={{ marginLeft: "auto", fontSize: 10.5, color: "var(--ink-faint)" }}>Latest</span>}
      </button>)}
    </div>}
  </Dropdown>;
}

function UserMenu({ state, go, toggleDark }) {
  const u = state.door === "portco" ? VCP.user.portco : VCP.user.firm;
  return <Dropdown width={260} align="right" trigger={() => <button style={{ display: "flex", alignItems: "center", gap: 0, border: "none", background: "transparent", padding: 0 }}>
    <Avatar name={u.name} size={32} color="var(--accent)" />
  </button>}>
    {(close) => <div>
      <div style={{ padding: "8px 10px 10px", display: "flex", gap: 10, alignItems: "center" }}>
        <Avatar name={u.name} size={36} color="var(--accent)" />
        <div style={{ lineHeight: 1.3, overflow: "hidden" }}>
          <div style={{ fontWeight: 700, fontSize: 13 }}>{u.name}</div>
          <div style={{ fontSize: 11, color: "var(--ink-soft)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{u.email}</div>
        </div>
      </div>
      <div style={{ padding: "0 10px 8px" }}><Badge variant={state.door === "portco" ? "warn" : "accent"}>{u.role}</Badge></div>
      <div style={{ height: 1, background: "var(--line-soft)", margin: "2px 0 6px" }} />
      <button onClick={() => { toggleDark(); }} style={menuRowStyle(false)}>
        <Icon name={state.dark ? "sun" : "moon"} size={16} color="var(--ink-soft)" />{state.dark ? "Light mode" : "Dark mode"}
      </button>
      <button onClick={() => { go({ door: null, route: "login", companyId: null }); close(); }} style={menuRowStyle(false)}>
        <Icon name="logout" size={16} color="var(--ink-soft)" />Sign out
      </button>
    </div>}
  </Dropdown>;
}

const ROUTE_TITLES = {
  "portfolio": "Portfolio", "value-creation": "Value Creation", "collaboration": "Collaboration", "admin": "Admin",
  "co-overview": "Overview", "co-oversight": "Investment", "co-valuecreation": "Value Creation", "co-collaboration": "Collaboration",
  "pc-company": "My Company", "pc-assessment": "Assessment", "pc-playbooks": "Playbooks",
};

function TopBar({ state, go, toggleDark }) {
  const company = state.companyId ? VCP.companyById(state.companyId) : null;
  let title = ROUTE_TITLES[state.route] || "";
  let crumb = null;
  if (state.door === "firm" && company) crumb = company.name;
  return <header style={{
    height: "var(--topbar-h)", flexShrink: 0, borderBottom: "1px solid var(--line)",
    background: "var(--surface-card)", display: "flex", alignItems: "center", gap: 14, padding: "0 18px",
  }}>
    <div style={{ minWidth: 0, display: "flex", alignItems: "baseline", gap: 8 }}>
      {crumb && <><span style={{ fontSize: 13, color: "var(--ink-soft)", whiteSpace: "nowrap" }}>{crumb}</span><span style={{ color: "var(--ink-faint)" }}>/</span></>}
      <h1 style={{ margin: 0, fontSize: 16, fontWeight: 700, letterSpacing: "-0.01em", whiteSpace: "nowrap" }}>{title}</h1>
    </div>
    <div style={{ flex: 1 }} />
    <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
      {state.door === "firm" && <CompanySwitcher state={state} go={go} />}
      <PeriodSelector state={state} go={go} />
      <div style={{ width: 1, height: 24, background: "var(--line)" }} />
      <IconBtn name={state.dark ? "sun" : "moon"} onClick={toggleDark} title="Toggle theme" />
      <UserMenu state={state} go={go} toggleDark={toggleDark} />
    </div>
  </header>;
}

Object.assign(window, { Sidebar, TopBar, Brand, ROUTE_TITLES });
