// MostlyPrivacy — Dashboard (screen E): Overview + Sites, plus Settings (H).
(function () {
const F = window.ForgeDesignSystem_e40d74;
const { Button, Badge, Card, CardBody, Stat, Table, Tabs, Switch, Field, Input, Avatar, LineChart } = F;
const { Icon, ICONS } = window.MP;

const SITES = [
  { id: "cl", dom: "café-lumiere.fr", fav: "CL", region: "EU · FR", policies: "good", banner: "good", scan: "2h ago", consents: "8,420" },
  { id: "b7", dom: "boulangerie-no7.de", fav: "B7", region: "EU · DE", policies: "good", banner: "good", scan: "1d ago", consents: "3,109" },
  { id: "sa", dom: "studio-aria.it", fav: "SA", region: "EU · IT", policies: "warn", banner: "good", scan: "5d ago", consents: "1,204" },
  { id: "nw", dom: "northwind.shop", fav: "NW", region: "US · CA", policies: "good", banner: "warn", scan: "3h ago", consents: "22,540" },
];
const statusLabel = { good: "Compliant", warn: "Needs review", bad: "Action needed" };
const api = window.MPApi || { ready: false, listSites: () => Promise.resolve(SITES), accountSummary: () => Promise.resolve(null), queryConsentLog: () => Promise.resolve({ entries: [], stats: { total: 0, accept: 0, reject: 0, consentRate: null } }) };

// Demo consent-log rows (shown when not signed in / no live data).
const DEMO_LOG = {
  stats: { total: 49680, accept: 24110, reject: 9420, custom: 1743, consentRate: 0.52 },
  entries: [
    { id: "1", decision: "accept", geo: { country: "DE" }, lang: "de", ts: "2026-06-10T09:14:00Z" },
    { id: "2", decision: "reject", geo: { country: "FR" }, lang: "fr", ts: "2026-06-10T09:11:00Z" },
    { id: "3", decision: "accept", geo: { country: "IT" }, lang: "it", ts: "2026-06-10T09:07:00Z" },
    { id: "4", decision: "custom", geo: { country: "GB" }, lang: "en", ts: "2026-06-10T09:02:00Z" },
    { id: "5", decision: "accept", geo: { country: "ES" }, lang: "es", ts: "2026-06-10T08:55:00Z" },
  ],
};

// Normalize a live site doc → the table row shape (demo rows pass through).
function toRow(s) {
  if (s && s.dom) return s;
  const dom = (s && s.domain) || "—";
  return {
    id: s.id, dom, fav: dom.replace(/^www\./, "").slice(0, 2).toUpperCase(),
    region: (s.banner && s.banner.rules && s.banner.rules.default === "ccpa") ? "US" : "EU",
    policies: s.policies_status === "none" ? "warn" : (s.policies_status || "good"),
    banner: s.banner_status || "good",
    scan: s.last_scan ? "recent" : "—",
    consents: "0",
  };
}
function fmtNum(n) { return (n == null) ? "—" : Number(n).toLocaleString("en-US"); }

function StatusPill({ s, kind }) {
  const txt = s === "good" ? (kind === "banner" ? "Live" : "Compliant") : kind === "banner" ? "Not installed" : "Review";
  return <Badge tone={s} dot>{txt}</Badge>;
}

function Overview({ nav }) {
  const [sites, setSites] = React.useState(SITES);
  const [sum, setSum] = React.useState(null);
  React.useEffect(() => {
    let ok = true;
    api.listSites().then((rows) => { if (ok && Array.isArray(rows)) setSites(rows.map(toRow)); }).catch(() => {});
    api.accountSummary().then((s) => { if (ok && s) setSum(s); }).catch(() => {});
    return () => { ok = false; };
  }, []);
  const compliant = sites.filter((r) => r.policies === "good" && r.banner === "good").length;
  const cols = [
    { key: "dom", label: "Site", render: (v, r) => (
      <span style={{ display: "inline-flex", alignItems: "center", gap: 10 }}>
        <span className="site-card__fav" style={{ width: 26, height: 26, fontSize: 11 }}>{r.fav}</span>{v}
      </span>) },
    { key: "policies", label: "Documents", render: (v) => <StatusPill s={v} kind="doc" /> },
    { key: "banner", label: "Cookie banner", render: (v) => <StatusPill s={v} kind="banner" /> },
    { key: "consents", label: "Consents", align: "right", mono: true },
  ];
  return (
    <div className="app-view">
      <div className="app-view__head">
        <div>
          <h1 className="app-h1">Good morning, Élise</h1>
          <p className="app-sub">Here's the compliance status across all your sites.</p>
        </div>
        <Button variant="primary" size="sm" iconLeft={<Icon d={ICONS.plus} size={15} />} onClick={() => nav("app", "sites")}>Add a site</Button>
      </div>

      <div className="relief">
        <span className="relief__badge"><Icon d={ICONS.shieldCheck} size={28} /></span>
        <div>
          <h2 className="relief__t">{compliant} of {sites.length} sites fully compliant</h2>
          <p className="relief__s">{compliant === sites.length ? "Everything is up to date. You're in good shape." : "A few items need review — open a site to see what's outstanding."}</p>
        </div>
        <div className="relief__meta">Last full scan<br /><strong style={{ color: "var(--fg)", fontSize: 13 }}>2 hours ago</strong></div>
      </div>

      <div className="app-stats">
        <Stat label="Active sites" value={String(sum ? sum.sites : sites.length)} delta={api.ready ? "" : "+1 this month"} trend="up" bordered />
        <Stat label="Documents published" value={String(sum ? sum.documents : 11)} delta="all languages" trend="flat" bordered />
        <Stat label="Consents captured" value={fmtNum(sum ? sum.consents : 35273)} delta={api.ready ? "" : "+18.4%"} trend="up" bordered />
        <Stat label="Consent rate" value={(sum ? (sum.consentRate == null ? "—" : Math.round(sum.consentRate * 100) + "%") : "71%")} delta={api.ready ? "" : "+4.2%"} trend="up" bordered />
      </div>

      <div className="app-grid2">
        <Card>
          <CardBody style={{ paddingBottom: 8 }}>
            <div className="app-card-head"><span className="app-card-title">Sites at a glance</span><Button variant="ghost" size="sm" onClick={() => nav("app", "sites")}>Manage all</Button></div>
          </CardBody>
          <Table columns={cols} rows={sites} />
        </Card>
        <Card>
          <CardBody>
            <div className="app-card-head"><span className="app-card-title">Consents over time</span><Badge tone="good" dot>Live</Badge></div>
            <LineChart data={[210, 260, 240, 320, 300, 390, 420, 480, 460, 540, 520, 610]} height={150} dots />
            <div style={{ display: "flex", flexDirection: "column", gap: 12, marginTop: 18, paddingTop: 16, borderTop: "1px solid var(--hairline)" }}>
              {[["Banner shown", "49,680"], ["Accepted all", "24,110"], ["Rejected / custom", "11,163"]].map(([l, v]) => (
                <div key={l} style={{ display: "flex", justifyContent: "space-between", fontSize: 13 }}>
                  <span style={{ color: "var(--fg-muted)" }}>{l}</span>
                  <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600 }}>{v}</span>
                </div>
              ))}
            </div>
          </CardBody>
        </Card>
      </div>

      <div className="app-grid2" style={{ marginTop: 14 }}>
        <BadgeReferralCard nav={nav} />
        <ConsentLogCard />
      </div>
    </div>
  );
}

