// Shared shell for the whole reseller/customer-facing portal — Dashboard,
// Quotes, Raise a ticket, My tickets, and (as Phase 1+ features land)
// Deal registration, Order history, Marketing downloads, etc.
//
// THEME UNIFICATION (pass 1): ResellerShell first mirrored AdminShell's
// STRUCTURE/MOTION only (left sidebar, icon + label nav, 2px active
// bar, hover nudge, shared ShellNavButton from portal-icons.jsx) while
// deliberately staying dark — the portal's own "night" identity.
//
// WHITE THEME (pass 2): ResellerShell flipped to the same pure
// white-on-black palette AdminShell uses.
//
// LIGHT/DARK TOGGLE (this pass): the flip in pass 2 is now a runtime
// CHOICE, not a hardcoded palette — every colour below reads a
// --pt-* CSS variable (defined + flipped by portal-theme.jsx) instead
// of a literal hex/rgba, and the root <section> stamps
// data-portal-theme={theme} so those variables resolve for this whole
// subtree, including AskSoloAiWidget mode="portal" and every child
// page rendered inside `children` (reseller-portal-dashboard.jsx,
// reseller-quotes-page.jsx, support-page.jsx — see their own files).
// Defaults to "light" (see usePortalTheme in portal-theme.jsx) per the
// portal's white-theme default; a reseller can flip to dark via the
// toggle in the sidebar footer, and the choice persists across pages/
// reloads via localStorage. AdminShell itself is untouched and stays
// permanently light — this toggle is reseller/customer-portal-only.
//
// Loaded AFTER portal-theme.jsx (theme system) and portal-icons.jsx
// (icon set + shared ShellNavButton). Loaded before
// reseller-portal-dashboard.jsx, reseller-quotes-page.jsx and
// support-page.jsx (see index.html) so ResellerShell is available on
// window by the time they run.

const RESELLER_NAV_ITEMS = [
  { id: "portal-dashboard",   targetPage: "portal-dashboard", label: "Overview", icon: IconOverview },
  { id: "portal-quotes",      targetPage: "portal-quotes",    label: "Quotes", icon: IconQuote },
  { id: "support-raise",      targetPage: "support", tab: "raise",       label: "Raise a ticket", icon: IconTicket },
  { id: "support-my-tickets", targetPage: "support", tab: "my-tickets",  label: "My tickets", icon: IconTicketList },
];

