// AMOMS — root app shell. Sidebar + topbar + page router.

const _unread = (window.MD?.NOTIFS || []).filter(n => !n.read).length;
const ROUTES = [
  { group: "OPERATIONS",   items: [
    { id: "procurement", label: "Procurement",          icon: window.Icons.Procurement, pill: "12", href: "../procurement/ADM-PROC-01.html" },
  ]},
  { group: "PLATFORM",     items: [
    { id: "users",         label: "User management",     icon: window.Icons.Users,         href: "../core/CORE-05.html" },
    { id: "permissions",   label: "Roles & permissions", icon: window.Icons.Settings,      href: "../core/CORE-08.html" },
    { id: "notifications", label: "Notifications",       icon: window.Icons.Bell, pill: _unread ? String(_unread) : null, pillTone: "muted", href: "../core/CORE-09.html" },
    { id: "auditLogNav",   label: "Audit log",           icon: window.Icons.ClipboardList, href: "../core/CORE-12.html" },
  ]},
];

// Full page directory — used by the Tweaks "Pages" navigator to jump between screens.
// href is relative to the current document (each screen is a sibling .html file).
const PAGE_NAV = [
  { route: "procurement",     code: "ADM-PROC-01", label: "Procurement dashboard",        href: "../procurement/ADM-PROC-01.html" },
  { route: "requirements",    code: "ADM-PROC-02", label: "Requirement list",             href: "../procurement/ADM-PROC-02.html" },
  { route: "createReq",       code: "ADM-PROC-03", label: "New requirement",              href: "../procurement/ADM-PROC-03.html" },
  { route: "bulkCreate",      code: "ADM-PROC-04", label: "Bulk create requirements",     href: "../procurement/ADM-PROC-04.html" },
  { route: "reqDetail",       code: "ADM-PROC-05", label: "Requirement detail",           href: "../procurement/ADM-PROC-05.html" },
  { route: "editReq",         code: "ADM-PROC-06", label: "Edit requirement",             href: "../procurement/ADM-PROC-06.html" },
  { route: "broadcastSelect", code: "ADM-PROC-07", label: "Broadcast — select farmers",   href: "../procurement/ADM-PROC-07.html" },
  { route: "broadcastPreview",code: "ADM-PROC-08", label: "Broadcast — preview & send",   href: "../procurement/ADM-PROC-08.html" },
  { route: "broadcastStatus", code: "ADM-PROC-09", label: "Broadcast status",             href: "../procurement/ADM-PROC-09.html" },
  { route: "responses",       code: "ADM-PROC-10", label: "Responses & gate-ins",            href: "../procurement/ADM-PROC-10.html" },
  { route: "compare",         code: "ADM-PROC-11", label: "Compare responses",            href: "../procurement/ADM-PROC-11.html" },
  { route: "shortlist",       code: "ADM-PROC-12", label: "Shortlist farmers",            href: "../procurement/ADM-PROC-12.html" },
  { route: "approve",         code: "ADM-PROC-13", label: "Gate-in detail",                 href: "../procurement/ADM-PROC-13.html" },
  { route: "agreement",       code: "ADM-PROC-14", label: "Digital agreement",            href: "../procurement/ADM-PROC-14.html" },
  { route: "reschedule",      code: "ADM-PROC-15", label: "Reschedule request",           href: "../procurement/ADM-PROC-15.html" },
  { route: "slotCalendar",    code: "ADM-PROC-16", label: "Gate-in schedule",       href: "../procurement/ADM-PROC-16.html" },
  { route: "payments",        code: "ADM-PROC-17", label: "Payments",               href: "../procurement/ADM-PROC-17.html" },
  { route: "firstRun",        code: "ADM-PROC-19", label: "First-run / empty state",      href: "../procurement/ADM-PROC-19.html" },
  // ── Core / Platform module ──
  { route: "profile",         code: "CORE-04",     label: "Profile & settings",           href: "../core/CORE-04.html" },
  { route: "users",           code: "CORE-05",     label: "User management — list",        href: "../core/CORE-05.html" },
  { route: "userCreate",      code: "CORE-06",     label: "User management — create",      href: "../core/CORE-06.html" },
  { route: "userEdit",        code: "CORE-07",     label: "User management — edit",        href: "../core/CORE-07.html" },
  { route: "permissions",     code: "CORE-08",     label: "Role & permissions matrix",     href: "../core/CORE-08.html" },
  { route: "notifications",   code: "CORE-09",     label: "Notifications inbox",           href: "../core/CORE-09.html" },
  { route: "globalSearch",    code: "CORE-10",     label: "Global search",                 href: "../core/CORE-10.html" },
  { route: "auditLog",        code: "CORE-12",     label: "Audit log viewer",              href: "../core/CORE-12.html" },
];

