// Doorpass Control Room — desktop web shell + shared primitives. Revision v2.
// Microstates everywhere (hover/focus/active on rows, chips, tiles, nav), sortable
// table headers, drillable stat tiles, metric-definition popovers (ⓘ), global period
// selector + freshness stamp in a slim topbar, ⌘K command palette, first-entry
// loading skeletons, and the photo-per-property recognition system from mobile.
;(function(){
const DS = window.DoorpassDesignSystem_eaad52;
const { Avatar } = DS;

/* ---------------- Microstate + a11y CSS (injected so standalone keeps working) ---------------- */

const crCSS = `
.sr-only { position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px; overflow: hidden; clip: rect(0 0 0 0); white-space: nowrap; border: 0; }
.cr-ia { transition: background var(--dur-fast) var(--ease-out), box-shadow var(--dur-fast) var(--ease-out), color var(--dur-fast) var(--ease-out), transform var(--dur-fast) var(--ease-out); }
.cr-ia:focus-visible { outline: 2px solid var(--green-300); outline-offset: 2px; }
.cr-row-i { cursor: pointer; }
.cr-row-i:hover, .cr-row-i:focus-visible { background: var(--surface-tint); border-radius: var(--radius-sm); }
.cr-row-i:focus-visible { outline-offset: -2px; }
.cr-row-i:active { background: var(--mist-100); }
.cr-row-i .cr-row-ch { opacity: 0; transition: opacity var(--dur-fast) var(--ease-out); }
.cr-row-i:hover .cr-row-ch, .cr-row-i:focus-visible .cr-row-ch { opacity: 1; }
.cr-navbtn:hover { background: var(--mist-100); color: var(--green-900); }
.cr-navbtn:focus-visible { outline-offset: -2px; }
.cr-navbtn:active { background: var(--line-200); }
.cr-stat-i { cursor: pointer; }
.cr-stat-i:hover { box-shadow: var(--shadow-raised); transform: translateY(-1px); }
.cr-stat-i:active { transform: translateY(0); box-shadow: var(--shadow-card); }
.cr-stat-i .cr-stat-ch { opacity: 0; transition: opacity var(--dur-fast) var(--ease-out); }
.cr-stat-i:hover .cr-stat-ch, .cr-stat-i:focus-visible .cr-stat-ch { opacity: 1; }
.cr-pill { cursor: pointer; }
.cr-pill:hover { box-shadow: inset 0 0 0 1px var(--neutral-300); }
.cr-pill.cr-pill-on:hover { box-shadow: var(--shadow-button); filter: brightness(1.08); }
.cr-pill:active { transform: translateY(0.5px); }
.cr-th-btn { cursor: pointer; background: none; border: none; padding: 0; display: inline-flex; align-items: center; gap: 4px; font-family: var(--font-sans); }
.cr-th-btn:hover span { color: var(--green-800); }
.cr-link { cursor: pointer; background: none; border: none; padding: 0; font-family: var(--font-sans); text-align: left; }
.cr-link:hover { text-decoration: underline; text-underline-offset: 2px; }
.cr-def-btn { cursor: pointer; background: none; border: none; padding: 1px; display: inline-flex; border-radius: 4px; color: var(--neutral-300); }
.cr-def-btn:hover, .cr-def-btn:focus-visible { color: var(--green-800); }
@keyframes crPulse { 0%, 100% { opacity: 0.55; } 50% { opacity: 1; } }
.cr-skel { background: var(--mist-100); border-radius: 8px; animation: crPulse 1.4s var(--ease-out) infinite; }
@keyframes crLiveDot { 0%, 100% { opacity: 1; } 50% { opacity: 0.35; } }
.cr-live-dot { animation: crLiveDot 1.6s ease-in-out infinite; }
@media (prefers-reduced-motion: reduce) { .cr-skel, .cr-live-dot { animation: none; } .cr-ia { transition: none; } }
`;
if (!document.getElementById("cr-css")) {
  const tag = document.createElement("style");
  tag.id = "cr-css"; tag.textContent = crCSS;
  document.head.appendChild(tag);
}

function CRIcon({ name, size = 16, color, style }) {
  return <i data-lucide={name} style={{ width: size, height: size, color, flex: "none", ...style }}></i>;
}

/* ---------------- Photo-per-property (same faces as the mobile kits) ---------------- */

const CR_IMG = "./img/";
const CR_RES = { "modern-home.png": "adImgModernHome", "front-door-dusk.png": "adImgFrontDoor", "keypad-door.png": "adImgKeypad", "door-teal.png": "adImgDoorTeal", "door-clay.png": "adImgDoorClay", "door-navy.png": "adImgDoorNavy", "aerial-oakmont.png": "adImgAerialOakmont" };
const CRImgSrc = (name) => (window.__resources && window.__resources[CR_RES[name]]) || (CR_IMG + name.replace(/\.png$/, ".svg"));

// Photo where one exists; consistent initial tile (street number, mono) where not.
// Never a borrowed photo — recognition beats decoration.
function CRPhoto({ listing, w = 34, h = 28, radius = 7 }) {
  if (listing && listing.img) {
    return <span aria-hidden="true" style={{ width: w, height: h, flex: "none", borderRadius: radius, backgroundImage: `url(${CRImgSrc(listing.img)})`, backgroundSize: "cover", backgroundPosition: "center", boxShadow: "inset 0 0 0 1px rgba(5,31,17,0.08)", display: "inline-block" }}></span>;
  }
  const num = listing ? (listing.addr.match(/^\d+/) || ["—"])[0] : "—";
  return (
    <span aria-hidden="true" style={{ width: w, height: h, flex: "none", borderRadius: radius, background: "var(--mist-100)", boxShadow: "inset 0 0 0 1px var(--line-200)", display: "inline-grid", placeItems: "center", fontFamily: "var(--font-mono)", fontSize: Math.min(10.5, h * 0.38), fontWeight: 600, color: "var(--neutral-500)", letterSpacing: "0.02em" }}>{num}</span>
  );
}

/* ---------------- One clock — global period context ---------------- */

const CRPeriodContext = React.createContext({ period: { id: "week", dataKey: "week", label: "This week", compare: "vs last week", window: "Jun 1 – 7" }, setPeriod: () => {} });
function usePeriod() { return React.useContext(CRPeriodContext); }

/* ---------------- One lens — global comparison scope (off · metro · region · national).
   Set from the topbar, consumed by stat tiles and the CRBenchBand on reporting views.
   enabled=false (no national coverage) hides the control and every overlay. ---------------- */

const CRBenchContext = React.createContext({ scope: "off", enabled: false, setScope: () => {} });
function useBench() { return React.useContext(CRBenchContext); }

function CRBenchControl() {
  const { scope, setScope, enabled } = useBench();
  if (!enabled) return null;
  const OPTS = [["off", "Off"], ["metro", "Metro"], ["region", "Region"], ["national", "National"]];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 2, background: "var(--surface-white)", borderRadius: "var(--radius-pill)", boxShadow: "inset 0 0 0 1px var(--line-200)", padding: 2 }} role="group" aria-label="Comparison scope">
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--neutral-500)", padding: "0 4px 0 9px" }}>vs</span>
      {OPTS.map(([id, label]) => {
        const on = scope === id;
        return (
          <button key={id} className={"cr-ia cr-pill" + (on ? " cr-pill-on" : "")} onClick={() => setScope(id)} aria-pressed={on} style={{
            padding: "4px 10px", borderRadius: "var(--radius-pill)", border: "none", whiteSpace: "nowrap",
            fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700,
            background: on ? "var(--green-800)" : "transparent",
            color: on ? "#fff" : "var(--neutral-700)",
            boxShadow: on ? "var(--shadow-button)" : "none",
          }}>{label}</button>
        );
      })}
    </div>
  );
}

