// ============================================
// APP: Campaign Dashboard — Grid of all campaigns
// ============================================

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

export interface CampaignDashboardData {
  accountName?: string;
  campaigns: CampaignCard[];
  sortBy?: "spend" | "conversions" | "ctr";
}

export interface CampaignCard {
  id: string;
  name: string;
  status: string;
  channelType: string;
  spend: number;          // micros
  clicks: number;
  impressions: number;
  ctr: number;            // decimal
  conversions: number;
  dailyBudget: number;    // micros
}

function channelBadge(channel: string): string {
  const ch = channel.toUpperCase().replace(/_/g, " ");
  const map: Record<string, string> = {
    SEARCH: "pill-blue",
    DISPLAY: "pill-purple",
    SHOPPING: "pill-orange",
    VIDEO: "pill-red",
    "PERFORMANCE MAX": "pill-green",
    DISCOVERY: "pill-yellow",
    LOCAL: "pill-muted",
    SMART: "pill-muted",
  };
  const cls = map[ch] || "pill-muted";
  return `<span class="pill ${cls}">${escapeHtml(ch)}</span>`;
}

function sortCampaigns(campaigns: CampaignCard[], sortBy: string): CampaignCard[] {
  const copy = [...campaigns];
  switch (sortBy) {
    case "conversions": return copy.sort((a, b) => b.conversions - a.conversions);
    case "ctr": return copy.sort((a, b) => b.ctr - a.ctr);
    case "spend":
    default: return copy.sort((a, b) => b.spend - a.spend);
  }
}

export function renderCampaignDashboard(data: CampaignDashboardData): string {
  const sortBy = data.sortBy || "spend";
  const sorted = sortCampaigns(data.campaigns, sortBy);
  const totalSpend = data.campaigns.reduce((s, c) => s + c.spend, 0);
  const totalConv = data.campaigns.reduce((s, c) => s + c.conversions, 0);

  const sortPills = (["spend", "conversions", "ctr"] as const).map(
    (s) => `<span class="pill ${s === sortBy ? "pill-red" : "pill-muted"}" style="cursor:default">${s.toUpperCase()}</span>`
  ).join(" ");

  const cards = sorted.map((c) => {
    const budgetPct = c.dailyBudget > 0 ? (c.spend / c.dailyBudget) * 100 : 0;
    const budgetColor = budgetPct > 95 ? "red" : budgetPct > 70 ? "yellow" : "green";

    return `
      <div class="card campaign-card">
        <div class="flex-between mb-8">
          <span class="card-title" style="margin-bottom:0">${escapeHtml(c.name)}</span>
          ${statusPill(c.status)}
        </div>
        <div class="flex gap-8 wrap mb-8">
          ${channelBadge(c.channelType)}
        </div>
        <div style="display:grid; grid-template-columns: 1fr 1fr; gap: 8px; margin-bottom: 12px;">
          <div>
            <div class="text-muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.5px">Spend</div>
            <div class="text-mono" style="font-size:15px; font-weight:700">${fmtMoney(c.spend)}</div>
          </div>
          <div>
            <div class="text-muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.5px">Conversions</div>
            <div class="text-mono" style="font-size:15px; font-weight:700">${fmtNum(c.conversions)}</div>
          </div>
          <div>
            <div class="text-muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.5px">Clicks</div>
            <div class="text-mono" style="font-size:14px">${fmtNum(c.clicks)}</div>
          </div>
          <div>
            <div class="text-muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.5px">CTR</div>
            <div class="text-mono" style="font-size:14px">${fmtPct(c.ctr)}</div>
          </div>
          <div style="grid-column: span 2">
            <div class="text-muted" style="font-size:10px; text-transform:uppercase; letter-spacing:0.5px">Impressions</div>
            <div class="text-mono" style="font-size:14px">${fmtNum(c.impressions)}</div>
          </div>
        </div>
        <div style="margin-top:auto">
          <div class="flex-between mb-8">
            <span class="text-muted" style="font-size:10px">Budget Utilization</span>
            <span class="text-mono" style="font-size:11px">${budgetPct.toFixed(0)}%</span>
          </div>
          ${progressBar(budgetPct, budgetColor)}
          <div class="text-muted" style="font-size:10px; margin-top:4px">${fmtMoney(c.spend)} / ${fmtMoney(c.dailyBudget)} daily</div>
        </div>
      </div>`;
  }).join("\n");

  const body = `
    <style>
      .campaign-card {
        display: flex;
        flex-direction: column;
      }
      .campaign-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
        gap: 16px;
      }
    </style>

    <div class="app-header">
      <h1>📊 Campaign Dashboard</h1>
      <div class="subtitle">${data.accountName ? escapeHtml(data.accountName) + " — " : ""}${sorted.length} campaigns · ${fmtMoney(totalSpend)} total spend · ${fmtNum(totalConv)} conversions</div>
    </div>

    <div class="section flex-between">
      <span class="text-muted" style="font-size:12px">Sort by: ${sortPills}</span>
    </div>

    <div class="campaign-grid">
      ${cards}
    </div>
  `;

  return wrapHtml("Campaign Dashboard", body);
}