// `nav` = which sidebar item stays highlighted for sub-screens of a module.
const PAGE_META = {
  procurement:  { crumbs: ["Operations", "Procurement"], title: "Procurement & farmer management", nav: "procurement" },
  requirements: { crumbs: ["Procurement", "Requirements"], title: "Requirements", nav: "procurement" },
  createReq:    { crumbs: ["Procurement", "Requirements", "New requirement"], title: "New requirement", nav: "procurement" },
  bulkCreate:   { crumbs: ["Procurement", "Requirements", "Bulk create"], title: "Bulk create requirements", nav: "procurement" },
  reqDetail:    { crumbs: ["Procurement", "Requirements", "Detail"], title: "Requirement detail", nav: "procurement" },
  editReq:      { crumbs: ["Procurement", "Requirements", "Edit"], title: "Edit requirement", nav: "procurement" },
  broadcastSelect:  { crumbs: ["Procurement", "Broadcast", "Select farmers"], title: "Broadcast — select farmers", nav: "procurement" },
  broadcastPreview: { crumbs: ["Procurement", "Broadcast", "Preview & send"], title: "Broadcast — preview & send", nav: "procurement" },
  broadcastStatus:  { crumbs: ["Procurement", "Broadcast", "Status"], title: "Broadcast status", nav: "procurement" },
  responses:    { crumbs: ["Procurement", "Requirements", "Responses"], title: "Responses & gate-ins", nav: "procurement" },
  compare:      { crumbs: ["Procurement", "Responses", "Compare"], title: "Compare responses", nav: "procurement" },
  shortlist:    { crumbs: ["Procurement", "Responses", "Shortlist"], title: "Shortlist farmers", nav: "procurement" },
  approve:      { crumbs: ["Procurement", "Gate-ins", "Detail"], title: "Gate-in detail", nav: "procurement" },
  agreement:    { crumbs: ["Procurement", "Order", "Agreement"], title: "Digital agreement", nav: "procurement" },
  reschedule:   { crumbs: ["Procurement", "Slots", "Reschedule request"], title: "Reschedule request", nav: "procurement" },
  slotCalendar: { crumbs: ["Procurement", "Gate-in schedule"], title: "Gate-in schedule", nav: "procurement" },
  payments:     { crumbs: ["Procurement", "Payments"], title: "Payments", nav: "procurement" },
  firstRun:     { crumbs: ["Procurement", "Requirements"], title: "Requirements", nav: "procurement" },
  // ── Core / Platform ──
  profile:      { crumbs: ["Platform", "Profile & settings"], title: "Profile & settings", nav: null },
  users:        { crumbs: ["Platform", "User management"], title: "User management", nav: "users" },
  userCreate:   { crumbs: ["Platform", "Users", "Add user"], title: "Add user", nav: "users" },
  userEdit:     { crumbs: ["Platform", "Users", "Edit"], title: "Edit user", nav: "users" },
  permissions:  { crumbs: ["Platform", "Users", "Roles & permissions"], title: "Roles & permissions", nav: "permissions" },
  notifications:{ crumbs: ["Platform", "Notifications"], title: "Notifications", nav: "notifications" },
  globalSearch: { crumbs: ["Platform", "Global search"], title: "Global search", nav: "search" },
  auditLog:     { crumbs: ["Platform", "Audit log"], title: "Audit log", nav: "auditLogNav" },
};

