// ============================================
// APP: Campaign Detail — Single Campaign Deep-Dive
// ============================================

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

export interface CampaignDetailData {
  campaign: {
    id: string;
    name: string;
    status: string;
    channelType: string;
    biddingStrategy: string;
    startDate?: string;
    endDate?: string;
  };
  budget: {
    dailyBudget: number;    // micros
    totalSpent: number;     // micros
    deliveryMethod?: string;
  };
  metrics: {
    impressions: number;
    clicks: number;
    ctr: number;            // decimal
    cost: number;           // micros
    conversions: number;
    conversionRate: number; // decimal
    costPerConversion: number; // micros
    avgCpc: number;         // micros
  };
  adGroups: AdGroupRow[];
}

export interface AdGroupRow {
  id: string;
  name: string;
  status: string;
  cpcBid: number;          // micros
  impressions: number;
  clicks: number;
  ctr: number;
  cost: number;            // micros
  conversions: number;
}

function metricRow(label: string, value: string): string {
  return `<div class="metric-row"><span class="metric-label">${escapeHtml(label)}</span><span class="metric-value">${value}</span></div>`;
}

export function renderCampaignDetail(data: CampaignDetailData): string {
  const { campaign: c, budget: b, metrics: m } = data;

  const utilizationPct = b.dailyBudget > 0 ? (b.totalSpent / b.dailyBudget) * 100 : 0;
  const budgetColor = utilizationPct > 95 ? "red" : utilizationPct > 70 ? "yellow" : "green";

  const strategyLabel = c.biddingStrategy.replace(/_/g, " ").replace(/\b\w/g, (l) => l.toUpperCase());

  // Ad groups table
  const adGroupRows = data.adGroups.map((ag) => `
    <tr>
      <td>${escapeHtml(ag.name)}</td>
      <td>${statusPill(ag.status)}</td>
      <td class="right text-mono">${fmtMoney(ag.cpcBid)}</td>
      <td class="right text-mono">${fmtNum(ag.impressions)}</td>
      <td class="right text-mono">${fmtNum(ag.clicks)}</td>
      <td class="right text-mono">${fmtPct(ag.ctr)}</td>
      <td class="right text-mono">${fmtMoney(ag.cost)}</td>
      <td class="right text-mono">${fmtNum(ag.conversions)}</td>
    </tr>`
  ).join("\n");

  const body = `
    <style>
      .detail-header {
        display: flex;
        align-items: center;
        gap: 12px;
        flex-wrap: wrap;
        margin-bottom: 6px;
      }
      .detail-header h1 { margin: 0; }
      .meta-pills {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-top: 4px;
      }
    </style>

    <div class="app-header">
      <div class="detail-header">
        <h1>🔍 ${escapeHtml(c.name)}</h1>
        ${statusPill(c.status)}
      </div>
      <div class="meta-pills">
        <span class="pill pill-blue">${escapeHtml(c.channelType.replace(/_/g, " "))}</span>
        <span class="pill pill-purple">${escapeHtml(strategyLabel)}</span>
        ${c.startDate ? `<span class="pill pill-muted">Started ${escapeHtml(c.startDate)}</span>` : ""}
        ${c.endDate ? `<span class="pill pill-muted">Ends ${escapeHtml(c.endDate)}</span>` : ""}
      </div>
    </div>

    <div class="section grid-2">
      <!-- Budget Section -->
      <div class="card">
        <div class="card-title">💰 Budget</div>
        ${metricRow("Daily Budget", fmtMoney(b.dailyBudget))}
        ${metricRow("Total Spent", fmtMoney(b.totalSpent))}
        ${b.deliveryMethod ? metricRow("Delivery", b.deliveryMethod) : ""}
        <div style="margin-top:12px">
          <div class="flex-between mb-8">
            <span class="text-muted" style="font-size:11px">Utilization</span>
            <span class="text-mono" style="font-size:12px">${utilizationPct.toFixed(1)}%</span>
          </div>
          ${progressBar(utilizationPct, budgetColor)}
        </div>
      </div>

      <!-- Performance Metrics -->
      <div class="card">
        <div class="card-title">📊 Performance</div>
        ${metricRow("Impressions", fmtNum(m.impressions))}
        ${metricRow("Clicks", fmtNum(m.clicks))}
        ${metricRow("CTR", fmtPct(m.ctr))}
        ${metricRow("Cost", fmtMoney(m.cost))}
        ${metricRow("Avg CPC", fmtMoney(m.avgCpc))}
        ${metricRow("Conversions", fmtNum(m.conversions))}
        ${metricRow("Conv. Rate", fmtPct(m.conversionRate))}
        ${metricRow("Cost / Conv.", fmtMoney(m.costPerConversion))}
      </div>
    </div>

    <div class="section">
      <div class="card" style="padding:0; overflow:hidden">
        <div style="padding:16px 18px 0">
          <div class="card-title">📂 Ad Groups (${data.adGroups.length})</div>
        </div>
        <div class="table-wrap" style="border:none; border-radius:0">
          <table>
            <thead>
              <tr>
                <th>Ad Group</th>
                <th>Status</th>
                <th class="right">CPC Bid</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>
              </tr>
            </thead>
            <tbody>
              ${adGroupRows || `<tr><td colspan="8" style="text-align:center; color:var(--text-muted); padding:24px">No ad groups found</td></tr>`}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  `;

  return wrapHtml(`Campaign: ${c.name}`, body);
}
