// dashboard-vc-outreach-view.js — extracted verbatim from dashboard.js (pure move).

// ── VC Outreach view ─────────────────────────────────────────────

async function renderVcQueue() {
  showLoading();
  const data = await api("vc-queue");
  if (data?.error) {
    showError(data.error, renderVcQueue);
    return;
  }

  const sessionBanner = data.session
    ? el(
        "div",
        {
          class: "alert-card",
          style: "background: #1a2a3a; border-color: #2a4a6a; color: #60a5fa;",
        },
        [
          el("div", { class: "alert-card-title" }, "✅ CryptoRank session connected"),
          el(
            "div",
            { class: "alert-card-body" },
            `Identifier: ${escapeHtml(data.session.identifier || "—")}`,
          ),
        ],
      )
    : el("div", { class: "alert-card" }, [
        el("div", { class: "alert-card-title" }, "⚠️ CryptoRank not connected"),
        el(
          "div",
          { class: "alert-card-body" },
          "Log into cryptorank.io in Chrome. The extension auto-syncs your session within ~3 seconds. Once connected you can scrape fund team pages to find partners.",
        ),
      ]);

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el("div", { class: "page-title" }, "VC Outreach"),
        el(
          "div",
          { class: "page-subtitle" },
          "Active crypto VCs — pursue partners with tailored multi-channel outreach",
        ),
      ]),
      // Auto-queue: batch-draft N VCs at once. Each takes ~10s for AI drafts,
      // so we set a generous timeout in the user prompt. Drafts land in the
      // Outreach campaigns table as status='draft' for the user to review.
      el(
        "button",
        {
          class: "btn btn-primary",
          type: "button",
          title:
            "Auto-pick top active VCs not yet pursued, draft 3-channel outreach for each, and queue as drafts to review",
          onclick: async (ev) => {
            const countStr = prompt(
              "How many VCs to auto-queue drafts for?\n\nEach takes ~10s. 5 = 50s, 10 = 100s.",
              "5",
            );
            if (countStr == null) return;
            const count = Math.max(1, Math.min(20, parseInt(countStr, 10) || 5));
            if (
              !confirm(
                `Generate AI drafts for the top ${count} active VCs?\n\nThis will pick the best partner + reference portfolio company for each, draft LinkedIn comment + X reply + email. Drafts land in your campaigns list as 'draft' status — nothing sends until you publish.\n\nExpected wait: ~${count * 10}s.`,
              )
            )
              return;
            await withProgress(ev.currentTarget, async () => {
              const r = await api("vc-auto-queue", { body: { count, daysBack: 90 } });
              if (r?.error) {
                toast(r.error, "err");
                return;
              }
              const queued = r.queued || 0;
              const skipCount = (r.skipped || []).length;
              const skipReasons = (r.skipped || [])
                .slice(0, 3)
                .map((s) => `${s.name}: ${s.reason}`)
                .join("\n");
              const detail = skipCount > 0 ? `\n\nSkipped ${skipCount}:\n${skipReasons}` : "";
              toast(`✅ Queued ${queued} VC drafts — click to review`, "ok", 10000, () =>
                navigate("vc/drafts"),
              );
              if (skipCount > 0)
                console.log(
                  `[vc-auto-queue] skipped ${skipCount}:\n${(r.skipped || []).map((s) => `  ${s.name}: ${s.reason}`).join("\n")}`,
                );
              // Refresh the list so the user sees activity
              renderVcQueue();
            });
          },
        },
        "⚡ Auto-queue drafts",
      ),
    ]),
    sessionBanner,
    el("div", { id: "vc-queue-list" }, []),
  ]);
  content.insertBefore(_discoverHubNav("vc"), content.children[1] || null);
  setContentNode(content);

  const list = $("#vc-queue-list");
  const investors = data.investors || [];
  if (investors.length === 0) {
    list.innerHTML = `<div class="empty-state"><div class="empty-state-icon">🏛</div><div class="empty-state-title">No active VCs</div><div class="empty-state-hint">Run /trigger cryptorank in Telegram to refresh the funding rounds feed</div></div>`;
    return;
  }

  // Card grid layout for fund browsing
  const grid = el("div", {
    style:
      "display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 12px;",
  });

  for (const i of investors) {
    const tierBadge = i.tier ? el("span", { class: "badge badge-purple" }, i.tier) : null;
    const partnersBadge =
      i.partners_known > 0
        ? el("span", { class: "badge badge-green" }, `${i.partners_known} partners`)
        : el("span", { class: "badge badge-yellow" }, "needs scrape");

    const card = el(
      "div",
      {
        class: "card",
        style: "cursor: pointer; transition: border-color 120ms;",
        onclick: () => navigate(`vc/${i.id}`),
        onmouseenter: (e) => {
          e.currentTarget.style.borderColor = "var(--accent)";
        },
        onmouseleave: (e) => {
          e.currentTarget.style.borderColor = "var(--border)";
        },
      },
      [
        el("div", { class: "row", style: "justify-content: space-between; margin-bottom: 8px;" }, [
          el("div", { class: "primary-cell", style: "font-size: 14px; font-weight: 600;" }, i.name),
          tierBadge,
        ]),
        el("div", { class: "row", style: "gap: 16px; margin-bottom: 8px;" }, [
          el("div", {}, [
            el("div", { class: "stat-label" }, "Recent deals"),
            el(
              "div",
              { style: "font-size: 18px; font-weight: 700; color: var(--text-1);" },
              String(i.portfolio_recent_count || 0),
            ),
          ]),
          el("div", {}, [
            el("div", { class: "stat-label" }, "Last round"),
            el("div", { class: "muted small" }, fmtDate(i.last_round_at)),
          ]),
          el("div", {}, [
            el("div", { class: "stat-label" }, "Partners"),
            el("div", {}, [partnersBadge]),
          ]),
        ]),
        el("div", { class: "row", style: "justify-content: flex-end;" }, [
          el("button", { class: "btn btn-tiny btn-secondary" }, "Open \u2192"),
        ]),
      ],
    );
    grid.appendChild(card);
  }
  list.appendChild(grid);
}

