// dashboard-clients-per-customer-segmentat.js — extracted verbatim from dashboard.js (pure move).

// ── Clients: per-customer segmentation ──────────────────────────
// A "client" is a customer the agency operates for. Accounts can serve many
// clients, so the attribution key is the WORK (campaigns tagged with client_id),
// while account_clients records which senders a client uses. See clients.js.

const CLIENT_PLATFORMS = [
  {
    key: "twitter",
    field: "twitter",
    icon: "𝕏",
    label: (a) => a.display_name || a.account_identifier || `#${a.id}`,
  },
  { key: "linkedin", field: "linkedin", icon: "💼", label: (a) => a.identifier || `#${a.id}` },
  {
    key: "telegram",
    field: "telegram",
    icon: "✈️",
    label: (a) => a.label || a.phone || `#${a.id}`,
  },
  {
    key: "email",
    field: "smtp",
    icon: "📧",
    label: (a) => a.display_name || a.email || `#${a.id}`,
  },
];

// Flatten the /api/accounts/all payload into [{platform,id,label,icon}].
function flattenClientAccounts(res) {
  const out = [];
  for (const p of CLIENT_PLATFORMS) {
    for (const a of res?.[p.field] || [])
      out.push({ platform: p.key, id: a.id, label: p.label(a), icon: p.icon });
  }
  return out;
}

