// Admin Panel — verborgen achter admin-IDs in app_config.
// Wordt geopend via 'meer' scherm als je admin bent.

(function() {
  const H = window.kretaHelpers;
  const DATA = window.CORVEE_DATA;
  const B = () => window.kretaBackend;

  // ---------------- Root ----------------
  function AdminScreen({ me, goBack }) {
    const [tab, setTab] = React.useState("dashboard");

    const tabs = [
      { id: "dashboard", label: "Overzicht", icon: "📊" },
      { id: "push", label: "Push", icon: "🔔" },
      { id: "moderate", label: "Moderatie", icon: "🧹" },
      { id: "activity", label: "Activiteit", icon: "📜" },
      { id: "security", label: "Beveiliging", icon: "🛡️" },
      { id: "data", label: "Data", icon: "🗂️" },
      { id: "settings", label: "Instellingen", icon: "⚙️" },
    ];

    return (
      <div className="screen" style={{ paddingBottom: 110 }}>
        <div style={{
          display: "flex", alignItems: "center", gap: 10,
          marginBottom: 12, marginTop: 4,
        }}>
          <button onClick={goBack} className="btn btn-ghost" style={{
            padding: "6px 10px", fontSize: 13, border: "1px solid var(--line)",
          }}>← Terug</button>
          <h1 className="serif" style={{ fontSize: 26, margin: 0, letterSpacing: -0.5 }}>
            🛠️ Admin
          </h1>
        </div>

        <div style={{
          display: "flex", gap: 6, overflowX: "auto",
          paddingBottom: 8, marginBottom: 12,
          scrollbarWidth: "none",
        }}>
          {tabs.map(t => (
            <button key={t.id} onClick={() => setTab(t.id)} style={{
              flexShrink: 0, border: "none", cursor: "pointer",
              padding: "8px 14px", borderRadius: 999,
              background: tab === t.id ? "var(--aegean-deep)" : "white",
              color: tab === t.id ? "white" : "var(--ink)",
              fontFamily: "inherit", fontSize: 13, fontWeight: 600,
              boxShadow: tab === t.id ? "0 2px 6px rgba(13,58,107,0.25)" : "0 1px 2px rgba(0,0,0,0.05)",
              border: tab === t.id ? "none" : "1px solid var(--line)",
            }}>
              <span style={{ marginRight: 4 }}>{t.icon}</span>{t.label}
            </button>
          ))}
        </div>

        {tab === "dashboard" && <AdminDashboard me={me} />}
        {tab === "push" && <AdminPush me={me} />}
        {tab === "moderate" && <AdminModerate />}
        {tab === "activity" && <AdminActivity />}
        {tab === "security" && <AdminSecurity />}
        {tab === "data" && <AdminData />}
        {tab === "settings" && <AdminSettings />}
      </div>
    );
  }

  // ---------------- Dashboard ----------------
  function AdminDashboard({ me }) {
    const [stats, setStats] = React.useState(null);
    const [log, setLog] = React.useState([]);

    React.useEffect(() => {
      refresh();
      const t = setInterval(refresh, 30000);
      return () => clearInterval(t);
    }, []);

    async function refresh() {
      const [activity, subs] = await Promise.all([
        B().fetchActivityLog(50),
        B().fetchPushSubscribers(),
      ]);
      const byPerson = {};
      for (const a of activity) {
        byPerson[a.person_id] = byPerson[a.person_id] || 0;
        byPerson[a.person_id]++;
      }
      const tasksToday = activity.filter(a => a.action === "task_done").length;
      const wallMsgs = activity.filter(a => a.action === "wall_post").length;

      setStats({
        people: DATA.people.length,
        pushEnabled: new Set(subs.map(s => s.person_id)).size,
        tasksToday,
        wallMsgs,
        recentActions: activity.length,
        byPerson,
      });
      setLog(activity.slice(0, 10));
    }

    if (!stats) return <div className="card">Laden…</div>;

    const cards = [
      { label: "Gezinsleden", value: stats.people, icon: "👨‍👩‍👧", color: "#1a5490" },
      { label: "Push aan", value: `${stats.pushEnabled}/${stats.people}`, icon: "🔔", color: "#7ba05b" },
      { label: "Taken (recent)", value: stats.tasksToday, icon: "✅", color: "#c2410c" },
      { label: "Berichten", value: stats.wallMsgs, icon: "💬", color: "#9333ea" },
    ];

    return (
      <div>
        <div style={{
          display: "grid", gridTemplateColumns: "1fr 1fr", gap: 10, marginBottom: 16,
        }}>
          {cards.map(c => (
            <div key={c.label} className="card" style={{ padding: 14 }}>
              <div style={{ fontSize: 20, marginBottom: 4 }}>{c.icon}</div>
              <div style={{ fontSize: 26, fontWeight: 800, color: c.color, letterSpacing: -0.5 }}>
                {c.value}
              </div>
              <div style={{ fontSize: 12, color: "var(--muted)" }}>{c.label}</div>
            </div>
          ))}
        </div>

        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>Leaderboard (per persoon)</div>
          {DATA.people.map(p => {
            const n = stats.byPerson[p.id] || 0;
            const max = Math.max(1, ...Object.values(stats.byPerson));
            return (
              <div key={p.id} style={{ display: "flex", alignItems: "center", gap: 10, marginBottom: 6 }}>
                <div style={{ width: 60, fontSize: 12, fontWeight: 600 }}>{p.name}</div>
                <div style={{ flex: 1, height: 8, borderRadius: 4, background: "#eee", overflow: "hidden" }}>
                  <div style={{ height: "100%", width: `${(n / max) * 100}%`, background: p.color }} />
                </div>
                <div style={{ width: 28, fontSize: 12, color: "var(--muted)", textAlign: "right" }}>{n}</div>
              </div>
            );
          })}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Laatste acties</div>
          {log.length === 0 && <div className="tiny-mute">Nog geen activiteit</div>}
          {log.map(a => (
            <ActivityRow key={a.id} a={a} />
          ))}
        </div>
      </div>
    );
  }

  // ---------------- Push ----------------
  const TEMPLATES = [
    { icon: "🍽️", title: "Eten klaar!", body: "Kom snel naar de keuken, het eten staat op tafel 🇬🇷" },
    { icon: "🏊", title: "Verzamelen bij het zwembad", body: "Iedereen naar het zwembad, we gaan beginnen!" },
    { icon: "🚗", title: "We gaan zo weg", body: "Over 10 minuten vertrekken we — klaar staan!" },
    { icon: "😴", title: "Bedtijd", body: "Tijd om naar bed te gaan. Welterusten! 🌙" },
    { icon: "🔔", title: "Vergeet je corvee niet", body: "Check de app — er staat een taak voor je klaar." },
    { icon: "🎉", title: "Surprise!", body: "Check de app voor een verrassing 🎁" },
    { icon: "📍", title: "Waar is iedereen?", body: "Laat even weten waar je bent — post op het prikbord!" },
    { icon: "☀️", title: "Goedemorgen!", body: "Kαλημέρα! Nieuwe dag, nieuwe avonturen." },
  ];

  function AdminPush({ me }) {
    const [title, setTitle] = React.useState("");
    const [body, setBody] = React.useState("");
    const [targets, setTargets] = React.useState([]); // empty = broadcast
    const [sending, setSending] = React.useState(false);
    const [result, setResult] = React.useState(null);
    const [history, setHistory] = React.useState([]);
    const [subs, setSubs] = React.useState([]);

    React.useEffect(() => { refresh(); }, []);
    async function refresh() {
      const [h, s] = await Promise.all([B().fetchPushLog(20), B().fetchPushSubscribers()]);
      setHistory(h);
      setSubs(s);
    }

    const pushed = new Set(subs.map(s => s.person_id));

    async function send() {
      if (!title.trim() || !body.trim()) return;
      setSending(true); setResult(null);
      const r = await B().sendAdminPush({
        title: title.trim(),
        body: body.trim(),
        targetIds: targets,
      });
      setSending(false);
      setResult(r);
      if (r.ok) { setTitle(""); setBody(""); setTargets([]); }
      refresh();
    }

    function useTemplate(t) {
      setTitle(t.title);
      setBody(t.body);
    }

    function toggleTarget(id) {
      setTargets(t => t.includes(id) ? t.filter(x => x !== id) : [...t, id]);
    }

    return (
      <div>
        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>Snel versturen</div>
          <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr", gap: 8 }}>
            {TEMPLATES.map(t => (
              <button key={t.title} onClick={() => useTemplate(t)} style={{
                appearance: "none", border: "1px solid var(--line)", cursor: "pointer",
                padding: "10px 12px", borderRadius: 12, background: "white",
                textAlign: "left", fontFamily: "inherit",
                display: "flex", alignItems: "center", gap: 8,
              }}>
                <span style={{ fontSize: 22 }}>{t.icon}</span>
                <span style={{ fontSize: 12, fontWeight: 600 }}>{t.title}</span>
              </button>
            ))}
          </div>
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Bericht</div>
          <input value={title} onChange={e => setTitle(e.target.value)} placeholder="Titel" style={inputStyle} />
          <textarea value={body} onChange={e => setBody(e.target.value)} placeholder="Bericht..." rows={3} style={{ ...inputStyle, marginTop: 8, resize: "vertical" }} />

          <div className="section-sub" style={{ marginTop: 14 }}>Naar wie?</div>
          <div style={{
            display: "flex", flexWrap: "wrap", gap: 6, marginBottom: 6,
          }}>
            <button onClick={() => setTargets([])} style={chipStyle(targets.length === 0)}>
              📣 Iedereen ({pushed.size})
            </button>
            {DATA.people.map(p => {
              const has = pushed.has(p.id);
              const sel = targets.includes(p.id);
              return (
                <button key={p.id} onClick={() => toggleTarget(p.id)} disabled={!has} style={{
                  ...chipStyle(sel), opacity: has ? 1 : 0.4,
                }}>
                  <span style={{ fontSize: 14 }}>{p.emoji}</span> {p.name}
                  {!has && <span style={{ fontSize: 10, marginLeft: 4 }}>(geen push)</span>}
                </button>
              );
            })}
          </div>

          <button onClick={send} disabled={!title.trim() || !body.trim() || sending} className="btn" style={{
            marginTop: 10, width: "100%", padding: 12,
            background: "var(--aegean-deep)", color: "white",
            fontWeight: 700, opacity: (!title.trim() || !body.trim()) ? 0.4 : 1,
          }}>
            {sending ? "Versturen…" : targets.length === 0 ? `📣 Naar iedereen (${pushed.size})` : `📤 Naar ${targets.length} ${targets.length === 1 ? 'persoon' : 'personen'}`}
          </button>

          {result && (
            <div style={{
              marginTop: 10, padding: 10, borderRadius: 8,
              background: result.ok ? "#e6f4ea" : "#fde8e8",
              color: result.ok ? "#1e6d33" : "#9b2226",
              fontSize: 12,
            }}>
              {result.ok
                ? `✅ Verstuurd naar ${result.delivered ?? "?"} apparaten`
                : result.reason === "edge-function-missing"
                  ? "⚠️ Opgeslagen in log, maar push-service nog niet gekoppeld (Edge Function nog niet gedeployed)"
                  : `❌ Fout: ${result.reason}`}
            </div>
          )}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Verstuurd (laatste 20)</div>
          {history.length === 0 && <div className="tiny-mute">Nog niets verstuurd</div>}
          {history.map(h => {
            const sender = H.getPerson(h.sent_by);
            return (
              <div key={h.id} style={{ padding: "8px 0", borderBottom: "1px solid var(--line-soft)" }}>
                <div style={{ fontSize: 13, fontWeight: 700 }}>{h.title}</div>
                <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>{h.body}</div>
                <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 4 }}>
                  {sender?.name || "?"} · {timeAgo(h.sent_at)} · {h.target_ids?.length ? `naar ${h.target_ids.length}` : "broadcast"}
                </div>
              </div>
            );
          })}
        </div>

        <PushResetPanel subs={subs} onChange={refresh} />
      </div>
    );
  }

  // Reset push-subscriptions per persoon (handig bij nieuwe telefoon / werkt niet)
  function PushResetPanel({ subs, onChange }) {
    const [busy, setBusy] = React.useState(null);
    const [msg, setMsg] = React.useState("");
    const byPerson = {};
    for (const s of subs) {
      byPerson[s.person_id] = (byPerson[s.person_id] || 0) + 1;
    }

    async function reset(pid) {
      if (!confirm(`Alle push-apparaten van ${H.getPerson(pid)?.name || pid} wissen?\n\nHij/zij moet opnieuw "Aanzetten" klikken in de app.`)) return;
      setBusy(pid);
      const r = await B().resetPushForPerson(pid);
      setBusy(null);
      setMsg(r.ok ? `✅ Push gereset voor ${H.getPerson(pid)?.name || pid}` : "❌ Fout");
      setTimeout(() => setMsg(""), 3000);
      onChange();
    }

    return (
      <div className="card" style={{ marginTop: 12 }}>
        <div className="section-sub" style={{ marginTop: 0 }}>Push-problemen? Reset per persoon</div>
        <div style={{ fontSize: 12, color: "var(--ink-soft)", marginBottom: 10 }}>
          Als iemand geen push krijgt: wis hier z'n subscriptions. Die persoon moet dan in de app opnieuw "🔔 Aanzetten" klikken.
        </div>
        <div style={{ display: "flex", flexDirection: "column", gap: 6 }}>
          {DATA.people.map(p => {
            const n = byPerson[p.id] || 0;
            return (
              <div key={p.id} style={{
                display: "flex", alignItems: "center", gap: 10,
                padding: "6px 8px", borderRadius: 8,
                background: n > 0 ? "#f4f8fb" : "transparent",
              }}>
                <div style={{ fontSize: 18 }}>{p.emoji}</div>
                <div style={{ flex: 1, fontSize: 13, fontWeight: 600 }}>{p.name}</div>
                <div style={{ fontSize: 11, color: "var(--muted)", minWidth: 60, textAlign: "right" }}>
                  {n === 0 ? "geen" : `${n} apparaat${n === 1 ? "" : "en"}`}
                </div>
                <button
                  onClick={() => reset(p.id)}
                  disabled={n === 0 || busy === p.id}
                  style={{
                    appearance: "none", border: "1px solid var(--line)", cursor: n === 0 ? "default" : "pointer",
                    padding: "4px 10px", borderRadius: 6, background: "white",
                    fontSize: 11, fontFamily: "inherit", fontWeight: 600,
                    color: n === 0 ? "var(--muted)" : "#9b2226",
                    opacity: n === 0 ? 0.4 : 1,
                  }}
                >
                  {busy === p.id ? "…" : "Reset"}
                </button>
              </div>
            );
          })}
        </div>
        {msg && <div style={{ fontSize: 12, marginTop: 8 }}>{msg}</div>}
      </div>
    );
  }

  // ---------------- Moderate (berichten & polls verwijderen) ----------------
  function AdminModerate() {
    const [tick, setTick] = React.useState(0);
    const [kudos, setKudos] = React.useState([]);
    const B0 = B();
    const st = B0.state;

    React.useEffect(() => {
      const unsub = B0.subscribe(() => setTick(t => t + 1));
      B0.fetchKudos?.(100).then(setKudos);
      return unsub;
    }, []);
    React.useEffect(() => { B0.fetchKudos?.(100).then(setKudos); }, [tick]);

    async function delMsg(id) {
      if (!confirm("Dit bericht verwijderen?")) return;
      await B0.deleteWall(id);
    }
    async function delPoll(id) {
      if (!confirm("Deze poll verwijderen (incl. alle stemmen)?")) return;
      await B0.deletePoll(id);
    }
    async function delKudo(id) {
      if (!confirm("Deze kudo verwijderen?")) return;
      await B0.deleteKudos(id);
      setKudos(k => k.filter(x => x.id !== id));
    }

    return (
      <div>
        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>
            💬 Prikbord ({st.wall.length})
          </div>
          {st.wall.length === 0 && <div className="tiny-mute">Geen berichten</div>}
          {[...st.wall].reverse().map(m => {
            const p = H.getPerson(m.from);
            return (
              <div key={m.id} style={{
                display: "flex", gap: 10, padding: "10px 0",
                borderBottom: "1px solid var(--line-soft)", alignItems: "start",
              }}>
                <div style={{
                  width: 28, height: 28, borderRadius: "50%", flexShrink: 0,
                  background: p?.color || "#888", color: "white",
                  display: "flex", alignItems: "center", justifyContent: "center",
                  fontSize: 12, fontWeight: 700,
                }}>{p?.emoji || "?"}</div>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 12, fontWeight: 700 }}>{p?.name || m.from}</div>
                  <div style={{ fontSize: 13, marginTop: 2, wordBreak: "break-word" }}>{m.text}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{timeAgo(new Date(m.ts).toISOString())}</div>
                </div>
                <button onClick={() => delMsg(m.id)} style={delBtn}>🗑️</button>
              </div>
            );
          })}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>
            🗳️ Polls ({st.polls.length})
          </div>
          {st.polls.length === 0 && <div className="tiny-mute">Geen polls</div>}
          {st.polls.map(p => {
            const author = H.getPerson(p.by);
            const totalVotes = p.options.reduce((n, o) => n + Object.keys(o.votes || {}).length, 0);
            return (
              <div key={p.id} style={{
                padding: "10px 0", borderBottom: "1px solid var(--line-soft)",
                display: "flex", gap: 10, alignItems: "start",
              }}>
                <div style={{ flex: 1, minWidth: 0 }}>
                  <div style={{ fontSize: 13, fontWeight: 700, wordBreak: "break-word" }}>{p.question}</div>
                  <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>
                    {author?.name || p.by} · {totalVotes} stemmen · {p.options.length} opties
                  </div>
                </div>
                <button onClick={() => delPoll(p.id)} style={delBtn}>🗑️</button>
              </div>
            );
          })}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>
            💛 Kudos ({kudos.length})
          </div>
          {kudos.length === 0 && <div className="tiny-mute">Nog geen kudos</div>}
          {kudos.map(k => {
            const from = H.getPerson(k.from_person);
            const to = H.getPerson(k.to_person);
            return (
              <div key={k.id} style={{
                padding: "10px 0", borderBottom: "1px solid var(--line-soft)",
                display: "flex", gap: 10, alignItems: "start",
              }}>
                <div style={{ flex: 1, minWidth: 0, fontSize: 13 }}>
                  <b>{from?.name || k.from_person}</b> → <b>{to?.name || k.to_person}</b>
                  {k.text && <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>"{k.text}"</div>}
                  <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{timeAgo(k.created_at)}</div>
                </div>
                <button onClick={() => delKudo(k.id)} style={delBtn}>🗑️</button>
              </div>
            );
          })}
        </div>
      </div>
    );
  }

  const delBtn = {
    appearance: "none", border: "1px solid var(--line)", cursor: "pointer",
    padding: "4px 8px", borderRadius: 6, background: "white",
    fontSize: 14, flexShrink: 0, height: 28,
  };

  // ---------------- Activity ----------------
  function AdminActivity() {
    const [log, setLog] = React.useState([]);
    const [filter, setFilter] = React.useState("all");
    const [person, setPerson] = React.useState("all");

    React.useEffect(() => {
      load();
      const t = setInterval(load, 15000);
      return () => clearInterval(t);
    }, []);
    async function load() { setLog(await B().fetchActivityLog(300)); }

    const filtered = log.filter(a =>
      (filter === "all" || a.action === filter) &&
      (person === "all" || a.person_id === person)
    );

    const actions = ["all", ...new Set(log.map(a => a.action))];

    return (
      <div>
        <div className="card" style={{ marginBottom: 12 }}>
          <div style={{ display: "flex", gap: 8, flexWrap: "wrap" }}>
            <select value={filter} onChange={e => setFilter(e.target.value)} style={selectStyle}>
              {actions.map(a => <option key={a} value={a}>{a === "all" ? "Alle acties" : ACTION_LABELS[a] || a}</option>)}
            </select>
            <select value={person} onChange={e => setPerson(e.target.value)} style={selectStyle}>
              <option value="all">Iedereen</option>
              {DATA.people.map(p => <option key={p.id} value={p.id}>{p.name}</option>)}
            </select>
            <button onClick={() => exportCSV(filtered)} className="btn btn-ghost" style={{
              border: "1px solid var(--line)", padding: "6px 10px", fontSize: 12,
            }}>⬇️ CSV</button>
          </div>
        </div>

        <div className="card" style={{ padding: 0 }}>
          {filtered.length === 0 && <div style={{ padding: 14 }} className="tiny-mute">Geen resultaten</div>}
          {filtered.map(a => <ActivityRow key={a.id} a={a} />)}
        </div>
      </div>
    );
  }

  // ---------------- Security ----------------
  function AdminSecurity() {
    const [attempts, setAttempts] = React.useState([]);
    React.useEffect(() => { load(); }, []);
    async function load() { setAttempts(await B().fetchLoginAttempts(100)); }

    const fails = attempts.filter(a => !a.success);
    const successes = attempts.filter(a => a.success);
    const last24h = attempts.filter(a => Date.now() - new Date(a.attempted_at).getTime() < 86400000);

    return (
      <div>
        <div style={{ display: "grid", gridTemplateColumns: "1fr 1fr 1fr", gap: 8, marginBottom: 12 }}>
          <StatCard label="Totaal" value={attempts.length} color="#1a5490" />
          <StatCard label="Geslaagd" value={successes.length} color="#7ba05b" />
          <StatCard label="Mislukt" value={fails.length} color="#c2410c" />
        </div>

        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>Laatste inlogpogingen</div>
          {attempts.length === 0 && <div className="tiny-mute">Nog geen pogingen</div>}
          {attempts.slice(0, 30).map(a => (
            <div key={a.id} style={{
              padding: "8px 0", borderBottom: "1px solid var(--line-soft)",
              display: "flex", gap: 10, alignItems: "start",
            }}>
              <div style={{ fontSize: 18 }}>{a.success ? "✅" : "🚫"}</div>
              <div style={{ flex: 1, fontSize: 12 }}>
                <div style={{ fontWeight: 600, color: a.success ? "var(--ink)" : "#9b2226" }}>
                  {a.success ? "Geslaagd" : "Fout wachtwoord"}
                </div>
                <div style={{ color: "var(--muted)", marginTop: 2 }}>
                  {timeAgo(a.attempted_at)} · {(a.user_agent || "").slice(0, 60)}
                </div>
              </div>
            </div>
          ))}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Laatste 24 uur</div>
          <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>
            {last24h.length} pogingen · {last24h.filter(a => !a.success).length} mislukt
          </div>
          {last24h.filter(a => !a.success).length >= 5 && (
            <div style={{
              marginTop: 8, padding: 10, borderRadius: 8,
              background: "#fde8e8", color: "#9b2226", fontSize: 12,
            }}>
              ⚠️ Veel mislukte pogingen — overweeg het wachtwoord te wijzigen.
            </div>
          )}
        </div>
      </div>
    );
  }

  // ---------------- Data ----------------
  function AdminData() {
    const [confirmReset, setConfirmReset] = React.useState(false);

    async function doExport() {
      const s = B().state;
      const activity = await B().fetchActivityLog(2000);
      const blob = new Blob([JSON.stringify({
        exported_at: new Date().toISOString(),
        people: DATA.people,
        done: s.done,
        wall: s.wall,
        polls: s.polls,
        program: s.program,
        greek: s.greek,
        activity,
      }, null, 2)], { type: "application/json" });
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `kreta-export-${new Date().toISOString().slice(0,10)}.json`;
      a.click();
      URL.revokeObjectURL(url);
    }

    async function doReset() {
      await B().resetAllData();
      setConfirmReset(false);
    }

    return (
      <div>
        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>Export</div>
          <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 10 }}>
            Download een complete JSON-backup van alle taken, berichten, polls en activiteit.
          </div>
          <button onClick={doExport} className="btn" style={{ background: "var(--aegean-deep)", color: "white" }}>
            ⬇️ Download backup (.json)
          </button>
        </div>

        <div className="card" style={{ marginTop: 12, borderColor: "#fecaca" }}>
          <div className="section-sub" style={{ marginTop: 0, color: "#c2410c" }}>Gevarenzone</div>
          <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 10 }}>
            Wis alle taken, berichten, polls, programma, Grieks. Mensen blijven staan.
          </div>
          {!confirmReset ? (
            <button onClick={() => setConfirmReset(true)} className="btn" style={{
              background: "#fde8e8", color: "#9b2226", fontWeight: 700,
            }}>
              🗑️ Alle data wissen
            </button>
          ) : (
            <div style={{ display: "flex", gap: 8 }}>
              <button onClick={doReset} className="btn" style={{
                background: "#c2410c", color: "white", fontWeight: 700, flex: 1,
              }}>Zeker weten — wissen</button>
              <button onClick={() => setConfirmReset(false)} className="btn btn-ghost" style={{
                border: "1px solid var(--line)", flex: 1,
              }}>Annuleren</button>
            </div>
          )}
        </div>
      </div>
    );
  }

  // ---------------- Settings ----------------
  function AdminSettings() {
    const [newPw, setNewPw] = React.useState("");
    const [status, setStatus] = React.useState("");

    async function save() {
      if (newPw.trim().length < 4) {
        setStatus("Minstens 4 tekens");
        return;
      }
      setStatus("Opslaan…");
      const r = await B().setFamilyPassword(newPw);
      setStatus(r.ok ? "✅ Opgeslagen. Deel het nieuwe wachtwoord met de familie." : "❌ Fout");
      setNewPw("");
    }

    return (
      <div>
        <div className="card">
          <div className="section-sub" style={{ marginTop: 0 }}>Familie-wachtwoord wijzigen</div>
          <div style={{ fontSize: 13, color: "var(--ink-soft)", marginBottom: 10 }}>
            Iedereen die al ingelogd is blijft ingelogd — nieuwe inlogs hebben het nieuwe wachtwoord nodig.
          </div>
          <input type="text" value={newPw} onChange={e => setNewPw(e.target.value)}
            placeholder="Nieuw wachtwoord" style={inputStyle} />
          <button onClick={save} className="btn" style={{
            marginTop: 10, background: "var(--aegean-deep)", color: "white", fontWeight: 700,
          }}>Opslaan</button>
          {status && <div style={{ fontSize: 12, marginTop: 8 }}>{status}</div>}
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Admins</div>
          <div style={{ fontSize: 13, color: "var(--ink-soft)" }}>
            Admin-status staat in de database (<code>app_config.admin_ids</code>).
            Momenteel zijn dat:
          </div>
          <AdminsDisplay />
        </div>

        <div className="card" style={{ marginTop: 12 }}>
          <div className="section-sub" style={{ marginTop: 0 }}>Versie</div>
          <div style={{ fontSize: 12, color: "var(--muted)" }}>
            Corvee Kreta 2026 · Admin v1.0<br/>
            Backend: {B()?.hasBackend?.() ? "Supabase (online)" : "Lokaal (offline)"}
          </div>
        </div>
      </div>
    );
  }

  function AdminsDisplay() {
    const [ids, setIds] = React.useState([]);
    React.useEffect(() => { B().getAdminIds().then(setIds); }, []);
    return (
      <div style={{ display: "flex", gap: 8, marginTop: 8, flexWrap: "wrap" }}>
        {ids.map(id => {
          const p = H.getPerson(id);
          if (!p) return <span key={id} style={chipStyle(false)}>{id}</span>;
          return <span key={id} style={{ ...chipStyle(true), background: p.color, color: "white" }}>{p.emoji} {p.name}</span>;
        })}
      </div>
    );
  }

  // ---------------- Helpers ----------------
  const ACTION_LABELS = {
    login: "🔑 Login",
    task_done: "✅ Taak gedaan",
    task_undo: "↩️ Taak teruggedraaid",
    wall_post: "💬 Bericht",
    poll_create: "🗳️ Poll gemaakt",
    poll_vote: "✓ Stem",
    greek_learned: "Ω Grieks woord",
    program_add: "📅 Programma",
    push_enabled: "🔔 Push aan",
    admin_action: "🛠️ Admin",
  };

  function ActivityRow({ a }) {
    const p = H.getPerson(a.person_id);
    const label = ACTION_LABELS[a.action] || a.action;
    const detail = formatDetails(a);
    return (
      <div style={{
        padding: "10px 14px", borderBottom: "1px solid var(--line-soft)",
        display: "flex", gap: 10, alignItems: "start",
      }}>
        <div style={{
          width: 32, height: 32, borderRadius: "50%", flexShrink: 0,
          background: p?.color || "#888", color: "white",
          display: "flex", alignItems: "center", justifyContent: "center",
          fontSize: 14, fontWeight: 700,
        }}>{p?.emoji || "?"}</div>
        <div style={{ flex: 1, fontSize: 13 }}>
          <div>
            <b>{p?.name || a.person_id || "Systeem"}</b>
            <span style={{ color: "var(--muted)", marginLeft: 6 }}>{label}</span>
          </div>
          {detail && <div style={{ fontSize: 12, color: "var(--ink-soft)", marginTop: 2 }}>{detail}</div>}
          <div style={{ fontSize: 11, color: "var(--muted)", marginTop: 2 }}>{timeAgo(a.created_at)}</div>
        </div>
      </div>
    );
  }

  function formatDetails(a) {
    const d = a.details || {};
    switch (a.action) {
      case "task_done":
      case "task_undo": return `${d.task_id} op ${d.date}`;
      case "wall_post": return `"${(d.text || "").slice(0, 80)}"`;
      case "poll_create": return `"${d.question}"`;
      case "greek_learned": return d.word_id;
      case "program_add": return `${d.time} — ${d.text}`;
      case "admin_action": return d.type + (d.title ? `: ${d.title}` : d.id ? ` #${d.id}` : "");
      default: return "";
    }
  }

  function timeAgo(iso) {
    const ms = Date.now() - new Date(iso).getTime();
    const s = Math.floor(ms / 1000);
    if (s < 60) return "zojuist";
    const m = Math.floor(s / 60);
    if (m < 60) return `${m} min geleden`;
    const h = Math.floor(m / 60);
    if (h < 24) return `${h} uur geleden`;
    const d = Math.floor(h / 24);
    return `${d} dag${d > 1 ? "en" : ""} geleden`;
  }

  function exportCSV(rows) {
    const header = ["time", "person", "action", "details"];
    const lines = [header.join(",")];
    for (const r of rows) {
      const d = JSON.stringify(r.details || {}).replace(/"/g, '""');
      lines.push([
        new Date(r.created_at).toISOString(),
        r.person_id || "",
        r.action,
        `"${d}"`,
      ].join(","));
    }
    const blob = new Blob([lines.join("\n")], { type: "text/csv" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `kreta-activity-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    URL.revokeObjectURL(url);
  }

  function StatCard({ label, value, color }) {
    return (
      <div className="card" style={{ padding: 12, textAlign: "center" }}>
        <div style={{ fontSize: 24, fontWeight: 800, color, letterSpacing: -0.5 }}>{value}</div>
        <div style={{ fontSize: 11, color: "var(--muted)" }}>{label}</div>
      </div>
    );
  }

  const inputStyle = {
    width: "100%", padding: "10px 12px",
    border: "1px solid var(--line)", borderRadius: 8,
    fontFamily: "inherit", fontSize: 14, boxSizing: "border-box",
  };

  const selectStyle = {
    padding: "8px 10px",
    border: "1px solid var(--line)", borderRadius: 8,
    fontFamily: "inherit", fontSize: 13,
    background: "white",
  };

  function chipStyle(active) {
    return {
      appearance: "none", border: "1px solid " + (active ? "var(--aegean-deep)" : "var(--line)"),
      cursor: "pointer",
      padding: "6px 12px", borderRadius: 999,
      background: active ? "var(--aegean-deep)" : "white",
      color: active ? "white" : "var(--ink)",
      fontFamily: "inherit", fontSize: 12, fontWeight: 600,
      display: "inline-flex", alignItems: "center", gap: 4,
    };
  }

  window.AdminScreen = AdminScreen;
})();