// ─── Sidebar ───
const Sidebar = ({ route, setRoute, onLinkClick, collapsed }) => (
  <aside className="sidebar">
    <div className="sb-brand">
      <span className="sb-brand-mark">
        <window.Icons.Leaf size={18}/>
      </span>
      <div className="sb-brand-text">
        <div className="sb-brand-name">AMOMS</div>
        <div className="sb-brand-sub">Murang'a Plant</div>
      </div>
    </div>
    {ROUTES.map(group => (
      <React.Fragment key={group.group}>
        <div className="sb-section">{group.group}</div>
        <nav className="sb-nav">
          {group.items.map(item => {
            const active = route === item.id || PAGE_META[route]?.nav === item.id;
            return (
            <a key={item.id}
               className={`sb-link ${active ? "active" : ""}`}
               data-label={item.label}
               onClick={()=> { if (item.href) { window.location.href = item.href; } else { setRoute(item.id); onLinkClick?.(); } }}>
              <item.icon size={16} className="icon"/>
              <span className="sb-link-label">{item.label}</span>
              {item.pill && <span className={`pill ${item.pillTone === "muted" ? "muted" : ""}`}>{item.pill}</span>}
            </a>
            );
          })}
        </nav>
      </React.Fragment>
    ))}
    <div className="sb-footer">
      <a className="sb-user" href="../core/CORE-04.html" title="Profile & settings" data-label="Caroline Wanjala">
        <Avatar initials="CW" tone="avocado"/>
        <div style={{minWidth:0, flex:1}}>
          <div className="name">Caroline Wanjala</div>
          <div className="role">Plant Manager</div>
        </div>
        <window.Icons.Settings size={14}/>
      </a>
    </div>
  </aside>
);

// ─── Topbar ───
const Topbar = ({ route, onNotifyClick, dark, onToggleDark, onMenuClick, onToggleSidebar, collapsed, onSearchClick }) => {
  const meta = PAGE_META[route] || PAGE_META.dashboard;
  return (
    <header className="topbar">
      <button className="tb-icon-btn tb-trigger"
              aria-label={collapsed ? "Expand sidebar" : "Collapse sidebar"}
              title={collapsed ? "Expand sidebar" : "Collapse sidebar"}
              aria-expanded={!collapsed}
              onClick={onToggleSidebar}>
        <window.Icons.PanelLeft size={18}/>
      </button>
      <button className="tb-icon-btn tb-menu-btn" aria-label="Open menu" onClick={onMenuClick}>
        <window.Icons.Menu size={18}/>
      </button>
      <div className="tb-sep" aria-hidden="true"/>
      <div className="tb-crumbs">
        {meta.crumbs.map((c, i) => (
          <span key={i} className="crumb-item">
            {i > 0 && <span className="sep">/</span>}
            <span className={i === meta.crumbs.length - 1 ? "now" : ""}>{c}</span>
          </span>
        ))}
      </div>
      <div className="tb-spacer"/>
      <button className="tb-search" onClick={onSearchClick}>
        <window.Icons.Search size={14}/>
        <span>Search batches, farmers, orders…</span>
        <span className="kbd-chip">⌘K</span>
      </button>
      <button className="tb-icon-btn tb-search-icon" aria-label="Search" onClick={onSearchClick}>
        <window.Icons.Search size={16}/>
      </button>
      <button className="tb-icon-btn" aria-label={dark ? "Switch to light mode" : "Switch to dark mode"} title={dark ? "Light mode" : "Dark mode"} onClick={onToggleDark}>
        {dark ? <window.Icons.Sun size={16}/> : <window.Icons.Moon size={16}/>}
      </button>
      <button className="tb-icon-btn" aria-label="Notifications" onClick={onNotifyClick}>
        <window.Icons.Bell size={16}/>
        <span className="dot"/>
      </button>
      <button className="tb-icon-btn" aria-label="New" title="Quick create">
        <window.Icons.Plus size={16}/>
      </button>
    </header>
  );
};

