// dashboard-client-report-everything-we-di.js — extracted verbatim from dashboard.js (pure move).
//
// Classic script: loaded by dashboard.html alongside dashboard.js, sharing one
// global scope. The shared helpers it calls (el, api, statCard, showError, …)
// are declared in .oxlintrc.json's chrome-extension override — oxlint cannot
// see across the script split, and every file in this bundle has the same
// dependency. tools/check-dashboard-refs.js guards that those declarations
// actually exist.

// ── Client report: "everything we did for you" ──────────────────

const _clientReport = { client: null, days: 30 };

async function renderClientReport(params = {}) {
  if (params.client) _clientReport.client = params.client;
  // Load client list for the picker (and to resolve a default selection).
  const clientsRes = await api("clients-list").catch(() => ({}));
  const clients = Array.isArray(clientsRes?.clients) ? clientsRes.clients : [];
  if (!_clientReport.client && clients.length) _clientReport.client = clients[0].id;

  showLoading("Building report…");
  const qs = `?days=${_clientReport.days}${_clientReport.client ? `&client=${encodeURIComponent(_clientReport.client)}` : ""}`;
  const data = await api("client-report", { queryString: qs }).catch((e) => ({
    error: e?.message || "unreachable",
  }));
  if (data?.error) {
    showError(data.error, () => renderClientReport());
    return;
  }

  const brand = data.brand || {};
  const h = data.headline || {};
  const fmt = (n) => (n == null ? "0" : Number(n).toLocaleString());
  const deltaBadge = (d) => {
    if (d == null) return null;
    const cls = d > 0 ? "badge-green" : d < 0 ? "badge-red" : "badge-gray";
    const arrow = d > 0 ? "↗" : d < 0 ? "↘" : "→";
    return el(
      "span",
      { class: `badge ${cls}`, style: "font-size:10px;margin-left:6px;" },
      `${arrow} ${d > 0 ? "+" : ""}${fmt(d)}`,
    );
  };

  // Picker + period controls.
  const clientSelect = el(
    "select",
    {
      class: "input",
      style: "min-width:180px;",
      onchange: (e) => {
        _clientReport.client = e.target.value;
        navigate(`client-report/${e.target.value}`);
      },
    },
    clients.map((c) => {
      const o = el("option", { value: c.id }, c.name);
      if (c.id === _clientReport.client) o.selected = true;
      return o;
    }),
  );
  const periodBtn = (days, label) =>
    el(
      "button",
      {
        type: "button",
        style: [
          "padding:5px 12px",
          "border:1px solid " + (_clientReport.days === days ? "rgba(99,102,241,0.6)" : "#2a2a2e"),
          "background:" + (_clientReport.days === days ? "rgba(99,102,241,0.18)" : "transparent"),
          "border-radius:14px",
          "color:" + (_clientReport.days === days ? "#a5b4fc" : "#cbd5e1"),
          "font-size:11px",
          "cursor:pointer",
          "font-weight:500",
        ].join(";"),
        onclick: () => {
          _clientReport.days = days;
          renderClientReport();
        },
      },
      label,
    );
  const mtdDays = new Date().getDate();

  if (clients.length === 0) {
    setContentNode(
      el("div", {}, [
        el("div", { class: "page-header" }, [
          el("div", {}, [el("div", { class: "page-title" }, "Client report")]),
        ]),
        el("div", { class: "empty-state" }, [
          el("div", { class: "empty-state-icon" }, icon("chart")),
          el("div", { class: "empty-state-title" }, "No clients yet"),
          el(
            "div",
            { class: "empty-state-hint" },
            "Create a client first, then come back to generate their report.",
          ),
          el("div", { style: "margin-top:14px;" }, [
            uiButton("Go to Clients", { variant: "primary", onClick: () => navigate("clients") }),
          ]),
        ]),
      ]),
    );
    return;
  }

  // Branded cover.
  const cover = el(
    "div",
    { class: "card", style: `border-left:4px solid ${brand.color || "#6366f1"};` },
    [
      el("div", { style: "display:flex;align-items:center;gap:14px;" }, [
        brand.logoUrl
          ? el("img", {
              src: brand.logoUrl,
              style: "height:40px;width:auto;border-radius:6px;",
              alt: "",
            })
          : null,
        el("div", { style: "flex:1;" }, [
          el(
            "div",
            { style: "font-size:20px;font-weight:700;color:#f3f4f6;" },
            brand.clientName || "Client report",
          ),
          el(
            "div",
            { class: "muted", style: "font-size:12px;" },
            `${data.period?.label || ""}${brand.agencyName ? ` · Prepared by ${brand.agencyName}` : ""}`,
          ),
        ]),
        el(
          "div",
          { class: "muted small" },
          new Date(data.generatedAt || Date.now()).toLocaleDateString(),
        ),
      ]),
    ],
  );

  // Headline hero band.
  const hero = el("div", { class: "stats-grid" }, [
    // Wording tracks the client-facing page exactly (nexus-bot client-report.js).
    // The total counts likes and follows alongside messages, so it is NOT
    // "people reached"; the direct/engagement split is shown beneath it.
    statCard(
      "Outreach actions",
      fmt(h.reached?.value),
      [
        h.reached?.direct != null
          ? el(
              "span",
              { class: "muted", style: "font-size:10px;" },
              h.reached.engagement
                ? `${fmt(h.reached.direct)} direct · ${fmt(h.reached.engagement)} engagement`
                : `${fmt(h.reached.direct)} direct outreach`,
            )
          : null,
        deltaBadge(h.reached?.delta),
      ].filter(Boolean),
    ),
    statCard(
      "People who replied",
      fmt(h.replied?.value),
      [
        el(
          "span",
          { class: "muted", style: "font-size:10px;" },
          `${h.replied?.replyRatePct || 0}% of direct outreach`,
        ),
        deltaBadge(h.replied?.delta),
      ].filter(Boolean),
    ),
    statCard("Meetings", fmt(h.meetings?.value), "Booked"),
    statCard("Deals", fmt(h.deals?.value), `${fmt(h.deals?.won)} won`),
    statCard("New contacts", fmt(h.newContacts?.value), "Added to pipeline"),
  ]);

  // Activity by channel.
  const maxChan = Math.max(1, ...(data.byChannel || []).map((c) => c.sent));
  const channels = (data.byChannel || []).length
    ? el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Activity by channel"),
        el(
          "div",
          { style: "display:flex;flex-direction:column;gap:10px;" },
          (data.byChannel || []).map((c) =>
            el("div", {}, [
              el(
                "div",
                {
                  style:
                    "display:flex;justify-content:space-between;font-size:12px;color:#d1d5db;margin-bottom:4px;",
                },
                [
                  el("span", {}, c.label),
                  el(
                    "span",
                    { class: "muted" },
                    `${fmt(c.sent)} sent · ${fmt(c.replied)} replied · ${Math.round((c.replyRate || 0) * 100)}%`,
                  ),
                ],
              ),
              el("div", { class: "channel-bar" }, [
                el("div", {
                  class: "channel-bar-fill healthy",
                  style: `width:${(c.sent / maxChan) * 100}%`,
                }),
              ]),
            ]),
          ),
        ),
      ])
    : null;

  // Per-sender breakdown.
  const maxSender = Math.max(1, ...(data.bySender || []).map((s) => s.sent));
  const senders = (data.bySender || []).length
    ? el("div", { class: "card", style: "padding:0;overflow:hidden;" }, [
        el("div", { class: "card-title", style: "padding:14px 14px 0;" }, "By sender"),
        el("table", { style: "width:100%;border-collapse:collapse;margin-top:8px;" }, [
          el(
            "tbody",
            {},
            (data.bySender || []).map((s) =>
              el("tr", { style: "border-bottom:1px solid var(--border);" }, [
                el(
                  "td",
                  { style: "padding:9px 14px;font-size:13px;color:var(--text-1);" },
                  `${s.label} · ${s.account || "—"}`,
                ),
                el("td", { style: "padding:9px 14px;text-align:right;" }, [
                  el(
                    "div",
                    { style: "display:flex;align-items:center;gap:8px;justify-content:flex-end;" },
                    [
                      el(
                        "span",
                        {
                          style:
                            "font-size:13px;color:var(--text-1);font-variant-numeric:tabular-nums;",
                        },
                        fmt(s.sent),
                      ),
                      el(
                        "div",
                        {
                          style:
                            "width:70px;height:5px;background:rgba(255,255,255,0.05);border-radius:2px;overflow:hidden;",
                        },
                        [
                          el("div", {
                            style: `width:${(s.sent / maxSender) * 100}%;height:100%;background:linear-gradient(90deg,#3b82f6,var(--green));`,
                          }),
                        ],
                      ),
                    ],
                  ),
                ]),
                el(
                  "td",
                  {
                    style: "padding:9px 14px;text-align:right;font-size:12px;color:var(--text-2);",
                  },
                  `${fmt(s.replied)} replied`,
                ),
              ]),
            ),
          ),
        ]),
      ])
    : null;

  // Outcomes pipeline.
  const p = data.pipeline || {};
  const stages = [
    { label: "Reached", value: p.reached || 0 },
    { label: "Replied", value: p.replied || 0 },
    { label: "Meetings", value: p.meetings || 0 },
    { label: "Deals", value: p.deals || 0 },
    { label: "Won", value: p.won || 0 },
  ];
  const maxStage = Math.max(1, ...stages.map((s) => s.value));
  const pipeline = el("div", { class: "card" }, [
    el("div", { class: "card-title" }, "Outcomes pipeline"),
    el(
      "div",
      { style: "display:flex;gap:8px;align-items:flex-end;" },
      stages.map((s) =>
        el("div", { style: "flex:1;text-align:center;" }, [
          el("div", { style: "font-size:18px;font-weight:700;color:var(--text-1);" }, fmt(s.value)),
          el("div", {
            style: `height:6px;border-radius:3px;margin:6px 0;background:linear-gradient(90deg,#3b82f6,var(--green));width:${Math.max(8, (s.value / maxStage) * 100)}%;margin-left:auto;margin-right:auto;`,
          }),
          el("div", { class: "muted small" }, s.label),
        ]),
      ),
    ),
  ]);

  // Goals.
  const goals = (data.goals || []).length
    ? el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Goal progress"),
        el(
          "div",
          { style: "display:flex;flex-direction:column;gap:10px;" },
          (data.goals || []).map((g) =>
            el("div", {}, [
              el(
                "div",
                {
                  style:
                    "display:flex;justify-content:space-between;font-size:12px;color:#d1d5db;margin-bottom:4px;",
                },
                [
                  el("span", {}, `${g.icon || "🎯"} ${g.name}`),
                  el("span", { class: "muted" }, `${g.pct}%`),
                ],
              ),
              el("div", { class: "channel-bar" }, [
                el("div", { class: "channel-bar-fill healthy", style: `width:${g.pct}%` }),
              ]),
            ]),
          ),
        ),
      ])
    : null;

  // Proof timeline.
  const timeline = (data.timeline || []).length
    ? el("div", { class: "card" }, [
        el("div", { class: "card-title" }, "Proof — what happened"),
        el(
          "div",
          { style: "display:flex;flex-direction:column;gap:2px;" },
          (data.timeline || []).map((t) =>
            el(
              "div",
              {
                style:
                  "display:flex;align-items:center;gap:10px;padding:7px 0;border-bottom:1px solid #1a1a1d;font-size:13px;",
              },
              [
                el("span", { class: "badge badge-green", style: "font-size:10px;" }, t.label),
                el(
                  "span",
                  { style: "color:var(--text-1);flex:1;" },
                  [t.contact, t.company ? ` (${t.company})` : ""].filter(Boolean).join(""),
                ),
                t.channel ? el("span", { class: "muted small" }, t.channel) : null,
                el("span", { class: "muted small" }, new Date(t.at).toLocaleDateString()),
              ],
            ),
          ),
        ),
      ])
    : null;

  const openShareLink = async () => {
    if (!_clientReport.client) {
      toast("Pick a client first", "err");
      return;
    }
    const body = el("div", {});
    const m = openModal({
      title: "Share this report",
      subtitle:
        "Create a read-only public link your client can open in a browser (no login). You can revoke it anytime.",
      body,
      actions: [uiButton("Close", { onClick: () => m.close() })],
    });
    const refresh = async () => {
      body.innerHTML = "";
      body.appendChild(el("div", { class: "muted small" }, "Loading links…"));
      const res = await api("client-report-shares", {
        queryString: `?client=${encodeURIComponent(_clientReport.client)}`,
      }).catch(() => ({}));
      const shares = (res?.shares || []).filter((s) => s.active);
      body.innerHTML = "";
      // Create row
      body.appendChild(
        el(
          "div",
          { style: "display:flex;gap:8px;align-items:center;margin-bottom:14px;flex-wrap:wrap;" },
          [
            el("span", { class: "muted small" }, `New link · ${_clientReport.days}d window`),
            uiButton("+ Create link", {
              variant: "primary",
              size: "tiny",
              onClick: (ev) =>
                withProgress(ev.currentTarget, async () => {
                  const r = await api("client-report-share", {
                    body: { client: _clientReport.client, days: _clientReport.days, ttlDays: 90 },
                  }).catch((e) => ({ error: e?.message }));
                  if (r?.error) {
                    toast(`Could not create link: ${r.error}`, "err", 5000);
                    return;
                  }
                  if (r?.warning) toast(r.warning, "warn", 6000);
                  await refresh();
                }),
            }),
          ],
        ),
      );
      if (!shares.length) {
        body.appendChild(el("div", { class: "muted small" }, "No active links yet."));
        return;
      }
      for (const s of shares) {
        const input = el("input", {
          class: "input",
          readonly: "",
          value: s.url || s.path || s.token,
          style: "flex:1;font-size:12px;font-family:ui-monospace,monospace;",
        });
        body.appendChild(
          el("div", { style: "display:flex;gap:6px;align-items:center;margin-bottom:8px;" }, [
            input,
            uiButton("Copy", {
              size: "tiny",
              onClick: () => {
                input.select();
                navigator.clipboard?.writeText(input.value).then(
                  () => toast("Copied", "ok"),
                  () => toast("Copy failed", "err"),
                );
              },
            }),
            uiButton("Open", {
              size: "tiny",
              onClick: () => window.open(s.url || s.path, "_blank"),
            }),
            uiButton("Revoke", {
              size: "tiny",
              onClick: (ev) =>
                mutateAction(
                  ev,
                  "client-report-share-revoke",
                  { token: s.token },
                  {
                    confirm: "Revoke this link? Anyone holding it will lose access.",
                    success: "Link revoked",
                    failPrefix: "Could not revoke",
                    after: refresh,
                  },
                ),
            }),
          ]),
        );
        body.appendChild(
          el(
            "div",
            { class: "muted small", style: "margin:-4px 0 12px;" },
            `Created ${new Date(s.createdAt).toLocaleDateString()}${s.expiresAt ? ` · expires ${new Date(s.expiresAt).toLocaleDateString()}` : ""}`,
          ),
        );
      }
    };
    await refresh();
  };

  const content = el(
    "div",
    { id: "client-report-root" },
    [
      el("div", { class: "page-header" }, [
        el("div", {}, [
          el("div", { class: "page-title" }, "Client report"),
          el(
            "div",
            { class: "page-subtitle" },
            "Everything we did — share this with your customer.",
          ),
        ]),
        el(
          "div",
          {
            class: "report-controls",
            style: "display:flex;align-items:center;gap:8px;flex-wrap:wrap;",
          },
          [
            clientSelect,
            uiButton("Share link", {
              onClick: openShareLink,
              title: "Create a public read-only link for your client",
            }),
            uiButton("⤵ Download PDF", {
              onClick: () => window.print(),
              title: "Save or print this report as a PDF",
            }),
          ],
        ),
      ]),
      el(
        "div",
        {
          class: "report-controls",
          style: "display:flex;align-items:center;gap:8px;margin-bottom:14px;flex-wrap:wrap;",
        },
        [
          el("span", { class: "muted small", style: "margin-right:4px;" }, "Period:"),
          periodBtn(mtdDays, "Month to date"),
          periodBtn(7, "7d"),
          periodBtn(30, "30d"),
          periodBtn(90, "90d"),
        ],
      ),
      cover,
      hero,
      channels,
      senders,
      pipeline,
      goals,
      timeline,
      el(
        "div",
        { class: "muted small", style: "margin-top:16px;text-align:center;" },
        brand.agencyName ? `Prepared by ${brand.agencyName}` : "Generated by Nexus",
      ),
    ].filter(Boolean),
  );
  setContentNode(content);
}
