// Shared navigation shell for the whole Solo staff admin area. Every
// admin page (Approvals, Customers, Assets, Price List, Orders, Invoices,
// Purchase Orders, ...) renders itself INSIDE <AdminShell> instead of
// duplicating its own header/nav-button row — this is the single,
// scalable nav surface the CRM/ERP/MRP page set builds against going
// forward (replacing the old per-page ad-hoc "Approvals / Customers /
// Assets / Sign out" button rows).
//
// A left sidebar was chosen over a top bar because the nav list will
// keep growing (more CRM/ERP/MRP modules to come) — a sidebar scales to
// more items far better than a horizontal bar squeezed under the public
// TopNav.
//
// THEME UNIFICATION (this pass): AdminShell and ResellerShell now share
// one visual language — strict black-on-white brand palette (no amber/
// orange accent — that's gone from both shells and every nav highlight;
// see portal-icons.jsx's header comment for the same note on
// ResellerShell), a labelled icon next to every nav item (see
// portal-icons.jsx), and the same hover/active motion language (2px
// black bar sliding in from the left, icon + label nudging right a
// touch, background tinting in). Both shells also share the identical
// sidebar skeleton now — width, header block, footer block, sign-out
// button styling — so a staff member who also has reseller access (the
// "Solo staff viewing as a company" case — see routes/portal.ts) sees
// one consistent nav idiom in both areas instead of two unrelated ones.
//
// Loaded before every other admin-*-page.jsx file, and after
// portal-icons.jsx (see index.html) so AdminShell + the icon set are
// both available on window by the time they run.

const ADMIN_NAV_ITEMS = [
  { id: "admin-approvals", label: "Approvals", icon: IconApprovals },
  { id: "admin-companies", label: "Customers", icon: IconCustomers },
  { id: "admin-assets", label: "Assets", icon: IconAssets },
  { id: "admin-pricing", label: "Price List", icon: IconPriceList },
  { id: "admin-quotes", label: "Quotes", icon: IconQuote },
  { id: "admin-orders", label: "Orders", icon: IconOrders },
  { id: "admin-invoices", label: "Invoices", icon: IconInvoices },
  { id: "admin-purchase-orders", label: "Purchase Orders", icon: IconPurchaseOrders },
  { id: "admin-spec-sheets", label: "Spec Sheets", icon: IconSpecSheets },
  { id: "admin-tickets", label: "Support Tickets", icon: IconTicketList },
  { id: "admin-settings", label: "Settings", icon: IconSettings },
  // Master-admin-only — Jay (role: "admin") can't see the Staff nav item at
  // all, matching the backend's requireSuperAdmin gate on every route in
  // routes/admin-staff.ts (he couldn't do anything on the page even if he
  // guessed the URL, but hiding the nav item avoids a confusing dead end).
  { id: "admin-staff", label: "Staff", icon: IconStaff, superAdminOnly: true },
];

// Mission Control lives OUTSIDE this shell (see mission-control.jsx's file
// header — it's a deliberately separate full-page area with its own top
// bar + sidebar, not another AdminShell page). This entry is rendered as
// a visually distinct link at the bottom of the sidebar rather than an
// ADMIN_NAV_ITEMS row, since selecting it navigates clean out of
// AdminShell instead of highlighting a page within it.
const MISSION_CONTROL_ENTRY_ID = "mission-control";

