// ============================================
// APP: Budget Optimizer — Budget allocation view
// ============================================

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

export interface BudgetOptimizerData {
  accountName?: string;
  period?: string;
  totalBudget: number;         // micros
  totalSpend: number;          // micros
  campaigns: BudgetCampaignRow[];
  suggestions?: BudgetSuggestion[];
}

export interface BudgetCampaignRow {
  name: string;
  dailyBudget: number;        // micros
  actualSpend: number;        // micros
  conversions: number;
  costPerConversion: number;  // micros
  roas?: number;
}

export interface BudgetSuggestion {
  campaignName: string;
  action: string;              // e.g. "Increase budget by 20%", "Reallocate $50/day to..."
  reason: string;
  estimatedImpact?: string;
}

type SpendStatus = "underspent" | "on-track" | "overspent";

function getSpendStatus(budget: number, spend: number): SpendStatus {
  if (budget <= 0) return "on-track";
  const ratio = spend / budget;
  if (ratio < 0.7) return "underspent";
  if (ratio > 1.0) return "overspent";
  return "on-track";
}

function statusColor(status: SpendStatus): string {
  switch (status) {
    case "underspent": return "blue";
    case "on-track": return "green";
    case "overspent": return "red";
  }
}

function statusLabel(status: SpendStatus): string {
  switch (status) {
    case "underspent": return "Underspent";
    case "on-track": return "On Track";
    case "overspent": return "Overspent";
  }
}

function statusPillClass(status: SpendStatus): string {
  switch (status) {
    case "underspent": return "pill-blue";
    case "on-track": return "pill-green";
    case "overspent": return "pill-red";
  }
}