// One benchmark comparison: "you X vs scope Y · ±pct%". Sign colored by direction.
function crBenchCalc(metricKey, scope) {
  const b = window.CRData.network.benchmarks.metrics[metricKey];
  if (!b || b[scope] == null) return null;
  const pct = Math.round((b.you / b[scope] - 1) * 100);
  const good = b.betterHigh ? pct >= 0 : pct <= 0;
  return { ...b, scopeVal: b[scope], pct, good };
}

// Slim comparison band for reporting views (Listings, Team) — the "same categories"
// measured at the selected scope. Renders nothing when the lens is off.
function CRBenchBand({ keys, style }) {
  const { scope, enabled } = useBench();
  if (!enabled || scope === "off") return null;
  const name = window.CRData.network.benchmarks.scopeNames[scope];
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 20, padding: "9px 14px", background: "var(--surface-white)", borderRadius: "var(--radius-md)", boxShadow: "inset 0 0 0 1px var(--line-200)", minWidth: 0, ...style }}>
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 600, letterSpacing: "0.05em", textTransform: "uppercase", color: "var(--neutral-500)", whiteSpace: "nowrap" }}>
        <CRIcon name="globe-2" size={12} color="var(--neutral-500)" />vs {name}
      </span>
      {keys.map((k) => {
        const c = crBenchCalc(k, scope);
        if (!c) return null;
        return (
          <span key={k} style={{ display: "inline-flex", alignItems: "center", gap: 7, minWidth: 0 }}>
            <span style={{ fontSize: 12, fontWeight: 600, color: "var(--neutral-700)", whiteSpace: "nowrap" }}>{c.label}</span>
            <span style={{ ...crMonoStyle(12), whiteSpace: "nowrap" }}>{c.you} <span style={{ color: "var(--neutral-500)", fontWeight: 500 }}>vs {c.scopeVal}{c.unit}</span></span>
            <span style={{ ...crMonoStyle(11.5, c.good ? "var(--green-600)" : "var(--red-600)") }}>{c.pct > 0 ? "+" : ""}{c.pct}%</span>
          </span>
        );
      })}
      <span style={{ flex: 1 }}></span>
      <CRDef k="benchband" align="right" />
    </div>
  );
}
// crMono is declared later in this file; tiny alias so CRBenchBand can hoist past it.
function crMonoStyle(size, color, weight) { return crMono(size, color, weight); }

function CRPeriodControl() {
  const { period, setPeriod } = usePeriod();
  const [customOpen, setCustomOpen] = React.useState(false);
  const D = window.CRData;
  return (
    <div style={{ display: "flex", alignItems: "center", gap: 2, background: "var(--surface-white)", borderRadius: "var(--radius-pill)", boxShadow: "inset 0 0 0 1px var(--line-200)", padding: 2, position: "relative" }}>
      {D.periods.map((p) => {
        const on = period.id === p.id;
        return (
          <button key={p.id} className={"cr-ia cr-pill" + (on ? " cr-pill-on" : "")} onClick={() => { setCustomOpen(false); setPeriod({ ...p, dataKey: p.id }); }} style={{
            padding: "4px 11px", borderRadius: "var(--radius-pill)", border: "none", whiteSpace: "nowrap",
            fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700,
            background: on ? "var(--green-800)" : "transparent",
            color: on ? "#fff" : "var(--neutral-700)",
            boxShadow: on ? "var(--shadow-button)" : "none",
          }}>{p.label}</button>
        );
      })}
      <button className={"cr-ia cr-pill" + (period.id === "custom" ? " cr-pill-on" : "")} onClick={() => setCustomOpen((o) => !o)} aria-expanded={customOpen} style={{
        padding: "4px 11px", borderRadius: "var(--radius-pill)", border: "none", whiteSpace: "nowrap",
        display: "inline-flex", alignItems: "center", gap: 5,
        fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700,
        background: period.id === "custom" ? "var(--green-800)" : "transparent",
        color: period.id === "custom" ? "#fff" : "var(--neutral-700)",
        boxShadow: period.id === "custom" ? "var(--shadow-button)" : "none",
      }}>{period.id === "custom" ? period.label : "Custom"}<CRIcon name="chevron-down" size={12} color={period.id === "custom" ? "#fff" : "var(--neutral-500)"} /></button>
      {customOpen && (
        <div style={{ position: "absolute", top: "calc(100% + 8px)", right: 0, zIndex: 70, width: 252, background: "var(--surface-card)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-float)", padding: 14 }}>
          <div style={{ fontSize: 12, fontWeight: 700, color: "var(--green-950)", marginBottom: 10 }}>Custom range</div>
          <div style={{ display: "flex", gap: 8, alignItems: "center", marginBottom: 12 }}>
            <input className="cr-ia" defaultValue="Jun 1" aria-label="Start date" style={{ flex: 1, minWidth: 0, fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 500, color: "var(--green-950)", padding: "7px 10px", border: "none", borderRadius: "var(--radius-sm)", background: "var(--mist-100)" }} />
            <span style={{ fontSize: 12, color: "var(--neutral-500)" }}>–</span>
            <input className="cr-ia" defaultValue="Jun 8" aria-label="End date" style={{ flex: 1, minWidth: 0, fontFamily: "var(--font-mono)", fontSize: 12.5, fontWeight: 500, color: "var(--green-950)", padding: "7px 10px", border: "none", borderRadius: "var(--radius-sm)", background: "var(--mist-100)" }} />
          </div>
          <button className="cr-ia cr-pill cr-pill-on" onClick={() => { setPeriod({ id: "custom", dataKey: "week", label: "Jun 1 – 8", compare: "vs prior 8 days", window: "Jun 1 – 8" }); setCustomOpen(false); }} style={{
            width: "100%", padding: "7px 0", borderRadius: "var(--radius-pill)", border: "none", cursor: "pointer",
            fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 700, background: "var(--green-800)", color: "#fff", boxShadow: "var(--shadow-button)",
          }}>Apply range</button>
        </div>
      )}
    </div>
  );
}