async function renderVcDetail({ investorId }) {
  showLoading();
  const data = await api("vc-detail", { investorId });
  if (data?.error) {
    setContent(
      `<div class="empty-state"><div class="empty-state-title">Error</div><div class="empty-state-hint">${escapeHtml(data.error)}</div></div>`,
    );
    return;
  }
  const { investor, portfolio, partners, emails, crmSummary } = data;

  // Compact "in CRM" header summary so users see warm-intro paths at a glance.
  const crmHeaderBadge =
    crmSummary && (crmSummary.partnersInCrm > 0 || crmSummary.portfolioContactCount > 0)
      ? el("div", { class: "muted small", style: "margin-top: 6px;" }, [
          el("span", { class: "badge badge-green", style: "margin-right: 6px;" }, "🔗 in CRM"),
          crmSummary.partnersInCrm > 0
            ? `${crmSummary.partnersInCrm} partner${crmSummary.partnersInCrm === 1 ? "" : "s"}`
            : null,
          crmSummary.partnersInCrm > 0 && crmSummary.portfolioContactCount > 0 ? " · " : null,
          crmSummary.portfolioContactCount > 0
            ? `${crmSummary.portfolioContactCount} portfolio contact${crmSummary.portfolioContactCount === 1 ? "" : "s"} across ${crmSummary.portfolioCompaniesWithContacts} compan${crmSummary.portfolioCompaniesWithContacts === 1 ? "y" : "ies"}`
            : null,
        ])
      : null;

  const content = el("div", {}, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el(
          "button",
          { class: "btn btn-secondary btn-tiny", onclick: () => navigate("vc") },
          "« Back",
        ),
        el("div", { class: "page-title", style: "margin-top: 10px;" }, investor.name),
        el("div", { class: "page-subtitle" }, [
          investor.tier ? `${investor.tier} · ` : "",
          investor.type || "",
          investor.website ? " · " : "",
          investor.website
            ? el(
                "a",
                { href: investor.website, target: "_blank", style: "color: #60a5fa;" },
                investor.website.replace(/^https?:\/\//, ""),
              )
            : "",
        ]),
        crmHeaderBadge,
      ]),
      el("div", {}, [
        el(
          "button",
          {
            class: "btn btn-primary",
            onclick: () => scrapeFund(investor.id),
          },
          "🔎 Scrape fund data",
        ),
      ]),
    ]),

    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, "Recent portfolio"),
      portfolio.length === 0
        ? el("div", { class: "muted small" }, "No rounds indexed yet — run /trigger cryptorank")
        : el("table", { class: "table" }, [
            el(
              "tbody",
              {},
              portfolio.map((p) =>
                el(
                  "tr",
                  {
                    title:
                      p.crmContactCount > 0
                        ? `${p.crmContactCount} CRM contact${p.crmContactCount === 1 ? "" : "s"} at ${p.name}: ` +
                          (p.crmSampleContacts || []).map((c) => c.displayName).join(", ")
                        : null,
                  },
                  [
                    el("td", { class: "primary-cell" }, [
                      p.is_lead
                        ? el(
                            "span",
                            { class: "badge badge-yellow", style: "margin-right: 6px;" },
                            "lead",
                          )
                        : null,
                      p.name,
                      p.crmContactCount > 0
                        ? el(
                            "span",
                            {
                              class: "badge badge-green",
                              style: "margin-left: 8px;",
                              onclick: (ev) => {
                                ev.stopPropagation();
                                showPortfolioCrmContacts(p);
                              },
                            },
                            `🔗 ${p.crmContactCount} in CRM`,
                          )
                        : null,
                    ]),
                    el("td", {}, p.round_type || "—"),
                    el("td", {}, fmtAmount(p.amount)),
                    el("td", { class: "secondary-cell" }, fmtDate(p.date)),
                  ],
                ),
              ),
            ),
          ]),
    ]),

    el("div", { class: "card" }, [
      el("div", { class: "card-title" }, `Known partners (${partners.length})`),
      partners.length === 0
        ? el("div", { class: "muted small" }, 'Tap "Scrape fund data" to fetch the team page')
        : el(
            "div",
            {},
            partners.map((p) =>
              el("div", { class: "field-row" }, [
                el("div", {}, [
                  el("strong", {}, p.full_name),
                  p.title ? el("span", { class: "muted small" }, ` · ${p.title}`) : null,
                  p.linkedin_url
                    ? el(
                        "a",
                        {
                          href: p.linkedin_url,
                          target: "_blank",
                          class: "muted small",
                          style: "margin-left: 10px; color: #60a5fa;",
                        },
                        "LinkedIn",
                      )
                    : null,
                  p.twitter_handle
                    ? el(
                        "a",
                        {
                          href: `https://x.com/${p.twitter_handle}`,
                          target: "_blank",
                          class: "muted small",
                          style: "margin-left: 10px; color: #60a5fa;",
                        },
                        "X",
                      )
                    : null,
                  p.crmMatch
                    ? el(
                        "span",
                        {
                          class: "badge badge-green",
                          style: "margin-left: 8px; cursor: pointer;",
                          title: `Matched in CRM via ${p.crmMatch.matchedBy.replace(/_/g, " ")}`,
                          onclick: () => showContactDrawer(p.crmMatch.id),
                        },
                        `🔗 in CRM${p.crmMatch.email ? " · ✉" : ""}`,
                      )
                    : null,
                ]),
                el(
                  "button",
                  {
                    class: "btn btn-tiny btn-primary",
                    onclick: () => showPortfolioPicker(investor, p, portfolio),
                  },
                  "🚀 Pursue",
                ),
              ]),
            ),
          ),
    ]),

    emails.length > 0
      ? el("div", { class: "card" }, [
          el("div", { class: "card-title" }, "Fund contact email"),
          el(
            "div",
            {},
            emails.map((e) =>
              el("div", { class: "field-row" }, [
                el("code", {}, e.email),
                e.is_primary ? el("span", { class: "badge badge-green" }, "primary") : null,
              ]),
            ),
          ),
        ])
      : null,
  ]);
  setContentNode(content);
}

