// PortalTable — Client Portal shared UI. Top nav, agency brand, stat/section
// cards, small helpers. Reuses dash-ui primitives (Surface, Pill, …), Ic (pd-brand),
// and DS Button. Light Stratum tokens via pd-tokens.css.

const { useState: useStateCU } = React;

function cpMoney(n) { return "$" + n.toLocaleString("en-US"); }

/* Agency brand mark — the chartreuse "SN" tile (white-labeled portal header) */
function AgencyMark({ size = 30 }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
      <span style={{ width: size, height: size, borderRadius: 8, background: "var(--accent)", color: "var(--accent-ink)", display: "grid", placeItems: "center", fontWeight: 700, fontSize: size * 0.42, fontFamily: "var(--font-mono)", letterSpacing: "-0.02em" }}>
        {CP_AGENCY.mark}
      </span>
      <span style={{ fontWeight: 600, fontSize: 16, color: "var(--fg-1)", letterSpacing: "-0.02em" }}>{CP_AGENCY.name}</span>
    </span>
  );
}

/* Round avatar with initials */
function CPAvatar({ initials, color = "var(--ink-700)", size = 32, ring = false }) {
  return (
    <span style={{
      width: size, height: size, borderRadius: 999, flexShrink: 0, background: color, color: "#fff",
      display: "grid", placeItems: "center", fontSize: size * 0.38, fontWeight: 600, fontFamily: "var(--font-mono)",
      boxShadow: ring ? "0 0 0 2px var(--ink-900), 0 0 0 4px var(--accent-line)" : "none",
    }}>{initials}</span>
  );
}

/* status → Pill */
function StatusPill({ map, value }) {
  const s = map[value] || { label: value, tone: "neutral" };
  return <Pill tone={s.tone} dot>{s.label}</Pill>;
}

/* file-kind → icon + tint */
const CP_FILE_ICON = {
  pdf: { icon: "file", color: "var(--red)" },
  zip: { icon: "folder", color: "var(--blue)" },
  image: { icon: "image", color: "var(--teal)" },
  doc: { icon: "file", color: "var(--fg-2)" },
};

/* ── Sidebar (matches the agency console) ──────────────────────────────────── */
function CPSidebar({ route, navigate, nav, open, onClose }) {
  return (
    <aside className={"cp-sidebar" + (open ? " cp-open" : "")} style={{
      width: 244, flexShrink: 0, height: "100vh", position: "sticky", top: 0, alignSelf: "flex-start",
      background: "var(--ink-900)", borderRight: "1px solid var(--line-2)",
      display: "flex", flexDirection: "column",
    }}>
      <div style={{ height: 62, display: "flex", alignItems: "center", gap: 10, padding: "0 18px", borderBottom: "1px solid var(--line-2)" }}>
        <AgencyMark />
        <button onClick={onClose} aria-label="Close menu" className="cp-sidebar-close"
          style={{ display: "none", marginLeft: "auto", width: 32, height: 32, placeItems: "center", borderRadius: 8, background: "transparent", border: "1px solid var(--line-2)", color: "var(--fg-2)", cursor: "pointer" }}>
          <Ic name="x" size={16} />
        </button>
      </div>

      {/* demo perspective switch */}
      <DemoSwitch current="client" />

      <nav style={{ flex: 1, overflowY: "auto", padding: "8px 12px 14px" }}>
        <div style={{ padding: "0 10px 8px", fontFamily: "var(--font-mono)", fontSize: 10, letterSpacing: "0.1em", color: "var(--fg-4)" }}>YOUR PORTAL</div>
        <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
          {nav.map((it) => <CPNavItem key={it.id} item={it} active={route === it.id} onClick={() => navigate(it.id)} />)}
        </div>
      </nav>

      {/* support card */}
      <div style={{ padding: 12 }}>
        <div style={{ borderRadius: 12, border: "1px solid var(--line-2)", background: "var(--ink-950)", padding: 14 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 8 }}>
            <span style={{ display: "inline-flex", padding: 5, borderRadius: 7, background: "var(--accent)", color: "var(--accent-ink)" }}><Ic name="message" size={14} /></span>
            <span style={{ fontSize: 13, fontWeight: 600, color: "var(--fg-1)" }}>Need a hand?</span>
          </div>
          <div style={{ fontSize: 12, color: "var(--fg-3)", margin: "8px 0 10px", lineHeight: 1.45 }}>Your {CP_AGENCY.name} team is a message away.</div>
          <Button variant="secondary" size="sm" icon="message" onClick={() => navigate("messages")} style={{ width: "100%", justifyContent: "center" }}>Message the team</Button>
        </div>
      </div>
    </aside>
  );
}