/* ---------------- Sidebar — warm paper at ops density (rev v3); 14px monochrome icons ---------------- */

const NAV = [
  { id: "overview",   label: "Overview",   icon: "layout-dashboard" },
  { id: "listings",   label: "Listings",   icon: "building-2" },
  { id: "team",       label: "Team",       icon: "users" },
  { id: "pipeline",   label: "Pipeline",   icon: "radar" },
  { id: "operations", label: "Operations", icon: "wrench" },
  { id: "activity",   label: "Activity",   icon: "scroll-text" },
  { id: "settings",   label: "Settings",   icon: "settings" },
];

// `network` (tweak) inserts the national/regional Markets data view after Pipeline.
function Sidebar({ active, onNav, network }) {
  const items = network
    ? [...NAV.slice(0, 4), { id: "markets", label: "Markets", icon: "globe-2" }, ...NAV.slice(4)]
    : NAV;
  return (
    <div style={{
      width: 228, flex: "none", background: "var(--surface-app)",
      borderRight: "1px solid var(--line-200)", boxSizing: "border-box",
      display: "flex", flexDirection: "column", padding: "20px 12px 16px",
    }}>
      <img src={(window.__resources && window.__resources.crLogoBlack) || "./brand/doorpass-horizontal-black.svg"} alt="Doorpass" style={{ width: 116, margin: "2px 10px 18px" }} />

      <button className="cr-ia cr-navbtn" style={{
        display: "flex", alignItems: "center", gap: 10, padding: "9px 10px", marginBottom: 16,
        background: "var(--surface-card)", border: "none",
        boxShadow: "var(--shadow-card)",
        borderRadius: "var(--radius-md)", cursor: "pointer", textAlign: "left",
        fontFamily: "var(--font-sans)",
      }}>
        <span style={{
          width: 28, height: 28, borderRadius: 8, background: "var(--green-800)", flex: "none",
          display: "grid", placeItems: "center", color: "#fff", fontSize: 12, fontWeight: 800,
        }}>B</span>
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: "block", fontSize: 13, fontWeight: 700, color: "var(--green-950)" }}>Brooks Group</span>
          <span style={{ display: "block", fontSize: 11, fontWeight: 500, color: "var(--neutral-500)" }}>Team · San Antonio</span>
        </span>
        <CRIcon name="chevrons-up-down" size={14} color="var(--neutral-500)" />
      </button>

      <nav style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {items.map((n) => {
          const on = n.id === active;
          return (
            <button key={n.id} className="cr-ia cr-navbtn" onClick={() => onNav(n.id)} aria-current={on ? "page" : undefined} style={{
              display: "flex", alignItems: "center", gap: 11, padding: "8px 10px",
              background: on ? "var(--surface-tint)" : "none",
              border: "none", borderRadius: "var(--radius-sm)", cursor: "pointer",
              fontFamily: "var(--font-sans)", fontSize: 13.5, fontWeight: on ? 700 : 600,
              color: on ? "var(--green-900)" : "var(--neutral-700)", textAlign: "left",
              boxShadow: on ? "inset 0 0 0 1px var(--green-300)" : "none",
            }}>
              <CRIcon name={n.icon} size={14} color="currentColor" />
              {n.label}
            </button>
          );
        })}
      </nav>

      <div style={{ flex: 1 }}></div>

      <button className="cr-ia cr-navbtn" onClick={() => onNav("activity")} style={{
        display: "flex", alignItems: "center", gap: 9, padding: "8px 10px", marginBottom: 10,
        background: "none", border: "none", cursor: "pointer", textAlign: "left",
        fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 600, color: "var(--neutral-500)",
        borderRadius: "var(--radius-sm)",
      }}>
        <CRIcon name="shield-check" size={14} color="currentColor" />
        How your data is used
      </button>

      <div style={{ borderTop: "1px solid var(--line-200)", display: "flex", alignItems: "center", gap: 10, padding: "12px 10px 0" }}>
        <Avatar name="Salena Brooks" size={30} />
        <span style={{ flex: 1, minWidth: 0 }}>
          <span style={{ display: "block", fontSize: 13, fontWeight: 700, color: "var(--green-950)" }}>Salena Brooks</span>
          <span style={{ display: "block", fontSize: 11, fontWeight: 500, color: "var(--neutral-500)" }}>Ops lead</span>
        </span>
        <CRIcon name="chevron-right" size={14} color="var(--neutral-500)" />
      </div>
    </div>
  );
}

/* ---------------- Topbar — ⌘K affordance · period · freshness stamp ---------------- */