/* Growth: the "by MostlyCookie" badge as an attributable referral channel */
function BadgeReferralCard({ nav }) {
  const funnel = [["Badge impressions", "1.24M", "across 3 sites"], ["Badge clicks", "3,180", "0.26% CTR"], ["Signups attributed", "214", "ref=mc_badge"]];
  return (
    <Card>
      <CardBody>
        <div className="app-card-head">
          <span className="app-card-title"><Icon d={ICONS.bolt} size={14} style={{ verticalAlign: "-2px", color: "var(--accent)" }} /> Badge referrals</span>
          <Badge tone="accent" dot>Top channel</Badge>
        </div>
        <div className="badge-funnel">
          {funnel.map(([l, v, s], i) => (
            <React.Fragment key={l}>
              {i > 0 && <span className="badge-funnel__arrow"><Icon d={ICONS.arrow} size={13} /></span>}
              <div className="badge-funnel__step">
                <div className="badge-funnel__v">{v}</div>
                <div className="badge-funnel__l">{l}</div>
                <div className="badge-funnel__s">{s}</div>
              </div>
            </React.Fragment>
          ))}
        </div>
        <div className="badge-attrib">
          <Icon d={ICONS.trend} size={15} />
          <span><b style={{ color: "var(--fg)" }}>Your biggest organic channel.</b> Every banner badge links with <code className="bb-inline-code">?ref=mc_badge</code>, attributing signups back to the site that referred them.</span>
        </div>
      </CardBody>
    </Card>
  );
}

