// Main app — shell, nav, routing, role switcher

const { useState, useEffect, useCallback } = React;

const SIDEBAR_W = 220;

const App = () => {
  const [booted, setBooted] = useState(window.LS_store?.loaded || false);
  useEffect(() => {
    if (booted) return;
    window.LS_store.load().then(() => {
      window.LS_currentPeriod = window.LS_deriveCurrentPeriod();
      setBooted(true);
    });
  }, [booted]);
  const [role, setRole] = useState(() => localStorage.getItem("ls_role") || "employer");
  const [route, setRoute] = useState(() => {
    try { return JSON.parse(localStorage.getItem("ls_route") || '{"view":"dashboard"}'); }
    catch { return { view: "dashboard" }; }
  });
  const [runOpen, setRunOpen] = useState(false);
  const [toasts, setToasts] = useState([]);

  useEffect(() => { localStorage.setItem("ls_role", role); }, [role]);
  useEffect(() => { localStorage.setItem("ls_route", JSON.stringify(route)); }, [route]);

  const toast = useCallback((msg, icon = "check") => {
    const id = Math.random().toString(36).slice(2);
    setToasts(ts => [...ts, { id, msg, icon }]);
    setTimeout(() => setToasts(ts => ts.filter(t => t.id !== id)), 2800);
  }, []);

  const navigate = (view, id) => setRoute({ view, id });

  if (!booted) {
    return (
      <div style={{ minHeight: "100vh", display: "flex", alignItems: "center", justifyContent: "center", color: "var(--ink-3)", fontSize: 13 }}>
        <div>Loonstrook laden…</div>
      </div>
    );
  }

  const onConfirm = () => {
    setRunOpen(false);
    toast("Loonrun april verzonden — 6 stroken gemaild", "check");
  };

  if (role === "employee") {
    return (
      <>
        <TopBar role={role} setRole={setRole} />
        <EmployeePortal toast={toast} />
        <ToastStack toasts={toasts} />
      </>
    );
  }

  return (
    <div style={{ display: "flex", minHeight: "100vh" }} data-screen-label="Werkgever">
      <Sidebar route={route} navigate={navigate} />
      <div style={{ flex: 1, marginLeft: SIDEBAR_W, display: "flex", flexDirection: "column" }}>
        <TopBar role={role} setRole={setRole} toast={toast} navigate={navigate} />
        <main style={{ flex: 1 }}>
          {route.view === "dashboard" && <EmployerDashboard onNavigate={navigate} onOpenRun={() => setRunOpen(true)} toast={toast} />}
          {route.view === "employees" && <EmployeesList onNavigate={navigate} toast={toast} />}
          {route.view === "employee"  && <EmployeeDetail empId={route.id} onBack={() => navigate("employees")} toast={toast} />}
          {route.view === "documents" && <EmployerDocuments toast={toast} />}
          {route.view === "settings"  && <EmployerSettings toast={toast} />}
        </main>
      </div>

      {runOpen && <LoonrunFlow onClose={() => setRunOpen(false)} onConfirm={onConfirm} toast={toast} />}
      <ToastStack toasts={toasts} />
      <TweaksPanel />
    </div>
  );
};