function CRTopbar() {
  const D = window.CRData;
  return (
    <div style={{ flex: "none", height: 50, display: "flex", alignItems: "center", gap: 14, padding: "0 32px", borderBottom: "1px solid var(--line-200)" }}>
      <button className="cr-ia cr-pill" onClick={() => window.dispatchEvent(new CustomEvent("cr-palette"))} aria-label="Search (Command K)" style={{
        display: "flex", alignItems: "center", gap: 8, width: 280, padding: "6px 12px",
        background: "var(--surface-white)", border: "none", borderRadius: "var(--radius-pill)",
        boxShadow: "inset 0 0 0 1px var(--line-200)", fontFamily: "var(--font-sans)",
      }}>
        <CRIcon name="search" size={13} color="var(--neutral-500)" />
        <span style={{ flex: 1, textAlign: "left", fontSize: 12.5, fontWeight: 500, color: "var(--neutral-500)" }}>Search listings, people, screens…</span>
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 500, color: "var(--neutral-500)", background: "var(--mist-100)", borderRadius: 5, padding: "1px 6px" }}>⌘K</span>
      </button>
      <span style={{ flex: 1 }}></span>
      <CRBenchControl />
      <CRPeriodControl />
      <span style={{ display: "inline-flex", alignItems: "center", gap: 6, fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, color: "var(--neutral-500)", whiteSpace: "nowrap" }}>
        <CRIcon name="refresh-cw" size={11} color="var(--neutral-500)" />
        Synced {D.synced}
      </span>
    </div>
  );
}

/* ---------------- Shell + page scaffold ---------------- */

function CRShell({ active, onNav, network, children }) {
  const isEmbed = new URLSearchParams(window.location.search).has('embed');
  return (
    <div style={{
      width: 1440, height: 900, display: "flex", overflow: "hidden",
      borderRadius: isEmbed ? 0 : 14, background: "var(--surface-app)",
      boxShadow: isEmbed ? "none" : "0 30px 60px rgba(5,31,17,0.28), 0 8px 20px rgba(5,31,17,0.16)",
    }}>
      <Sidebar active={active} onNav={onNav} network={network} />
      <div style={{ flex: 1, minWidth: 0, display: "flex", flexDirection: "column", overflow: "hidden" }}>
        <CRTopbar />
        <div style={{ flex: 1, minHeight: 0, display: "flex", flexDirection: "column" }}>
          {children}
        </div>
      </div>
    </div>
  );
}

/* ---- First-entry loading skeleton (per screen, 1.4s pulse, reduced-motion safe) ---- */

const crSeen = new Set();
function useCRLoad(key) {
  const [loading, setLoading] = React.useState(!crSeen.has(key));
  React.useEffect(() => {
    if (crSeen.has(key)) { setLoading(false); return; }
    const t = setTimeout(() => { crSeen.add(key); setLoading(false); }, 650);
    return () => clearTimeout(t);
  }, [key]);
  return loading;
}

function CRSkel({ w = "100%", h = 14, r = 8, style }) {
  return <span className="cr-skel" style={{ display: "block", width: w, height: h, borderRadius: r, ...style }}></span>;
}

function CRSkeletonBody() {
  return (
    <div aria-hidden="true">
      <div style={{ display: "flex", gap: 12, marginBottom: 16 }}>
        {[0, 1, 2, 3, 4].map((i) => (
          <div key={i} style={{ flex: 1, background: "var(--surface-card)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-card)", padding: "14px 16px" }}>
            <CRSkel w="60%" h={10} style={{ marginBottom: 12 }} />
            <CRSkel w="44%" h={24} style={{ marginBottom: 10 }} />
            <CRSkel w="70%" h={9} />
          </div>
        ))}
      </div>
      <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 16 }}>
        {[0, 1].map((i) => (
          <div key={i} style={{ background: "var(--surface-card)", borderRadius: "var(--radius-md)", boxShadow: "var(--shadow-card)", padding: 16 }}>
            <CRSkel w="32%" h={12} style={{ marginBottom: 16 }} />
            {[0, 1, 2, 3].map((j) => (
              <div key={j} style={{ display: "flex", gap: 12, alignItems: "center", padding: "11px 0" }}>
                <CRSkel w={32} h={32} r={9} style={{ flex: "none" }} />
                <span style={{ flex: 1 }}><CRSkel w={`${78 - j * 9}%`} h={11} style={{ marginBottom: 7 }} /><CRSkel w={`${52 - j * 5}%`} h={9} /></span>
              </div>
            ))}
          </div>
        ))}
      </div>
    </div>
  );
}

function CRPage({ label, eyebrow, title, sub, actions, display = false, children }) {
  const loading = useCRLoad(label);
  return (
    <div data-screen-label={label} style={{ display: "flex", flexDirection: "column", height: "100%", minHeight: 0 }}>
      <div style={{ flex: "none", padding: display ? "24px 32px 16px" : "20px 32px 16px", display: "flex", alignItems: "flex-end", gap: 16 }}>
        <div style={{ flex: 1, minWidth: 0 }}>
          {eyebrow && <div style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 500, letterSpacing: "0.08em", color: "var(--neutral-500)", textTransform: "uppercase", marginBottom: 6 }}>{eyebrow}</div>}
          {/* Display discipline (rev v3): screen titles at h2-22 bold; the one
              display-44 semibold moment per product is the Overview lead (display). */}
          {display
            ? <h1 style={{ margin: 0, fontSize: "var(--t-display-size)", lineHeight: "var(--t-display-line)", fontWeight: "var(--t-display-weight)", letterSpacing: "var(--t-display-track)", color: "var(--green-950)" }}>{title}</h1>
            : <h1 style={{ margin: 0, fontSize: "var(--t-h2-size)", lineHeight: "var(--t-h2-line)", fontWeight: "var(--t-h2-weight)", letterSpacing: "var(--t-h2-track)", color: "var(--green-950)" }}>{title}</h1>}
          {sub && <div style={{ marginTop: display ? 8 : 4, fontSize: 13.5, fontWeight: 500, color: "var(--neutral-700)" }}>{sub}</div>}
        </div>
        {actions && <div style={{ display: "flex", gap: 8, alignItems: "center", flex: "none" }}>{actions}</div>}
      </div>
      <div style={{ flex: 1, minHeight: 0, overflowY: "auto", padding: "0 32px 32px" }}>
        {loading ? <CRSkeletonBody /> : children}
      </div>
    </div>
  );
}