/* Consent log as a streamable endpoint — API + webhook, not only CSV */
function ConsentLogCard() {
  const [copied, setCopied] = React.useState(false);
  const copy = () => { setCopied(true); setTimeout(() => setCopied(false), 1500); };
  return (
    <Card>
      <CardBody>
        <div className="app-card-head">
          <span className="app-card-title"><Icon d={ICONS.radio} size={14} style={{ verticalAlign: "-2px", color: "var(--good)" }} /> Consent log delivery</span>
          <Badge tone="good" dot>Streaming</Badge>
        </div>
        <div className="log-endpoint">
          <span className="log-endpoint__method">GET</span>
          <code className="log-endpoint__url">api.mostlyprivacy.com/v1/consent/stream</code>
          <Button variant="ghost" size="sm" iconLeft={<Icon d={copied ? ICONS.check : ICONS.copy} size={13} />} onClick={copy}>{copied ? "Copied" : "Copy"}</Button>
        </div>
        <div className="log-delivery">
          {[[ICONS.radio, "Webhook", "Real-time POST on every choice", "good"], [ICONS.code, "REST API", "Query & replay the full log", "accent"], [ICONS.download, "CSV export", "On-demand audit download", "neutral"]].map(([d, t, s, tone]) => (
            <div className="log-delivery__row" key={t}>
              <span className={"log-delivery__ic log-delivery__ic--" + tone}><Icon d={d} size={14} /></span>
              <div><div className="log-delivery__t">{t}</div><div className="log-delivery__s">{s}</div></div>
              <Icon d={ICONS.check} size={14} />
            </div>
          ))}
        </div>
        <div style={{ display: "flex", justifyContent: "space-between", alignItems: "center", marginTop: 14, paddingTop: 14, borderTop: "1px solid var(--hairline)", fontSize: 12.5 }}>
          <span style={{ color: "var(--fg-muted)" }}>Consent rate (server-side metric)</span>
          <span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, color: "var(--good)" }}>71% accept</span>
        </div>
      </CardBody>
    </Card>
  );
}

function Sites({ nav }) {
  const [sites, setSites] = React.useState(SITES);
  const [busy, setBusy] = React.useState(false);
  const [err, setErr] = React.useState("");
  React.useEffect(() => {
    let ok = true;
    api.listSites().then((rows) => { if (ok && Array.isArray(rows)) setSites(rows.map(toRow)); }).catch(() => {});
    return () => { ok = false; };
  }, []);
  async function addSite() {
    setErr("");
    const domain = (window.prompt("Add a site — enter its domain (e.g. example.com):") || "").trim();
    if (!domain) return;
    setBusy(true);
    try {
      const s = await api.createSite(domain);
      setSites((prev) => [toRow(s), ...prev]);
    } catch (e) {
      setErr((e && e.message) || "Could not add the site.");
    } finally { setBusy(false); }
  }
  return (
    <div className="app-view">
      <div className="app-view__head">
        <div>
          <h1 className="app-h1">Sites</h1>
          <p className="app-sub">Every site on your account — no per-domain fees.</p>
        </div>
        <Button variant="primary" size="sm" disabled={busy} iconLeft={<Icon d={ICONS.plus} size={15} />} onClick={addSite}>{busy ? "Adding…" : "Add a site"}</Button>
      </div>

      <div className="wz-transparent" style={{ marginTop: 0, marginBottom: 18 }}>
        <Icon d={ICONS.shieldCheck} size={18} />
        <span><b style={{ color: "var(--fg)" }}>{sites.length} site{sites.length === 1 ? "" : "s"} on your account.</b> Every one gets the same documents, banner and all 30+ languages — no per-domain fees.</span>
      </div>
      {err && <div style={{ color: "var(--danger, #b3261e)", fontSize: 13, marginBottom: 12 }}>{err}</div>}

      <Card>
        <CardBody style={{ padding: 0 }}>
          {sites.map((s) => (
            <div className="site-card" key={s.id}>
              <div className="site-card__name">
                <span className="site-card__fav">{s.fav}</span>
                <div>
                  <div className="site-card__dom">{s.dom}</div>
                  <div className="site-card__url">{s.region} · scanned {s.scan}</div>
                </div>
              </div>
              <div><div className="site-card__cell-l">Documents</div><StatusPill s={s.policies} kind="doc" /></div>
              <div><div className="site-card__cell-l">Cookie banner</div><StatusPill s={s.banner} kind="banner" /></div>
              <div><div className="site-card__cell-l">Consents</div><span style={{ fontFamily: "var(--font-mono)", fontWeight: 600, fontSize: 13 }}>{s.consents}</span></div>
              <div className="site-card__actions">
                <Button variant="secondary" size="sm" onClick={() => nav("app", "banner", s.id)}>Edit banner</Button>
                <Button variant="ghost" size="sm" onClick={() => nav("app", "documents")}>Docs</Button>
                <Button variant="ghost" size="sm" iconLeft={<Icon d={ICONS.radio} size={14} />} onClick={() => nav("app", "consentlog", s.id)}>Consent log</Button>
              </div>
            </div>
          ))}
        </CardBody>
      </Card>
    </div>
  );
}

