// dashboard-competitor-intel-phase-5.js — extracted verbatim from dashboard.js (pure move).

// ─── Competitor Intel (Phase 5) ──────────────────────────────────

const PLATFORM_ICONS = { linkedin: "💼", twitter: "🐦", telegram: "💬" };
let competitorsTab = "manual";

async function renderCompetitors() {
  showLoading("Loading competitors…");
  const data = await api("competitors-list").catch((err) => ({ error: err.message }));
  if (data?.error) {
    showError(data.error, renderCompetitors);
    return;
  }

  const stats = data.stats || { total: 0, totalContacts: 0, activeRoutines: 0 };
  const manual = data.manual || [];
  const auto = data.auto || [];

  const header = el("div", { class: "page-header" }, [
    el("div", {}, [
      el("div", { class: "page-title" }, "Competitor Intel"),
      el(
        "div",
        { class: "page-subtitle" },
        "Track competitors, harvest their audiences, run automated routines",
      ),
    ]),
    el("div", { class: "row", style: "gap: 8px;" }, [
      el(
        "button",
        {
          class: "btn btn-secondary btn-tiny",
          type: "button",
          onclick: async () => {
            const r = await api("competitors-scan-all");
            if (r?.error) toast(r.error, "err");
            else {
              toast(`Queued ${r.queued || 0} for rescan`, "ok");
              renderCompetitors();
            }
          },
        },
        "↻ Rescan all",
      ),
      el(
        "button",
        { class: "btn btn-primary btn-tiny", type: "button", onclick: openAddCompetitorDrawer },
        "+ Add competitor",
      ),
    ]),
  ]);

  const statsCard = el("div", { class: "card" }, [
    el("div", { class: "stats-grid" }, [
      statCard("Tracked", stats.total, "active competitors"),
      statCard("Contacts imported", fmtNum(stats.totalContacts || 0), "via discovery"),
      statCard("Active routines", stats.activeRoutines, "running"),
      statCard("Auto-discovered", auto.length, "from routines"),
    ]),
  ]);

  const tabs = el("div", { class: "tabs" }, [
    tabBtn("manual", `Manual (${manual.length})`, () => {
      competitorsTab = "manual";
      renderCompetitors();
    }),
    tabBtn("auto", `Auto-discovered (${auto.length})`, () => {
      competitorsTab = "auto";
      renderCompetitors();
    }),
  ]);

  setTimeout(() => {
    $$(".tab").forEach((t) =>
      t.classList.toggle("active", t.getAttribute("data-tab") === competitorsTab),
    );
  }, 0);

  const list = competitorsTab === "manual" ? manual : auto;
  const body =
    list.length === 0
      ? el("div", { class: "empty-state", style: "padding: 32px;" }, [
          el("div", { class: "empty-state-icon" }, competitorsTab === "manual" ? "🕵" : "🤖"),
          el(
            "div",
            { class: "empty-state-title" },
            competitorsTab === "manual"
              ? "No competitors tracked yet"
              : "Nothing auto-discovered yet",
          ),
          el(
            "div",
            { class: "empty-state-hint" },
            competitorsTab === "manual"
              ? "Add a LinkedIn company URL, t.me/group link, or X handle to start tracking."
              : "Auto-discovered competitors come from routines like Audience Steal — they show up here as the engine surfaces new targets.",
          ),
          competitorsTab === "manual"
            ? el(
                "button",
                {
                  class: "btn btn-primary",
                  style: "margin-top: 16px;",
                  type: "button",
                  onclick: openAddCompetitorDrawer,
                },
                "+ Add your first competitor",
              )
            : null,
        ])
      : el("div", {}, list.map(renderCompetitorCard));

  setContentNode(el("div", {}, [header, _discoverHubNav("competitors"), statsCard, tabs, body]));
}