async function scrapeFund(investorId) {
  toast("Scraping fund data — takes 15-30s…", "info", 30000);
  const result = await api("vc-scrape", { investorId });
  if (result?.error) {
    toast(`Error: ${result.error}`, "err");
    return;
  }
  const parts = [];
  if (result.overview?.ok) parts.push("✅ Overview");
  if (result.team?.ok) parts.push(`✅ ${result.team.partnersAdded} partners`);
  if (result.emails?.ok) parts.push(`✅ ${result.emails.added} emails`);
  toast(parts.join(" · ") || "Done", "ok");
  await renderVcDetail({ investorId: String(investorId) });
}

// Show the CRM contacts we have at a portfolio company. Lets the user spot
// a warm-intro path: "we know X at AcmeCo, who can intro us to the VC".
function showPortfolioCrmContacts(portfolioCompany) {
  const samples = portfolioCompany.crmSampleContacts || [];
  const body = el("div", {}, [
    el(
      "div",
      { class: "muted small", style: "margin-bottom: 8px;" },
      `Contacts at ${portfolioCompany.name} who could provide a warm intro to the VC:`,
    ),
    samples.length === 0
      ? el(
          "div",
          { class: "muted" },
          "No sample data — open the company in CRM to see all contacts.",
        )
      : el(
          "div",
          {},
          samples.map((c) =>
            el(
              "div",
              {
                class: "field-row",
                style: "cursor: pointer;",
                onclick: () => {
                  closeDrawer();
                  setTimeout(() => showContactDrawer(c.id), 150);
                },
              },
              [
                el("div", {}, [
                  el("strong", {}, c.displayName || "—"),
                  c.role ? el("span", { class: "muted small" }, ` · ${c.role}`) : null,
                  el(
                    "div",
                    { class: "muted small" },
                    [
                      c.linkedinUrl ? "LinkedIn · " : "",
                      c.twitterHandle ? "X · " : "",
                      c.username ? `@${c.username} · ` : "",
                      c.email ? "✉" : "",
                    ]
                      .join("")
                      .replace(/ · $/, ""),
                  ),
                ]),
                el("button", { class: "btn btn-tiny btn-secondary" }, "View →"),
              ],
            ),
          ),
        ),
    portfolioCompany.crmContactCount > samples.length
      ? el(
          "div",
          { class: "muted small", style: "margin-top: 8px;" },
          `+ ${portfolioCompany.crmContactCount - samples.length} more — search "${portfolioCompany.name}" in CRM to see all`,
        )
      : null,
    el("div", { style: "margin-top: 12px;" }, [
      el(
        "button",
        {
          class: "btn btn-secondary btn-tiny",
          type: "button",
          onclick: () => {
            closeDrawer();
            setTimeout(() => navigate(`crm`), 150);
          },
        },
        "Open CRM",
      ),
    ]),
  ]);
  openDrawer(`Warm intro path: ${portfolioCompany.name}`, body);
}

