// Corridor dashboard shell — persistent left sidebar + Cmd-K command
// palette, matching the product's two-pane IA. Topbar now carries the
// demo banner and the persistent "Take the tour" affordance.
const { useState, useEffect, useRef } = React;

const NAV_GROUPS = [
  { group: "Overview", items: [["overview", "Overview"], ["account", "Account"]] },
  { group: "Setup", items: [["onboarding", "Onboarding"], ["pricing", "Pricing"], ["policies", "Policies"]] },
  { group: "Activity", items: [["agents", "Agents"], ["events", "Events"], ["settlement", "Settlement"]] },
  { group: "Delivery & access", items: [["webhooks", "Webhooks"], ["api-keys", "API keys"]] },
];
const FLAT = NAV_GROUPS.flatMap((g) => g.items);

function Mark({ size = 22 }) {
  return (
    <svg width={size} height={size} viewBox="0 0 20 20" fill="none" aria-hidden="true">
      <rect x="2.5" y="2" width="3" height="16" rx="1.5" fill="#1e2230" />
      <rect x="14.5" y="2" width="3" height="16" rx="1.5" fill="#1e2230" />
      <circle cx="10" cy="10" r="2.6" fill="hsl(243 72% 58%)" />
    </svg>
  );
}

function Sidebar({ route, setRoute }) {
  return (
    <aside style={S.sidebar}>
      <div style={S.brandRow}>
        <Mark size={22} />
        <span style={S.brandWord}>Corridor</span>
      </div>
      <nav style={S.nav} aria-label="Primary">
        {NAV_GROUPS.map((g) => (
          <div key={g.group} style={{ marginBottom: 22 }}>
            <p style={S.navGroupLabel}>{g.group}</p>
            {g.items.map(([id, label]) => {
              const active = route === id;
              return (
                <a key={id} href="#" onClick={(e) => { e.preventDefault(); setRoute(id); }}
                  aria-current={active ? "page" : undefined}
                  style={{ ...S.navItem, ...(active ? S.navItemActive : null) }}
                  onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "var(--surface-accent)"; }}
                  onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}>
                  {label}
                </a>
              );
            })}
          </div>
        ))}
      </nav>
      <div style={S.userRow}>
        <span style={S.userAvatar}>AC</span>
        <span style={S.userMeta}>Demo viewer · synthetic data</span>
      </div>
    </aside>
  );
}

function CommandPalette({ open, setOpen, setRoute }) {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { if (open && inputRef.current) inputRef.current.focus(); if (!open) setQ(""); }, [open]);
  if (!open) return null;
  const matches = FLAT.filter(([, label]) => label.toLowerCase().includes(q.toLowerCase()));
  const isId = /^(agt|evt|pr_|prl|whk|apk)/i.test(q.trim());
  return (
    <div style={S.cmdOverlay} onClick={() => setOpen(false)}>
      <div style={S.cmdPanel} onClick={(e) => e.stopPropagation()}>
        <input ref={inputRef} value={q} onChange={(e) => setQ(e.target.value)} placeholder="Jump to a section, or paste an ID…" style={S.cmdInput} />
        <div style={S.cmdList}>
          {isId ? (
            <div style={S.cmdItem} onClick={() => { setRoute("events"); setOpen(false); }}>
              <span style={{ fontFamily: "var(--font-mono)", fontSize: 13 }}>{q.trim()}</span>
              <span style={S.cmdHint}>Open detail →</span>
            </div>
          ) : null}
          {matches.length === 0 && !isId ? <p style={S.cmdEmpty}>No matches.</p> : null}
          {matches.map(([id, label]) => (
            <div key={id} style={S.cmdItem} onClick={() => { setRoute(id); setOpen(false); }}>
              <span>{label}</span><span style={S.cmdHint}>Go →</span>
            </div>
          ))}
        </div>
        <div style={S.cmdFoot}><kbd style={S.kbd}>esc</kbd> to close · <kbd style={S.kbd}>⌘K</kbd> to toggle</div>
      </div>
    </div>
  );
}

function Topbar({ onOpenCmd, onStartTour }) {
  return (
    <div className="cor-topbar" style={S.topbar}>
      <div data-tour="demo-banner" style={S.demoBanner}>
        <span style={S.demoDot} />
        <span><strong style={{ fontWeight: 600, color: "var(--text-strong)" }}>Demo</strong> — the real provider console on <span style={{ fontFamily: "var(--font-mono)", fontSize: 12 }}>synthetic data</span>. Nothing here is real.</span>
      </div>
      <div style={S.topRight}>
        <TourButton onStart={onStartTour} />
        <button style={S.cmdTrigger} onClick={onOpenCmd}>
          <span style={{ color: "var(--text-muted)" }}>Search or jump to…</span>
          <kbd style={S.kbd}>⌘K</kbd>
        </button>
      </div>
    </div>
  );
}

