// App shell — sidebar, topbar, view routing, tweaks panel, auth gate.

const { useState: useAppState, useEffect: useAppEffect, useMemo: useAppMemo, useRef: useAppRef, Component } = React;

const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "theme": "light",
  "density": "regular",
  "accent": "#2563eb",
  "rowEmphasis": "hairline"
}/*EDITMODE-END*/;

const ACCENT_PRESETS = {
  "#2563eb": { l: 48, c: 0.16, h: 252, name: "Indigo (default)" },
  "#0f766e": { l: 48, c: 0.12, h: 190, name: "Teal" },
  "#7c3aed": { l: 48, c: 0.18, h: 290, name: "Violet" },
  "#111827": { l: 22, c: 0.008, h: 260, name: "Monochrome" },
};

function applyAccent(hex, theme) {
  const p = ACCENT_PRESETS[hex] || ACCENT_PRESETS["#2563eb"];
  const root = document.documentElement;
  const dark = theme === "dark";
  const l = dark ? (p.h === 260 && p.c < 0.02 ? 96 : Math.min(p.l + 22, 78)) : p.l;
  const l2 = dark ? Math.min(l + 6, 88) : p.l + 6;
  const tintL = dark ? 26 : 95;
  const tintC = dark ? p.c * 0.4 : p.c * 0.25;
  root.style.setProperty("--accent", `oklch(${l}% ${p.c} ${p.h})`);
  root.style.setProperty("--accent-2", `oklch(${l2}% ${p.c} ${p.h})`);
  root.style.setProperty("--accent-tint", `oklch(${tintL}% ${tintC} ${p.h})`);
}

// Marks a nav label / page title as backed by fixture data rather than the live API,
// so it reads visually distinct from the (differently-colored) real data around it.
function DemoTag() {
  return (
    <span style={{
      display: "inline-block", marginLeft: 6,
      fontSize: 9.5, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase",
      color: "var(--risk-med)", background: "var(--risk-med-bg)",
      padding: "1px 5px", borderRadius: 4, verticalAlign: 1,
    }}>Demo</span>
  );
}

function SoonTag() {
  return (
    <span style={{
      display: "inline-block", marginLeft: 6,
      fontSize: 9.5, fontWeight: 700, letterSpacing: "0.04em", textTransform: "uppercase",
      color: "var(--fg-3)", background: "var(--bg-3)",
      padding: "1px 5px", borderRadius: 4, verticalAlign: 1,
    }}>Soon</span>
  );
}

function LoginScreen({ onLogin, error, onReset }) {
  const [email, setEmail] = useAppState("admin@mossad.io");
  const [password, setPassword] = useAppState("admin");
  const [busy, setBusy] = useAppState(false);
  const [err, setErr] = useAppState(error);

  const submit = async (e) => {
    e.preventDefault();
    setBusy(true);
    setErr(null);
    try {
      await onLogin(email, password);
    } catch (e) {
      let msg = e.message;
      if (e.message === "UNAUTHORIZED") msg = "Invalid email or password";
      setErr(msg);
    } finally {
      setBusy(false);
    }
  };

  const resetSession = () => {
    if (onReset) onReset();
    setErr(null);
  };

  return (
    <div style={{
      minHeight: "100vh", display: "grid", placeItems: "center",
      background: "var(--bg)", padding: 24,
    }}>
      <div className="card" style={{ width: 380, padding: 28 }}>
        <div style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 20 }}>
          <div className="brand-mark">M</div>
          <span style={{ fontWeight: 600, fontSize: 15 }}>Mossad</span>
        </div>
        <h2 style={{ margin: "0 0 6px", fontSize: 18, fontWeight: 600 }}>Sign in</h2>
        <p style={{ margin: "0 0 20px", color: "var(--fg-3)", fontSize: 13 }}>
          Transaction monitoring workspace
        </p>
        {err && (
          <div style={{ color: "var(--risk-high)", fontSize: 12.5, marginBottom: 14, lineHeight: 1.4 }}>
            {err}
          </div>
        )}
        <form onSubmit={submit}>
          <div style={{ marginBottom: 12 }}>
            <label style={{ display: "block", fontSize: 11.5, color: "var(--fg-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>Email</label>
            <input className="field" value={email} onChange={(e) => setEmail(e.target.value)} required />
          </div>
          <div style={{ marginBottom: 18 }}>
            <label style={{ display: "block", fontSize: 11.5, color: "var(--fg-3)", marginBottom: 4, textTransform: "uppercase", letterSpacing: "0.04em" }}>Password</label>
            <input className="field" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required />
          </div>
          <button className="btn primary" style={{ width: "100%", justifyContent: "center", height: 34 }} disabled={busy}>
            {busy ? "Signing in…" : "Sign in"}
          </button>
        </form>
        <div style={{ marginTop: 14, textAlign: "center" }}>
          <button type="button" className="btn ghost sm" onClick={resetSession}>
            Reset session
          </button>
        </div>
        <div style={{ marginTop: 12, fontSize: 11.5, color: "var(--fg-3)", textAlign: "center" }}>
          Default: admin@mossad.io / admin
        </div>
      </div>
    </div>
  );
}