// ─── Notifications drawer ───
const NOTIF_SOFT = { destructive:"soil-soft", warning:"warning-soft", info:"info-soft", success:"success-soft" };
const NOTIF_FG   = { destructive:"soil", warning:"warning", info:"info", success:"success" };
const NotificationsDrawer = ({ open, onClose, onNavigate }) => {
  const items = (window.MD?.NOTIFS || []).slice(0, 6);
  return (
    <Drawer open={open} onClose={onClose} title="Notifications" sub="Real-time plant alerts"
      footer={<>
        <Button variant="ghost" onClick={onClose}>Close</Button>
        <div style={{flex:1}}/>
        <Button variant="outline" icon={window.Icons.Bell} onClick={()=> { window.location.href = "../core/CORE-09.html"; }}>View all</Button>
      </>}>
      <div style={{display:"flex", flexDirection:"column", gap:10}}>
        {items.map((n) => {
          const Icon = window.Icons[n.icon] || window.Icons.Bell;
          return (
          <div key={n.id} onClick={()=> { if (n.link) window.location.href = n.link; else { onClose(); onNavigate(n.cat); } }}
               style={{display:"flex", gap:12, padding:"12px 14px", border:"1px solid var(--border)", borderRadius:"var(--radius-md)", cursor:"pointer", background: n.read ? "var(--card)" : "var(--surface)", position:"relative"}}>
            {!n.read && <span style={{position:"absolute", top:14, right:14, width:7, height:7, borderRadius:"50%", background:"var(--soil)"}}/>}
            <div style={{
              width:32, height:32, borderRadius:8,
              background:`var(--${NOTIF_SOFT[n.tone] || "info-soft"})`,
              color:`var(--${NOTIF_FG[n.tone] || "info"})`,
              display:"inline-flex", alignItems:"center", justifyContent:"center", flexShrink:0,
            }}>
              <Icon size={16}/>
            </div>
            <div style={{flex:1, minWidth:0}}>
              <div style={{fontSize:13.5, fontWeight: n.read ? 500 : 600, lineHeight:1.35, paddingRight:12}}>{n.title}</div>
              <div className="muted" style={{fontSize:12, marginTop:2}}>{n.desc}</div>
              <div className="muted" style={{fontSize:11, marginTop:4}}>{n.time}</div>
            </div>
          </div>
          );
        })}
      </div>
    </Drawer>
  );
};

// ─── Search overlay ───
const SearchOverlay = ({ open, onClose, onNavigate }) => {
  const [q, setQ] = useState("");
  const inputRef = useRef(null);
  useEffect(() => { if (open) setTimeout(()=> inputRef.current?.focus(), 30); else setQ(""); }, [open]);
  if (!open) return null;
  const items = [
    ...ROUTES.flatMap(g => g.items.map(i => ({ kind: "Page", label: i.label, route: i.id }))),
    { kind: "Batch",  label: "BAT-26-0512-04 · Mary Wairimu",      route: "inventory" },
    { kind: "Batch",  label: "BAT-26-0512-03 · Grace Wambui",      route: "inventory" },
    { kind: "Farmer", label: "Mary Wairimu · Kangema, Murang'a",   route: "procurement" },
    { kind: "Farmer", label: "Esther Njeri · Kandara, Murang'a",   route: "procurement" },
    { kind: "Order",  label: "SO-2026-0413 · Karibu Foods",        route: "orders" },
    { kind: "Order",  label: "SO-2026-0412 · Olivado EPZ",         route: "orders" },
    { kind: "Run",    label: "PRO-26-0512-A · Line 1 · Hass",      route: "production" },
    { kind: "QC",     label: "QC-8429 · BAT-26-0512-04 · pass",    route: "qc" },
  ];
  const hits = q ? items.filter(i => i.label.toLowerCase().includes(q.toLowerCase())) : items.slice(0, 8);
  return (
    <div className="search-overlay" onClick={(e)=> { if (e.target === e.currentTarget) onClose(); }}>
      <div className="panel">
        <input ref={inputRef} value={q} onChange={(e)=> setQ(e.target.value)} placeholder="Search batches, farmers, orders, runs…"/>
        <div className="hits">
          {hits.length === 0
            ? <div className="empty">No results for "{q}"</div>
            : hits.map((h, i) => (
                <div key={i} className="hit" onClick={()=> { onNavigate(h.route); onClose(); }}>
                  <window.Icons.ChevronRight size={14} style={{color:"var(--muted-foreground)"}}/>
                  <span>{h.label}</span>
                  <span className="meta">{h.kind}</span>
                </div>
              ))
          }
        </div>
      </div>
    </div>
  );
};