const Sidebar = ({ route, navigate }) => {
  const items = [
    { id: "dashboard", label: "Dashboard", icon: "home" },
    { id: "employees", label: "Medewerkers", icon: "users", badge: LS_employees.length },
    { id: "documents", label: "Documenten", icon: "docs" },
    { id: "settings",  label: "Instellingen", icon: "settings" },
  ];
  const isActive = (id) => route.view === id || (id === "employees" && route.view === "employee");
  return (
    <aside style={{
      width: SIDEBAR_W, position: "fixed", top: 0, bottom: 0, left: 0,
      background: "var(--surface)", borderRight: "1px solid var(--line)",
      display: "flex", flexDirection: "column",
      padding: "20px 14px",
    }}>
      <Row style={{ gap: 10, padding: "2px 8px 24px" }}>
        <div style={{
          width: 30, height: 30, borderRadius: 8,
          background: "var(--ink)", color: "#fff",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontFamily: "'Instrument Sans', sans-serif", fontWeight: 700, fontSize: 16,
          letterSpacing: "-0.02em",
        }}>L</div>
        <div>
          <div style={{ fontSize: 14, fontWeight: 600, fontFamily: "'Instrument Sans', sans-serif", letterSpacing: "-0.01em" }}>Loonstrook</div>
          <div style={{ fontSize: 10.5, color: "var(--ink-3)" }}>Ehold B.V.</div>
        </div>
      </Row>

      <div style={{ display: "flex", flexDirection: "column", gap: 2 }}>
        {items.map(it => {
          const active = isActive(it.id);
          return (
            <button key={it.id} onClick={() => navigate(it.id)}
              style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "8px 10px",
                background: active ? "var(--bg-3)" : "transparent",
                border: "none", borderRadius: 7,
                cursor: "pointer", fontFamily: "inherit",
                fontSize: 13.5, fontWeight: active ? 600 : 500,
                color: active ? "var(--ink)" : "var(--ink-2)",
                textAlign: "left",
              }}>
              <Icon name={it.icon} size={16} />
              <span style={{ flex: 1 }}>{it.label}</span>
              {it.badge !== undefined && (
                <span style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 500, fontFamily: "'JetBrains Mono', monospace" }}>{it.badge}</span>
              )}
            </button>
          );
        })}
      </div>

      <div style={{ flex: 1 }} />

      {/* Run shortcut */}
      <div style={{ padding: 12, background: "var(--bg-2)", borderRadius: 10, marginBottom: 10 }}>
        <div style={{ fontSize: 11, color: "var(--ink-3)", textTransform: "uppercase", letterSpacing: 0.6, fontWeight: 600 }}>Volgende run</div>
        <div style={{ fontSize: 13, fontWeight: 600, marginTop: 4 }}>April · za 25 apr</div>
        <div style={{ fontSize: 11, color: "var(--ink-3)", marginTop: 2 }}>Regels v2026.1</div>
      </div>

      <Row style={{ gap: 8, padding: "6px 8px" }}>
        <Icon name="help" size={14} style={{ color: "var(--ink-3)" }} />
        <span style={{ fontSize: 12, color: "var(--ink-3)" }}>Hulp & documentatie</span>
      </Row>
    </aside>
  );
};

const NotificationBell = ({ navigate }) => {
  const [open, setOpen] = useState(false);
  const [count, setCount] = useState(() => (window.LS_notifications || []).length);
  useEffect(() => {
    const iv = setInterval(async () => {
      await window.LS_store?.refreshNotifications?.();
      setCount((window.LS_notifications || []).length);
    }, 30000);
    return () => clearInterval(iv);
  }, []);
  return (
    <>
      <button style={iconBtn} onClick={async () => {
        await window.LS_store?.refreshNotifications?.();
        setCount((window.LS_notifications || []).length);
        setOpen(true);
      }}>
        <Icon name="bell" size={15} />
        {count > 0 && (
          <span style={{
            position: "absolute", top: 6, right: 6, width: 7, height: 7, borderRadius: 999,
            background: "var(--danger)", border: "2px solid var(--surface)",
          }} />
        )}
      </button>
      <NotificationsMenu open={open} onClose={() => setOpen(false)} onNavigate={navigate} />
    </>
  );
};