function CPNavItem({ item, active, onClick }) {
  const [h, setH] = useStateCU(false);
  return (
    <button onClick={onClick} onMouseEnter={() => setH(true)} onMouseLeave={() => setH(false)}
      style={{
        width: "100%", display: "flex", alignItems: "center", gap: 11, padding: "8px 10px", borderRadius: 9,
        border: 0, cursor: "pointer", fontFamily: "inherit", fontSize: 13.5, fontWeight: active ? 600 : 500,
        background: active || h ? "var(--ink-800)" : "transparent",
        color: active || h ? "var(--fg-1)" : "var(--fg-2)",
        transition: "background var(--dur-1) var(--ease-out), color var(--dur-1) var(--ease-out)", position: "relative",
      }}>
      {active && <span style={{ position: "absolute", left: -12, top: 8, bottom: 8, width: 3, borderRadius: 2, background: "var(--accent)" }} />}
      <Ic name={item.icon} size={17} style={{ color: active ? "var(--fg-1)" : "var(--fg-3)" }} />
      <span style={{ flex: 1, textAlign: "left" }}>{item.label}</span>
      {item.badge ? (
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, minWidth: 18, height: 18, padding: "0 5px", borderRadius: 999, display: "grid", placeItems: "center", background: "var(--amber-soft)", color: "var(--amber)", border: "1px solid rgba(181,121,11,0.28)" }}>{item.badge}</span>
      ) : null}
    </button>
  );
}