// `page`: current page id ("portal-dashboard" / "portal-quotes" /
// "support") — used with `activeTab` (only meaningful when
// page === "support") to highlight the right nav entry, since "Raise a
// ticket" and "My tickets" are both the "support" page, just different
// tabs.
// `activeTab`: "raise" | "my-tickets" | undefined.
// `userName`/`companyName`: plain strings for the signed-in reseller +
// their company (already fetched by the calling page via
// /api/portal/me) — shown in the sidebar footer so every portal page
// reads as "you, signed in, at this company" without re-fetching.
// `title`/`subtitle`/`actions`: optional page-header block, same
// contract as AdminShell's, rendered above `children`.
//
// Solo-staff "view as company" switcher — only ever rendered for an
// is_solo_staff reseller account (see migrations/0017 +
// routes/portal.ts's loadResellerContext); a normal reseller never gets
// these props populated, so they see plain text exactly as before.
// `isSoloStaff`: bool — gates whether the dropdown renders at all.
// `companies`: [{ id, name }] — every approved company, fetched by the
// calling page from GET /api/portal/companies once it knows
// isSoloStaff is true.
// `companyName`/an implicit `companyId` via `currentCompanyId`: which
// company is CURRENTLY being viewed (defaults to the staff member's own
// home company — Solo — on a fresh sign-in, per session; see
// sessions.active_company_id).
// `onSwitchCompany(companyId)`: called with the newly-selected company's
// id when the dropdown changes; the calling page is responsible for
// POSTing /api/portal/switch-company and then refetching whatever
// company-scoped data it shows (assets, tickets, invoices, ...).
function ResellerShell({
  page, activeTab, onNavigate, userName, companyName, title, subtitle, actions, children,
  isSoloStaff, companies, currentCompanyId, onSwitchCompany,
}) {
  const [theme, toggleTheme] = usePortalTheme();
  const isDark = theme === "dark";

  const handleLogout = async () => {
    try { await fetch("/api/portal/logout", { method: "POST", credentials: "same-origin" }); }
    finally { onNavigate("home"); }
  };

  const isActive = (item) => {
    if (item.targetPage !== page) return false;
    if (!item.tab) return true;
    return activeTab === item.tab;
  };

  const handleNavClick = (item) => {
    onNavigate(item.targetPage, item.tab ? { tab: item.tab } : undefined);
  };

  return (
    <section data-portal-theme={theme} style={{ background: "var(--pt-bg)", color: "var(--pt-fg)", minHeight: "calc(100vh - 88px)", display: "flex" }}>
      <PortalThemeStyles />
      <aside
        data-testid="reseller-shell-sidebar"
        style={{
          width: 240, flex: "0 0 240px",
          borderRight: "1px solid var(--pt-border)",
          display: "flex", flexDirection: "column",
          position: "sticky", top: 88, height: "calc(100vh - 88px)",
          alignSelf: "flex-start",
        }}
      >
        <div style={{ padding: "30px 26px 22px" }}>
          <div style={{
            display: "flex", alignItems: "center", justifyContent: "space-between", gap: 10,
          }}>
            <div style={{
              fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
              letterSpacing: "0.04em", textTransform: "uppercase", color: "var(--pt-fg)",
            }}>Solo Portal</div>
            <PortalThemeToggle theme={theme} onToggle={toggleTheme} compact />
          </div>
          <div style={{ marginTop: 12 }}>
            {isSoloStaff && Array.isArray(companies) && companies.length > 0 ? (
              <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
                <IconSwitch size={12} />
                <select
                  value={currentCompanyId || ""}
                  onChange={(e) => onSwitchCompany && onSwitchCompany(Number(e.target.value))}
                  data-testid="reseller-shell-company-switcher"
                  style={{
                    background: "var(--pt-bg)", border: "1px solid var(--pt-border-strong)",
                    color: "var(--pt-fg)", cursor: "pointer", padding: "6px 8px",
                    fontFamily: "var(--font-body)", fontSize: 12, flex: 1, minWidth: 0,
                  }}
                >
                  {companies.map((co) => (
                    <option key={co.id} value={co.id}>{co.name}</option>
                  ))}
                </select>
              </div>
            ) : companyName ? (
              <div style={{ fontFamily: "var(--font-body)", fontSize: 12.5, color: "var(--pt-fg-dim)" }}>
                {companyName}
              </div>
            ) : null}
            {userName && (
              <div style={{ fontFamily: "var(--font-body)", fontSize: 11.5, color: "var(--pt-fg-faint2)", marginTop: 4 }}>
                {userName}
              </div>
            )}
          </div>
        </div>

        <nav style={{ display: "flex", flexDirection: "column", gap: 1, flex: 1, overflowY: "auto", padding: "4px 12px" }}>
          {RESELLER_NAV_ITEMS.map((item) => (
            <ShellNavButton
              key={item.id} label={item.label} Icon={item.icon}
              active={isActive(item)} onClick={() => handleNavClick(item)}
              testId={`reseller-nav-${item.id}`} dark={isDark}
            />
          ))}
        </nav>

        <div style={{ padding: "0 22px 24px", borderTop: "1px solid var(--pt-border)", paddingTop: 18 }}>
          <button
            type="button" onClick={handleLogout} data-testid="reseller-shell-logout"
            className="pt-signout-btn"
            style={{
              width: "100%", background: "none", border: "1px solid var(--pt-border-strong)",
              color: "var(--pt-fg-3)", cursor: "pointer", padding: "10px 14px",
              fontFamily: "var(--font-body)", fontSize: 11.5, fontWeight: 500,
              letterSpacing: "0.12em", textTransform: "uppercase",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 8,
              transition: "background 140ms, color 140ms, border-color 140ms",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "var(--pt-fg)"; e.currentTarget.style.color = "var(--pt-bg)"; e.currentTarget.style.borderColor = "var(--pt-fg)"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "none"; e.currentTarget.style.color = "var(--pt-fg-3)"; e.currentTarget.style.borderColor = "var(--pt-border-strong)"; }}
          >
            <IconSignOut size={14} />
            Sign out
          </button>
        </div>
      </aside>

      <div style={{ flex: 1, minWidth: 0, padding: "48px 40px 120px" }}>
        <div style={{ maxWidth: 1100, margin: "0 auto" }}>
          {(title || subtitle || actions) && (
            <div style={{
              display: "flex", justifyContent: "space-between", alignItems: "flex-start",
              flexWrap: "wrap", gap: 20, marginBottom: 36,
              borderBottom: "1px solid var(--pt-border)", paddingBottom: 30,
            }}>
              <div>
                {subtitle && (
                  <div style={{
                    fontFamily: "var(--font-body)", fontSize: 10, letterSpacing: "0.28em",
                    textTransform: "uppercase", color: "var(--pt-fg-faint)",
                    fontWeight: 500, marginBottom: 12,
                  }}>{subtitle}</div>
                )}
                {title && (
                  <h1 style={{
                    fontFamily: "var(--font-display)", fontWeight: 700,
                    fontSize: "clamp(26px, 3.6vw, 38px)", textTransform: "uppercase",
                    margin: 0, color: "var(--pt-fg)",
                  }}>{title}</h1>
                )}
              </div>
              {actions && <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>{actions}</div>}
            </div>
          )}
          {children}
        </div>
      </div>

      <AskSoloAiWidget mode="portal" />
    </section>
  );
}

Object.assign(window, { ResellerShell, RESELLER_NAV_ITEMS });