function renderCompetitorCard(c) {
  const platformIcon = PLATFORM_ICONS[c.platform] || "❓";
  const discoveryBadge =
    c.discoveryStatus === "running"
      ? el("span", { class: "badge badge-yellow" }, "Scanning…")
      : c.discoveryStatus === "failed"
        ? el("span", { class: "badge badge-red" }, "Scan failed")
        : c.lastDiscoveryAt
          ? el("span", { class: "badge badge-green" }, `Scanned ${fmtDate(c.lastDiscoveryAt)}`)
          : el("span", { class: "badge badge-gray" }, "Pending first scan");

  return el(
    "div",
    {
      class: "card",
      style: "padding: 14px; margin-bottom: 8px; cursor: pointer;",
      onclick: (ev) => {
        if (ev.target.closest("button")) return;
        openCompetitorDetail(c.id);
      },
    },
    [
      el("div", { style: "display: flex; gap: 12px; align-items: flex-start;" }, [
        el("div", { style: "font-size: 28px; flex-shrink: 0;" }, platformIcon),
        el("div", { style: "flex: 1; min-width: 0;" }, [
          el("div", { class: "primary-cell", style: "font-size: 14px;" }, [
            c.displayName || c.identifier,
            el(
              "span",
              { class: "muted small", style: "margin-left: 8px;" },
              `· ${c.platform}/${c.identifier}`,
            ),
          ]),
          el(
            "div",
            { class: "muted", style: "font-size: 12px; margin-top: 2px;" },
            [
              c.followerCount != null ? `${fmtNum(c.followerCount)} followers · ` : "",
              c.employeeCount != null ? `${fmtNum(c.employeeCount)} employees · ` : "",
              c.memberCount != null ? `${fmtNum(c.memberCount)} members · ` : "",
              `${fmtNum(c.contactsImported || 0)} contacts imported`,
            ]
              .filter(Boolean)
              .join(""),
          ),
          el(
            "div",
            {
              style:
                "margin-top: 6px; display: flex; gap: 6px; align-items: center; flex-wrap: wrap;",
            },
            [
              discoveryBadge,
              c.autoSource
                ? el("span", { class: "badge badge-blue" }, `Auto: ${c.autoSource}`)
                : null,
              c.discoveryError
                ? el("span", { class: "muted small", title: c.discoveryError }, "ℹ Error info")
                : null,
            ],
          ),
        ]),
        el("div", { style: "flex-shrink: 0; display: flex; gap: 4px;" }, [
          el(
            "button",
            {
              class: "btn btn-tiny btn-secondary",
              type: "button",
              onclick: async (ev) => {
                ev.stopPropagation();
                await withProgress(ev.currentTarget, async () => {
                  const r = await api("competitor-scan", { id: c.id });
                  if (r?.error) toast(r.error, "err");
                  else {
                    toast("Queued for rescan", "ok");
                    renderCompetitors();
                  }
                });
              },
            },
            "↻",
          ),
        ]),
      ]),
    ],
  );
}

