// ============================================
// APP: Recommendations — Google optimization recommendations
// ============================================

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

export interface RecommendationsData {
  accountName?: string;
  recommendations: RecommendationItem[];
}

export interface RecommendationItem {
  type: string;
  category: string;          // BIDS, KEYWORDS, ADS, TARGETING, BUDGET, EXTENSIONS, etc.
  impact: "LOW" | "MEDIUM" | "HIGH";
  title: string;
  description: string;
  campaignName?: string;
  estimatedImprovement?: string;  // e.g. "+12% clicks", "+$240 revenue"
  resourceName?: string;
}

function impactBadge(impact: string): string {
  const i = impact.toUpperCase();
  const map: Record<string, { cls: string; icon: string }> = {
    HIGH:   { cls: "pill-red",    icon: "🔴" },
    MEDIUM: { cls: "pill-yellow", icon: "🟡" },
    LOW:    { cls: "pill-blue",   icon: "🔵" },
  };
  const m = map[i] || { cls: "pill-muted", icon: "⚪" };
  return `<span class="pill ${m.cls}">${m.icon} ${i} IMPACT</span>`;
}

function categoryPill(category: string): string {
  const cat = category.toUpperCase();
  const colorMap: Record<string, string> = {
    BIDS: "pill-purple",
    KEYWORDS: "pill-blue",
    ADS: "pill-orange",
    TARGETING: "pill-green",
    BUDGET: "pill-red",
    EXTENSIONS: "pill-yellow",
    BIDDING: "pill-purple",
    CAMPAIGN: "pill-blue",
  };
  const cls = colorMap[cat] || "pill-muted";
  return `<span class="pill ${cls}">${escapeHtml(cat)}</span>`;
}

export function renderRecommendations(data: RecommendationsData): string {
  const recs = data.recommendations;
  const byImpact = { HIGH: 0, MEDIUM: 0, LOW: 0 };
  recs.forEach((r) => {
    const key = r.impact.toUpperCase() as keyof typeof byImpact;
    if (key in byImpact) byImpact[key]++;
  });

  // Group by category
  const categories = [...new Set(recs.map((r) => r.category.toUpperCase()))];

  const cards = recs.map((r) => `
    <div class="card rec-card">
      <div class="flex-between mb-8">
        ${impactBadge(r.impact)}
        ${categoryPill(r.category)}
      </div>
      <div class="rec-title">${escapeHtml(r.title)}</div>
      <div class="rec-desc">${escapeHtml(r.description)}</div>
      ${r.campaignName ? `<div class="rec-campaign">📂 ${escapeHtml(r.campaignName)}</div>` : ""}
      ${r.estimatedImprovement ? `
        <div class="rec-improvement">
          <span class="pill pill-green" style="font-size:11px">⬆ ${escapeHtml(r.estimatedImprovement)}</span>
        </div>
      ` : ""}
    </div>`
  ).join("\n");

  const body = `
    <style>
      .rec-grid {
        display: grid;
        grid-template-columns: repeat(auto-fill, minmax(340px, 1fr));
        gap: 16px;
      }
      .rec-card {
        display: flex;
        flex-direction: column;
        gap: 4px;
      }
      .rec-title {
        font-size: 14px;
        font-weight: 600;
        color: var(--text-primary);
        margin-top: 8px;
        line-height: 1.4;
      }
      .rec-desc {
        font-size: 13px;
        color: var(--text-secondary);
        line-height: 1.5;
        margin-top: 4px;
      }
      .rec-campaign {
        font-size: 12px;
        color: var(--text-muted);
        margin-top: 8px;
      }
      .rec-improvement {
        margin-top: 10px;
      }
      .filter-bar {
        display: flex;
        gap: 8px;
        flex-wrap: wrap;
        margin-bottom: 16px;
      }
    </style>

    <div class="app-header">
      <h1>💡 Optimization Recommendations</h1>
      <div class="subtitle">${data.accountName ? escapeHtml(data.accountName) + " · " : ""}${recs.length} recommendations</div>
    </div>

    <div class="section grid-3">
      <div class="kpi-card">
        <div class="kpi-value text-red">${byImpact.HIGH}</div>
        <div class="kpi-label">High Impact</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value text-yellow">${byImpact.MEDIUM}</div>
        <div class="kpi-label">Medium Impact</div>
      </div>
      <div class="kpi-card">
        <div class="kpi-value text-blue">${byImpact.LOW}</div>
        <div class="kpi-label">Low Impact</div>
      </div>
    </div>

    <div class="section">
      <div class="filter-bar">
        ${categories.map((cat) => categoryPill(cat)).join(" ")}
      </div>
    </div>

    <div class="rec-grid">
      ${cards || `<div class="card" style="text-align:center; color:var(--text-muted); padding:40px">No recommendations available</div>`}
    </div>
  `;

  return wrapHtml("Recommendations", body);
}