function Settings() {
  const [tab, setTab] = React.useState("account");
  const [whitelabel, setWhitelabel] = React.useState(false);
  return (
    <div className="app-view">
      <div className="app-view__head"><div><h1 className="app-h1">Settings</h1><p className="app-sub">Manage your account, plan and branding.</p></div></div>
      <div style={{ marginBottom: 22 }}>
        <Tabs value={tab} onChange={setTab} items={[
          { value: "account", label: "Account" }, { value: "billing", label: "Billing & plan" },
          { value: "branding", label: "Branding" }, { value: "team", label: "Team" }]} />
      </div>

      {tab === "account" && (
        <Card><CardBody style={{ display: "flex", flexDirection: "column", gap: 16, maxWidth: 460 }}>
          <Field label="Full name"><Input defaultValue="Élise Moreau" /></Field>
          <Field label="Email"><Input defaultValue="elise@cafe-lumiere.fr" /></Field>
          <Field label="Default language"><Select options={[{ value: "fr", label: "Français" }, { value: "en", label: "English" }, { value: "de", label: "Deutsch" }]} defaultValue="fr" /></Field>
          <div><Button variant="primary" size="sm">Save changes</Button></div>
        </CardBody></Card>
      )}

      {tab === "billing" && (
        <Card><CardBody>
          <div className="relief" style={{ margin: "0 0 18px" }}>
            <span className="relief__badge"><Icon d={ICONS.card} size={24} /></span>
            <div><div className="relief__t">Pro · $35 / month</div><div className="relief__s">Up to 10 sites · all languages · white-label available on Agency.</div></div>
            <div className="relief__meta"><Button variant="secondary" size="sm">Change plan</Button></div>
          </div>
          <div style={{ fontSize: 13, color: "var(--fg-muted)" }}>Next invoice 1 Jul 2026 · Visa ending 4242.</div>
        </CardBody></Card>
      )}

      {tab === "branding" && (
        <Card><CardBody style={{ display: "flex", flexDirection: "column", gap: 16, maxWidth: 480 }}>
          <div className="wz-toggle-card is-on" style={{ cursor: "default" }}>
            <div><div className="wz-toggle-card__t">White-label the banner</div><div className="wz-toggle-card__s">Remove the “by MostlyCookie” badge · Agency plan</div></div>
            <span className="wz-toggle-card__sw"><Switch checked={whitelabel} onChange={() => setWhitelabel(!whitelabel)} /></span>
          </div>
          <Field label="Upload your logo" hint="Shown on hosted policy pages."><Input placeholder="logo.svg" icon={<Icon d={ICONS.download} size={15} />} /></Field>
          <Field label="Brand accent"><Input defaultValue="#159a8c" /></Field>
        </CardBody></Card>
      )}

      {tab === "team" && (
        <Card><CardBody style={{ padding: 0 }}>
          {[["Élise Moreau", "elise@cafe-lumiere.fr", "Owner"], ["Marco Bianchi", "marco@studio-aria.it", "Editor"], ["Lena Vogt", "lena@boulangerie-no7.de", "Viewer"]].map(([n, e, r]) => (
            <div className="site-card" key={e} style={{ gridTemplateColumns: "1fr auto auto" }}>
              <div className="site-card__name"><Avatar name={n} size="sm" /><div><div className="site-card__dom" style={{ fontSize: 13 }}>{n}</div><div className="site-card__url">{e}</div></div></div>
              <Badge tone={r === "Owner" ? "accent" : "neutral"}>{r}</Badge>
              <Button variant="ghost" size="sm">Manage</Button>
            </div>
          ))}
          <div style={{ padding: 14 }}><Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.plus} size={15} />}>Invite teammate</Button></div>
        </CardBody></Card>
      )}
    </div>
  );
}