const TopBar = ({ role, setRole, toast, navigate }) => {
  return (
    <header style={{
      height: 56, display: "flex", alignItems: "center",
      padding: "0 24px",
      background: "var(--surface)",
      borderBottom: "1px solid var(--line)",
      position: "sticky", top: 0, zIndex: 20,
    }}>
      {role === "employee" && (
        <Row style={{ gap: 10 }}>
          <div style={{
            width: 28, height: 28, borderRadius: 7,
            background: "var(--ink)", color: "#fff",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontFamily: "'Instrument Sans', sans-serif", fontWeight: 700, fontSize: 14,
          }}>L</div>
          <div style={{ fontSize: 14, fontWeight: 600, fontFamily: "'Instrument Sans', sans-serif" }}>Mijn Loonstrook</div>
          <Pill tone="neutral">Ehold B.V.</Pill>
        </Row>
      )}
      {role === "employer" && (
        <Row style={{ gap: 10 }}>
          <button style={companyBtn}>
            <Icon name="building" size={14} />
            <span>Ehold B.V.</span>
            <Icon name="chevron" size={13} />
          </button>
        </Row>
      )}

      <div style={{ flex: 1 }} />

      <Row style={{ gap: 8 }}>
        <PrivacyBadge />
        {/* Role switcher */}
        <div style={{
          display: "inline-flex", padding: 3,
          background: "var(--bg-3)", borderRadius: 8,
        }}>
          {[
            { id: "employer", l: "Werkgever" },
            { id: "employee", l: "Medewerker" },
          ].map(o => (
            <button key={o.id} onClick={() => setRole(o.id)} style={{
              padding: "5px 12px", fontSize: 12, fontWeight: 500,
              background: role === o.id ? "var(--surface)" : "transparent",
              color: role === o.id ? "var(--ink)" : "var(--ink-3)",
              border: "none", borderRadius: 6,
              cursor: "pointer", fontFamily: "inherit",
              boxShadow: role === o.id ? "0 1px 2px oklch(20% 0.01 85 / 0.1)" : "none",
            }}>{o.l}</button>
          ))}
        </div>

        <NotificationBell navigate={navigate} />


        {/* User */}
        <Row style={{ gap: 8, padding: "4px 8px 4px 4px", borderRadius: 8, background: "var(--bg-2)", border: "1px solid var(--line)" }}>
          <div style={{
            width: 26, height: 26, borderRadius: 999,
            background: role === "employer" ? "oklch(78% 0.08 50)" : LS_employees[0].avatar_color,
            color: "oklch(28% 0.02 85)",
            display: "flex", alignItems: "center", justifyContent: "center",
            fontSize: 11, fontWeight: 600,
          }}>{role === "employer" ? "EH" : "AC"}</div>
          <div style={{ fontSize: 12.5, fontWeight: 500 }}>{role === "employer" ? "Erik Holleman" : "AC Sjamaar-Huber"}</div>
          <Icon name="chevron" size={13} style={{ color: "var(--ink-3)" }} />
        </Row>
      </Row>
    </header>
  );
};

const PrivacyBadge = () => {
  const [open, setOpen] = useState(false);
  const [health, setHealth] = useState(null);

  useEffect(() => {
    window.LS_ai?.health().then(setHealth).catch(() => setHealth({ ok: false }));
  }, []);

  return (
    <>
      <button onClick={() => setOpen(true)} style={{
        display: "inline-flex", alignItems: "center", gap: 6,
        padding: "5px 10px", fontSize: 11.5, fontWeight: 500,
        background: "var(--accent-2)", color: "var(--accent)",
        border: "1px solid oklch(85% 0.06 148)", borderRadius: 999,
        cursor: "pointer", fontFamily: "inherit",
      }} title="AI-privacy instellingen">
        🔒 AI in EU
      </button>
      <Modal open={open} onClose={() => setOpen(false)} width={520}>
        <div style={{ padding: "18px 22px", borderBottom: "1px solid var(--line)" }}>
          <Row style={{ justifyContent: "space-between" }}>
            <Row style={{ gap: 10 }}><Icon name="shield" size={16} style={{ color: "var(--accent)" }} /><div style={{ fontSize: 14, fontWeight: 600 }}>AI-gegevensverwerking</div></Row>
            <Btn size="sm" variant="ghost" icon="x" onClick={() => setOpen(false)} />
          </Row>
        </div>
        <div style={{ padding: "20px 22px", fontSize: 13.5, lineHeight: 1.6, color: "var(--ink-2)" }}>
          <p style={{ margin: "0 0 10px" }}><strong>Deze demo</strong> gebruikt OpenRouter als proxy naar <span className="num">{health?.models?.check || "Claude Sonnet"}</span> (controle &amp; uitleg) en <span className="num">{health?.models?.ocr || "Gemini Flash"}</span> (OCR). OpenRouter routeert via EU-endpoints waar mogelijk; geen data wordt opgeslagen langer dan de request zelf.</p>
          <p style={{ margin: "0 0 10px" }}><strong>In productie</strong> draaien deze modellen op een eigen GPU in Nederland (Gemma 3 27B op RTX 4090 of groter). Loongegevens verlaten dan nooit onze server — dat is de standaard voor Brainwaive-klanten.</p>
          <p style={{ margin: "0 0 10px" }}><strong>AI rekent niet.</strong> Alle loon-, ZVW- en premieberekeningen komen uit de gepinde rekenregels (v2026.1). AI flagt alleen mogelijke afwijkingen en genereert uitleg in natuurlijke taal.</p>
          <div style={{ marginTop: 14, padding: "10px 12px", background: "var(--bg-2)", borderRadius: 8, fontSize: 12 }}>
            <strong>Status:</strong> {health?.hasKey ? <span style={{ color: "var(--accent)" }}>OpenRouter-key actief</span> : <span style={{ color: "var(--danger)" }}>Geen OPENROUTER_API_KEY gezet — vul .env in</span>}
          </div>
        </div>
      </Modal>
    </>
  );
};

