// ============================================
// APP: Performance Overview — Account-level KPI Dashboard
// ============================================

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

export interface PerformanceOverviewData {
  accountName?: string;
  period: string;
  kpis: {
    totalSpend: number;       // micros
    clicks: number;
    impressions: number;
    ctr: number;              // decimal
    avgCpc: number;           // micros
    conversions: number;
  };
  previousKpis?: {
    totalSpend: number;
    clicks: number;
    impressions: number;
    ctr: number;
    avgCpc: number;
    conversions: number;
  };
  dailySpend: DailySpendPoint[];
  topCampaigns: TopCampaign[];
}

export interface DailySpendPoint {
  date: string;       // e.g. "Mon", "Tue" or "2024-01-15"
  spend: number;      // micros
}

export interface TopCampaign {
  name: string;
  spend: number;      // micros
  conversions: number;
  ctr: number;
  roas?: number;
}

function kpiCard(label: string, value: string, current: number, previous?: number): string {
  let deltaHtml = "";
  if (previous !== undefined && previous !== 0) {
    const pctChange = ((current - previous) / Math.abs(previous)) * 100;
    const arrow = pctChange >= 0 ? "↑" : "↓";
    const cls = pctChange >= 0 ? "up" : "down";
    deltaHtml = `<div class="kpi-delta ${cls}">${arrow} ${Math.abs(pctChange).toFixed(1)}%</div>`;
  } else {
    deltaHtml = `<div class="kpi-delta neutral">—</div>`;
  }

  return `
    <div class="kpi-card">
      <div class="kpi-value">${value}</div>
      <div class="kpi-label">${escapeHtml(label)}</div>
      ${deltaHtml}
    </div>`;
}

export function renderPerformanceOverview(data: PerformanceOverviewData): string {
  const k = data.kpis;
  const p = data.previousKpis;

  const kpis = [
    kpiCard("Total Spend", fmtMoney(k.totalSpend), k.totalSpend, p?.totalSpend),
    kpiCard("Clicks", fmtNum(k.clicks), k.clicks, p?.clicks),
    kpiCard("Impressions", fmtNum(k.impressions), k.impressions, p?.impressions),
    kpiCard("CTR", fmtPct(k.ctr), k.ctr, p?.ctr),
    kpiCard("Avg CPC", fmtMoney(k.avgCpc), k.avgCpc, p?.avgCpc),
    kpiCard("Conversions", fmtNum(k.conversions), k.conversions, p?.conversions),
  ].join("\n");

  // Daily spend bar chart (CSS-only)
  const maxSpend = Math.max(...data.dailySpend.map((d) => d.spend), 1);
  const bars = data.dailySpend.map((d) => {
    const heightPct = (d.spend / maxSpend) * 100;
    const shortDate = d.date.length > 5 ? d.date.slice(-5) : d.date;
    return `
      <div class="bar-col">
        <div style="font-size:10px; color:var(--text-muted); font-family:var(--mono)">${fmtMoney(d.spend)}</div>
        <div class="bar" style="height:${heightPct}%"></div>
        <div class="bar-label">${escapeHtml(shortDate)}</div>
      </div>`;
  }).join("\n");

  // Top campaigns table
  const rows = data.topCampaigns.map((c, i) => `
    <tr>
      <td style="color:var(--text-muted); font-weight:600">${i + 1}</td>
      <td>${escapeHtml(c.name)}</td>
      <td class="right text-mono">${fmtMoney(c.spend)}</td>
      <td class="right text-mono">${fmtNum(c.conversions)}</td>
      <td class="right text-mono">${fmtPct(c.ctr)}</td>
      <td class="right text-mono">${c.roas !== undefined ? c.roas.toFixed(2) + "x" : "—"}</td>
    </tr>`
  ).join("\n");

  const body = `
    <div class="app-header">
      <h1>📈 Performance Overview</h1>
      <div class="subtitle">${data.accountName ? escapeHtml(data.accountName) + " · " : ""}${escapeHtml(data.period)}</div>
    </div>

    <div class="section grid-6">
      ${kpis}
    </div>

    <div class="section">
      <div class="card">
        <div class="card-title">Daily Spend — Last 7 Days</div>
        <div class="bar-chart">
          ${bars}
        </div>
      </div>
    </div>

    <div class="section">
      <div class="card" style="padding:0; overflow:hidden">
        <div style="padding:16px 18px 0">
          <div class="card-title">Top Campaigns</div>
        </div>
        <div class="table-wrap" style="border:none; border-radius:0">
          <table>
            <thead>
              <tr>
                <th style="width:32px">#</th>
                <th>Campaign</th>
                <th class="right">Spend</th>
                <th class="right">Conv.</th>
                <th class="right">CTR</th>
                <th class="right">ROAS</th>
              </tr>
            </thead>
            <tbody>
              ${rows}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  `;

  return wrapHtml("Performance Overview", body);
}