function openAddCompetitorDrawer() {
  let input = "";
  const body = el("div", { class: "drawer-body" }, [
    el(
      "div",
      { class: "muted", style: "font-size: 13px; margin-bottom: 12px;" },
      "Paste a competitor URL or handle. Supported:",
    ),
    el(
      "ul",
      {
        class: "muted",
        style: "font-size: 12px; padding-left: 20px; margin-bottom: 16px; line-height: 1.7;",
      },
      [
        el("li", {}, [el("code", {}, "linkedin.com/company/<slug>"), " — LinkedIn company"]),
        el("li", {}, [el("code", {}, "x.com/<handle>"), " — X / Twitter account"]),
        el("li", {}, [el("code", {}, "@handle"), " — bare X handle"]),
        el("li", {}, [el("code", {}, "t.me/<group>"), " — Telegram group/channel"]),
      ],
    ),
    el("div", { class: "wizard-label" }, "URL or handle"),
    el("input", {
      class: "wizard-input",
      placeholder: "https://linkedin.com/company/competitorco",
      oninput: (e) => {
        input = e.target.value.trim();
      },
    }),
    el(
      "div",
      { class: "muted small", style: "margin-top: 8px;" },
      "We'll auto-activate the Intelligence Gather routine — it scans the audience and imports new contacts to your CRM. No outreach until you enable an action routine.",
    ),
    el("div", { style: "display: flex; gap: 8px; margin-top: 16px;" }, [
      el(
        "button",
        {
          class: "btn btn-primary",
          type: "button",
          onclick: async (ev) => {
            if (!input) {
              toast("Enter a URL or handle", "err");
              return;
            }
            await withProgress(ev.currentTarget, async () => {
              const r = await api("competitors-add", { body: { input } });
              if (r?.error) toast(r.error, "err");
              else {
                toast("Added — first scan queued", "ok");
                closeDrawer();
                renderCompetitors();
              }
            });
          },
        },
        "Add competitor",
      ),
      el("button", { class: "btn btn-secondary", type: "button", onclick: closeDrawer }, "Cancel"),
    ]),
  ]);
  openDrawer("Add competitor", body);
}