function showPortfolioPicker(investor, partner, portfolio) {
  if (portfolio.length === 0) {
    toast("No portfolio companies — run /trigger cryptorank first", "err");
    return;
  }
  const body = el("div", {}, [
    el("h4", {}, `Pick a portfolio company to reference`),
    el(
      "div",
      { class: "muted small", style: "margin-bottom: 12px;" },
      `Pursuing: ${partner.full_name}${partner.title ? ` · ${partner.title}` : ""} at ${investor.name}`,
    ),
    ...portfolio.map((p) =>
      el(
        "div",
        {
          class: "field-row",
          style: "cursor: pointer;",
          onclick: () => {
            closeDrawer();
            navigate(`vc/${investor.id}/pursue/${partner.id}/${p.id}`);
          },
        },
        [
          el("div", {}, [
            el("strong", {}, p.name),
            el("div", { class: "muted small" }, `${p.round_type || "?"} · ${fmtAmount(p.amount)}`),
          ]),
          el("button", { class: "btn btn-tiny btn-primary" }, "Use →"),
        ],
      ),
    ),
  ]);
  openDrawer("Select reference company", body);
}

async function renderVcPursue({ investorId, contactId, companyId }) {
  showLoading("Generating 3-channel drafts — 10-20 seconds…");
  const data = await api("vc-generate", { investorId, contactId, companyId });
  if (data?.error) {
    setContent(
      `<div class="empty-state"><div class="empty-state-title">Error</div><div class="empty-state-hint">${escapeHtml(data.error)}</div></div>`,
    );
    return;
  }
  const { investor, partner, referenceCompany, pitch } = data;

  // Resolve recipient email
  const fullDetail = await api("vc-detail", { investorId });
  const recipientEmail = fullDetail?.emails?.[0]?.email || partner.email || "";

  dashboardState.vcWizard = {
    investor,
    partner,
    referenceCompany,
    linkedin: {
      postContext: pitch.linkedin?.postContext || null,
      comment: pitch.linkedin?.comment || "",
      connectionState: pitch.linkedin?.connectionState || "unknown",
      toggles: {
        doLike: !!pitch.linkedin?.postContext,
        doComment: !!pitch.linkedin?.comment,
        doConnect: !!partner.linkedin_url,
      },
    },
    x: {
      tweetContext: pitch.x?.tweetContext || null,
      reply: pitch.x?.reply || "",
      toggles: {
        doLike: !!pitch.x?.tweetContext,
        doReply: !!pitch.x?.reply,
        doFollow: !!partner.twitter_handle,
      },
    },
    email: {
      to: recipientEmail,
      subject: pitch.email?.subject || "",
      body: pitch.email?.body || "",
      toggles: { doSend: !!(recipientEmail && pitch.email?.body) },
    },
  };
  renderVcPursueView();
}