// `admin`: the signed-in admin user object (id/name/email/role) or null
// while still loading — pages fetch this themselves via /api/admin/me
// (unchanged from before) and pass it straight through.
// `page`: current page id (one of ADMIN_NAV_ITEMS' ids) — highlights the
// active nav entry.
// `title`/`subtitle`: rendered in the shared page-header block. Either
// can be omitted (e.g. a page that wants a fully custom header) and the
// header block won't render at all.
// `actions`: optional ReactNode rendered top-right of the header (e.g. a
// "+ Add unit" button) — mirrors where each page used to put its own
// action button before this refactor.
// `children`: the page's own body content, unchanged.
function AdminShell({ admin, page, onNavigate, title, subtitle, actions, children }) {
  const handleLogout = async () => {
    try { await fetch("/api/admin/logout", { method: "POST", credentials: "same-origin" }); }
    finally { onNavigate("home"); }
  };

  return (
    <section style={{ background: "#fff", color: "#000", minHeight: "calc(100vh - 88px)", display: "flex" }}>
      <aside
        data-testid="admin-shell-sidebar"
        style={{
          width: 240, flex: "0 0 240px",
          borderRight: "1px solid rgba(0,0,0,0.1)",
          display: "flex", flexDirection: "column",
          position: "sticky", top: 88, height: "calc(100vh - 88px)",
          alignSelf: "flex-start",
        }}
      >
        <div style={{ padding: "30px 26px 22px" }}>
          <div style={{
            fontFamily: "var(--font-display)", fontWeight: 700, fontSize: 15,
            letterSpacing: "0.04em", textTransform: "uppercase", color: "#000",
          }}>Solo Admin</div>
          <div style={{
            fontFamily: "var(--font-body)", fontSize: 10, letterSpacing: "0.2em",
            textTransform: "uppercase", color: "rgba(0,0,0,0.4)", fontWeight: 500, marginTop: 4,
          }}>Staff area</div>
        </div>

        <nav style={{ display: "flex", flexDirection: "column", gap: 1, flex: 1, overflowY: "auto", padding: "4px 12px" }}>
          {ADMIN_NAV_ITEMS.filter((item) => !item.superAdminOnly || (admin && admin.role === "super_admin")).map((item) => (
            <ShellNavButton
              key={item.id} label={item.label} Icon={item.icon}
              active={page === item.id} onClick={() => onNavigate(item.id)}
              testId={`admin-nav-${item.id}`} dark={false}
            />
          ))}
        </nav>

        <div style={{ padding: "16px 22px" }}>
          <button
            type="button" onClick={() => onNavigate(MISSION_CONTROL_ENTRY_ID)}
            data-testid="admin-nav-mission-control"
            style={{
              width: "100%", background: "#000", border: "1px solid #000",
              color: "#fff", cursor: "pointer", padding: "12px 14px",
              fontFamily: "var(--font-body)", fontSize: 11, fontWeight: 600,
              letterSpacing: "0.12em", textTransform: "uppercase",
              display: "flex", alignItems: "center", justifyContent: "center", gap: 9,
              transition: "background 140ms, transform 140ms",
            }}
            onMouseEnter={(e) => { e.currentTarget.style.background = "#222"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "#000"; }}
          >
            <IconMissionControl size={15} />
            Mission Control
          </button>
        </div>

        <div style={{ padding: "0 22px 24px", borderTop: "1px solid rgba(0,0,0,0.1)", paddingTop: 18 }}>
          {admin && (
            <div style={{
              fontFamily: "var(--font-body)", fontSize: 11.5, color: "rgba(0,0,0,0.5)",
              marginBottom: 14, wordBreak: "break-word", lineHeight: 1.5,
            }}>
              Signed in as<br /><span style={{ color: "#000", fontWeight: 500 }}>{admin.email}</span>
            </div>
          )}
          <button
            type="button" onClick={handleLogout} data-testid="admin-nav-logout"
            style={{
              width: "100%", background: "none", border: "1px solid rgba(0,0,0,0.25)",
              color: "rgba(0,0,0,0.75)", 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 = "#000"; e.currentTarget.style.color = "#fff"; e.currentTarget.style.borderColor = "#000"; }}
            onMouseLeave={(e) => { e.currentTarget.style.background = "none"; e.currentTarget.style.color = "rgba(0,0,0,0.75)"; e.currentTarget.style.borderColor = "rgba(0,0,0,0.25)"; }}
          >
            <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 rgba(0,0,0,0.1)", paddingBottom: 30,
            }}>
              <div>
                {subtitle && (
                  <div style={{
                    fontFamily: "var(--font-body)", fontSize: 10, letterSpacing: "0.28em",
                    textTransform: "uppercase", color: "rgba(0,0,0,0.42)",
                    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: "#000",
                  }}>{title}</h1>
                )}
              </div>
              {actions && <div style={{ display: "flex", gap: 10, flexWrap: "wrap" }}>{actions}</div>}
            </div>
          )}
          {children}
        </div>
      </div>

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

Object.assign(window, { AdminShell, ADMIN_NAV_ITEMS });