const S = {
  sidebar: { position: "sticky", top: 0, height: "100vh", width: 232, flexShrink: 0, display: "flex", flexDirection: "column", borderRight: "1px solid var(--hairline)", background: "var(--surface-card)" },
  brandRow: { display: "flex", alignItems: "center", gap: 9, height: 56, padding: "0 20px", borderBottom: "1px solid var(--hairline)" },
  brandWord: { fontSize: 16, fontWeight: 600, letterSpacing: "-0.01em", color: "var(--text-strong)" },
  nav: { flex: 1, overflowY: "auto", padding: "20px 12px" },
  navGroupLabel: { padding: "0 12px 6px", margin: 0, fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: "0.04em", color: "var(--text-muted)" },
  navItem: { display: "block", padding: "8px 12px", borderRadius: "var(--radius-md)", fontSize: 14, fontWeight: 500, color: "var(--text-muted)", textDecoration: "none", transition: "background-color 150ms, color 150ms" },
  navItemActive: { background: "var(--brand-fill)", color: "var(--brand)" },
  userRow: { display: "flex", alignItems: "center", gap: 10, padding: "14px 20px", borderTop: "1px solid var(--hairline)" },
  userAvatar: { display: "flex", alignItems: "center", justifyContent: "center", width: 28, height: 28, borderRadius: "50%", background: "var(--brand-fill)", color: "var(--brand)", fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 600 },
  userMeta: { fontSize: 12, color: "var(--text-muted)" },
  topbar: { display: "flex", justifyContent: "space-between", alignItems: "center", gap: 16, height: 56, padding: "0 24px 0 32px", borderBottom: "1px solid var(--hairline)", background: "var(--surface-card)", position: "sticky", top: 0, zIndex: 5 },
  demoBanner: { display: "flex", alignItems: "center", gap: 9, minWidth: 0, fontSize: 13, color: "var(--text-muted)" },
  demoDot: { width: 7, height: 7, borderRadius: "50%", background: "var(--warning-ink)", flexShrink: 0 },
  topRight: { display: "flex", alignItems: "center", gap: 10, flexShrink: 0 },
  kbd: { fontFamily: "var(--font-mono)", fontSize: 11, padding: "2px 6px", borderRadius: 4, background: "var(--surface-muted)", color: "var(--text-muted)", border: "1px solid var(--hairline)" },
  cmdTrigger: { display: "flex", alignItems: "center", justifyContent: "space-between", gap: 32, width: 240, height: 36, padding: "0 12px", border: "1px solid var(--hairline)", borderRadius: "var(--radius-md)", background: "var(--surface-page)", fontFamily: "var(--font-sans)", fontSize: 13, cursor: "pointer" },
  cmdOverlay: { position: "fixed", inset: 0, background: "hsl(230 25% 12% / 0.32)", backdropFilter: "blur(2px)", display: "flex", justifyContent: "center", alignItems: "flex-start", paddingTop: "14vh", zIndex: 50 },
  cmdPanel: { width: 540, maxWidth: "90vw", background: "var(--surface-card)", border: "1px solid var(--hairline)", borderRadius: "var(--radius-lg)", boxShadow: "var(--shadow-lg)", overflow: "hidden" },
  cmdInput: { width: "100%", boxSizing: "border-box", height: 52, padding: "0 18px", border: "none", borderBottom: "1px solid var(--hairline)", fontFamily: "var(--font-sans)", fontSize: 15, color: "var(--text-strong)", outline: "none" },
  cmdList: { maxHeight: 320, overflowY: "auto", padding: 8 },
  cmdItem: { display: "flex", alignItems: "center", justifyContent: "space-between", padding: "10px 12px", borderRadius: "var(--radius-md)", fontSize: 14, color: "var(--text-strong)", cursor: "pointer" },
  cmdHint: { fontSize: 12, color: "var(--text-muted)" },
  cmdEmpty: { padding: "12px", fontSize: 13, color: "var(--text-muted)", textAlign: "center" },
  cmdFoot: { padding: "10px 16px", borderTop: "1px solid var(--hairline)", fontSize: 12, color: "var(--text-muted)" },
};

Object.assign(window, { Sidebar, CommandPalette, Topbar, Mark, NAV_GROUPS });