/* ---------------- Metric definitions — ⓘ popover, one component everywhere ---------------- */

function CRDef({ k, align = "center" }) {
  const d = window.CRData.defs[k];
  const [open, setOpen] = React.useState(false);
  if (!d) return null;
  const pos = align === "left" ? { left: -10 } : align === "right" ? { right: -10 } : { left: "50%", transform: "translateX(-50%)" };
  // Trigger is a focusable span (not <button>) — CRDef nests inside drillable
  // stat tiles and sortable header buttons, and buttons cannot nest.
  return (
    <span style={{ position: "relative", display: "inline-flex" }} onMouseEnter={() => setOpen(true)} onMouseLeave={() => setOpen(false)}>
      <span className="cr-ia cr-def-btn" role="button" tabIndex={0} aria-label={`Definition: ${d.title}`}
        onFocus={() => setOpen(true)} onBlur={() => setOpen(false)}
        onClick={(e) => { e.stopPropagation(); setOpen((o) => !o); }}
        onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); e.stopPropagation(); setOpen((o) => !o); } }}>
        <CRIcon name="info" size={12} color="currentColor" />
      </span>
      {open && (
        <span role="tooltip" style={{
          position: "absolute", bottom: "calc(100% + 8px)", ...pos, zIndex: 80, width: 236,
          background: "var(--green-950)", borderRadius: 10, padding: "11px 13px",
          boxShadow: "var(--shadow-float)", textAlign: "left", pointerEvents: "none",
        }}>
          <span style={{ display: "block", fontSize: 12, fontWeight: 700, color: "#fff", fontFamily: "var(--font-sans)" }}>{d.title}</span>
          <span style={{ display: "block", fontSize: 11.5, fontWeight: 500, color: "rgba(255,255,255,0.78)", lineHeight: "16px", marginTop: 3, fontFamily: "var(--font-sans)" }}>{d.body}</span>
          <span style={{ display: "block", fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 500, letterSpacing: "0.05em", color: "var(--green-300)", marginTop: 7, textTransform: "uppercase" }}>{d.src}</span>
        </span>
      )}
    </span>
  );
}

/* ---------------- Data primitives ---------------- */

// Stat tile — number paired with comparison, drillable, defined. `benchKey` adds a
// scope-benchmark footer (rate-based) when the global comparison lens is on.
function CRStat({ label, value, unit, delta, good, note, onClick, info, ariaLabel, benchKey }) {
  const { period } = usePeriod();
  const bench = useBench();
  const bc = benchKey && bench.enabled && bench.scope !== "off" ? crBenchCalc(benchKey, bench.scope) : null;
  const Tag = onClick ? "button" : "div";
  return (
    <Tag className={"cr-ia" + (onClick ? " cr-stat-i" : "")} onClick={onClick} aria-label={ariaLabel || (onClick ? `${label} ${value}${unit || ""} — open detail` : undefined)} style={{
      flex: 1, minWidth: 0, background: "var(--surface-card)", borderRadius: "var(--radius-md)",
      boxShadow: "var(--shadow-card)", padding: "14px 16px", border: "none", textAlign: "left",
      fontFamily: "var(--font-sans)", position: "relative", display: "block",
    }}>
      {onClick && <span className="cr-stat-ch" style={{ position: "absolute", top: 12, right: 12 }} aria-hidden="true"><CRIcon name="chevron-right" size={13} color="var(--neutral-300)" /></span>}
      <div style={{ display: "flex", alignItems: "center", gap: 5, marginBottom: 8 }}>
        <span style={{ fontSize: 12, fontWeight: 600, color: "var(--neutral-500)" }}>{label}</span>
        {info && <CRDef k={info} align="left" />}
      </div>
      <div style={{ display: "flex", alignItems: "baseline", gap: 4 }}>
        {/* Stat heroes: mono-display — the value is a ledger fact, regular weight */}
        <span style={{ fontFamily: "var(--font-mono)", fontSize: "var(--t-mono-display-size)", lineHeight: "var(--t-mono-display-line)", fontWeight: "var(--t-mono-display-weight)", color: "var(--green-950)", fontVariantNumeric: "tabular-nums" }}>{value}</span>
        {unit && <span style={{ fontFamily: "var(--font-mono)", fontSize: 14, fontWeight: 500, color: "var(--neutral-500)" }}>{unit}</span>}
      </div>
      <div style={{ marginTop: 7, display: "flex", alignItems: "center", gap: 5 }}>
        {delta != null && <>
          <CRIcon name={good ? "trending-up" : "trending-down"} size={13} color={good ? "var(--green-600)" : "var(--red-600)"} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", color: good ? "var(--green-600)" : "var(--red-600)" }}>{delta}</span>
        </>}
        <span style={{ fontSize: 11.5, fontWeight: 500, whiteSpace: "nowrap", color: "var(--neutral-500)", overflow: "hidden", textOverflow: "ellipsis" }}>{note || period.compare}</span>
      </div>
      {bc && (
        <div style={{ marginTop: 8, paddingTop: 7, borderTop: "1px dashed var(--line-200)", display: "flex", alignItems: "center", gap: 6, minWidth: 0 }}>
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 500, color: "var(--neutral-500)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{{ metro: "metro", region: "region", national: "nat'l" }[bench.scope]}: {bc.scopeVal}{bc.unit}</span>
          <span style={{ marginLeft: "auto", fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, whiteSpace: "nowrap", color: bc.good ? "var(--green-600)" : "var(--red-600)" }}>{bc.pct > 0 ? "+" : ""}{bc.pct}%</span>
        </div>
      )}
    </Tag>
  );
}

