// dashboard-score-a-company-wizard-ai-filt.js — extracted verbatim from dashboard.js (pure move).

// ── Score-a-company wizard (AI filter eval + base signals fallback) ───
function renderIcpScoreWizard(body) {
  body.innerHTML = "";

  // ── AI filter evaluation path (primary) ──────────────────────
  const aiBox = el(
    "div",
    {
      class: "wizard-section",
      style: "background:var(--accent-soft);border:1px solid var(--accent);",
    },
    [
      el("div", { class: "wizard-section-title" }, "🤖 Evaluate a CRM company with AI filters"),
      el(
        "div",
        { class: "muted small", style: "margin-bottom:10px;" },
        "Claude evaluates each of your active filters against this company's data (website, socials, base signals) and returns a scored verdict with reasoning per filter. Saves the breakdown to the company.",
      ),
    ],
  );
  const idInput = el("input", {
    class: "wizard-input",
    type: "number",
    placeholder: "Company ID from CRM (open any company → URL has /companies/<id>)",
    value: icpState.editingCompany?.id || "",
    style: "margin-bottom:8px;",
  });
  const aiStatus = el("div", { class: "muted small", style: "margin-top:6px;" });
  const aiBtn = el(
    "button",
    {
      class: "btn btn-primary",
      type: "button",
      onclick: async () => {
        const id = Number(idInput.value);
        if (!id) {
          toast("Enter a company ID", "err");
          return;
        }
        aiBtn.textContent = "Evaluating (20–40s for N filters)…";
        aiBtn.disabled = true;
        aiStatus.textContent = "Claude is evaluating each active filter…";
        try {
          const r = await api("icp-score-one-ai", { body: { companyId: id } });
          if (r?.error) {
            toast(`❌ ${r.error}`, "err");
            aiStatus.textContent = r.error;
          } else {
            icpState.aiEvalResult = r;
            toast(`✅ ${r.band.toUpperCase()} — ${r.final0to10}/10`, "ok");
            renderIcp();
            return;
          }
        } catch (err) {
          toast(`❌ ${err.message}`, "err");
          aiStatus.textContent = err.message;
        }
        aiBtn.textContent = "Evaluate with AI filters";
        aiBtn.disabled = false;
      },
    },
    "Evaluate with AI filters",
  );
  aiBox.appendChild(idInput);
  aiBox.appendChild(aiBtn);
  aiBox.appendChild(aiStatus);

  // Render the filter breakdown if we have one
  if (icpState.aiEvalResult) {
    aiBox.appendChild(renderAiEvalResult(icpState.aiEvalResult));
  }
  body.appendChild(aiBox);

  // ── Separator + manual base-signals fallback ────────────────
  body.appendChild(
    el(
      "div",
      { class: "muted small", style: "margin:20px 0 8px;text-align:center;" },
      "— or score manually with base signals —",
    ),
  );

  const tax = icpState._taxonomy || {};
  const editing = icpState.editingCompany;
  const prefill = editing
    ? {
        ecosystem: editing.ecosystem,
        crypto_category: editing.crypto_category,
        tvl_band: editing.tvl_band,
        token_mc_band: editing.token_mc_band,
        treasury_band: editing.treasury_band,
        protocol_stage: editing.protocol_stage,
        has_token: editing.has_token,
        is_rugged: editing.is_rugged,
        is_pre_mainnet: editing.is_pre_mainnet,
        anon_team: editing.anon_team,
        memecoin_only: editing.memecoin_only,
        backed_by_tier_1: editing.backed_by_tier_1,
        community_size_band: editing.community_size_band,
        differentiation_notes: editing.differentiation_notes,
      }
    : {};
  const current = { ...prefill, ...icpState.adhoc };

  const form = el("div", { class: "wizard-section" }, [
    el(
      "div",
      { class: "wizard-section-title" },
      editing ? `Scoring ${editing.name}` : "Score any crypto company",
    ),
    el(
      "div",
      { class: "muted small", style: "margin-bottom:12px;" },
      editing
        ? "Edits persist to this company and override passive enrichment for the fields you set."
        : "Fill in what you know. The score updates live. No persistence unless you save.",
    ),
  ]);

  // Yes/No chip builder — returns a row element, caller decides where to append it.
  const yesNoRow = (key, label) => {
    const val = current[key];
    const isYes = val === 1 || val === true;
    const isNo = val === 0 || val === false;
    return el("div", { style: "display:flex;align-items:center;gap:12px;margin-bottom:6px;" }, [
      el("div", { class: "wizard-label", style: "flex:1;margin:0;" }, label),
      el(
        "button",
        {
          type: "button",
          class: `btn btn-tiny ${isYes ? "btn-danger" : "btn-secondary"}`,
          onclick: () => {
            icpState.adhoc[key] = 1;
            runAdhocScore();
            renderIcp();
          },
        },
        "Yes",
      ),
      el(
        "button",
        {
          type: "button",
          class: `btn btn-tiny ${isNo ? "btn-primary" : "btn-secondary"}`,
          onclick: () => {
            icpState.adhoc[key] = 0;
            runAdhocScore();
            renderIcp();
          },
        },
        "No",
      ),
    ]);
  };

  // Gate 1: disqualifiers
  const gate1 = el(
    "div",
    { class: "wizard-section", style: "background:var(--red-soft);border:1px solid var(--red);" },
    [
      el(
        "div",
        { class: "wizard-section-title" },
        "Gate 1 — Disqualifiers (instant kill if any = Yes)",
      ),
      yesNoRow("is_rugged", "Rugged / abandoned project?"),
      yesNoRow("is_pre_mainnet", "Pre-mainnet (no live product)?"),
      yesNoRow("anon_team", "Fully anonymous team?"),
      yesNoRow("memecoin_only", "Memecoin only (no utility/roadmap)?"),
    ],
  );
  form.appendChild(gate1);

  // Gate 2: TAM
  const gate2 = el("div", { class: "wizard-section" }, [
    el("div", { class: "wizard-section-title" }, "Gate 2 — TAM qualifiers"),
  ]);
  gate2.appendChild(
    renderIcpSelect("Crypto category", "crypto_category", current.crypto_category, [
      "",
      ...(tax.categories || []),
    ]),
  );
  gate2.appendChild(
    renderIcpSelect("Ecosystem (primary chain)", "ecosystem", current.ecosystem, [
      "",
      ...(tax.ecosystems || []),
    ]),
  );
  gate2.appendChild(
    renderIcpSelect("TVL band", "tvl_band", current.tvl_band, ["", ...(tax.tvl_bands || [])]),
  );
  gate2.appendChild(
    renderIcpSelect("Token market cap band", "token_mc_band", current.token_mc_band, [
      "",
      ...(tax.token_mc_bands || []),
    ]),
  );
  gate2.appendChild(
    renderIcpSelect("Treasury band (raised/runway)", "treasury_band", current.treasury_band, [
      "",
      ...(tax.treasury_bands || []),
    ]),
  );
  gate2.appendChild(
    renderIcpSelect("Protocol stage", "protocol_stage", current.protocol_stage, [
      "",
      ...(tax.protocol_stages || []),
    ]),
  );
  form.appendChild(gate2);

  // Gate 3: ICP positives
  const gate3 = el("div", { class: "wizard-section" }, [
    el("div", { class: "wizard-section-title" }, "Gate 3 — ICP positives"),
    yesNoRow("has_token", "Has a launched/transferable token?"),
    yesNoRow("backed_by_tier_1", "Backed by tier-1 VC (a16z, Paradigm, Multicoin, etc.)?"),
  ]);
  gate3.appendChild(
    renderIcpSelect("Community size", "community_size_band", current.community_size_band, [
      "",
      ...(tax.community_bands || []),
    ]),
  );
  gate3.appendChild(
    renderIcpText(
      "Differentiation notes",
      "differentiation_notes",
      current.differentiation_notes,
      "Optional: what sets this project apart?",
    ),
  );
  form.appendChild(gate3);

  // Action row
  const actions = el("div", { class: "wizard-actions" }, [
    el(
      "button",
      {
        class: "btn btn-primary",
        type: "button",
        onclick: () => runAdhocScore(true).then(() => renderIcp()),
      },
      "↻ Recalculate",
    ),
    editing
      ? el(
          "button",
          {
            class: "btn btn-primary",
            type: "button",
            onclick: async () => {
              const payload = { ...icpState.adhoc };
              const r = await api("icp-company-signals", {
                companyId: editing.id,
                body: payload,
              }).catch((e) => ({ error: e.message }));
              if (r?.error) toast(`Save failed: ${r.error}`, "err");
              else {
                toast(`Saved — ${r.breakdown.band.toUpperCase()} (${r.breakdown.score}/10)`, "ok");
                icpState.editingCompany = null;
                icpState.adhoc = {};
                icpState.adhocResult = null;
                icpState.status = null;
                icpState.tab = "overview";
                renderIcp();
              }
            },
          },
          "💾 Save to CRM",
        )
      : null,
    editing
      ? el(
          "button",
          {
            class: "btn btn-secondary",
            type: "button",
            onclick: () => {
              icpState.editingCompany = null;
              icpState.adhoc = {};
              icpState.adhocResult = null;
              renderIcp();
            },
          },
          "Cancel",
        )
      : null,
    el(
      "button",
      {
        class: "btn btn-secondary",
        type: "button",
        onclick: () => {
          icpState.adhoc = {};
          icpState.adhocResult = null;
          renderIcp();
        },
      },
      "Reset",
    ),
  ]);
  form.appendChild(actions);

  // Live score panel
  const scorePanel = el(
    "div",
    { class: "wizard-section", style: "background:var(--bg-2);position:sticky;bottom:12px;" },
    [el("div", { class: "wizard-section-title" }, "Live score")],
  );
  if (icpState.adhocResult) {
    const r = icpState.adhocResult;
    scorePanel.appendChild(
      el("div", { style: "display:flex;align-items:center;gap:16px;margin-bottom:12px;" }, [
        el("div", { style: "font-size:42px;font-weight:700;" }, `${r.score.toFixed(1)}`),
        el("div", { class: "muted" }, "/ 10"),
        renderIcpBandBadge(r.band),
      ]),
    );
    if (r.declarative?.disqualifiedBy?.length) {
      scorePanel.appendChild(
        el(
          "div",
          { class: "badge badge-red", style: "margin-bottom:8px;" },
          `Killed by: ${r.declarative.disqualifiedBy.join(", ")}`,
        ),
      );
    }
    const copy = r.band_copy || {};
    if (copy.blurb) scorePanel.appendChild(el("div", { class: "muted small" }, copy.blurb));
    if (r.declarative) {
      scorePanel.appendChild(
        el(
          "div",
          { class: "muted small", style: "margin-top:8px;" },
          `Declarative ${r.declarative.score}/10 · Empirical ${r.empirical?.score ?? "—"}/10 (conf ${Math.round((r.empirical?.confidence || 0) * 100)}%)`,
        ),
      );
    }
  } else {
    scorePanel.appendChild(
      el("div", { class: "muted small" }, "Fill in signals above to see the live score."),
    );
  }
  form.appendChild(scorePanel);

  body.appendChild(form);
}