const iconBtn = {
  position: "relative",
  width: 34, height: 34,
  display: "inline-flex", alignItems: "center", justifyContent: "center",
  background: "var(--bg-2)", border: "1px solid var(--line)", borderRadius: 8,
  cursor: "pointer", color: "var(--ink-2)", fontFamily: "inherit",
};

const companyBtn = {
  display: "inline-flex", alignItems: "center", gap: 8,
  padding: "6px 12px", background: "var(--bg-2)",
  border: "1px solid var(--line)", borderRadius: 8,
  fontSize: 13, fontWeight: 500, color: "var(--ink)",
  cursor: "pointer", fontFamily: "inherit",
};

// Employees list page (richer than sidebar widget)
const EmployeesList = ({ onNavigate, toast }) => {
  const [q, setQ] = useState("");
  const [addOpen, setAddOpen] = useState(false);
  const emps = LS_employees.filter(e =>
    !q || `${e.first_name} ${e.last_name} ${e.function}`.toLowerCase().includes(q.toLowerCase())
  );
  return (
    <div style={{ padding: "28px 32px 48px", maxWidth: 1180, margin: "0 auto" }}>
      <Row style={{ justifyContent: "space-between", marginBottom: 22 }}>
        <div>
          <div style={{ fontSize: 12.5, color: "var(--ink-3)", fontWeight: 500, letterSpacing: 0.5, textTransform: "uppercase", marginBottom: 6 }}>Team</div>
          <h1 style={{ fontSize: 28 }}>Medewerkers</h1>
          <div style={{ color: "var(--ink-2)", marginTop: 4, fontSize: 14 }}>{LS_employees.length} actieve medewerkers · 0 uit dienst</div>
        </div>
        <Row style={{ gap: 8 }}>
          <div style={{ display: "flex", alignItems: "center", gap: 6, padding: "6px 10px", background: "var(--surface)", border: "1px solid var(--line-2)", borderRadius: 8, width: 220 }}>
            <Icon name="search" size={14} style={{ color: "var(--ink-3)" }} />
            <input value={q} onChange={e => setQ(e.target.value)} placeholder="Zoeken…" style={{ flex: 1, border: "none", outline: "none", fontSize: 13, fontFamily: "inherit", background: "transparent" }} />
          </div>
          <Btn variant="secondary" icon="upload">CSV-import</Btn>
          <Btn variant="primary" icon="plus" onClick={() => setAddOpen(true)}>Toevoegen</Btn>
        </Row>
      </Row>

      <Card pad={0}>
        <div style={{
          display: "grid", gridTemplateColumns: "2.4fr 1.4fr 1fr 1fr 1fr 40px",
          padding: "10px 18px",
          borderBottom: "1px solid var(--line)",
          fontSize: 11, fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5, color: "var(--ink-3)",
        }}>
          <div>Naam</div>
          <div>Functie</div>
          <div>In dienst</div>
          <div style={{ textAlign: "right" }}>Uren</div>
          <div style={{ textAlign: "right" }}>Bruto</div>
          <div />
        </div>
        {emps.map((e, i) => (
          <button key={e.id} onClick={() => onNavigate("employee", e.id)} style={{
            display: "grid", gridTemplateColumns: "2.4fr 1.4fr 1fr 1fr 1fr 40px",
            padding: "12px 18px", width: "100%",
            background: "transparent", border: "none",
            borderTop: i === 0 ? "none" : "1px solid var(--line)",
            cursor: "pointer", alignItems: "center", textAlign: "left", fontFamily: "inherit",
          }} onMouseEnter={ev => ev.currentTarget.style.background = "var(--bg-2)"}
             onMouseLeave={ev => ev.currentTarget.style.background = "transparent"}>
            <Row style={{ gap: 12 }}>
              <Avatar emp={e} size={32} />
              <div>
                <div style={{ fontSize: 13.5, fontWeight: 500 }}>{e.last_name}, {e.first_name}</div>
                <div style={{ fontSize: 11.5, color: "var(--ink-3)" }} className="num">#{e.number} · {e.email}</div>
              </div>
            </Row>
            <div style={{ fontSize: 13 }}>{e.function}</div>
            <div className="num" style={{ fontSize: 13 }}>{LS_fmt.date(e.hired_at)}</div>
            <div className="num" style={{ textAlign: "right", fontSize: 13 }}>{e.hours.toLocaleString("nl-NL", { minimumFractionDigits: 2 })}</div>
            <div className="num" style={{ textAlign: "right", fontSize: 13, fontWeight: 500 }}>{LS_fmt.eurSigned(e.base_salary)}</div>
            <Icon name="chevronr" size={14} style={{ color: "var(--ink-3)" }} />
          </button>
        ))}
      </Card>

      <EmployeeEditModal open={addOpen} onClose={() => setAddOpen(false)} toast={toast} />
    </div>
  );
};