async function renderClients() {
  showLoading("Loading clients…");
  const [clientsRes, accountsRes] = await Promise.all([
    api("clients-list").catch((e) => ({ error: e?.message || "unreachable" })),
    api("accounts-all").catch(() => ({})),
  ]);
  if (clientsRes?.error) {
    showError(clientsRes.error, renderClients);
    return;
  }
  const clients = Array.isArray(clientsRes?.clients) ? clientsRes.clients : [];
  const allAccounts = flattenClientAccounts(accountsRes);
  const { clientId: activeClientId } = await chrome.storage.local
    .get(["clientId"])
    .catch(() => ({}));

  const openNewClient = () => {
    const nameInput = el("input", {
      class: "input",
      type: "text",
      placeholder: "Client name (e.g. Acme Corp)",
      style: "width:100%;margin-bottom:10px;",
    });
    const colorInput = el("input", {
      type: "color",
      value: "#6366f1",
      style: "width:48px;height:34px;border:none;background:none;cursor:pointer;",
    });
    const m = openModal({
      title: "New client",
      subtitle:
        "Group the accounts and campaigns you run for this customer, then show them a report.",
      body: el("div", {}, [
        nameInput,
        el("div", { style: "display:flex;align-items:center;gap:8px;" }, [
          el("span", { class: "muted small" }, "Accent color"),
          colorInput,
        ]),
      ]),
      actions: [
        uiButton("Cancel", { onClick: () => m.close() }),
        uiButton("Create client", {
          variant: "primary",
          onClick: (ev) =>
            mutateAction(
              ev,
              "client-create",
              { body: { name: nameInput.value.trim(), color: colorInput.value } },
              {
                success: "Client created",
                failPrefix: "Could not create client",
                after: () => {
                  m.close();
                  renderClients();
                },
              },
            ),
        }),
      ],
    });
    setTimeout(() => nameInput.focus(), 30);
  };

  const openAssignAccounts = (c) => {
    const owned = new Set((c.accounts || []).map((a) => `${a.platform}:${a.account_id}`));
    const checks = [];
    const rows = CLIENT_PLATFORMS.map((p) => {
      const accts = allAccounts.filter((a) => a.platform === p.key);
      if (!accts.length) return null;
      return el("div", { style: "margin-bottom:12px;" }, [
        el(
          "div",
          {
            class: "muted small",
            style: "text-transform:uppercase;letter-spacing:0.05em;margin-bottom:6px;",
          },
          `${p.icon} ${p.key}`,
        ),
        ...accts.map((a) => {
          const cb = el("input", { type: "checkbox", style: "margin-right:8px;" });
          if (owned.has(`${a.platform}:${a.id}`)) cb.checked = true;
          checks.push({ cb, platform: a.platform, id: a.id });
          return el(
            "label",
            {
              style:
                "display:flex;align-items:center;padding:5px 0;cursor:pointer;font-size:13px;color:#d1d5db;",
            },
            [cb, el("span", {}, a.label)],
          );
        }),
      ]);
    }).filter(Boolean);
    const body = rows.length
      ? el("div", {}, rows)
      : el(
          "div",
          { class: "muted", style: "font-size:13px;" },
          "No connected accounts yet. Connect accounts first, then assign them here.",
        );
    const m = openModal({
      title: `Accounts for ${c.name}`,
      subtitle:
        "Which of your connected accounts do work for this customer? (An account can serve several customers.)",
      body,
      actions: [
        uiButton("Cancel", { onClick: () => m.close() }),
        uiButton("Save", {
          variant: "primary",
          onClick: (ev) => {
            const accounts = checks
              .filter((x) => x.cb.checked)
              .map((x) => ({ platform: x.platform, account_id: x.id }));
            return mutateAction(
              ev,
              "client-set-accounts",
              { id: c.id, body: { accounts } },
              {
                success: "Accounts updated",
                failPrefix: "Could not save",
                after: () => {
                  m.close();
                  renderClients();
                },
              },
            );
          },
        }),
      ],
    });
  };

  const openRename = (c) => {
    const nameInput = el("input", {
      class: "input",
      type: "text",
      value: c.name,
      style: "width:100%;",
    });
    const m = openModal({
      title: "Rename client",
      body: nameInput,
      actions: [
        uiButton("Cancel", { onClick: () => m.close() }),
        uiButton("Save", {
          variant: "primary",
          onClick: (ev) =>
            mutateAction(
              ev,
              "client-update",
              { id: c.id, body: { name: nameInput.value.trim() } },
              {
                success: "Renamed",
                failPrefix: "Could not rename",
                after: () => {
                  m.close();
                  renderClients();
                },
              },
            ),
        }),
      ],
    });
    setTimeout(() => nameInput.focus(), 30);
  };

  const openAssignCompanies = async (c) => {
    const res = await api("client-companies", { id: c.id }).catch((e) => ({
      error: e?.message || "unreachable",
    }));
    if (res?.error) {
      toast(`Could not load companies: ${res.error}`, "err", 5000);
      return;
    }
    const companies = Array.isArray(res?.companies) ? res.companies : [];
    if (!companies.length) {
      openModal({
        title: `Companies for ${c.name}`,
        subtitle:
          "Assigning a company attributes its outreach (and future outreach) to this client.",
        body: el(
          "div",
          { class: "muted", style: "font-size:13px;" },
          "No outreach companies yet. Once you run outreach, the companies you targeted show up here to assign.",
        ),
        actions: [],
      });
      return;
    }
    const checks = [];
    const body = el(
      "div",
      { style: "max-height:50vh;overflow:auto;" },
      companies.map((co) => {
        const cb = el("input", { type: "checkbox", style: "margin-right:8px;" });
        if (co.clientId === c.id) cb.checked = true;
        checks.push({ cb, id: co.id, was: co.clientId });
        const other =
          co.clientId && co.clientId !== c.id
            ? el(
                "span",
                { class: "badge badge-gray", style: "font-size:9px;margin-left:6px;" },
                `→ ${clientName(co.clientId)}`,
              )
            : null;
        return el(
          "label",
          {
            style:
              "display:flex;align-items:center;padding:5px 0;cursor:pointer;font-size:13px;color:#d1d5db;border-bottom:1px solid #1a1a1d;",
          },
          [cb, el("span", { style: "flex:1;" }, co.name), other].filter(Boolean),
        );
      }),
    );
    const m = openModal({
      title: `Companies for ${c.name}`,
      subtitle:
        "Pick the companies whose outreach belongs to this customer. Existing + future outreach for them attributes to this client.",
      body,
      actions: [
        uiButton("Cancel", { onClick: () => m.close() }),
        uiButton("Save", {
          variant: "primary",
          onClick: (ev) => {
            const company_ids = checks.filter((x) => x.cb.checked).map((x) => x.id);
            return mutateAction(
              ev,
              "client-set-companies",
              { id: c.id, body: { company_ids } },
              {
                success: "Companies updated — outreach re-attributed",
                failPrefix: "Could not save",
                after: () => {
                  m.close();
                  renderClients();
                },
              },
            );
          },
        }),
      ],
    });
  };

  const clientName = (id) => clients.find((x) => x.id === id)?.name || "another client";
  const KIND_LABEL = {
    email_campaign: "Email campaign",
    composition: "Workflow",
    custom_workflow: "Scheduled workflow",
    campaign_workflow: "Campaign",
  };

  const openTagWork = async (c) => {
    const res = await api("work-taggable").catch((e) => ({ error: e?.message || "unreachable" }));
    if (res?.error) {
      toast(`Could not load campaigns: ${res.error}`, "err", 5000);
      return;
    }
    const work = Array.isArray(res?.work) ? res.work : [];
    if (!work.length) {
      openModal({
        title: `Tag work for ${c.name}`,
        subtitle:
          "Tagging a campaign/workflow to a client is what makes it show up in their report.",
        body: el(
          "div",
          { class: "muted", style: "font-size:13px;" },
          "No taggable campaigns or workflows yet. Create an email campaign, workflow, or composition first.",
        ),
        actions: [],
      });
      return;
    }
    const checks = [];
    const body = el(
      "div",
      {},
      work.map((w) => {
        const cb = el("input", { type: "checkbox", style: "margin-right:8px;" });
        if (w.client_id === c.id) cb.checked = true;
        checks.push({ cb, w, was: w.client_id });
        const otherTag =
          w.client_id && w.client_id !== c.id
            ? el(
                "span",
                { class: "badge badge-gray", style: "font-size:9px;margin-left:6px;" },
                `→ ${clientName(w.client_id)}`,
              )
            : null;
        return el(
          "label",
          {
            style:
              "display:flex;align-items:center;padding:6px 0;cursor:pointer;font-size:13px;color:#d1d5db;border-bottom:1px solid #1a1a1d;",
          },
          [
            cb,
            el(
              "span",
              { style: "flex:1;" },
              [
                el("span", {}, w.name),
                el(
                  "span",
                  { class: "muted small", style: "margin-left:6px;" },
                  KIND_LABEL[w.kind] || w.kind,
                ),
                otherTag,
              ].filter(Boolean),
            ),
          ],
        );
      }),
    );
    const m = openModal({
      title: `Tag work for ${c.name}`,
      subtitle:
        "Pick the campaigns and workflows you run for this customer. Their results feed this client's report.",
      body,
      actions: [
        uiButton("Cancel", { onClick: () => m.close() }),
        uiButton("Save", {
          variant: "primary",
          onClick: (ev) =>
            withProgress(ev.currentTarget, async () => {
              let changed = 0,
                failed = 0;
              for (const { cb, w, was } of checks) {
                const want = cb.checked ? c.id : was === c.id ? null : undefined;
                if (want === undefined) continue; // unrelated to this client — leave as-is
                if (want === was) continue; // no change
                const r = await api("work-tag-client", {
                  kind: w.kind,
                  workId: w.id,
                  body: { client_id: want },
                }).catch(() => ({ error: "x" }));
                if (r?.error) failed++;
                else changed++;
              }
              if (failed)
                toast(`${changed} updated, ${failed} failed`, failed ? "err" : "ok", 5000);
              else toast(`${changed} item${changed === 1 ? "" : "s"} tagged`, "ok");
              m.close();
              renderClients();
            }),
        }),
      ],
    });
  };

  const clientCard = (c) =>
    uiCard({ style: "display:flex;flex-direction:column;gap:10px;" }, [
      el("div", { style: "display:flex;align-items:center;gap:10px;" }, [
        el("span", {
          style: `width:12px;height:12px;border-radius:50%;background:${c.color || "#6366f1"};flex:none;`,
        }),
        el("div", { style: "font-size:15px;font-weight:600;color:#e5e7eb;flex:1;" }, c.name),
      ]),
      el("div", { style: "display:flex;gap:14px;font-size:12px;color:#9ca3af;" }, [
        el("span", {}, `${c.accountCount} account${c.accountCount === 1 ? "" : "s"}`),
        el("span", {}, `${c.campaignCount} campaign${c.campaignCount === 1 ? "" : "s"}`),
      ]),
      el("div", { style: "display:flex;gap:6px;flex-wrap:wrap;" }, [
        uiButton("📊 Report", {
          variant: "primary",
          size: "tiny",
          onClick: () => navigate(`client-report/${c.id}`),
        }),
        uiButton("Tag campaigns", { size: "tiny", onClick: () => openTagWork(c) }),
        uiButton("Assign companies", { size: "tiny", onClick: () => openAssignCompanies(c) }),
        uiButton("Assign accounts", { size: "tiny", onClick: () => openAssignAccounts(c) }),
        uiButton("Rename", { size: "tiny", onClick: () => openRename(c) }),
        uiButton("Delete", {
          size: "tiny",
          onClick: (ev) =>
            mutateAction(
              ev,
              "client-delete",
              { id: c.id, queryString: "?hard=1" },
              {
                confirm: `Delete client "${c.name}"? Its campaigns will be untagged (data is kept).`,
                success: "Client deleted",
                failPrefix: "Could not delete",
                after: renderClients,
              },
            ),
        }),
      ]),
    ]);

  // Active-client context: while set, NEW campaigns/workflows you create
  // auto-tag to this client (via the X-Client-Id header). Persisted in storage.
  const activeSelect = el(
    "select",
    {
      class: "input",
      style: "min-width:180px;",
      onchange: async (e) => {
        const v = e.target.value;
        if (v) await chrome.storage.local.set({ clientId: v });
        else await chrome.storage.local.remove("clientId");
        toast(
          v
            ? `New campaigns will tag to ${clients.find((c) => c.id === v)?.name || "this client"}`
            : "Auto-tagging off",
          "ok",
        );
        renderClients();
      },
    },
    [
      el("option", { value: "" }, "— none (don't auto-tag) —"),
      ...clients.map((c) => {
        const o = el("option", { value: c.id }, c.name);
        if (c.id === activeClientId) o.selected = true;
        return o;
      }),
    ],
  );
  const activeRow = clients.length
    ? el(
        "div",
        {
          style:
            "display:flex;align-items:center;gap:10px;margin-bottom:16px;padding:10px 12px;background:rgba(99,102,241,0.06);border:1px solid rgba(99,102,241,0.25);border-radius:8px;flex-wrap:wrap;",
        },
        [
          el("span", { style: "font-size:13px;color:#cbd5e1;" }, "🎯 Working on behalf of:"),
          activeSelect,
          el(
            "span",
            { class: "muted small" },
            activeClientId
              ? "new campaigns/workflows auto-tag to this client"
              : "pick a client to auto-tag the campaigns you create",
          ),
        ],
      )
    : null;

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el("div", { class: "page-title" }, "Clients"),
        el(
          "div",
          { class: "page-subtitle" },
          "Segment your accounts and campaigns per customer, then report on each.",
        ),
      ]),
      uiButton("+ New client", { variant: "primary", onClick: openNewClient }),
    ]),
    activeRow,
    clients.length === 0
      ? el("div", { class: "empty-state" }, [
          el("div", { class: "empty-state-icon" }, "👥"),
          el("div", { class: "empty-state-title" }, "No clients yet"),
          el(
            "div",
            { class: "empty-state-hint" },
            "Create a client to group the accounts and campaigns you run for that customer — then generate a report you can show them.",
          ),
          el("div", { style: "margin-top:14px;" }, [
            uiButton("+ New client", { variant: "primary", onClick: openNewClient }),
          ]),
        ])
      : el(
          "div",
          {
            style:
              "display:grid;grid-template-columns:repeat(auto-fill,minmax(260px,1fr));gap:12px;",
          },
          clients.map(clientCard),
        ),
    el(
      "div",
      {
        style:
          "margin-top:14px;padding:10px 12px;background:rgba(255,255,255,0.02);border:1px dashed #2a2a2e;border-radius:6px;font-size:11px;color:#9ca3af;line-height:1.6;",
      },
      [
        el("span", { style: "color:#cbd5e1;" }, "How attribution works: "),
        el(
          "span",
          {},
          "an account can serve several customers, so a report counts the campaigns you tag to that client. Tag a campaign from the Campaigns view, or assign its accounts here for the senders panel.",
        ),
      ],
    ),
  ]);
  setContentNode(content);
}