// Consent log view — the audit trail + consent-rate metric (queryConsentLog).
function ConsentLog({ nav, initial }) {
  const [data, setData] = React.useState(null);
  const [err, setErr] = React.useState("");
  const siteId = initial;
  React.useEffect(() => {
    let ok = true;
    const fallback = () => { if (ok) setData(DEMO_LOG); };
    if (!api.ready || !siteId) { fallback(); return; }
    api.queryConsentLog(siteId, { limit: 100 })
      .then((r) => { if (ok) setData(r && r.entries !== undefined ? r : DEMO_LOG); })
      .catch((e) => { if (ok) { setErr((e && e.message) || ""); setData(DEMO_LOG); } });
    return () => { ok = false; };
  }, [siteId]);

  const s = (data && data.stats) || { total: 0, accept: 0, reject: 0, custom: 0, consentRate: null };
  const rate = s.consentRate == null ? "—" : Math.round(s.consentRate * 100) + "%";
  const cols = [
    { key: "decision", label: "Decision", render: (v) => <Badge tone={v === "reject" ? "warn" : "good"} dot>{v === "accept" ? "Accepted" : v === "reject" ? "Rejected" : "Custom"}</Badge> },
    { key: "geo", label: "Region", render: (v) => (v && v.country) || "—" },
    { key: "lang", label: "Language", render: (v) => (v || "—").toUpperCase() },
    { key: "ts", label: "When", align: "right", render: (v) => v ? new Date(v).toLocaleString("en-GB", { day: "2-digit", month: "short", hour: "2-digit", minute: "2-digit" }) : "—" },
  ];
  return (
    <div className="app-view">
      <div className="app-view__head">
        <div>
          <button className="wz-back" onClick={() => nav("app", "sites")}><Icon d={ICONS.arrow} size={14} style={{ transform: "rotate(180deg)" }} /> Sites</button>
          <h1 className="app-h1" style={{ marginTop: 8 }}>Consent log</h1>
          <p className="app-sub">Every consent decision — your audit trail, exportable any time.</p>
        </div>
        <Button variant="secondary" size="sm" iconLeft={<Icon d={ICONS.download} size={14} />}>Export CSV</Button>
      </div>
      {err && <div style={{ color: "var(--fg-subtle)", fontSize: 12.5, marginBottom: 10 }}>Showing sample data — {err}</div>}
      <div className="app-stats" style={{ marginBottom: 18 }}>
        <Stat label="Total decisions" value={fmtNum(s.total)} bordered />
        <Stat label="Accepted" value={fmtNum((s.accept || 0) + (s.custom || 0))} bordered />
        <Stat label="Rejected" value={fmtNum(s.reject)} bordered />
        <Stat label="Consent rate" value={rate} bordered />
      </div>
      <Card>
        <CardBody style={{ paddingBottom: 6 }}>
          <div className="app-card-head"><span className="app-card-title">Recent decisions</span><Badge tone="good" dot>Live</Badge></div>
        </CardBody>
        {data ? <Table columns={cols} rows={data.entries || []} /> : <CardBody><span style={{ color: "var(--fg-subtle)" }}>Loading…</span></CardBody>}
      </Card>
    </div>
  );
}

Object.assign(window.MP, { Overview, Sites, Settings, ConsentLog });
})();