function renderIcpSelect(label, key, current, options) {
  const sel = el(
    "select",
    {
      class: "filter-select",
      style: "width:100%;margin-bottom:8px;",
      onchange: (e) => {
        icpState.adhoc[key] = e.target.value || null;
        runAdhocScore();
        renderIcp();
      },
    },
    options.map((o) => {
      const opt = el("option", { value: o }, o || "—");
      if (String(current ?? "") === String(o)) opt.selected = true;
      return opt;
    }),
  );
  return el("div", {}, [el("label", { class: "wizard-label" }, label), sel]);
}

function renderIcpText(label, key, current, placeholder = "") {
  const input = el("input", {
    class: "wizard-input",
    type: "text",
    value: current || "",
    placeholder,
    onchange: (e) => {
      icpState.adhoc[key] = e.target.value || null;
      runAdhocScore();
    },
    onblur: () => renderIcp(),
  });
  return el("div", {}, [el("label", { class: "wizard-label" }, label), input]);
}

let _adhocSeq = 0;
async function runAdhocScore(forceRender = false) {
  const seq = ++_adhocSeq;
  // overlay adhoc on any prefill from editingCompany
  const editing = icpState.editingCompany;
  const adhoc = editing
    ? { companyId: editing.id, adhoc: { ...icpState.adhoc }, persist: false }
    : { adhoc: { ...icpState.adhoc } };
  try {
    const r = await api("icp-score-one", { body: adhoc });
    if (seq !== _adhocSeq) return; // stale response
    if (r?.error) {
      icpState.adhocResult = null;
      toast(`Score error: ${r.error}`, "err");
    } else {
      icpState.adhocResult = r;
    }
    if (forceRender) renderIcp();
  } catch (err) {
    icpState.adhocResult = null;
    toast(`Score error: ${err.message}`, "err");
  }
}