// ——— Tweaks panel ———
const TWEAK_DEFAULTS = /*EDITMODE-BEGIN*/{
  "accentHue": 148,
  "warmth": 85,
  "mono": true,
  "density": "comfortable"
}/*EDITMODE-END*/;

const TweaksPanel = () => {
  const [available, setAvailable] = useState(false);
  const [visible, setVisible] = useState(false);
  const [t, setT] = useState(TWEAK_DEFAULTS);

  useEffect(() => {
    const handler = (e) => {
      const d = e.data || {};
      if (d.type === "__activate_edit_mode") setVisible(true);
      if (d.type === "__deactivate_edit_mode") setVisible(false);
    };
    window.addEventListener("message", handler);
    window.parent.postMessage({ type: "__edit_mode_available" }, "*");
    return () => window.removeEventListener("message", handler);
  }, []);

  useEffect(() => {
    const r = document.documentElement.style;
    r.setProperty("--accent",   `oklch(52% 0.13 ${t.accentHue})`);
    r.setProperty("--accent-2", `oklch(94% 0.05 ${t.accentHue})`);
    r.setProperty("--bg",       `oklch(98.4% 0.004 ${t.warmth})`);
    r.setProperty("--bg-2",     `oklch(96.5% 0.006 ${t.warmth})`);
    r.setProperty("--bg-3",     `oklch(93.8% 0.008 ${t.warmth})`);
  }, [t]);

  const set = (k, v) => {
    setT(s => ({ ...s, [k]: v }));
    window.parent.postMessage({ type: "__edit_mode_set_keys", edits: { [k]: v } }, "*");
  };

  if (!visible) return null;

  return (
    <div style={{
      position: "fixed", bottom: 20, right: 20, width: 280, zIndex: 90,
      background: "var(--surface)", border: "1px solid var(--line-2)",
      borderRadius: 12, padding: 16,
      boxShadow: "0 20px 50px -20px oklch(20% 0.01 85 / 0.3)",
    }}>
      <Row style={{ justifyContent: "space-between", marginBottom: 12 }}>
        <div style={{ fontSize: 13, fontWeight: 600 }}>Tweaks</div>
        <Icon name="sparkle" size={14} style={{ color: "var(--accent)" }} />
      </Row>

      <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5, marginBottom: 6 }}>Accent hue</div>
      <input type="range" min={0} max={360} value={t.accentHue} onChange={e => set("accentHue", +e.target.value)} style={{ width: "100%", accentColor: "var(--accent)" }} />

      <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5, marginTop: 12, marginBottom: 6 }}>Warmth</div>
      <input type="range" min={30} max={260} value={t.warmth} onChange={e => set("warmth", +e.target.value)} style={{ width: "100%", accentColor: "var(--accent)" }} />

      <div style={{ fontSize: 11, color: "var(--ink-3)", fontWeight: 600, textTransform: "uppercase", letterSpacing: 0.5, marginTop: 14, marginBottom: 6 }}>Samples</div>
      <Row style={{ gap: 6, flexWrap: "wrap" }}>
        {[148, 35, 240, 300, 200, 75].map(h => (
          <button key={h} onClick={() => set("accentHue", h)} style={{
            width: 26, height: 26, borderRadius: 999,
            background: `oklch(52% 0.13 ${h})`,
            border: t.accentHue === h ? "2px solid var(--ink)" : "2px solid transparent",
            cursor: "pointer",
          }} />
        ))}
      </Row>
    </div>
  );
};

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