function Sidebar({ view, setView, sidebarOpen, setSidebarOpen, data }) {
  const NavItem = ({ id, icon, label, count, dot, active, demo, soon }) => (
    <button className={`sb-item ${active ? "active" : ""} ${soon ? "disabled" : ""}`}
            onClick={soon ? undefined : () => setView(id)}
            disabled={soon}>
      <span className="sb-icon">{icon}</span>
      <span className="sb-label">{label}{demo && <DemoTag />}{soon && <SoonTag />}</span>
      {count != null && <span className="sb-count">{count}</span>}
      {dot && <span className="sb-dot" />}
    </button>
  );

  return (
    <aside className="sb">
      <div className="sb-hd">
        <div className="brand">
          <div className="brand-mark">M</div>
          <span>Mossad</span>
        </div>
        <span style={{ flex: 1 }} />
        <button className="btn ghost icon sm" title="Notifications" style={{ color: "var(--fg-3)" }}>
          <Icon.Bell size={12} />
        </button>
      </div>

      <div className="sb-section">Workspace</div>
      <nav className="sb-nav">
        <NavItem id="alerts"    icon={<Icon.Inbox size={14} />}    label="Alert queue"    count={String(data.alerts.length)} active={view === "alerts"} />
        <NavItem id="my-cases"  icon={<Icon.Folder size={14} />}   label="My cases"       count={String(data.cases.length)}  active={view === "my-cases"} />
        <NavItem id="sars"      icon={<Icon.Flag size={14} />}     label="SAR drafts"     count="3"   active={view === "sars"} dot />
        <NavItem id="watchlist" icon={<Icon.Shield size={14} />}   label="Watchlist"      count={String(WATCHLIST_ENTITIES.length)}  active={view === "watchlist"} demo />
      </nav>

      <div className="sb-section">Investigate</div>
      <nav className="sb-nav">
        <NavItem id="customers" icon={<Icon.Users size={14} />}    label="Customers"               active={view === "customers"} />
        <NavItem id="ratings"   icon={<Icon.Gauge size={14} />}    label="Risk ratings"   count={String(data.riskProfiles.length)} dot active={view === "ratings"} demo />
        <NavItem id="periodic"  icon={<Icon.Cycle size={14} />}    label="Periodic review" count="9" active={view === "periodic"} demo />
        <NavItem id="txns"      icon={<Icon.Flow size={14} />}     label="Transactions"            active={view === "txns"} />
        <NavItem id="rules"     icon={<Icon.Sliders size={14} />}  label="Rule Settings"  count={String(data.rules.length)} active={view === "rules"} />
        <NavItem id="agents"    icon={<Icon.Bot size={14} />}      label="Agents"                   active={view === "agents"} demo />
      </nav>

      <div className="sb-section">Insights</div>
      <nav className="sb-nav">
        <NavItem id="analytics" icon={<Icon.Chart size={14} />}    label="Analytics"     active={view === "analytics"} />
        <NavItem id="tenants"   icon={<Icon.Bank size={14} />}     label="Tenants"       count={String(data.tenants.length)} active={view === "tenants"} />
        <NavItem id="reports"   icon={<Icon.Calendar size={14} />} label="Reports"       active={view === "reports"} />
      </nav>

      <div className="sb-section">Onboarding</div>
      <nav className="sb-nav">
        <NavItem icon={<Icon.Person size={14} />}   label="KYC"                    soon />
        <NavItem icon={<Icon.Building size={14} />} label="KYB"                    soon />
        <NavItem icon={<Icon.Cycle size={14} />}    label="Workflows"    soon />
        <NavItem icon={<Icon.Settings size={14} />} label="Settings"     soon />
      </nav>

      <div className="sb-spacer" />

      <div className="sb-foot">
        <div className="sb-user">AA</div>
        <div className="sb-user-info">
          <b>Asyet Argynbai</b>
          <span>Admin · FIU</span>
        </div>
        <button className="btn ghost icon sm" style={{ color: "var(--fg-3)" }}
                onClick={() => setView("settings")} title="Account settings">
          <Icon.ChevronD size={11} />
        </button>
      </div>
    </aside>
  );
}

