// MostlyPrivacy — Dashboard "Requests" section (F155). The owner-side DSAR queue:
// list incoming data-subject requests, watch the statutory-deadline countdown, and
// walk each one through the workflow (received → verifying → in_progress →
// fulfilled/denied) with an audit trail. Mounts as window.MP.DsarRequests; App.jsx
// routes to it and Dashboard adds the nav entry.
(function () {
const F = window.ForgeDesignSystem_e40d74;
const { Button, Badge, Card, CardBody, Stat, Table, Select } = F;
const { Icon, ICONS } = window.MP;
const I18N = (typeof window !== "undefined" && window.ForgeI18n) || { t: (k) => k };
const tr = (k, d) => { const v = I18N.t(k); return v === k && d != null ? d : v; };

// The allowed forward moves — mirrors TRANSITIONS in functions/dsar.js (the server
// re-validates every transition, so this only drives which buttons to show).
const NEXT = {
  received: ["verifying", "denied"],
  verifying: ["in_progress", "denied"],
  in_progress: ["fulfilled", "denied"],
  fulfilled: [],
  denied: [],
};
const STATUS_TONE = { received: "neutral", verifying: "accent", in_progress: "warn", fulfilled: "good", denied: "neutral" };
const TYPE_LABEL = { access: "Access", delete: "Delete", correct: "Correct", "opt-out": "Opt-out", portability: "Portability" };
const statusLabel = (s) => tr("dsar.status." + s, ({ received: "Received", verifying: "Verifying", in_progress: "In progress", fulfilled: "Fulfilled", denied: "Denied" })[s] || s);
const actionLabel = (s) => tr("dsar.action." + s, ({ verifying: "Start verifying", in_progress: "Begin work", fulfilled: "Mark fulfilled", denied: "Deny" })[s] || s);

const api = window.MPApi || { ready: false };

// Demo queue (shown signed-out / no live data). Deadlines relative to "now" so the
// countdown looks live in the prototype.
function demoData() {
  const now = Date.now(), D = 86400000;
  const mk = (id, type, status, regime, verified, deadlineDays, ago) => ({
    id, type, status, regime, verified,
    subject_ref: id + "9f3a12",
    received_at: new Date(now - ago * D).toISOString(),
    deadline_at: new Date(now + deadlineDays * D).toISOString(),
    days_remaining: deadlineDays, overdue: deadlineDays < 0,
    statutory_days: regime === "ccpa" ? 45 : 30,
    audit: [{ action: "submitted", to: "received" }],
  });
  const requests = [
    mk("a1", "access", "received", "gdpr", false, 27, 3),
    mk("b2", "delete", "verifying", "gdpr", true, 21, 9),
    mk("c3", "opt-out", "in_progress", "ccpa", true, 12, 33),
    mk("d4", "portability", "in_progress", "gdpr", true, -2, 32),
    mk("e5", "correct", "fulfilled", "uk_gdpr", true, 6, 24),
  ];
  const stats = { total: requests.length, open: 4, overdue: 1, received: 1, verifying: 1, in_progress: 2, fulfilled: 1, denied: 0 };
  return { requests, stats };
}

function DeadlinePill({ r }) {
  if (r.status === "fulfilled" || r.status === "denied") return <span className="dsar-deadline dsar-deadline--closed">{tr("dsar.deadline.closed", "Closed")}</span>;
  const dr = r.days_remaining;
  if (dr == null) return <span>—</span>;
  const tone = dr < 0 ? "bad" : dr <= 5 ? "warn" : "good";
  const txt = dr < 0 ? Math.abs(dr) + " " + tr("dsar.deadline.overdue", "d overdue") : dr + " " + tr("dsar.deadline.left", "d left");
  return <Badge tone={tone} dot>{txt}</Badge>;
}

function DsarRequests({ nav }) {
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState("");
  const [filter, setFilter] = React.useState("open");
  const [busy, setBusy] = React.useState("");

  const load = React.useCallback(() => {
    let ok = true;
    const fallback = () => { if (ok) setData(demoData()); };
    if (!api.ready || !api.listDsar) { fallback(); return () => { ok = false; }; }
    api.listDsar({ limit: 200 })
      .then((r) => { if (ok) setData(r && r.requests ? r : demoData()); })
      .catch((e) => { if (ok) { setErr((e && e.message) || ""); setData(demoData()); } });
    return () => { ok = false; };
  }, []);
  React.useEffect(() => load(), [load]);

  async function advance(r, to) {
    if (!api.ready || !api.updateDsarStatus) {
      // Demo mode: optimistically reflect the transition locally.
      setData((d) => ({ ...d, requests: d.requests.map((x) => x.id === r.id ? { ...x, status: to } : x) }));
      return;
    }
    setBusy(r.id + ":" + to);
    try {
      const updated = await api.updateDsarStatus(r.id, to);
      setData((d) => ({ ...d, requests: d.requests.map((x) => x.id === r.id ? Object.assign({}, x, updated) : x) }));
    } catch (e) { setErr((e && e.message) || tr("dsar.update.error", "Could not update the request.")); }
    finally { setBusy(""); }
  }

  const s = (data && data.stats) || { total: 0, open: 0, overdue: 0, fulfilled: 0 };
  const all = (data && data.requests) || [];
  const rows = all.filter((r) => filter === "all" ? true : filter === "open" ? (r.status !== "fulfilled" && r.status !== "denied") : r.status === filter);

  const cols = [
    { key: "type", label: tr("dsar.col.type", "Request"), render: (v) => <span style={{ fontWeight: 600 }}>{TYPE_LABEL[v] || v}</span> },
    { key: "subject_ref", label: tr("dsar.col.subject", "Subject"), mono: true, render: (v) => <span title={tr("dsar.col.subjectHint", "Opaque reference — the email is never stored in the clear")}>{(v || "—").slice(0, 8)}…</span> },
    { key: "regime", label: tr("dsar.col.regime", "Regime"), render: (v) => (v || "—").toUpperCase() },
    { key: "verified", label: tr("dsar.col.verified", "Verified"), render: (v) => v ? <Badge tone="good" dot>{tr("dsar.verified.yes", "Verified")}</Badge> : <Badge tone="neutral">{tr("dsar.verified.no", "Pending")}</Badge> },
    { key: "status", label: tr("dsar.col.status", "Status"), render: (v) => <Badge tone={STATUS_TONE[v] || "neutral"} dot>{statusLabel(v)}</Badge> },
    { key: "deadline_at", label: tr("dsar.col.deadline", "Deadline"), render: (_v, r) => <DeadlinePill r={r} /> },
    { key: "actions", label: "", align: "right", render: (_v, r) => (
      <span style={{ display: "inline-flex", gap: 6, justifyContent: "flex-end" }}>
        {(NEXT[r.status] || []).map((to) => (
          <Button key={to} size="sm" variant={to === "denied" ? "ghost" : "secondary"} disabled={busy === r.id + ":" + to} onClick={() => advance(r, to)}>
            {actionLabel(to)}
          </Button>
        ))}
      </span>) },
  ];

  return (
    <div className="app-view">
      <div className="app-view__head">
        <div>
          <h1 className="app-h1">{tr("dsar.head.title", "Data requests")}</h1>
          <p className="app-sub">{tr("dsar.head.sub", "Verified data-subject requests from your sites, with statutory-deadline tracking and an audit trail.")}</p>
        </div>
        <Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.refresh} size={14} />} onClick={() => load()}>{tr("dsar.head.refresh", "Refresh")}</Button>
      </div>

      {err && <div style={{ color: "var(--fg-subtle)", fontSize: 12.5, marginBottom: 10 }}>{tr("dsar.showingSample", "Showing sample data.")} {err}</div>}

      <div className="app-stats" style={{ marginBottom: 18 }}>
        <Stat label={tr("dsar.stat.open", "Open requests")} value={String(s.open || 0)} bordered />
        <Stat label={tr("dsar.stat.overdue", "Overdue")} value={String(s.overdue || 0)} trend={s.overdue ? "down" : "flat"} bordered />
        <Stat label={tr("dsar.stat.fulfilled", "Fulfilled")} value={String(s.fulfilled || 0)} bordered />
        <Stat label={tr("dsar.stat.total", "All time")} value={String(s.total || 0)} bordered />
      </div>

      <Card>
        <CardBody style={{ paddingBottom: 6 }}>
          <div className="app-card-head">
            <span className="app-card-title">{tr("dsar.queue.title", "Request queue")}</span>
            <div style={{ width: 180 }}>
              <Select value={filter} onChange={(e) => setFilter(e && e.target ? e.target.value : e)}
                options={[
                  { value: "open", label: tr("dsar.filter.open", "Open") },
                  { value: "all", label: tr("dsar.filter.all", "All") },
                  { value: "received", label: statusLabel("received") },
                  { value: "verifying", label: statusLabel("verifying") },
                  { value: "in_progress", label: statusLabel("in_progress") },
                  { value: "fulfilled", label: statusLabel("fulfilled") },
                  { value: "denied", label: statusLabel("denied") },
                ]} />
            </div>
          </div>
        </CardBody>
        {data ? <Table columns={cols} rows={rows} /> : <CardBody><span style={{ color: "var(--fg-subtle)" }}>{tr("dsar.loading", "Loading…")}</span></CardBody>}
        <CardBody>
          <div className="wz-transparent" style={{ marginTop: 0 }}>
            <Icon d={ICONS.shieldCheck} size={18} />
            <span><b style={{ color: "var(--fg)" }}>{tr("dsar.footer.privacy", "Privacy by design.")}</b> {tr("dsar.footer.body", "We store only a one-way hash of each requester's email — never the address itself — plus the request type, deadline and audit trail.")}</span>
          </div>
        </CardBody>
      </Card>
    </div>
  );
}

window.MP = Object.assign(window.MP || {}, { DsarRequests });
})();