export function renderBudgetOptimizer(data: BudgetOptimizerData): string {
  const { campaigns, totalBudget, totalSpend } = data;
  const utilizationPct = totalBudget > 0 ? (totalSpend / totalBudget) * 100 : 0;
  const utilizationColor = utilizationPct > 100 ? "red" : utilizationPct > 85 ? "yellow" : "green";

  const underspent = campaigns.filter((c) => getSpendStatus(c.dailyBudget, c.actualSpend) === "underspent").length;
  const onTrack = campaigns.filter((c) => getSpendStatus(c.dailyBudget, c.actualSpend) === "on-track").length;
  const overspent = campaigns.filter((c) => getSpendStatus(c.dailyBudget, c.actualSpend) === "overspent").length;

  // Stacked allocation bar
  const maxBudget = Math.max(...campaigns.map((c) => c.dailyBudget), 1);
  const allocationBars = campaigns.map((c) => {
    const budgetPct = (c.dailyBudget / totalBudget) * 100;
    const spendPct = c.dailyBudget > 0 ? (c.actualSpend / c.dailyBudget) * 100 : 0;
    const status = getSpendStatus(c.dailyBudget, c.actualSpend);
    const color = statusColor(status);

    return `
      <div class="alloc-row">
        <div class="alloc-label">
          <span style="font-weight:500">${escapeHtml(c.name)}</span>
          <span class="pill ${statusPillClass(status)}" style="font-size:9px">${statusLabel(status)}</span>
        </div>
        <div class="alloc-bars">
          <div class="alloc-track">
            <div class="alloc-budget" style="width:100%"></div>
            <div class="alloc-spend alloc-${color}" style="width:${Math.min(spendPct, 100)}%"></div>
          </div>
          <div class="alloc-values">
            <span class="text-mono">${fmtMoney(c.actualSpend)}</span>
            <span class="text-muted"> / ${fmtMoney(c.dailyBudget)}</span>
          </div>
        </div>
      </div>`;
  }).join("\n");

  // Campaign detail table
  const tableRows = campaigns.map((c) => {
    const status = getSpendStatus(c.dailyBudget, c.actualSpend);
    return `
      <tr>
        <td style="font-weight:500">${escapeHtml(c.name)}</td>
        <td><span class="pill ${statusPillClass(status)}">${statusLabel(status)}</span></td>
        <td class="right text-mono">${fmtMoney(c.dailyBudget)}</td>
        <td class="right text-mono">${fmtMoney(c.actualSpend)}</td>
        <td class="right text-mono">${fmtNum(c.conversions)}</td>
        <td class="right text-mono">${fmtMoney(c.costPerConversion)}</td>
        <td class="right text-mono">${c.roas !== undefined ? c.roas.toFixed(2) + "x" : "—"}</td>
      </tr>`;
  }).join("\n");

  // Suggestions
  const suggestionsHtml = data.suggestions?.length ? data.suggestions.map((s) => `
    <div class="card" style="border-left:3px solid var(--highlight)">
      <div style="font-weight:600; font-size:13px; margin-bottom:4px">📂 ${escapeHtml(s.campaignName)}</div>
      <div style="font-size:14px; font-weight:500; color:var(--text-primary); margin-bottom:4px">${escapeHtml(s.action)}</div>
      <div style="font-size:12px; color:var(--text-secondary)">${escapeHtml(s.reason)}</div>
      ${s.estimatedImpact ? `<div style="margin-top:8px"><span class="pill pill-green" style="font-size:11px">⬆ ${escapeHtml(s.estimatedImpact)}</span></div>` : ""}
    </div>`
  ).join("\n") : `<div class="card" style="text-align:center; color:var(--text-muted); padding:24px">No reallocation suggestions at this time</div>`;

  const body = `
    <style>
      .alloc-row {
        margin-bottom: 14px;
      }
      .alloc-label {
        display: flex;
        align-items: center;
        gap: 8px;
        margin-bottom: 6px;
        font-size: 13px;
      }
      .alloc-bars {
        display: flex;
        align-items: center;
        gap: 12px;
      }
      .alloc-track {
        flex: 1;
        height: 14px;
        background: var(--bg-input);
        border-radius: 7px;
        overflow: hidden;
        position: relative;
      }
      .alloc-budget {
        position: absolute;
        inset: 0;
        background: var(--border);
        border-radius: 7px;
      }
      .alloc-spend {
        position: absolute;
        top: 0; left: 0; bottom: 0;
        border-radius: 7px;
        transition: width 0.3s;
      }
      .alloc-blue  { background: var(--blue); }
      .alloc-green { background: var(--green); }
      .alloc-red   { background: var(--red); }
      .alloc-values {
        font-size: 12px;
        white-space: nowrap;
        min-width: 140px;
      }
      .suggestion-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(320px, 1fr));
        gap: 12px;
      }
    </style>

    <div class="app-header">
      <h1>💰 Budget Optimizer</h1>
      <div class="subtitle">${data.accountName ? escapeHtml(data.accountName) + " · " : ""}${data.period ? escapeHtml(data.period) : "Current Period"}</div>
    </div>

    <div class="section grid-4">
      <div class="kpi-card">
        <div class="kpi-value">${fmtMoney(totalBudget)}</div>
        <div class="kpi-label">Total Budget</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value">${fmtMoney(totalSpend)}</div>
        <div class="kpi-label">Total Spend</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value" style="color:var(--${utilizationColor})">${utilizationPct.toFixed(1)}%</div>
        <div class="kpi-label">Utilization</div>
      </div>
      <div class="kpi-card">
        <div class="flex gap-8" style="justify-content:center">
          <span class="text-blue" style="font-weight:700">${underspent}</span>
          <span class="text-green" style="font-weight:700">${onTrack}</span>
          <span class="text-red" style="font-weight:700">${overspent}</span>
        </div>
        <div class="kpi-label">Under / On / Over</div>
      </div>
    </div>

    <div class="section">
      <div class="card">
        <div class="card-title">Budget Allocation</div>
        <div class="mt-16">
          ${allocationBars}
        </div>
        <div style="display:flex; gap:16px; margin-top:16px; font-size:11px">
          <span><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:var(--blue);vertical-align:middle;margin-right:4px"></span>Underspent</span>
          <span><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:var(--green);vertical-align:middle;margin-right:4px"></span>On Track</span>
          <span><span style="display:inline-block;width:10px;height:10px;border-radius:2px;background:var(--red);vertical-align:middle;margin-right:4px"></span>Overspent</span>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="card" style="padding:0; overflow:hidden">
        <div style="padding:16px 18px 0">
          <div class="card-title">Campaign Breakdown</div>
        </div>
        <div class="table-wrap" style="border:none; border-radius:0">
          <table>
            <thead>
              <tr>
                <th>Campaign</th>
                <th>Status</th>
                <th class="right">Budget</th>
                <th class="right">Spend</th>
                <th class="right">Conv.</th>
                <th class="right">Cost/Conv</th>
                <th class="right">ROAS</th>
              </tr>
            </thead>
            <tbody>
              ${tableRows}
            </tbody>
          </table>
        </div>
      </div>
    </div>

    <div class="section">
      <div class="section-title">🔄 Reallocation Suggestions</div>
      <div class="suggestion-grid">
        ${suggestionsHtml}
      </div>
    </div>
  `;

  return wrapHtml("Budget Optimizer", body);
}