// Forecast / status chip — 12px semibold floor, amber-700 for AA on cream.
const CHIP_TONES = {
  good:    { bg: "var(--surface-tint)", fg: "var(--green-800)", ring: "var(--green-300)" },
  warn:    { bg: "var(--cream-100)",    fg: "var(--amber-700)", ring: "#E8DFB8" },
  bad:     { bg: "#FBEEED",             fg: "var(--red-600)",   ring: "#ECCFCD" },
  info:    { bg: "#EFF5FB",             fg: "var(--blue-700)",  ring: "#CDDDF0" },
  neutral: { bg: "var(--mist-100)",     fg: "var(--neutral-700)", ring: "var(--line-200)" },
};
function CRChip({ tone = "neutral", children, style }) {
  const t = CHIP_TONES[tone] || CHIP_TONES.neutral;
  return (
    <span style={{
      display: "inline-flex", alignItems: "center", gap: 5, padding: "2px 9px",
      borderRadius: "var(--radius-pill)", background: t.bg, color: t.fg,
      boxShadow: `inset 0 0 0 1px ${t.ring}`,
      fontSize: 12, fontWeight: 600, whiteSpace: "nowrap", fontFamily: "var(--font-sans)", ...style,
    }}>{children}</span>
  );
}

// Sparkline — token colors only.
function CRSpark({ data, w = 76, h = 22, color = "var(--green-600)", baseline }) {
  if (!data || data.length < 2) return <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, color: "var(--neutral-300)" }}>—</span>;
  const max = Math.max(...data, 1), min = Math.min(...data, 0);
  const pt = (v, i) => `${(i / (data.length - 1)) * (w - 4) + 2},${h - 3 - ((v - min) / (max - min || 1)) * (h - 6)}`;
  return (
    <svg width={w} height={h} style={{ display: "block", flex: "none" }} aria-hidden="true">
      {baseline != null && (
        <line x1="2" x2={w - 2}
          y1={h - 3 - ((baseline - min) / (max - min || 1)) * (h - 6)}
          y2={h - 3 - ((baseline - min) / (max - min || 1)) * (h - 6)}
          stroke="var(--neutral-300)" strokeWidth="1" strokeDasharray="2 3" />
      )}
      <polyline points={data.map(pt).join(" ")} fill="none" stroke={color} strokeWidth="1.6" strokeLinejoin="round" strokeLinecap="round" />
      <circle cx={pt(data[data.length - 1], data.length - 1).split(",")[0]} cy={pt(data[data.length - 1], data.length - 1).split(",")[1]} r="2.2" fill={color} />
    </svg>
  );
}

// Horizontal bar with mono value.
function CRBar({ label, n, max, suffix = "", color = "var(--green-600)" }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: "118px 1fr 34px", alignItems: "center", gap: 10 }}>
      <span style={{ fontSize: 12.5, fontWeight: 600, color: "var(--neutral-700)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{label}</span>
      <span style={{ height: 8, borderRadius: 4, background: "var(--mist-100)", overflow: "hidden", display: "block" }}>
        <span style={{ display: "block", height: "100%", width: `${Math.round((n / max) * 100)}%`, borderRadius: 4, background: color }}></span>
      </span>
      <span style={{ fontFamily: "var(--font-mono)", fontSize: 12, fontWeight: 600, color: "var(--green-950)", textAlign: "right" }}>{n}{suffix}</span>
    </div>
  );
}

// Card section wrapper. `info` adds a metric-definition ⓘ next to the title.
function CRCard({ title, hint, info, action, children, pad = 16, style }) {
  return (
    <section style={{
      background: "var(--surface-card)", borderRadius: "var(--radius-md)",
      boxShadow: "var(--shadow-card)", padding: pad, minWidth: 0, ...style,
    }}>
      {(title || action) && (
        <div style={{ display: "flex", alignItems: "baseline", gap: 10, marginBottom: 12 }}>
          <h2 style={{ margin: 0, fontSize: 14.5, fontWeight: 800, color: "var(--green-950)", letterSpacing: "-0.005em", display: "inline-flex", alignItems: "center", gap: 6 }}>{title}{info && <CRDef k={info} align="left" />}</h2>
          <span style={{ flex: 1 }}></span>
          {hint && <span style={{ fontSize: 11.5, fontWeight: 500, color: "var(--neutral-500)", whiteSpace: "nowrap" }}>{hint}</span>}
          {action}
        </div>
      )}
      {children}
    </section>
  );
}

/* ---- Tables: sortable headers + keyboard-traversable rows ---- */

// useCRSort: [sort, toggle]. crSorted: apply accessor map.
function useCRSort(defKey, defDir = "desc") {
  const [sort, setSort] = React.useState({ key: defKey, dir: defDir });
  const toggle = (key, firstDir = "desc") => setSort((s) => s.key === key ? { key, dir: s.dir === "asc" ? "desc" : "asc" } : { key, dir: firstDir });
  return [sort, toggle];
}
function crSorted(rows, sort, accessors) {
  const acc = accessors[sort.key];
  if (!acc) return rows;
  const dir = sort.dir === "asc" ? 1 : -1;
  return [...rows].sort((a, b) => {
    const va = acc(a), vb = acc(b);
    if (typeof va === "string") return va.localeCompare(vb) * dir;
    return (va - vb) * dir;
  });
}

// Header row. keys[i] (string) makes column i sortable; defs[i] adds ⓘ.
function CRTh({ cols, labels, aligns = [], keys, defs, sort, onSort }) {
  return (
    <div style={{ display: "grid", gridTemplateColumns: cols, gap: 12, alignItems: "center", padding: "0 12px 8px", borderBottom: "1px solid var(--line-200)" }}>
      {labels.map((l, i) => {
        const k = keys && keys[i];
        const on = k && sort && sort.key === k;
        const cell = (
          <span style={{ fontSize: 11, fontWeight: 700, letterSpacing: "0.05em", textTransform: "uppercase", color: on ? "var(--green-800)" : "var(--neutral-500)", whiteSpace: "nowrap" }}>{l}</span>
        );
        const def = defs && defs[i] ? <CRDef k={defs[i]} align={aligns[i] === "right" ? "right" : "left"} /> : null;
        return (
          <span key={i} style={{ display: "flex", alignItems: "center", gap: 4, justifyContent: aligns[i] === "right" ? "flex-end" : "flex-start", minWidth: 0 }}>
            {k ? (
              <button className="cr-ia cr-th-btn" onClick={() => onSort(k)} aria-label={`Sort by ${l}${on ? (sort.dir === "asc" ? ", ascending" : ", descending") : ""}`}>
                {cell}
                {on
                  ? <CRIcon name={sort.dir === "asc" ? "arrow-up" : "arrow-down"} size={11} color="var(--green-800)" />
                  : <CRIcon name="arrow-up-down" size={10} color="var(--neutral-300)" />}
              </button>
            ) : cell}
            {def}
          </span>
        );
      })}
    </div>
  );
}

