// ============================================
// APP: Search Terms — Search terms report with actions
// ============================================

import { wrapHtml, escapeHtml, fmtMoney, fmtNum, fmtPct } from "./theme.js";

export interface SearchTermsData {
  period?: string;
  costThreshold?: number;    // micros — terms above this with 0 conversions flagged
  terms: SearchTermRow[];
}

export interface SearchTermRow {
  searchTerm: string;
  campaign: string;
  adGroup: string;
  impressions: number;
  clicks: number;
  ctr: number;               // decimal
  cost: number;              // micros
  conversions: number;
  suggestedAction?: "add_keyword" | "add_negative" | "none";
}

function actionBadge(action?: string): string {
  switch (action) {
    case "add_keyword":
      return `<span class="pill pill-green">＋ Add Keyword</span>`;
    case "add_negative":
      return `<span class="pill pill-red">— Add Negative</span>`;
    default:
      return `<span class="pill pill-muted">No Action</span>`;
  }
}

function inferAction(term: SearchTermRow, costThreshold: number): string {
  if (term.suggestedAction && term.suggestedAction !== "none") return term.suggestedAction;
  // Auto-infer: high cost + 0 conversions → negative; good CTR + conversions → add keyword
  if (term.cost > costThreshold && term.conversions === 0) return "add_negative";
  if (term.conversions > 0 && term.ctr > 0.03) return "add_keyword";
  return "none";
}

export function renderSearchTerms(data: SearchTermsData): string {
  const costThreshold = data.costThreshold || 5_000_000; // default $5
  const terms = data.terms;
  const totalTerms = terms.length;
  const totalCost = terms.reduce((s, t) => s + t.cost, 0);
  const negCandidates = terms.filter((t) => inferAction(t, costThreshold) === "add_negative").length;
  const kwCandidates = terms.filter((t) => inferAction(t, costThreshold) === "add_keyword").length;

  const rows = terms.map((t) => {
    const action = inferAction(t, costThreshold);
    const isHighCostLowConv = t.cost > costThreshold && t.conversions === 0;
    const rowStyle = isHighCostLowConv ? 'style="background:var(--red-dim)"' : "";

    return `
      <tr ${rowStyle}>
        <td style="font-weight:500; max-width:280px; overflow:hidden; text-overflow:ellipsis">${escapeHtml(t.searchTerm)}</td>
        <td class="text-muted" style="max-width:160px; overflow:hidden; text-overflow:ellipsis">${escapeHtml(t.campaign)}</td>
        <td class="text-muted" style="max-width:140px; overflow:hidden; text-overflow:ellipsis">${escapeHtml(t.adGroup)}</td>
        <td class="right text-mono">${fmtNum(t.impressions)}</td>
        <td class="right text-mono">${fmtNum(t.clicks)}</td>
        <td class="right text-mono">${fmtPct(t.ctr)}</td>
        <td class="right text-mono">${fmtMoney(t.cost)}</td>
        <td class="right text-mono">${fmtNum(t.conversions)}</td>
        <td>${actionBadge(action)}</td>
      </tr>`;
  }).join("\n");

  const body = `
    <div class="app-header">
      <h1>🔍 Search Terms Report</h1>
      <div class="subtitle">${data.period ? escapeHtml(data.period) + " · " : ""}${fmtNum(totalTerms)} search terms · ${fmtMoney(totalCost)} total cost</div>
    </div>

    <div class="section grid-3">
      <div class="kpi-card">
        <div class="kpi-value">${fmtNum(totalTerms)}</div>
        <div class="kpi-label">Search Terms</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value text-green">${fmtNum(kwCandidates)}</div>
        <div class="kpi-label">Add as Keyword</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value text-red">${fmtNum(negCandidates)}</div>
        <div class="kpi-label">Add as Negative</div>
      </div>
    </div>

    <div class="section">
      <div class="card" style="padding:0; overflow:hidden">
        <div class="table-wrap" style="border:none; border-radius:0">
          <table>
            <thead>
              <tr>
                <th>Search Term</th>
                <th>Campaign</th>
                <th>Ad Group</th>
                <th class="right">Impr.</th>
                <th class="right">Clicks</th>
                <th class="right">CTR</th>
                <th class="right">Cost</th>
                <th class="right">Conv.</th>
                <th>Suggested Action</th>
              </tr>
            </thead>
            <tbody>
              ${rows || `<tr><td colspan="9" style="text-align:center; color:var(--text-muted); padding:24px">No search terms found</td></tr>`}
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="section" style="margin-top:8px">
      <div style="font-size:11px; color:var(--text-muted)">
        <span style="display:inline-block; width:12px; height:12px; background:var(--red-dim); border-radius:2px; vertical-align:middle; margin-right:4px"></span>
        Highlighted rows indicate high-cost terms (>${fmtMoney(costThreshold)}) with zero conversions
      </div>
    </div>
  `;

  return wrapHtml("Search Terms Report", body);
}
