/**
 * Branded HTML email template for intelligence reports.
 * Table-based layout with inline CSS for Gmail/Outlook/Apple Mail.
 */

export interface EmailReportData {
  brandName: string;
  brandDomain: string;
  brandLogoUrl?: string | null;
  period: string; // "Apr 1 – Apr 7, 2026"
  frequency: string;
  appUrl: string;

  // Data sections
  gsc?: { clicks: number; impressions: number; ctr: number; position: number; clicksDelta?: number; impressionsDelta?: number };
  ga4?: { sessions: number; conversions: number; newUsers: number; sessionsDelta?: number };
  auditHealth?: number;
  newIssues?: number;
  rankChanges?: Array<{ keyword: string; from: number | null; to: number | null }>;
  newPages?: string[];
  pages404?: string[];
  conversions?: { total: number; byChannel: Array<{ channel: string; count: number }> };
  /** Site Tag first-party analytics for the period. Populated when
   *  schedule.sections includes "site_tag" AND the brand has a
   *  TrackedSite installed. Pulled from TrackedEvent (sessions,
   *  pageviews, top pages) + SiteEvent (outbound clicks, form
   *  starts) so the email carries data the server has independently
   *  of GA4 / GSC. */
  siteTag?: {
    pageViews: number;
    sessions: number;
    formStarts: number;
    outboundClicks: number;
    conversionRate: number | null; // percentage, null when sessions === 0
    topPages: Array<{ url: string; views: number }>;
  };
  uxSignals?: { rageClicks: number; jsErrors: number };

  // AI Attribution performance
  aiPerformance?: {
    referrals: number;
    conversions: number;
    newCitations: number;
    topPage: string | null;
    referralsDelta?: number;
  };

  // AI-generated content
  aiSummary?: string;
  aiWins?: string[];
  aiConcerns?: string[];
  aiRecommendation?: string;
  competitorActivity?: string;
  marketInsights?: string;
}