function AiAssistChat({ onClose }) {
  const [messages, setMessages] = useAppState(() => [
    { role: "bot", text: "Hi! I can answer questions about Mossad from the docs. Ask me anything." },
  ]);
  const [input, setInput] = useAppState("");

  const send = (e) => {
    e.preventDefault();
    const text = input.trim();
    if (!text) return;
    setMessages(m => [
      ...m,
      { role: "user", text },
      { role: "bot", text: "I hear you want to use the AI capabilities big dawg. It's better than Sloppy Jo's AI Slop and will take some time to develop." },
    ]);
    setInput("");
  };

  return (
    <div className="ai-chat-panel">
      <div className="ai-chat-hd">
        <Icon.Bot size={14} />
        <span>AI Assist</span>
        <span style={{ flex: 1 }} />
        <button type="button" className="btn ghost icon sm" onClick={onClose} title="Close">
          <Icon.X size={12} />
        </button>
      </div>
      <div className="ai-chat-body">
        {messages.map((m, i) => (
          <div key={i} className={`ai-chat-msg ${m.role}`}>{m.text}</div>
        ))}
      </div>
      <form className="ai-chat-ft" onSubmit={send}>
        <input className="field" placeholder="Ask a question…" value={input} onChange={e => setInput(e.target.value)} />
        <button type="submit" className="btn primary icon sm" title="Send">
          <Icon.ArrowR size={12} />
        </button>
      </form>
    </div>
  );
}

function computeSearchResults(data, query) {
  const q = query.trim().toLowerCase();
  if (!q) return null;

  const alerts = (data?.alerts || []).filter(a =>
    (a.external_id || "").toLowerCase().includes(q) ||
    (a.subject || "").toLowerCase().includes(q) ||
    (a.typology || "").toLowerCase().includes(q) ||
    (a.customerId || "").toLowerCase().includes(q)
  ).slice(0, 5);

  const cases = (data?.cases || []).filter(c =>
    (c.id || "").toLowerCase().includes(q) ||
    (c.title || "").toLowerCase().includes(q) ||
    (c.entity || "").toLowerCase().includes(q) ||
    (c.customerId || "").toLowerCase().includes(q)
  ).slice(0, 5);

  const customers = (data?.customers || []).filter(c =>
    (c.customer_id || "").toLowerCase().includes(q)
  ).slice(0, 5);

  const transactions = (data?.transactions || []).filter(t =>
    (t.external_id || "").toLowerCase().includes(q) ||
    (t.originator_id || "").toLowerCase().includes(q) ||
    (t.beneficiary_id || "").toLowerCase().includes(q)
  ).slice(0, 5);

  const sars = (data?.sars || []).filter(s =>
    (s.external_id || "").toLowerCase().includes(q) ||
    (s.suspicious_activity_description || "").toLowerCase().includes(q)
  ).slice(0, 5);

  const total = alerts.length + cases.length + customers.length + transactions.length + sars.length;
  return { alerts, cases, customers, transactions, sars, total };
}