function renderVcPursueView() {
  const w = dashboardState.vcWizard;
  if (!w) return navigate("vc");
  const { investor, partner, referenceCompany, linkedin, x: xState, email } = w;

  const content = el("div", { class: "wizard" }, [
    el("div", { class: "page-header" }, [
      el("div", {}, [
        el(
          "button",
          { class: "btn btn-secondary btn-tiny", onclick: () => navigate(`vc/${investor.id}`) },
          "« Back",
        ),
        el("div", { class: "page-title", style: "margin-top: 10px;" }, `🎯 ${partner.full_name}`),
        el(
          "div",
          { class: "page-subtitle" },
          `${partner.title || "Partner"} at ${investor.name} · Referencing: ${referenceCompany.name}`,
        ),
      ]),
    ]),

    // LinkedIn section
    partner.linkedin_url
      ? el("div", { class: "wizard-section" }, [
          el("div", { class: "wizard-section-title" }, "🔗 LinkedIn"),
          linkedin.postContext?.postText
            ? el("div", {}, [
                el("div", { class: "wizard-label" }, "Their latest post:"),
                el("div", { class: "wizard-post" }, linkedin.postContext.postText),
              ])
            : el("div", { class: "muted small" }, "No recent post found — like + comment disabled"),
          el("div", { class: "wizard-label" }, "Draft comment:"),
          el(
            "textarea",
            {
              class: "wizard-textarea",
              id: "vc-li-comment",
              oninput: (e) => {
                dashboardState.vcWizard.linkedin.comment = e.target.value;
              },
            },
            linkedin.comment || "",
          ),
          el(
            "div",
            { class: "muted small", style: "margin-top: 6px;" },
            linkedin.connectionState === "connected"
              ? "✅ Already connected (will DM)"
              : linkedin.connectionState === "not_connected"
                ? "❌ Not connected (will connect)"
                : "❓ Status unknown",
          ),
          toggleRow("Like the post", linkedin.toggles.doLike, (v) => {
            linkedin.toggles.doLike = v;
            renderVcPursueView();
          }),
          toggleRow("Post comment", linkedin.toggles.doComment, (v) => {
            linkedin.toggles.doComment = v;
            renderVcPursueView();
          }),
          toggleRow(
            linkedin.connectionState === "connected" ? "Send DM" : "Connection request",
            linkedin.toggles.doConnect,
            (v) => {
              linkedin.toggles.doConnect = v;
              renderVcPursueView();
            },
          ),
        ])
      : null,

    // X section
    partner.twitter_handle
      ? el("div", { class: "wizard-section" }, [
          el("div", { class: "wizard-section-title" }, "🐦 X / Twitter"),
          xState.tweetContext?.postText
            ? el("div", {}, [
                el("div", { class: "wizard-label" }, "Their latest tweet:"),
                el("div", { class: "wizard-post" }, xState.tweetContext.postText),
              ])
            : el("div", { class: "muted small" }, "No recent tweet found"),
          el("div", { class: "wizard-label" }, "Draft reply:"),
          el(
            "textarea",
            {
              class: "wizard-textarea",
              id: "vc-x-reply",
              oninput: (e) => {
                dashboardState.vcWizard.x.reply = e.target.value;
              },
            },
            xState.reply || "",
          ),
          toggleRow("Like the tweet", xState.toggles.doLike, (v) => {
            xState.toggles.doLike = v;
            renderVcPursueView();
          }),
          toggleRow("Post reply", xState.toggles.doReply, (v) => {
            xState.toggles.doReply = v;
            renderVcPursueView();
          }),
          toggleRow("Follow the account", xState.toggles.doFollow, (v) => {
            xState.toggles.doFollow = v;
            renderVcPursueView();
          }),
        ])
      : null,

    // Email section
    el("div", { class: "wizard-section" }, [
      el("div", { class: "wizard-section-title" }, "📧 Email"),
      el("div", { class: "wizard-label" }, "To:"),
      el("input", {
        class: "wizard-input",
        id: "vc-email-to",
        value: email.to || "",
        placeholder: "contact@fund.com",
        oninput: (e) => {
          dashboardState.vcWizard.email.to = e.target.value;
        },
      }),
      el("div", { class: "wizard-label", style: "margin-top: 10px;" }, "Subject:"),
      el("input", {
        class: "wizard-input",
        id: "vc-email-subject",
        value: email.subject || "",
        oninput: (e) => {
          dashboardState.vcWizard.email.subject = e.target.value;
        },
      }),
      el("div", { class: "wizard-label", style: "margin-top: 10px;" }, "Body:"),
      el(
        "textarea",
        {
          class: "wizard-textarea",
          id: "vc-email-body",
          style: "min-height: 200px;",
          oninput: (e) => {
            dashboardState.vcWizard.email.body = e.target.value;
          },
        },
        email.body || "",
      ),
      toggleRow("Send email", email.toggles.doSend, (v) => {
        email.toggles.doSend = v;
        renderVcPursueView();
      }),
    ]),

    el("div", { class: "wizard-actions" }, [
      el("button", { class: "btn btn-primary", onclick: publishVc }, "🚀 Publish all channels"),
      el(
        "button",
        { class: "btn btn-secondary", onclick: () => navigate(`vc/${investor.id}`) },
        "Cancel",
      ),
    ]),
  ]);
  setContentNode(content);
}

async function publishVc() {
  const w = dashboardState.vcWizard;
  if (!w) return;
  toast("Publishing 3 channels in parallel — 15-30s…", "info", 30000);
  const result = await api("vc-publish", {
    investorId: w.investor.id,
    contactId: w.partner.id,
    companyId: w.referenceCompany.id,
    body: {
      linkedin: w.linkedin,
      x: w.x,
      email: w.email,
    },
  });
  if (result?.ok || result?.actions) {
    const okCount = (result.actions || []).filter((a) => a.status === "ok").length;
    const errCount = (result.actions || []).filter((a) => a.status === "error").length;
    toast(`✅ ${okCount} succeeded, ${errCount} failed`, errCount > 0 ? "info" : "ok", 6000);
    dashboardState.vcWizard = null;
    setTimeout(() => navigate(`vc/${w.investor.id}`), 2000);
  } else {
    toast(`Error: ${result?.error || "publish failed"}`, "err");
  }
}