// ─── Tweak defaults (host-persisted) ───
const TWEAKS_DEFAULTS = /*EDITMODE-BEGIN*/{
  "dark": false,
  "bgPattern": "two",
  "density": "comfortable",
  "procState": "default",
  "reqState": "default",
  "formState": "empty",
  "bulkState": "valid",
  "detailState": "receiving",
  "editMode": "newversion",
  "selectState": "default",
  "sendState": "ready",
  "bcastStatusState": "complete",
  "respState": "receiving",
  "compareCount": "4",
  "shortlistState": "fully",
  "approveStep": "1",
  "gateInState": "awaitingFarmer",
  "agreementState": "awaiting1",
  "rescheduleState": "noconflict",
  "calendarView": "week",
  "usersState": "default",
  "userCreateState": "empty",
  "userEditState": "active",
  "permRole": "procurement-officer",
  "notifState": "default",
  "searchState": "results",
  "auditState": "default",
  "profileTab": "profile"
}/*EDITMODE-END*/;

// ─── Root ───
const App = () => {
  const [route, setRoute] = useState(() => {
    const hash = location.hash.replace("#", "");
    return PAGE_META[hash] ? hash : "procurement";
  });
  const [notifOpen, setNotifOpen] = useState(false);
  const [menuOpen, setMenuOpen] = useState(false);
  const [searchOpen, setSearchOpen] = useState(false);
  const [collapsed, setCollapsed] = useState(() => {
    try { return localStorage.getItem("amoms-sb-collapsed") === "1"; } catch (e) { return false; }
  });

  // persist desktop collapse state
  useEffect(() => {
    try { localStorage.setItem("amoms-sb-collapsed", collapsed ? "1" : "0"); } catch (e) {}
  }, [collapsed]);

  // Trigger: collapse to icon-rail on desktop, open off-canvas sheet on mobile.
  const toggleSidebar = () => {
    if (window.matchMedia("(max-width: 960px)").matches) setMenuOpen(o => !o);
    else setCollapsed(c => !c);
  };

  // sync URL hash
  useEffect(() => {
    location.hash = route;
    document.title = `AMOMS — ${PAGE_META[route]?.title || ""}`;
    setMenuOpen(false); // close menu on route change
  }, [route]);

  // ⌘K shortcut + ⌘B sidebar toggle
  useEffect(() => {
    const onKey = (e) => {
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "k") { e.preventDefault(); setSearchOpen(true); }
      if ((e.metaKey || e.ctrlKey) && e.key.toLowerCase() === "b") { e.preventDefault(); toggleSidebar(); }
      if (e.key === "Escape") { setSearchOpen(false); setMenuOpen(false); }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const [t, setTweak] = window.useTweaks ? window.useTweaks(TWEAKS_DEFAULTS) : [TWEAKS_DEFAULTS, () => {}];
  useEffect(() => {
    document.documentElement.classList.toggle("dark", !!t.dark);
  }, [t.dark]);
  useEffect(() => {
    document.documentElement.setAttribute("data-pattern", t.bgPattern || "two");
  }, [t.bgPattern]);

  const PageComp = window.Pages?.[route];
  const meta = PAGE_META[route];

  return (
    <ToastProvider>
      <div className={`app ${menuOpen ? "menu-open" : ""} ${collapsed ? "collapsed" : ""}`}>
        {menuOpen && <div className="sidebar-scrim" onClick={()=> setMenuOpen(false)}/>}
        <Sidebar route={route} setRoute={setRoute} collapsed={collapsed} onLinkClick={()=> setMenuOpen(false)}/>
        <div className="main">
          <Topbar route={route}
                  onNotifyClick={()=> setNotifOpen(true)}
                  dark={!!t.dark}
                  onToggleDark={()=> setTweak("dark", !t.dark)}
                  onMenuClick={()=> setMenuOpen(true)}
                  onToggleSidebar={toggleSidebar}
                  collapsed={collapsed}
                  onSearchClick={()=> setSearchOpen(true)}/>
          {PageComp
            ? <PageComp route={route} setRoute={setRoute} tweaks={t}/>
            : <div className="page"><Empty title="Page coming soon" desc={`The "${route}" module is under construction.`} /></div>
          }
        </div>
        <NotificationsDrawer open={notifOpen} onClose={()=> setNotifOpen(false)} onNavigate={setRoute}/>
        <SearchOverlay open={searchOpen} onClose={()=> setSearchOpen(false)} onNavigate={setRoute}/>
        {window.TweaksPanel && (
          <window.TweaksPanel title="Tweaks">
            <window.TweakSection title="Pages">
              <window.TweakSelect label="Go to screen"
                                  value={PAGE_NAV.some(p => p.route === route) ? route : ""}
                                  onChange={(v)=> { const p = PAGE_NAV.find(x => x.route === v); if (p) window.location.href = p.href; }}
                                  options={PAGE_NAV.map(p => ({ value: p.route, label: `${p.code} · ${p.label}` }))}/>
            </window.TweakSection>
            <window.TweakSection title="Appearance">
              <window.TweakToggle label="Dark mode" value={t.dark} onChange={(v)=> setTweak("dark", v)}/>
              <window.TweakRadio label="Background pattern" value={t.bgPattern} onChange={(v)=> setTweak("bgPattern", v)}
                                 options={[{value:"two", label:"Fields"},{value:"none", label:"None"}]}/>
            </window.TweakSection>
            {route === "procurement" && (
              <window.TweakSection title="Procurement dashboard">
                <window.TweakSelect label="Screen state" value={t.procState} onChange={(v)=> setTweak("procState", v)}
                                    options={[
                                      {value:"default", label:"Default (populated)"},
                                      {value:"empty", label:"First-run / empty"},
                                      {value:"noresults", label:"Filtered — no results"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "requirements" && (
              <window.TweakSection title="Requirement list">
                <window.TweakSelect label="Screen state" value={t.reqState} onChange={(v)=> setTweak("reqState", v)}
                                    options={[
                                      {value:"default", label:"Default (populated)"},
                                      {value:"empty", label:"First-run / no requirements"},
                                      {value:"noresults", label:"Filters — no results"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "createReq" && (
              <window.TweakSection title="Create requirement">
                <window.TweakSelect label="Screen state" value={t.formState} onChange={(v)=> setTweak("formState", v)}
                                    options={[
                                      {value:"empty", label:"Empty form"},
                                      {value:"autosaved", label:"Auto-saved"},
                                      {value:"errors", label:"Validation errors"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "bulkCreate" && (
              <window.TweakSection title="Bulk create">
                <window.TweakSelect label="CSV preview state" value={t.bulkState} onChange={(v)=> setTweak("bulkState", v)}
                                    options={[
                                      {value:"empty", label:"Empty"},
                                      {value:"parsing", label:"Parsing"},
                                      {value:"valid", label:"Valid preview"},
                                      {value:"partial", label:"Partial errors"},
                                      {value:"allerrors", label:"All errors"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "reqDetail" && (
              <window.TweakSection title="Requirement detail">
                <window.TweakSelect label="Screen state" value={t.detailState} onChange={(v)=> setTweak("detailState", v)}
                                    options={[
                                      {value:"draft", label:"Draft"},
                                      {value:"receiving", label:"Broadcasted — receiving"},
                                      {value:"pastdeadline", label:"Past deadline"},
                                      {value:"approved", label:"Approved"},
                                      {value:"cancelled", label:"Cancelled"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "editReq" && (
              <window.TweakSection title="Edit requirement">
                <window.TweakRadio label="Mode" value={t.editMode} onChange={(v)=> setTweak("editMode", v)}
                                   options={[{value:"draft", label:"Draft edit"},{value:"newversion", label:"New version"}]}/>
              </window.TweakSection>
            )}
            {route === "broadcastSelect" && (
              <window.TweakSection title="Broadcast — select">
                <window.TweakSelect label="Screen state" value={t.selectState} onChange={(v)=> setTweak("selectState", v)}
                                    options={[
                                      {value:"default", label:"Default"},
                                      {value:"nofarmers", label:"No farmers match"},
                                      {value:"nochannels", label:"No channels selected"},
                                      {value:"large", label:"Large selection (500+)"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "broadcastPreview" && (
              <window.TweakSection title="Broadcast — preview">
                <window.TweakSelect label="Send state" value={t.sendState} onChange={(v)=> setTweak("sendState", v)}
                                    options={[
                                      {value:"ready", label:"Ready (send now)"},
                                      {value:"scheduled", label:"Scheduled"},
                                      {value:"sending", label:"Sending"},
                                      {value:"sent", label:"Sent success"},
                                      {value:"partial", label:"Partial failure"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "broadcastStatus" && (
              <window.TweakSection title="Broadcast status">
                <window.TweakSelect label="Screen state" value={t.bcastStatusState} onChange={(v)=> setTweak("bcastStatusState", v)}
                                    options={[
                                      {value:"sending", label:"Sending"},
                                      {value:"complete", label:"Complete"},
                                      {value:"failures", label:"Has failures"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "responses" && (
              <window.TweakSection title="Response dashboard">
                <window.TweakSelect label="Screen state" value={t.respState} onChange={(v)=> setTweak("respState", v)}
                                    options={[
                                      {value:"receiving", label:"Receiving (live)"},
                                      {value:"closed", label:"Closed (past deadline)"},
                                      {value:"waiting", label:"No responses yet"},
                                      {value:"none", label:"None received (closed)"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "compare" && (
              <window.TweakSection title="Compare responses">
                <window.TweakRadio label="Columns" value={t.compareCount} onChange={(v)=> setTweak("compareCount", v)}
                                   options={[{value:"2", label:"2"},{value:"4", label:"4"},{value:"6", label:"6+"}]}/>
              </window.TweakSection>
            )}
            {route === "shortlist" && (
              <window.TweakSection title="Shortlist">
                <window.TweakSelect label="Allocation state" value={t.shortlistState} onChange={(v)=> setTweak("shortlistState", v)}
                                    options={[
                                      {value:"under", label:"Under-allocated"},
                                      {value:"fully", label:"Fully allocated"},
                                      {value:"over", label:"Over-allocated"},
                                      {value:"single", label:"Single farmer"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "approve" && (
              <window.TweakSection title="Gate-in detail">
                <window.TweakSelect label="Gate-in state" value={t.gateInState} onChange={(v)=> setTweak("gateInState", v)}
                                    options={[
                                      {value:"awaitingFarmer", label:"Awaiting farmer confirm"},
                                      {value:"confirmed", label:"Farmer confirmed — QR active"},
                                      {value:"arrived", label:"Arrived at gate"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "agreement" && (
              <window.TweakSection title="Digital agreement">
                <window.TweakSelect label="Signing state" value={t.agreementState} onChange={(v)=> setTweak("agreementState", v)}
                                    options={[
                                      {value:"awaiting1", label:"Awaiting first sign"},
                                      {value:"awaiting2", label:"First signed"},
                                      {value:"both", label:"Both signed"},
                                      {value:"declined", label:"Declined"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "reschedule" && (
              <window.TweakSection title="Reschedule request">
                <window.TweakSelect label="Decision state" value={t.rescheduleState} onChange={(v)=> setTweak("rescheduleState", v)}
                                    options={[
                                      {value:"noconflict", label:"Approve — no conflict"},
                                      {value:"conflict", label:"Approve — conflict"},
                                      {value:"reject", label:"Reject"},
                                      {value:"counter", label:"Counter-propose"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "slotCalendar" && (
              <window.TweakSection title="Slot calendar">
                <window.TweakRadio label="View" value={t.calendarView} onChange={(v)=> setTweak("calendarView", v)}
                                   options={[{value:"day", label:"Day"},{value:"week", label:"Week"},{value:"month", label:"Month"}]}/>
              </window.TweakSection>
            )}
            {route === "profile" && (
              <window.TweakSection title="Profile & settings">
                <window.TweakRadio label="Active tab" value={t.profileTab} onChange={(v)=> setTweak("profileTab", v)}
                                   options={[{value:"profile", label:"Profile"},{value:"security", label:"Security"},{value:"prefs", label:"Prefs"}]}/>
              </window.TweakSection>
            )}
            {route === "users" && (
              <window.TweakSection title="User management">
                <window.TweakSelect label="Screen state" value={t.usersState} onChange={(v)=> setTweak("usersState", v)}
                                    options={[
                                      {value:"default", label:"Default (populated)"},
                                      {value:"empty", label:"First-run / no users"},
                                      {value:"noresults", label:"Filtered — no results"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "userCreate" && (
              <window.TweakSection title="Add user">
                <window.TweakSelect label="Form state" value={t.userCreateState} onChange={(v)=> setTweak("userCreateState", v)}
                                    options={[
                                      {value:"empty", label:"Empty form"},
                                      {value:"filled", label:"Filled in"},
                                      {value:"errors", label:"Validation errors"},
                                      {value:"invited", label:"Invite sent"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "userEdit" && (
              <window.TweakSection title="Edit user">
                <window.TweakSelect label="Account state" value={t.userEditState} onChange={(v)=> setTweak("userEditState", v)}
                                    options={[
                                      {value:"active", label:"Active"},
                                      {value:"invited", label:"Invite pending"},
                                      {value:"deactivated", label:"Deactivated"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "permissions" && (
              <window.TweakSection title="Roles & permissions">
                <window.TweakSelect label="Selected role" value={t.permRole} onChange={(v)=> setTweak("permRole", v)}
                                    options={(window.MD?.ROLES || []).map(r => ({ value:r.id, label:r.name }))}/>
              </window.TweakSection>
            )}
            {route === "notifications" && (
              <window.TweakSection title="Notifications inbox">
                <window.TweakSelect label="Screen state" value={t.notifState} onChange={(v)=> setTweak("notifState", v)}
                                    options={[
                                      {value:"default", label:"Default (all)"},
                                      {value:"unread", label:"Unread only"},
                                      {value:"empty", label:"Inbox zero"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "globalSearch" && (
              <window.TweakSection title="Global search">
                <window.TweakSelect label="Screen state" value={t.searchState} onChange={(v)=> setTweak("searchState", v)}
                                    options={[
                                      {value:"results", label:"Results"},
                                      {value:"typing", label:"Recent / typing"},
                                      {value:"empty", label:"No results"},
                                    ]}/>
              </window.TweakSection>
            )}
            {route === "auditLog" && (
              <window.TweakSection title="Audit log">
                <window.TweakSelect label="Screen state" value={t.auditState} onChange={(v)=> setTweak("auditState", v)}
                                    options={[
                                      {value:"default", label:"Default (all events)"},
                                      {value:"filtered", label:"Filtered (auth only)"},
                                      {value:"loading", label:"Loading"},
                                    ]}/>
              </window.TweakSection>
            )}
          </window.TweaksPanel>
        )}
      </div>
    </ToastProvider>
  );
};

const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<App/>);
