/* Sentinel — app shell: Logo, role-aware Sidebar, Topbar with role switcher, AppShell. */

function Logo({ size = 22 }) {
  return <img src="assets/logo.svg" alt="Ginja·Ai" style={{ height: size * 1.3, width: "auto", display: "block" }} />;
}

function navFor(role) {
  const records = { section: "Records", items: [
    { id: "tracker", label: "Change tracker", icon: "history" },
    { id: "sla", label: "SLA dashboard", icon: "gauge" },
    { id: "audit", label: "Audit trail", icon: "shield-check" },
  ]};
  if (role === "rm") return [
    { section: "Contracting", items: [
      { id: "queue", label: "My contracts", icon: "folder-open" },
      { id: "upload", label: "Upload contract", icon: "file-up" },
    ]}, records ];
  if (role === "admin") return [
    { section: "Platform", items: [
      { id: "admin", label: "Rules & routing", icon: "sliders-horizontal" },
      { id: "access", label: "Users & access", icon: "users" },
    ]}, records ];
  return [
    { section: "Review", items: [
      { id: "queue", label: "Review queue", icon: "list-checks" },
    ]}, records ];
}

function Sidebar({ role, current, onNavigate, queueCount }) {
  const r = ROLES[role];
  return (
    <aside style={{ width: 236, flex: "none", background: "var(--bg-surface)", borderRight: "1px solid var(--border-base)",
      display: "flex", flexDirection: "column", height: "100%" }}>
      <div style={{ padding: "18px 18px 14px", borderBottom: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", justifyContent: "space-between" }}>
        <Logo size={21} />
        <span style={{ fontFamily: "var(--font-mono)", fontSize: 10, fontWeight: 600, letterSpacing: "0.1em", color: "var(--content-faint)", textTransform: "uppercase", border: "1px solid var(--border-base)", borderRadius: 4, padding: "2px 5px" }}>Sentinel</span>
      </div>
      <nav style={{ padding: "10px 12px", overflowY: "auto", flex: 1 }}>
        {navFor(role).map((grp) => (
          <div key={grp.section} style={{ marginBottom: 14 }}>
            <div className="text-label" style={{ padding: "8px 10px 6px" }}>{grp.section}</div>
            {grp.items.map((it) => {
              const active = current === it.id;
              return (
                <button key={it.id} onClick={() => onNavigate(it.id)} style={{
                  display: "flex", alignItems: "center", gap: 10, width: "100%", textAlign: "left",
                  padding: "8px 10px", marginBottom: 2, borderRadius: "var(--radius-md)", border: "none", cursor: "pointer",
                  fontSize: 14, fontFamily: "var(--font-body)",
                  background: active ? "var(--green-50)" : "transparent", color: active ? "var(--green-800)" : "var(--content-base)", fontWeight: active ? 600 : 400 }}
                  onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "var(--ec-muted)"; }}
                  onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}>
                  <Icon name={it.icon} size={16} />
                  <span style={{ flex: 1 }}>{it.label}</span>
                  {it.id === "queue" && queueCount > 0 && (
                    <span style={{ fontFamily: "var(--font-mono)", fontSize: 11, fontWeight: 600, minWidth: 18, height: 18, padding: "0 5px",
                      borderRadius: 999, background: active ? "var(--green-700)" : "var(--neutral-300)", color: active ? "#fff" : "var(--content-base)",
                      display: "inline-flex", alignItems: "center", justifyContent: "center" }}>{queueCount}</span>
                  )}
                </button>
              );
            })}
          </div>
        ))}
      </nav>
      <div style={{ padding: "12px 14px", borderTop: "1px solid var(--border-subtle)", display: "flex", alignItems: "center", gap: 10 }}>
        <Avatar name={r.name} size={32} tone={r.tone} />
        <div style={{ minWidth: 0 }}>
          <div style={{ fontSize: 13.5, fontWeight: 600, color: "var(--content-strong)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.name}</div>
          <div style={{ fontSize: 12.5, color: "var(--content-muted)", whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>{r.title}</div>
        </div>
      </div>
    </aside>
  );
}

function RoleSwitcher({ role, onChange, onSignOut }) {
  const [open, setOpen] = React.useState(false);
  const r = ROLES[role];
  const ref = React.useRef(null);
  React.useEffect(() => {
    const h = (e) => { if (ref.current && !ref.current.contains(e.target)) setOpen(false); };
    document.addEventListener("mousedown", h); return () => document.removeEventListener("mousedown", h);
  }, []);
  return (
    <div ref={ref} style={{ position: "relative" }}>
      <button onClick={() => setOpen((o) => !o)} style={{ display: "flex", alignItems: "center", gap: 9, padding: "5px 10px 5px 7px",
        border: "1px solid var(--border-strong)", borderRadius: "var(--radius-full)", background: "var(--bg-surface)", cursor: "pointer", fontFamily: "var(--font-body)" }}>
        <Avatar name={r.name} size={26} tone={r.tone} />
        <span style={{ textAlign: "left", lineHeight: 1.15 }}>
          <span style={{ display: "block", fontSize: 10, color: "var(--content-faint)", textTransform: "uppercase", letterSpacing: "0.07em", fontWeight: 600 }}>Viewing as</span>
          <span style={{ display: "block", fontSize: 13, fontWeight: 600, color: "var(--content-strong)" }}>{r.title}</span>
        </span>
        <Icon name="chevrons-up-down" size={15} style={{ color: "var(--content-muted)" }} />
      </button>
      {open && (
        <div style={{ position: "absolute", top: "calc(100% + 6px)", right: 0, width: 264, background: "var(--bg-surface)",
          border: "1px solid var(--border-base)", borderRadius: "var(--radius-lg)", boxShadow: "var(--elev-3)", padding: 6, zIndex: 50 }}>
          <div className="text-label" style={{ padding: "8px 10px 6px" }}>Switch role · prototype</div>
          {Object.values(ROLES).map((x) => {
            const active = x.id === role;
            return (
              <button key={x.id} onClick={() => { onChange(x.id); setOpen(false); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%",
                padding: "8px 10px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", textAlign: "left",
                background: active ? "var(--green-50)" : "transparent" }}
                onMouseEnter={(e) => { if (!active) e.currentTarget.style.background = "var(--ec-muted)"; }}
                onMouseLeave={(e) => { if (!active) e.currentTarget.style.background = "transparent"; }}>
                <Avatar name={x.name} size={30} tone={x.tone} />
                <span style={{ flex: 1, minWidth: 0 }}>
                  <span style={{ display: "block", fontSize: 13.5, fontWeight: 600, color: "var(--content-strong)" }}>{x.name}</span>
                  <span style={{ display: "block", fontSize: 12.5, color: "var(--content-muted)" }}>{x.title}</span>
                </span>
                {active && <Icon name="check" size={16} style={{ color: "var(--ec-primary)" }} />}
              </button>
            );
          })}
          <div style={{ borderTop: "1px solid var(--border-subtle)", marginTop: 6, paddingTop: 6 }}>
            <button onClick={() => { setOpen(false); onSignOut && onSignOut(); }} style={{ display: "flex", alignItems: "center", gap: 10, width: "100%", padding: "8px 10px", borderRadius: "var(--radius-md)", border: "none", cursor: "pointer", textAlign: "left", background: "transparent", color: "var(--content-base)", fontFamily: "var(--font-body)", fontSize: 13.5 }}
              onMouseEnter={(e) => (e.currentTarget.style.background = "var(--ec-muted)")} onMouseLeave={(e) => (e.currentTarget.style.background = "transparent")}>
              <span style={{ width: 30, display: "inline-flex", justifyContent: "center", color: "var(--content-muted)" }}><Icon name="log-out" size={16} /></span>Sign out
            </button>
          </div>
        </div>
      )}
    </div>
  );
}

function Topbar({ title, subtitle, role, onRole, onSignOut, killSwitch, search, onSearch, actions, breadcrumb }) {
  return (
    <header style={{ minHeight: 64, flex: "none", background: "var(--bg-surface)", borderBottom: "1px solid var(--border-base)",
      display: "flex", alignItems: "center", gap: 16, padding: "0 24px" }}>
      <div style={{ minWidth: 0 }}>
        {breadcrumb}
        <div style={{ fontSize: 18, fontWeight: 600, color: "var(--content-strong)", letterSpacing: "-0.01em" }}>{title}</div>
        {subtitle && <div style={{ fontSize: 13, color: "var(--content-muted)" }}>{subtitle}</div>}
      </div>
      <div style={{ flex: 1 }} />
      {onSearch && (
        <div style={{ position: "relative", width: 240 }}>
          <span style={{ position: "absolute", left: 11, top: "50%", transform: "translateY(-50%)", color: "var(--content-muted)", display: "flex" }}><Icon name="search" size={15} /></span>
          <input value={search} onChange={(e) => onSearch(e.target.value)} placeholder="Search contracts, providers…" style={{
            width: "100%", fontFamily: "var(--font-body)", fontSize: 14, padding: "8px 12px 8px 32px",
            border: "1px solid var(--border-strong)", borderRadius: "var(--radius-md)", background: "var(--bg-page)", color: "var(--content-strong)", boxSizing: "border-box" }} />
        </div>
      )}
      {actions}
      {killSwitch && (
        <span style={{ display: "inline-flex", alignItems: "center", gap: 6, padding: "5px 11px", borderRadius: "var(--radius-full)",
          background: "var(--status-danger-bg)", color: "var(--status-danger)", fontSize: 12.5, fontWeight: 600 }}>
          <Icon name="power-off" size={14} /> Auto-accept paused
        </span>
      )}
      <RoleSwitcher role={role} onChange={onRole} onSignOut={onSignOut} />
    </header>
  );
}

function AppShell({ role, current, onNavigate, onRole, queueCount, killSwitch, topbar, children }) {
  return (
    <div className="ginja-root" style={{ display: "flex", height: "100vh", overflow: "hidden", background: "var(--bg-page)" }}>
      <Sidebar role={role} current={current} onNavigate={onNavigate} queueCount={queueCount} />
      <div style={{ flex: 1, display: "flex", flexDirection: "column", minWidth: 0 }}>
        {topbar}
        <main style={{ flex: 1, overflowY: "auto", minWidth: 0 }}>{children}</main>
      </div>
    </div>
  );
}

Object.assign(window, { Logo, navFor, Sidebar, RoleSwitcher, Topbar, AppShell });