async function openCompetitorDetail(id) {
  openDrawer("Competitor", el("div", { class: "loading" }, "Loading…"));
  const data = await api("competitor-detail", { id }).catch((err) => ({ error: err.message }));
  if (data?.error) {
    openDrawer("Competitor", el("div", { class: "muted" }, `Error: ${data.error}`));
    return;
  }
  const c = data.competitor;
  const routines = data.routines || [];
  const templates = data.templates || [];
  const recentContacts = data.recentContacts || [];

  const platformIcon = PLATFORM_ICONS[c.platform] || "❓";

  const body = el("div", { class: "drawer-body" }, [
    el("div", { style: "display: flex; gap: 12px; align-items: center; margin-bottom: 16px;" }, [
      el("div", { style: "font-size: 36px;" }, platformIcon),
      el("div", { style: "flex: 1;" }, [
        el("div", { style: "font-size: 16px; font-weight: 600;" }, c.displayName),
        el("div", { class: "muted small mono" }, `${c.platform} · ${c.identifier}`),
      ]),
    ]),

    // Stats
    el("div", { class: "card" }, [
      el(
        "div",
        { class: "stats-grid" },
        [
          c.followerCount != null ? statCard("Followers", fmtNum(c.followerCount), "") : null,
          c.employeeCount != null ? statCard("Employees", fmtNum(c.employeeCount), "") : null,
          c.memberCount != null ? statCard("Members", fmtNum(c.memberCount), "") : null,
          statCard(
            "Contacts imported",
            fmtNum(c.contactsImported || 0),
            `${fmtNum(c.contactsDiscovered || 0)} discovered`,
          ),
        ].filter(Boolean),
      ),
    ]),

    // Active routines
    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, `Routines (${routines.length})`),
      routines.length === 0
        ? el("div", { class: "muted small" }, "No routines yet. Add one below.")
        : el(
            "div",
            {},
            routines.map((r) =>
              el(
                "div",
                {
                  class: "channel-row",
                  style:
                    "padding: 8px 10px; border-bottom: 1px solid var(--border); display: flex; align-items: center; gap: 10px;",
                },
                [
                  el("span", { style: "font-size: 18px;" }, r.icon || "•"),
                  el("div", { style: "flex: 1;" }, [
                    el("div", { class: "primary-cell", style: "font-size: 13px;" }, r.name),
                    el(
                      "div",
                      { class: "muted small" },
                      [
                        r.runCount ? `${r.runCount} runs` : "Pending first run",
                        r.lastRunAt ? ` · last ${fmtDate(r.lastRunAt)}` : "",
                      ].join(""),
                    ),
                  ]),
                  el(
                    "button",
                    {
                      class: `btn btn-tiny ${r.status === "active" ? "btn-primary" : "btn-secondary"}`,
                      type: "button",
                      onclick: async (ev) => {
                        await withProgress(ev.currentTarget, async () => {
                          const next = r.status === "active" ? "paused" : "active";
                          const resp = await api("competitor-routine-toggle", {
                            routineId: r.id,
                            body: { status: next },
                          });
                          if (resp?.error) toast(resp.error, "err");
                          else {
                            toast(next === "active" ? "Resumed" : "Paused", "ok");
                            openCompetitorDetail(id);
                          }
                        });
                      },
                    },
                    r.status === "active" ? "● Active" : r.status,
                  ),
                ],
              ),
            ),
          ),
    ]),

    // Add routine
    templates.length > 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, "Activate a routine"),
          el(
            "div",
            { class: "muted small", style: "margin-bottom: 12px;" },
            "Each routine runs in the background. Read the description carefully — some send DMs/comments, others just gather data.",
          ),
          el(
            "div",
            { class: "routine-template-grid" },
            templates
              .filter((t) => !routines.find((r) => r.template === t.id))
              .map((t) =>
                el(
                  "button",
                  {
                    class: "routine-template-card",
                    type: "button",
                    onclick: async (ev) => {
                      if (!confirm(`Activate "${t.name}"?\n\n${t.desc}`)) return;
                      await withProgress(ev.currentTarget, async () => {
                        const resp = await api("competitor-routine-add", {
                          id,
                          body: { template: t.id },
                        });
                        if (resp?.error) toast(resp.error, "err");
                        else {
                          toast("Activated", "ok");
                          openCompetitorDetail(id);
                        }
                      });
                    },
                  },
                  [
                    el("div", { class: "routine-template-card-icon" }, t.icon),
                    el("div", { class: "routine-template-card-body" }, [
                      el("div", { class: "routine-template-card-title" }, t.name),
                      el("div", { class: "routine-template-card-desc" }, t.desc),
                    ]),
                    el("div", { class: "routine-template-card-cta" }, "+"),
                  ],
                ),
              ),
          ),
        ])
      : null,

    // Recent contacts (best-effort — table may be empty)
    recentContacts.length > 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, `Recent imported contacts (${recentContacts.length})`),
          ...recentContacts.slice(0, 10).map((rc) =>
            el(
              "div",
              {
                class: "channel-row",
                style: "padding: 6px 8px; border-bottom: 1px solid var(--border);",
              },
              [
                el("div", { style: "flex: 1; min-width: 0;" }, [
                  el(
                    "div",
                    { class: "primary-cell", style: "font-size: 12px;" },
                    rc.display_name || "—",
                  ),
                  el(
                    "div",
                    { class: "muted small" },
                    [rc.role, rc.company].filter(Boolean).join(" @ ") ||
                      (rc.telegram_username ? `@${rc.telegram_username}` : ""),
                  ),
                ]),
                el("div", { class: "muted small" }, fmtDate(rc.first_seen_at)),
              ],
            ),
          ),
        ])
      : null,

    // Action bar
    el("div", { style: "display: flex; gap: 8px; margin-top: 16px;" }, [
      el(
        "button",
        {
          class: "btn btn-tiny btn-primary",
          type: "button",
          onclick: async (ev) => {
            await withProgress(ev.currentTarget, async () => {
              const r = await api("competitor-scan", { id });
              if (r?.error) toast(r.error, "err");
              else {
                toast("Queued", "ok");
                openCompetitorDetail(id);
              }
            });
          },
        },
        "↻ Rescan now",
      ),
      el(
        "button",
        {
          class: "btn btn-tiny btn-danger",
          type: "button",
          onclick: async () => {
            if (!confirm("Archive this competitor? You can re-add them later.")) return;
            const r = await api("competitor-archive", { id });
            if (r?.error) toast(r.error, "err");
            else {
              toast("Archived", "ok");
              closeDrawer();
              renderCompetitors();
            }
          },
        },
        "Archive",
      ),
    ]),
  ]);

  openDrawer(c.displayName || "Competitor", body);
}