/* ── Topbar (breadcrumb + bell + account) ──────────────────────────────────── */
function CPTopbar({ title, onOpenNav }) {
  return (
    <header className="cp-topbar" style={{
      height: 62, flexShrink: 0, position: "sticky", top: 0, zIndex: 40,
      background: "rgba(255,255,255,0.82)", backdropFilter: "blur(14px)",
      borderBottom: "1px solid var(--line-2)", display: "flex", alignItems: "center", gap: 14, padding: "0 26px",
    }}>
      <button onClick={onOpenNav} aria-label="Open menu" className="cp-hamburger"
        style={{ display: "none", width: 36, height: 36, placeItems: "center", borderRadius: 8, background: "transparent", border: "1px solid var(--line-2)", color: "var(--fg-1)", cursor: "pointer", flexShrink: 0 }}>
        <Ic name="menu" size={18} />
      </button>
      <div style={{ display: "flex", alignItems: "center", gap: 8, fontSize: 13.5, minWidth: 0 }}>
        <span className="cp-crumb" style={{ display: "inline-flex", alignItems: "center", gap: 8 }}>
          <span style={{ color: "var(--fg-3)" }}>{CP_AGENCY.name}</span>
          <Ic name="chevronRight" size={14} style={{ color: "var(--fg-4)" }} />
        </span>
        <span style={{ color: "var(--fg-1)", fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{title}</span>
      </div>
      <div style={{ marginLeft: "auto", display: "flex", alignItems: "center", gap: 12, flexShrink: 0 }}>
        <IconButton icon="bell" label="Notifications" onClick={() => window.pdToast({ tone: "info", title: "You're all caught up" })} />
        <DropdownMenu align="right" width={220}
          trigger={(open) => (
            <button aria-label="Account" style={{ display: "flex", alignItems: "center", padding: 3, borderRadius: 999, cursor: "pointer", background: "transparent", border: "1px solid", borderColor: open ? "var(--line-3)" : "transparent" }}>
              <CPAvatar initials={CP_CLIENT.initials} color="#111317" ring={open} />
            </button>
          )}
          items={[
            { label: CP_CLIENT.contact, header: true },
            { label: "Account", icon: "users", onClick: () => window.pdToast("Account") },
            { label: "Notifications", icon: "bell", onClick: () => window.pdToast("Notifications") },
            { separator: true },
            { label: "Sign out", icon: "external", tone: "danger", onClick: () => window.pdToast({ tone: "info", title: "Signed out" }) },
          ]} />
      </div>
    </header>
  );
}

/* ── Page header ───────────────────────────────────────────────────────────── */
function CPPageHeader({ title, subtitle, actions }) {
  return (
    <div style={{ display: "flex", alignItems: "flex-end", gap: 16, flexWrap: "wrap", marginBottom: 22 }}>
      <div style={{ flex: 1, minWidth: 220 }}>
        <h1 style={{ fontSize: 24, fontWeight: 600, letterSpacing: "-0.025em", color: "var(--fg-1)", margin: 0 }}>{title}</h1>
        {subtitle && <p style={{ fontSize: 14, color: "var(--fg-2)", margin: "6px 0 0", lineHeight: 1.5 }}>{subtitle}</p>}
      </div>
      {actions && <div style={{ display: "flex", alignItems: "center", gap: 10, flexWrap: "wrap" }}>{actions}</div>}
    </div>
  );
}

/* ── Stat card (matches the agency StatCard vocabulary) ────────────────────── */
function CPStat({ icon, label, value, sub, tone }) {
  const toneFg = tone ? { amber: "var(--amber)", red: "var(--red)", green: "var(--green)" }[tone] : "var(--fg-2)";
  const toneBg = tone ? { amber: "var(--amber-soft)", red: "var(--red-soft)", green: "var(--green-soft)" }[tone] : "var(--ink-800)";
  return (
    <Surface hover pad={18} style={{ display: "flex", flexDirection: "column", gap: 14, minHeight: 116 }}>
      <div style={{ display: "flex", alignItems: "center", gap: 10 }}>
        <span style={{ width: 30, height: 30, borderRadius: 8, display: "grid", placeItems: "center", background: toneBg, color: toneFg, flexShrink: 0 }}>
          <Ic name={icon} size={16} />
        </span>
        <span style={{ fontSize: 13, color: "var(--fg-2)", fontWeight: 500 }}>{label}</span>
      </div>
      <div>
        <div style={{ fontSize: 27, fontWeight: 600, letterSpacing: "-0.03em", color: "var(--fg-1)", lineHeight: 1, fontVariantNumeric: "tabular-nums" }}>{value}</div>
        {sub && <div style={{ fontSize: 12, color: "var(--fg-3)", marginTop: 8 }}>{sub}</div>}
      </div>
    </Surface>
  );
}

/* ── Section card (header + body) ──────────────────────────────────────────── */
function CPSection({ title, action, children, pad = 18, style = {} }) {
  return (
    <Surface pad={0} style={style}>
      <div style={{ display: "flex", alignItems: "center", gap: 12, padding: "15px 18px", borderBottom: "1px solid var(--line-2)" }}>
        <h3 style={{ fontSize: 14.5, fontWeight: 600, color: "var(--fg-1)", margin: 0, letterSpacing: "-0.01em" }}>{title}</h3>
        <div style={{ marginLeft: "auto" }}>{action}</div>
      </div>
      <div style={{ padding: pad }}>{children}</div>
    </Surface>
  );
}

const cpLinkBtn = { background: "none", border: 0, padding: 0, cursor: "pointer", fontSize: 12.5, fontWeight: 500, color: "var(--fg-2)", fontFamily: "inherit" };

Object.assign(window, { cpMoney, AgencyMark, CPAvatar, StatusPill, CP_FILE_ICON, CPSidebar, CPNavItem, CPTopbar, CPPageHeader, CPStat, CPSection, cpLinkBtn });