// Row — real interactive element: focusable, Enter/Space activates, ↑↓ traverses.
function CRRow({ cols, onClick, children, last, ariaLabel }) {
  const ref = React.useRef(null);
  const onKeyDown = (e) => {
    if (e.key === "ArrowDown" || e.key === "ArrowUp") {
      const rows = Array.from(ref.current.parentElement.querySelectorAll('[data-cr-row="1"]'));
      const next = rows[rows.indexOf(ref.current) + (e.key === "ArrowDown" ? 1 : -1)];
      if (next) { e.preventDefault(); next.focus(); }
    } else if (e.key === "Enter" || e.key === " ") {
      e.preventDefault(); onClick && onClick();
    }
  };
  return (
    <div
      ref={ref}
      data-cr-row={onClick ? "1" : undefined}
      role={onClick ? "button" : undefined}
      tabIndex={onClick ? 0 : undefined}
      aria-label={ariaLabel}
      className={"cr-ia" + (onClick ? " cr-row-i" : "")}
      onClick={onClick}
      onKeyDown={onClick ? onKeyDown : undefined}
      style={{
        display: "grid", gridTemplateColumns: cols, gap: 12, alignItems: "center",
        padding: "9px 12px", borderBottom: last ? "none" : "1px solid var(--line-200)",
      }}>
      {children}
    </div>
  );
}

// Inline entity link — every named entity routes to its evidence.
function CRLink({ onClick, children, size = 12.5, weight = 700, color = "var(--green-950)" }) {
  return (
    <button className="cr-ia cr-link" onClick={(e) => { e.stopPropagation(); onClick(); }} style={{ fontSize: size, fontWeight: weight, color }}>{children}</button>
  );
}

// Filter pill — removable ✕ when active.
function CRFilterPill({ on, label, onClick, onClear }) {
  return (
    <button className={"cr-ia cr-pill" + (on ? " cr-pill-on" : "")} onClick={on && onClear ? onClear : onClick} aria-pressed={on} style={{
      padding: "5px 12px", borderRadius: "var(--radius-pill)", border: "none",
      display: "inline-flex", alignItems: "center", gap: 6,
      fontFamily: "var(--font-sans)", fontSize: 12, fontWeight: 700, whiteSpace: "nowrap",
      background: on ? "var(--green-800)" : "var(--surface-white)",
      color: on ? "#fff" : "var(--neutral-700)",
      boxShadow: on ? "var(--shadow-button)" : "inset 0 0 0 1px var(--line-200)",
    }}>
      {label}
      {on && onClear && <CRIcon name="x" size={11} color="rgba(255,255,255,0.75)" />}
    </button>
  );
}

// Type-to-filter field for tables.
function CRSearch({ value, onChange, placeholder, width = 220 }) {
  return (
    <span style={{ display: "inline-flex", alignItems: "center", gap: 7, width, padding: "5px 11px", background: "var(--surface-white)", borderRadius: "var(--radius-pill)", boxShadow: "inset 0 0 0 1px var(--line-200)" }}>
      <CRIcon name="search" size={12} color="var(--neutral-500)" />
      <input className="cr-ia" value={value} onChange={(e) => onChange(e.target.value)} placeholder={placeholder} aria-label={placeholder} style={{
        flex: 1, minWidth: 0, border: "none", outline: "none", background: "transparent",
        fontFamily: "var(--font-sans)", fontSize: 12.5, fontWeight: 600, color: "var(--green-950)",
      }} />
      {value && <button className="cr-ia cr-def-btn" aria-label="Clear search" onClick={() => onChange("")}><CRIcon name="x" size={12} color="currentColor" /></button>}
    </span>
  );
}

// Filtered-to-zero empty state. `ghost` renders the Pass silhouette — use it
// when the missing subject is passes/showings; keep honest text for data empties.
function CREmpty({ icon = "search-x", title, body, action, ghost = false }) {
  const DSx = window.DoorpassDesignSystem_eaad52;
  return (
    <div style={{ padding: "36px 20px", display: "flex", flexDirection: "column", alignItems: "center", gap: 6, textAlign: "center" }}>
      {ghost && DSx && DSx.PassGhost
        ? <span style={{ width: 200, marginBottom: 6 }}><DSx.PassGhost size="row" /></span>
        : <span style={{ width: 40, height: 40, borderRadius: 12, background: "var(--mist-100)", display: "grid", placeItems: "center", marginBottom: 4 }}>
            <CRIcon name={icon} size={18} color="var(--neutral-500)" />
          </span>}
      <div style={{ fontSize: 13.5, fontWeight: 700, color: "var(--green-950)" }}>{title}</div>
      {body && <div style={{ fontSize: 12.5, fontWeight: 500, color: "var(--neutral-700)", maxWidth: 360, lineHeight: "17px" }}>{body}</div>}
      {action && <div style={{ marginTop: 8 }}>{action}</div>}
    </div>
  );
}

const crMono = (size = 13, color = "var(--green-950)", weight = 600) => ({
  fontFamily: "var(--font-mono)", fontSize: size, fontWeight: weight, color,
});

// Latency chip — the coaching metric, color-banded.
function CRLatency({ min }) {
  const tone = min <= 10 ? "good" : min <= 20 ? "warn" : "bad";
  return <CRChip tone={tone} style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{min} min</CRChip>;
}

/* ---------------- ⌘K command palette — navigation + entities, nothing more ---------------- */