function GlobalSearch({ data, onOpenAlert, onOpenCase, onNavigate }) {
  const [query, setQuery] = useAppState("");
  const [open, setOpen] = useAppState(false);
  const inputRef = useAppRef(null);

  useAppEffect(() => {
    const onKey = (e) => {
      const meta = e.metaKey || e.ctrlKey;
      if (meta && e.key.toLowerCase() === "k") {
        e.preventDefault();
        inputRef.current?.focus();
        setOpen(true);
      } else if (e.key === "Escape" && document.activeElement === inputRef.current) {
        setOpen(false);
        inputRef.current?.blur();
      }
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, []);

  const results = useAppMemo(() => computeSearchResults(data, query), [data, query]);

  const select = (fn) => {
    fn();
    setOpen(false);
    setQuery("");
  };

  return (
    <div className="search">
      <Icon.Search size={13} className="search-ico" />
      <input
        ref={inputRef}
        placeholder="Search alerts, entities, transactions, IDs…"
        value={query}
        onChange={e => { setQuery(e.target.value); setOpen(true); }}
        onFocus={() => { if (query) setOpen(true); }}
      />
      {query ? (
        <button type="button" className="search-clear" onMouseDown={e => e.preventDefault()}
                onClick={() => { setQuery(""); inputRef.current?.focus(); }} title="Clear">
          <Icon.X size={11} />
        </button>
      ) : (
        <span className="search-kbd">⌘K</span>
      )}

      {open && results && (
        <div className="search-results" onMouseDown={e => e.preventDefault()}>
          {results.total === 0 && <div className="search-empty">No matches for "{query}"</div>}

          {results.alerts.length > 0 && (
            <>
              <div className="search-group-label">Alerts</div>
              {results.alerts.map(a => (
                <button key={a.id} type="button" className="search-result-row" onClick={() => select(() => onOpenAlert(a))}>
                  <Icon.Inbox size={12} style={{ color: "var(--fg-3)", flexShrink: 0 }} />
                  <span>{a.external_id}</span>
                  <span className="search-result-sub">{a.subject} · {a.typology}</span>
                </button>
              ))}
            </>
          )}

          {results.cases.length > 0 && (
            <>
              <div className="search-group-label">Cases</div>
              {results.cases.map(c => (
                <button key={c.id} type="button" className="search-result-row" onClick={() => select(() => onOpenCase(c))}>
                  <Icon.Folder size={12} style={{ color: "var(--fg-3)", flexShrink: 0 }} />
                  <span>{c.id}</span>
                  <span className="search-result-sub">{c.title}</span>
                </button>
              ))}
            </>
          )}

          {results.customers.length > 0 && (
            <>
              <div className="search-group-label">Customers</div>
              {results.customers.map(c => (
                <button key={c.customer_id} type="button" className="search-result-row"
                        onClick={() => select(() => onNavigate("customers", { query: c.customer_id }))}>
                  <Icon.Users size={12} style={{ color: "var(--fg-3)", flexShrink: 0 }} />
                  <span>{c.customer_id}</span>
                  <span className="search-result-sub">{c.transaction_count} txns</span>
                </button>
              ))}
            </>
          )}

          {results.transactions.length > 0 && (
            <>
              <div className="search-group-label">Transactions</div>
              {results.transactions.map(t => (
                <button key={t.id} type="button" className="search-result-row"
                        onClick={() => select(() => onNavigate("txns", { query: t.external_id }))}>
                  <Icon.Flow size={12} style={{ color: "var(--fg-3)", flexShrink: 0 }} />
                  <span>{t.external_id}</span>
                  <span className="search-result-sub">${Number(t.amount).toLocaleString()} {t.currency}</span>
                </button>
              ))}
            </>
          )}

          {results.sars.length > 0 && (
            <>
              <div className="search-group-label">SARs</div>
              {results.sars.map(s => (
                <button key={s.id} type="button" className="search-result-row"
                        onClick={() => select(() => onNavigate("sars", { id: s.id }))}>
                  <Icon.Flag size={12} style={{ color: "var(--fg-3)", flexShrink: 0 }} />
                  <span>{s.external_id}</span>
                  <span className="search-result-sub">{(s.suspicious_activity_description || "").slice(0, 40)}</span>
                </button>
              ))}
            </>
          )}
        </div>
      )}
    </div>
  );
}

function TopBar({ view, currentAlert, onCloseCase, theme, onToggleTheme, onLogout, data, onOpenAlert, onOpenCase, onNavigate }) {
  const [aiOpen, setAiOpen] = useAppState(false);
  const titles = {
    alerts:    { title: "Alerts", crumb: ["Workspace", "Alerts"] },
    "my-cases":{ title: "My cases", crumb: ["Workspace", "My cases"] },
    sars:      { title: "SAR drafts", crumb: ["Workspace", "SAR drafts"] },
    watchlist: { title: "Watchlist", crumb: ["Workspace", "Watchlist"], demo: true },
    customers: { title: "Customers", crumb: ["Investigate", "Customers"] },
    agents:    { title: "Agents", crumb: ["Investigate", "Agents"], demo: true },
    ratings:   { title: "Risk ratings", crumb: ["Investigate", "Risk ratings"], demo: true },
    periodic:  { title: "Periodic review", crumb: ["Investigate", "Periodic review"], demo: true },
    txns:      { title: "Transactions", crumb: ["Investigate", "Transactions"] },
    rules:     { title: "Rule Settings", crumb: ["Investigate", "Rule Settings"] },
    analytics: { title: "Analytics", crumb: ["Insights", "Analytics"] },
    tenants:   { title: "Tenants", crumb: ["Insights", "Tenants"] },
    reports:   { title: "Reports", crumb: ["Insights", "Reports"] },
    settings:  { title: "Settings", crumb: ["Settings"] },
  }[view] || { title: view, crumb: [view] };

  return (
    <div className="topbar">
      <div className="crumbs">
        {titles.crumb.map((c, i) => (
          <React.Fragment key={i}>
            {i > 0 && <Icon.Chevron size={10} className="crumbs-sep" />}
            {i === titles.crumb.length - 1 && !currentAlert
              ? <b>{c}{titles.demo && <DemoTag />}</b>
              : <span style={{ cursor: currentAlert ? "default" : undefined }}
                      onClick={currentAlert && i === titles.crumb.length - 1 ? onCloseCase : undefined}>
                  {c}
                </span>}
          </React.Fragment>
        ))}
        {currentAlert && (
          <>
            <Icon.Chevron size={10} className="crumbs-sep" />
            <b className="mono" style={{ fontWeight: 500 }}>{currentAlert.external_id}</b>
          </>
        )}
      </div>

      <div className="tb-spacer" />

      <GlobalSearch data={data} onOpenAlert={onOpenAlert} onOpenCase={onOpenCase} onNavigate={onNavigate} />

      <button className="btn ghost icon sm" onClick={onToggleTheme}
              title={theme === "dark" ? "Switch to light" : "Switch to dark"}>
        {theme === "dark" ? <Icon.Sun size={13} /> : <Icon.Moon size={13} />}
      </button>
      <div className="ai-assist-wrap">
        <button className={`btn sm ${aiOpen ? "active" : ""}`} onClick={() => setAiOpen(o => !o)}>
          <Icon.Bot size={13} />
          <span>AI Assist</span>
        </button>
        {aiOpen && <AiAssistChat onClose={() => setAiOpen(false)} />}
      </div>
      <button className="btn ghost sm" onClick={onLogout} title="Sign out">
        <Icon.Logout size={12} /> Sign out
      </button>
    </div>
  );
}

function PlaceholderView({ icon, title, msg }) {
  return (
    <div style={{
      flex: 1, display: "grid", placeItems: "center",
      color: "var(--fg-3)", padding: 40,
    }}>
      <div style={{ textAlign: "center", maxWidth: 360 }}>
        <div style={{
          width: 48, height: 48, borderRadius: 10,
          background: "var(--bg-2)", border: "1px solid var(--border)",
          display: "grid", placeItems: "center",
          margin: "0 auto 16px",
          color: "var(--fg-3)",
        }}>{icon}</div>
        <h2 style={{ margin: 0, fontSize: 16, fontWeight: 500, color: "var(--fg)" }}>{title}</h2>
        <p style={{ marginTop: 6, fontSize: 13 }}>{msg}</p>
      </div>
    </div>
  );
}

function AppShell() {
  const data = useData();
  const [t, setTweak] = useTweaks(TWEAK_DEFAULTS);
  const [view, setView] = useAppState("alerts");
  const [currentAlert, setCurrentAlert] = useAppState(null);
  const [currentCase, setCurrentCase] = useAppState(null);
  const [sidebarOpen, setSidebarOpen] = useAppState(true);
  const [searchNav, setSearchNav] = useAppState(null);

  const handleSearchNavigate = (targetView, payload) => {
    setView(targetView);
    setSearchNav({ view: targetView, token: Date.now(), ...payload });
  };
  if (typeof document !== "undefined") {
    document.documentElement.dataset.theme = t.theme;
    document.documentElement.dataset.density = t.density;
  }

  useAppEffect(() => {
    applyAccent(t.accent, t.theme);
  }, [t.theme, t.accent]);

  useAppEffect(() => { setCurrentAlert(null); setCurrentCase(null); }, [view]);

  const renderView = () => {
    if (currentAlert) {
      return (
        <CaseDetailView
          alert={currentAlert}
          onClose={() => setCurrentAlert(null)}
          backLabel={currentCase ? "Back to case" : "Back to queue"}
          data={data}
        />
      );
    }
    if (currentCase) {
      return (
        <CaseDetailPage
          caseItem={currentCase}
          onClose={() => setCurrentCase(null)}
          onOpenAlert={(a) => setCurrentAlert(a)}
          data={data}
        />
      );
    }
    switch (view) {
      case "alerts":
        return (
          <AlertsView
            data={data}
            onOpenCase={(a) => setCurrentAlert(a)}
            rowStyle={t.rowEmphasis}
          />
        );
      case "analytics":
        return <AnalyticsView data={data} />;
      case "tenants":
        return <TenantsView data={data} />;
      case "ratings":
        return <RiskRatingsView data={data} onOpenCustomer={() => {}} />;
      case "periodic":
        return <PeriodicReviewView />;
      case "my-cases":
        return <CasesView data={data} onOpenCase={(c) => setCurrentCase(c)} />;
      case "sars":
        return <SARsView data={data} initialId={searchNav?.view === "sars" ? searchNav.id : undefined} />;
      case "watchlist":
        return <WatchlistView />;
      case "customers":
        return <CustomersView data={data} initialQuery={searchNav?.view === "customers" ? searchNav.query : undefined} />;
      case "agents":
        return <AgentsView />;
      case "txns":
        return <TransactionsView data={data} initialQuery={searchNav?.view === "txns" ? searchNav.query : undefined} />;
      case "rules":
        return <RulesView data={data} />;
      case "reports":
        return <PlaceholderView icon={<Icon.Calendar size={20} />} title="Scheduled reports"
                                msg="Regulatory reports, MIS summaries, and team performance — generated daily, weekly, or on demand." />;
      case "settings":
        return <PlaceholderView icon={<Icon.Settings size={20} />} title="Settings"
                                msg="Org thresholds, escalation paths, integrations, and audit log retention." />;
      default:
        return null;
    }
  };

  return (
    <div className={`app ${sidebarOpen ? "" : "collapsed"}`}>
      <Sidebar view={view} setView={(id) => { setCurrentAlert(null); setView(id); }}
               sidebarOpen={sidebarOpen} setSidebarOpen={setSidebarOpen} data={data} />
      <div className="main">
        <TopBar view={view} currentAlert={currentAlert}
                onCloseCase={() => setCurrentAlert(null)}
                theme={t.theme}
                onToggleTheme={() => setTweak("theme", t.theme === "dark" ? "light" : "dark")}
                onLogout={data.logout}
                data={data}
                onOpenAlert={(a) => setCurrentAlert(a)}
                onOpenCase={(c) => setCurrentCase(c)}
                onNavigate={handleSearchNavigate} />
        <div className="content">
          {data.loading && (
            <div className="banner">
              <span className="dot dot-info live-dot" style={{ margin: 0 }} />
              Syncing with backend…
            </div>
          )}
          {data.error && (
            <div className="banner" style={{ justifyContent: "space-between" }}>
              <span>{data.error}</span>
              <button className="btn ghost sm" onClick={data.logout}>Sign out</button>
            </div>
          )}
          {renderView()}
        </div>
      </div>

      <TweaksPanel>
        <TweakSection label="Appearance">
          <TweakRadio label="Theme" value={t.theme}
                      options={["light", "dark"]}
                      onChange={(v) => setTweak("theme", v)} />
          <TweakRadio label="Density" value={t.density}
                      options={["compact", "regular", "comfy"]}
                      onChange={(v) => setTweak("density", v)} />
          <TweakColor label="Accent" value={t.accent}
                      options={Object.keys(ACCENT_PRESETS)}
                      onChange={(v) => setTweak("accent", v)} />
        </TweakSection>
        <TweakSection label="Table">
          <TweakRadio label="Row treatment" value={t.rowEmphasis}
                      options={["hairline", "zebra", "card"]}
                      onChange={(v) => setTweak("rowEmphasis", v)} />
        </TweakSection>
      </TweaksPanel>
    </div>
  );
}

class ErrorBoundary extends Component {
  constructor(props) {
    super(props);
    this.state = { error: null };
  }
  static getDerivedStateFromError(error) {
    return { error };
  }
  render() {
    if (this.state.error) {
      return (
        <div style={{ padding: 24, fontFamily: "var(--font-sans), system-ui, sans-serif", color: "var(--fg)" }}>
          <h2 style={{ margin: "0 0 12px" }}>Something went wrong</h2>
          <pre style={{
            background: "var(--bg-2)", border: "1px solid var(--border)",
            padding: 12, borderRadius: 6, overflow: "auto", fontSize: 12,
          }}>{this.state.error.stack || this.state.error.message || String(this.state.error)}</pre>
          <button className="btn" onClick={() => { window.mossadApi && window.mossadApi.logout(); location.reload(); }}>
            Reset and reload
          </button>
        </div>
      );
    }
    return this.props.children;
  }
}

function App() {
  const data = useData();
  if (!data.isAuthenticated) {
    return <LoginScreen onLogin={data.login} onReset={data.logout} />;
  }
  return <AppShell />;
}

function Root() {
  return (
    <DataProvider>
      <ErrorBoundary>
        <App />
      </ErrorBoundary>
    </DataProvider>
  );
}

// Row treatment via injected stylesheet (driven by data-row attr on body)
function applyRowEmphasis(mode) {
  document.body.dataset.row = mode;
}

const rowStyle = document.createElement("style");
rowStyle.textContent = `
  body[data-row="zebra"] .tbl tbody tr:nth-child(even) { background: var(--bg-2); }
  body[data-row="zebra"] .tbl tbody tr:hover { background: var(--bg-3); }
  body[data-row="card"] .tbl { border-spacing: 0 4px; border-collapse: separate; }
  body[data-row="card"] .tbl tbody tr { background: var(--bg-2); }
  body[data-row="card"] .tbl tbody td { border-bottom: 0; }
  body[data-row="card"] .tbl tbody td:first-child { border-top-left-radius: 6px; border-bottom-left-radius: 6px; }
  body[data-row="card"] .tbl tbody td:last-child  { border-top-right-radius: 6px; border-bottom-right-radius: 6px; }
  body[data-row="card"] .tbl thead th { background: transparent; }
`;
document.head.appendChild(rowStyle);

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

window.addEventListener("tweakchange", (e) => {
  if (e.detail && e.detail.rowEmphasis) applyRowEmphasis(e.detail.rowEmphasis);
});
applyRowEmphasis(TWEAK_DEFAULTS.rowEmphasis);
