// Admin App — wires sections, drawer, suspend modal, command palette, and theme toggle.

function AdminApp() {
  const [section, setSection] = React.useState("dashboard");
  const [detail, setDetail] = React.useState(null);
  const [drawerOpen, setDrawerOpen] = React.useState(false);
  const [suspendOpen, setSuspendOpen] = React.useState(false);
  const [suspendCount, setSuspendCount] = React.useState(0);
  const [cmdkOpen, setCmdkOpen] = React.useState(false);
  const [theme, setTheme] = React.useState(() => {
    try { return localStorage.getItem("thaihao-theme") || "light"; } catch { return "light"; }
  });

  // Apply theme to <html data-theme="…">
  React.useEffect(() => {
    document.documentElement.setAttribute("data-theme", theme);
    try { localStorage.setItem("thaihao-theme", theme); } catch {}
  }, [theme]);

  // ⌘K to open command palette
  React.useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") {
        e.preventDefault();
        setCmdkOpen(o => !o);
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const counts = { tenants: 247, onboarding: 18, sanctions: 2, staff: 8, kols: 6 };
  const openDetail = (t) => { setDetail(t); setDrawerOpen(true); };
  const closeDetail = () => setDrawerOpen(false);
  const openSuspend = (ids) => { setSuspendCount(ids.length); setSuspendOpen(true); };
  const toggleTheme = () => setTheme(t => t === "dark" ? "light" : "dark");

  const crumbs = section === "dashboard"  ? ["Admin", "Dashboard"]
              : section === "tenants"     ? ["Admin", "Tenants"]
              : section === "sanctions"   ? ["Admin", "Compliance", "Sanctions"]
              : section === "audit"       ? ["Admin", "Audit search"]
              : section === "settlements" ? ["Admin", "Finance", "Settlements"]
              : section === "onboarding"  ? ["Admin", "Onboarding"]
              : section === "staff"       ? ["Admin", "People", "Staff"]
              : section === "kols"        ? ["Admin", "People", "KOLs & agencies"]
              : section === "consumers"   ? ["Admin", "People", "Consumers"]
              : ["Admin"];

  return (
    <div className="workspace">
      <AdminSidebar section={section} setSection={setSection} counts={counts} />
      <div className="main">
        <AdminTopbar crumbs={crumbs} onCmdK={() => setCmdkOpen(true)} theme={theme} onToggleTheme={toggleTheme} />
        <div className="content" key={section}>
          {section === "dashboard" && <Dashboard />}
          {section === "tenants"   && <TenantsTable onOpenDetail={openDetail} onBulkSuspend={openSuspend} />}
          {section === "sanctions" && <SanctionsQueue />}
          {section === "staff"     && <StaffList />}
          {section === "kols"      && <KolsList />}
          {section === "consumers" && <ConsumersList />}
          {!["dashboard","tenants","sanctions","staff","kols","consumers"].includes(section) && <EmptyPlaceholder section={section} />}
        </div>
      </div>
      <TenantDrawer tenant={detail} open={drawerOpen} onClose={closeDetail} />
      <SuspendModal open={suspendOpen} count={suspendCount} onClose={() => setSuspendOpen(false)} onConfirm={() => setSuspendOpen(false)} />
      <CommandPalette open={cmdkOpen} onClose={() => setCmdkOpen(false)} onNavigate={(s) => setSection(s)} />
    </div>
  );
}

function EmptyPlaceholder({ section }) {
  const t = {
    onboarding:  { icon: "ti-user-plus",        title: "Onboarding pipelines", body: "All active onboarding pipelines with PipelineBar + SLA timers." },
    audit:       { icon: "ti-history",          title: "Audit search",  body: "Cross-tenant audit log search by actor, action, reason code, or resource." },
    settlements: { icon: "ti-receipt-2",        title: "Settlements",   body: "Settlement batches with multi-tier approval queue (Phase 3)." },
    departments: { icon: "ti-users-group",      title: "Departments",   body: "Department staff with role + scope per ADR-009." },
    system:      { icon: "ti-settings",         title: "System",        body: "Feature flags, KMS rotation, retention policy enforcement." },
  }[section] || { icon: "ti-layout-dashboard", title: section, body: "Coming in a later phase." };
  return (
    <div style={{display:"flex", flexDirection:"column", alignItems:"center", gap:10, padding:"64px 0", color:"var(--on-surface-variant)"}}>
      <i className={"ti " + t.icon} style={{fontSize:48}}></i>
      <h2 style={{fontFamily:"var(--font-display)", fontSize:18, color:"var(--on-surface)", margin:0}}>{t.title}</h2>
      <p style={{maxWidth:480, textAlign:"center", margin:0, fontSize:13}}>{t.body}</p>
      <span style={{fontSize:11, fontFamily:"var(--font-mono)"}}>UI kit · prototype</span>
    </div>
  );
}

ReactDOM.createRoot(document.getElementById("root")).render(<AdminApp />);