function CRPalette({ go, network }) {
  const D = window.CRData;
  const [open, setOpen] = React.useState(false);
  const [q, setQ] = React.useState("");
  const [sel, setSel] = React.useState(0);
  const inputRef = React.useRef(null);

  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setOpen((o) => !o); setQ(""); setSel(0); }
      else if (e.key === "Escape") setOpen(false);
    };
    const onOpen = () => { setOpen(true); setQ(""); setSel(0); };
    window.addEventListener("keydown", onKey);
    window.addEventListener("cr-palette", onOpen);
    return () => { window.removeEventListener("keydown", onKey); window.removeEventListener("cr-palette", onOpen); };
  }, []);
  React.useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); }, [open]);

  if (!open) return null;

  const SCREENS = [
    { label: "Overview", icon: "layout-dashboard", view: "overview" },
    { label: "Listings board", icon: "building-2", view: "listings" },
    { label: "Team", icon: "users", view: "team" },
    { label: "Pipeline · market demand", icon: "radar", view: "pipeline" },
    { label: "Pipeline · recruiting", icon: "radar", view: "recruiting" },
    ...(network ? [{ label: "Markets · national & regional", icon: "globe-2", view: "markets" }] : []),
    { label: "Operations", icon: "wrench", view: "operations" },
    { label: "Activity & trust", icon: "scroll-text", view: "activity" },
    { label: "Settings", icon: "settings", view: "settings" },
  ];
  const ql = q.trim().toLowerCase();
  const match = (s) => !ql || s.toLowerCase().includes(ql);
  const items = [
    ...SCREENS.filter((s) => match(s.label)).map((s) => ({ group: "Screens", label: s.label, icon: s.icon, run: () => go(s.view) })),
    ...D.listings.filter((l) => match(l.addr + " " + l.hood)).map((l) => ({ group: "Listings", label: l.addr, sub: `${l.hood} · ${l.price}`, listing: l, run: () => go("listing", l.id) })),
    ...D.agents.filter((a) => match(a.name)).map((a) => ({ group: "Team", label: a.name, sub: a.role, avatar: a.name, run: () => go("team") })),
    ...D.buyerAgents.filter((b) => match(b.name + " " + b.brokerage)).map((b) => ({ group: "Buyer-agents", label: b.name, sub: b.brokerage, avatar: b.name, run: () => go("recruiting") })),
  ].slice(0, 9);
  const selIdx = Math.min(sel, Math.max(items.length - 1, 0));

  const onKeyDown = (e) => {
    if (e.key === "ArrowDown") { e.preventDefault(); setSel((s) => Math.min(s + 1, items.length - 1)); }
    else if (e.key === "ArrowUp") { e.preventDefault(); setSel((s) => Math.max(s - 1, 0)); }
    else if (e.key === "Enter" && items[selIdx]) { setOpen(false); items[selIdx].run(); }
  };

  let lastGroup = null;
  return (
    <div onClick={() => setOpen(false)} style={{ position: "fixed", inset: 0, zIndex: 90, background: "rgba(5,31,17,0.40)", display: "flex", justifyContent: "center", alignItems: "flex-start", paddingTop: 150 }}>
      <div onClick={(e) => e.stopPropagation()} role="dialog" aria-label="Command palette" style={{ width: 560, background: "var(--surface-card)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-float)", overflow: "hidden" }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, padding: "13px 16px", borderBottom: "1px solid var(--line-200)" }}>
          <CRIcon name="search" size={15} color="var(--neutral-500)" />
          <input ref={inputRef} value={q} onChange={(e) => { setQ(e.target.value); setSel(0); }} onKeyDown={onKeyDown}
            placeholder="Jump to a listing, agent, or screen…" aria-label="Command palette search"
            style={{ flex: 1, border: "none", outline: "none", background: "transparent", fontFamily: "var(--font-sans)", fontSize: 14.5, fontWeight: 600, color: "var(--green-950)" }} />
          <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, fontWeight: 500, color: "var(--neutral-500)", background: "var(--mist-100)", borderRadius: 5, padding: "1px 6px" }}>esc</span>
        </div>
        <div style={{ maxHeight: 380, overflowY: "auto", padding: "6px 8px 8px" }}>
          {items.length === 0 && <CREmpty title={`No matches for “${q}”`} body="Try a street name, agent, or screen." />}
          {items.map((it, i) => {
            const head = it.group !== lastGroup ? it.group : null;
            lastGroup = it.group;
            const on = i === selIdx;
            return (
              <React.Fragment key={i}>
                {head && <div style={{ fontSize: 10.5, fontWeight: 700, letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--neutral-500)", padding: "9px 10px 4px" }}>{head}</div>}
                <button className="cr-ia" onClick={() => { setOpen(false); it.run(); }} onMouseEnter={() => setSel(i)} style={{
                  display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "8px 10px",
                  background: on ? "var(--surface-tint)" : "transparent", border: "none", borderRadius: "var(--radius-sm)",
                  cursor: "pointer", textAlign: "left", fontFamily: "var(--font-sans)",
                  boxShadow: on ? "inset 0 0 0 1px var(--green-300)" : "none",
                }}>
                  {it.listing ? <CRPhoto listing={it.listing} w={30} h={24} radius={6} />
                    : it.avatar ? <Avatar name={it.avatar} size={24} />
                    : <span style={{ width: 30, display: "grid", placeItems: "center" }}><CRIcon name={it.icon} size={14} color="var(--neutral-500)" /></span>}
                  <span style={{ flex: 1, minWidth: 0, fontSize: 13, fontWeight: 700, color: "var(--green-950)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{it.label}</span>
                  {it.sub && <span style={{ fontSize: 11.5, fontWeight: 500, color: "var(--neutral-500)", whiteSpace: "nowrap" }}>{it.sub}</span>}
                  {on && <span style={{ fontFamily: "var(--font-mono)", fontSize: 10.5, color: "var(--neutral-500)" }}>↵</span>}
                </button>
              </React.Fragment>
            );
          })}
        </div>
      </div>
    </div>
  );
}

Object.assign(window, {
  CRIcon, CRPhoto, CRImgSrc, CRPeriodContext, usePeriod, CRShell, CRPage, CRStat, CRDef,
  CRChip, CRSpark, CRBar, CRCard, CRTh, CRRow, CRLink, CRFilterPill, CRSearch, CREmpty,
  CRLatency, CRPalette, CRSkel, useCRSort, crSorted, crMono,
  CRBenchContext, useBench, CRBenchControl, CRBenchBand, crBenchCalc,
});
})();
