// ============================================
// APP: Keyword Analyzer — Keyword analysis view
// ============================================

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

export interface KeywordAnalyzerData {
  campaignName?: string;
  adGroupName?: string;
  keywords: KeywordRow[];
}

export interface KeywordRow {
  keyword: string;
  matchType: string;     // BROAD, PHRASE, EXACT
  status: string;
  qualityScore: number;  // 1-10
  clicks: number;
  impressions: number;
  ctr: number;           // decimal
  cpc: number;           // micros
  conversions: number;
}

function matchTypeBadge(matchType: string): string {
  const mt = matchType.toUpperCase();
  const map: Record<string, string> = {
    BROAD: "pill-blue",
    PHRASE: "pill-purple",
    EXACT: "pill-green",
  };
  return `<span class="pill ${map[mt] || "pill-muted"}">${escapeHtml(mt)}</span>`;
}

function qualityScoreBar(qs: number): string {
  const clamped = Math.max(0, Math.min(10, qs));
  const pct = clamped * 10;
  let color: string;
  let textColor: string;
  if (clamped >= 7) {
    color = "var(--green)";
    textColor = "text-green";
  } else if (clamped >= 4) {
    color = "var(--yellow)";
    textColor = "text-yellow";
  } else {
    color = "var(--red)";
    textColor = "text-red";
  }

  return `
    <div class="qs-bar">
      <div class="qs-track">
        <div class="qs-fill" style="width:${pct}%; background:${color}"></div>
      </div>
      <span class="qs-num ${textColor}">${clamped}</span>
    </div>`;
}

function statusPillKw(status: string): string {
  const s = status.toUpperCase();
  if (s === "ENABLED") return `<span class="pill pill-green">${s}</span>`;
  if (s === "PAUSED") return `<span class="pill pill-yellow">${s}</span>`;
  if (s === "REMOVED") return `<span class="pill pill-red">${s}</span>`;
  return `<span class="pill pill-muted">${s}</span>`;
}

export function renderKeywordAnalyzer(data: KeywordAnalyzerData): string {
  const kws = data.keywords;
  const totalKws = kws.length;
  const avgQS = totalKws > 0
    ? (kws.reduce((s, k) => s + k.qualityScore, 0) / totalKws)
    : 0;
  const topPerformer = [...kws].sort((a, b) => b.conversions - a.conversions)[0];

  const avgQSColor = avgQS >= 7 ? "text-green" : avgQS >= 4 ? "text-yellow" : "text-red";

  // Build table rows
  const rows = kws.map((k) => `
    <tr>
      <td style="font-weight:500">${escapeHtml(k.keyword)}</td>
      <td>${matchTypeBadge(k.matchType)}</td>
      <td>${statusPillKw(k.status)}</td>
      <td>${qualityScoreBar(k.qualityScore)}</td>
      <td class="right text-mono">${fmtNum(k.clicks)}</td>
      <td class="right text-mono">${fmtNum(k.impressions)}</td>
      <td class="right text-mono">${fmtPct(k.ctr)}</td>
      <td class="right text-mono">${fmtMoney(k.cpc)}</td>
      <td class="right text-mono">${fmtNum(k.conversions)}</td>
    </tr>`
  ).join("\n");

  const body = `
    <div class="app-header">
      <h1>🔑 Keyword Analyzer</h1>
      <div class="subtitle">${data.campaignName ? escapeHtml(data.campaignName) : "All campaigns"}${data.adGroupName ? " → " + escapeHtml(data.adGroupName) : ""}</div>
    </div>

    <div class="section grid-3">
      <div class="kpi-card">
        <div class="kpi-value">${fmtNum(totalKws)}</div>
        <div class="kpi-label">Total Keywords</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value ${avgQSColor}">${avgQS.toFixed(1)}</div>
        <div class="kpi-label">Avg Quality Score</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value" style="font-size:16px">${topPerformer ? escapeHtml(topPerformer.keyword) : "—"}</div>
        <div class="kpi-label">Top Performer</div>
        ${topPerformer ? `<div class="kpi-delta up">${fmtNum(topPerformer.conversions)} conv</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>Keyword</th>
                <th>Match Type</th>
                <th>Status</th>
                <th style="min-width:130px">Quality Score</th>
                <th class="right">Clicks</th>
                <th class="right">Impr.</th>
                <th class="right">CTR</th>
                <th class="right">CPC</th>
                <th class="right">Conv.</th>
              </tr>
            </thead>
            <tbody>
              ${rows || `<tr><td colspan="9" style="text-align:center; color:var(--text-muted); padding:24px">No keywords found</td></tr>`}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  `;

  return wrapHtml("Keyword Analyzer", body);
}