function esc(s: unknown): string { return String(s ?? "").replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;"); }
function num(n: number): string { return n.toLocaleString(); }
function delta(n: number | undefined): string {
  if (n == null) return "";
  const sign = n >= 0 ? "+" : "";
  const color = n >= 0 ? "#16a34a" : "#dc2626";
  return ` <span style="color:${color};font-weight:700;font-size:12px;">${sign}${n.toFixed(1)}%</span>`;
}

function section(title: string, body: string): string {
  return `<tr><td style="padding:24px 32px 0">
    <h2 style="margin:0 0 12px;font-size:16px;font-weight:700;color:#0f172a;border-bottom:2px solid #e2e8f0;padding-bottom:8px">${esc(title)}</h2>
    ${body}
  </td></tr>`;
}

function metric(label: string, value: string, deltaHtml = ""): string {
  return `<td style="padding:8px 16px;text-align:center;vertical-align:top;width:25%">
    <div style="font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:1px;font-weight:700">${esc(label)}</div>
    <div style="font-size:28px;font-weight:800;color:#0f172a;margin-top:4px">${value}${deltaHtml}</div>
  </td>`;
}

function bulletList(items: string[], color = "#0f172a"): string {
  return items.map((item) => `<li style="margin-bottom:6px;color:${color};font-size:14px;line-height:1.6">${esc(item)}</li>`).join("");
}

export function buildReportEmail(data: EmailReportData): string {
  const rows: string[] = [];

  // KPI row
  if (data.gsc || data.ga4) {
    const cells: string[] = [];
    if (data.gsc) {
      cells.push(metric("Clicks", num(data.gsc.clicks), delta(data.gsc.clicksDelta)));
      cells.push(metric("Impressions", num(data.gsc.impressions), delta(data.gsc.impressionsDelta)));
    }
    if (data.ga4) {
      cells.push(metric("Sessions", num(data.ga4.sessions), delta(data.ga4.sessionsDelta)));
      cells.push(metric("Conversions", num(data.ga4.conversions)));
    }
    rows.push(`<tr><td style="padding:24px 32px 0"><table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>${cells.join("")}</tr></table></td></tr>`);
  }

  // AI Summary
  if (data.aiSummary) {
    rows.push(section("Executive Summary", `<p style="font-size:14px;color:#334155;line-height:1.7;margin:0">${esc(data.aiSummary)}</p>`));
  }

  // Wins & Concerns
  if (data.aiWins?.length) {
    rows.push(section("Wins", `<ul style="margin:0;padding-left:20px">${bulletList(data.aiWins, "#16a34a")}</ul>`));
  }
  if (data.aiConcerns?.length) {
    rows.push(section("Concerns", `<ul style="margin:0;padding-left:20px">${bulletList(data.aiConcerns, "#dc2626")}</ul>`));
  }
  if (data.aiRecommendation) {
    rows.push(section("Key Recommendation", `<p style="font-size:14px;color:#334155;line-height:1.7;margin:0;padding:12px 16px;background:#f0fdf4;border-left:4px solid #16a34a;border-radius:4px">${esc(data.aiRecommendation)}</p>`));
  }

  // Rank changes
  if (data.rankChanges?.length) {
    const trs = data.rankChanges.slice(0, 10).map((r) => {
      const fromStr = r.from != null ? String(r.from) : "—";
      const toStr = r.to != null ? String(r.to) : "—";
      const improved = r.to != null && (r.from == null || r.to < r.from);
      const color = improved ? "#16a34a" : "#dc2626";
      return `<tr><td style="padding:6px 12px;font-size:13px;color:#0f172a">${esc(r.keyword)}</td><td style="padding:6px 12px;font-size:13px;color:#64748b;text-align:center">${fromStr}</td><td style="padding:6px 12px;font-size:13px;font-weight:700;color:${color};text-align:center">${toStr}</td></tr>`;
    }).join("");
    rows.push(section("Ranking Changes", `<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid #e2e8f0;border-radius:8px;overflow:hidden">
      <tr style="background:#f8fafc"><th style="padding:8px 12px;text-align:left;font-size:11px;color:#64748b;text-transform:uppercase;letter-spacing:1px">Keyword</th><th style="text-align:center;padding:8px;font-size:11px;color:#64748b">Before</th><th style="text-align:center;padding:8px;font-size:11px;color:#64748b">Now</th></tr>
      ${trs}</table>`));
  }

  // Conversions
  if (data.conversions && data.conversions.total > 0) {
    const channels = data.conversions.byChannel.slice(0, 5).map((c) => `<li style="margin-bottom:4px;font-size:13px;color:#334155">${esc(c.channel)}: <strong>${c.count}</strong></li>`).join("");
    rows.push(section(`Conversions (${num(data.conversions.total)} total)`, `<ul style="margin:0;padding-left:20px">${channels}</ul>`));
  }

  // Page lifecycle
  if (data.newPages?.length || data.pages404?.length) {
    let body = "";
    if (data.newPages?.length) body += `<p style="font-size:13px;color:#334155;margin:0 0 8px"><strong>${data.newPages.length} new page(s)</strong> detected: ${data.newPages.slice(0, 5).map(esc).join(", ")}</p>`;
    if (data.pages404?.length) body += `<p style="font-size:13px;color:#dc2626;margin:0"><strong>${data.pages404.length} page(s) went 404</strong>: ${data.pages404.slice(0, 5).map(esc).join(", ")}</p>`;
    rows.push(section("Page Lifecycle", body));
  }

  // Site Tag first-party analytics — rendered when the schedule
  // includes "site_tag" and the brand has a Site Tag installed.
  // Keeps the copy compact: one-line vitals on top, short top-
  // pages list below. Email clients don't tolerate fancy layouts
  // (Outlook's Word renderer is especially finicky) so we stick
  // to plain <p> tags + pipe separators.
  if (data.siteTag && data.siteTag.sessions > 0) {
    const st = data.siteTag;
    const convRate = st.conversionRate != null ? `${st.conversionRate.toFixed(2)}%` : "—";
    let body = `<p style="font-size:13px;color:#334155;margin:0 0 8px">`
      + `${num(st.sessions)} sessions · ${num(st.pageViews)} page views · ${num(st.formStarts)} form starts · ${num(st.outboundClicks)} outbound clicks · ${esc(convRate)} conversion rate`
      + `</p>`;
    if (st.topPages.length > 0) {
      body += `<p style="font-size:12px;color:#64748b;margin:0 0 4px;font-weight:600">Top pages</p><ul style="margin:0;padding-left:18px;font-size:13px;color:#334155;line-height:1.5">`;
      for (const p of st.topPages.slice(0, 5)) {
        body += `<li>${esc(p.url.replace(/^https?:\/\/[^/]+/, "") || "/")} — ${num(p.views)} views</li>`;
      }
      body += `</ul>`;
    }
    rows.push(section("Site Tag Analytics", body));
  }

  // UX signals
  if (data.uxSignals && (data.uxSignals.rageClicks > 0 || data.uxSignals.jsErrors > 0)) {
    rows.push(section("UX Signals", `<p style="font-size:13px;color:#334155;margin:0">${data.uxSignals.rageClicks} rage clicks · ${data.uxSignals.jsErrors} JS errors this period</p>`));
  }

  // AI Performance
  if (data.aiPerformance && (data.aiPerformance.referrals > 0 || data.aiPerformance.newCitations > 0)) {
    const ai = data.aiPerformance;
    let body = `<p style="font-size:13px;color:#334155;margin:0 0 4px">AI referrals: <b>${num(ai.referrals)}</b>${ai.referralsDelta != null ? ` ${delta(ai.referralsDelta)}` : ""}</p>`;
    body += `<p style="font-size:13px;color:#334155;margin:0 0 4px">AI conversions: <b>${num(ai.conversions)}</b></p>`;
    if (ai.newCitations > 0) body += `<p style="font-size:13px;color:#334155;margin:0 0 4px">New AI citations detected: <b>${num(ai.newCitations)}</b></p>`;
    if (ai.topPage) body += `<p style="font-size:13px;color:#334155;margin:0">Top AI page: <b>${esc(ai.topPage)}</b></p>`;
    rows.push(section("AI Performance", body));
  }

  // Competitor
  if (data.competitorActivity) rows.push(section("Competitor Activity", `<p style="font-size:14px;color:#334155;line-height:1.7;margin:0">${esc(data.competitorActivity)}</p>`));
  if (data.marketInsights) rows.push(section("Market Insights", `<p style="font-size:14px;color:#334155;line-height:1.7;margin:0">${esc(data.marketInsights)}</p>`));

  const logoHtml = data.brandLogoUrl
    ? `<img src="${esc(data.brandLogoUrl)}" alt="${esc(data.brandName)}" style="max-height:40px;max-width:160px" />`
    : `<span style="font-size:20px;font-weight:800;color:#0f172a">${esc(data.brandName)}</span>`;

  return `<!DOCTYPE html><html lang="en"><head><meta charset="UTF-8"><meta name="viewport" content="width=device-width,initial-scale=1"></head>
<body style="margin:0;padding:0;background:#f1f5f9;font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,Oxygen,sans-serif">
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#f1f5f9"><tr><td align="center" style="padding:24px 16px">
<table role="presentation" width="600" cellpadding="0" cellspacing="0" style="background:#ffffff;border-radius:12px;overflow:hidden;max-width:600px;width:100%">

  <!-- Header -->
  <tr><td style="background:linear-gradient(135deg,#0F172A,#1E293B);padding:32px;text-align:center">
    <div style="margin-bottom:12px">${logoHtml.replace(/#0f172a/g, "#ffffff")}</div>
    <h1 style="margin:0;font-size:22px;font-weight:700;color:#ffffff">${esc(data.frequency.charAt(0).toUpperCase() + data.frequency.slice(1))} Intelligence Report</h1>
    <p style="margin:8px 0 0;font-size:13px;color:rgba(255,255,255,.8)">${esc(data.period)} · ${esc(data.brandDomain)}</p>
  </td></tr>

  ${rows.join("\n")}

  <!-- CTA -->
  <tr><td style="padding:32px;text-align:center">
    <a href="${esc(data.appUrl)}" style="display:inline-block;padding:14px 32px;background:#EF4444;color:#ffffff;font-weight:700;font-size:14px;border-radius:8px;text-decoration:none">View Full Report in meSEO</a>
  </td></tr>

  <!-- Footer -->
  <tr><td style="padding:16px 32px;border-top:1px solid #e2e8f0;text-align:center">
    <p style="margin:0;font-size:11px;color:#94a3b8">Powered by <strong style="color:#EF4444">meSEO</strong> · Automated Intelligence Report</p>
    <p style="margin:4px 0 0;font-size:11px;color:#cbd5e1">You're receiving this because an admin configured email reports for ${esc(data.brandName)}.</p>
  </td></tr>

</table>
</td></tr></table></body></html>`;
}
