/**
 * Ad Ops Email Templates
 * All outbound emails from the ad ops system
 */

export const SYSTEM_SIGNATURE = 'Relevant Media Properties Ad Ops System';

export function emailWrapper(content: string, publication?: string): string {
  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1"></head>
<body style="font-family: Arial, sans-serif; font-size: 14px; color: #333; max-width: 600px; margin: 0 auto; padding: 20px;">
${content}
<hr style="border: none; border-top: 1px solid #eee; margin: 24px 0;">
<p style="font-size: 12px; color: #888;">— ${SYSTEM_SIGNATURE}${publication ? ` | ${publication}` : ''}</p>
</body>
</html>`;
}

export function missingInfoBannerEmail(params: {
  clientName: string;
  missingFields: string[];
  hasImage?: boolean;
}): { subject: string; html: string } {
  const fieldList = params.missingFields
    .map((f, i) => `<li style="margin: 6px 0;">${i + 1}. ${f}</li>`)
    .join('');

  return {
    subject: `Re: ${params.clientName} Banner Campaign — Additional Info Needed`,
    html: emailWrapper(`
      <p>Hi Jeff — thanks for sending over the <strong>${params.clientName}</strong> banner${params.hasImage ? '' : ' (no image attached yet)'}.</p>
      <p>Before I get this set up, I need a few more details:</p>
      <ul style="padding-left: 20px;">${fieldList}</ul>
      <p>Once I have these I'll get it live and send you a confirmation screenshot.</p>
    `),
  };
}

export function missingInfoEmailDistEmail(params: {
  clientName: string;
  missingFields: string[];
}): { subject: string; html: string } {
  const fieldList = params.missingFields
    .map((f, i) => `<li style="margin: 6px 0;">${i + 1}. ${f}</li>`)
    .join('');

  return {
    subject: `Re: ${params.clientName} Email Distribution — Additional Info Needed`,
    html: emailWrapper(`
      <p>Hi Jeff — thanks for submitting the <strong>${params.clientName}</strong> email distribution.</p>
      <p>I need a few more details before I can proceed:</p>
      <ul style="padding-left: 20px;">${fieldList}</ul>
      <p>Once I have everything I'll send a test email for your approval.</p>
    `),
  };
}

export function bannerPreviewEmail(params: {
  clientName: string;
  publication: string;
  screenshotUrl?: string;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `${params.clientName} Banner Preview — Approval Needed`,
    html: emailWrapper(`
      <p>Hi Jeff — all details confirmed for the <strong>${params.clientName}</strong> campaign.</p>
      <p>Here's a preview of how the banner will appear on <strong>${params.publication}</strong>.</p>
      ${params.screenshotUrl
        ? `<p><img src="${params.screenshotUrl}" alt="Banner preview" style="max-width: 100%; border: 2px solid #e74c3c; border-radius: 4px;"></p>`
        : '<p><em>(Preview screenshot will be attached to this email.)</em></p>'
      }
      <p><strong>Reply "APPROVED" to go live</strong>, or let me know if any changes are needed.</p>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function emailTestSendEmail(params: {
  clientName: string;
  subject: string;
  listSize: number;
  scheduledDate: string;
  scheduledTime: string;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `[TEST] ${params.subject} — Approval Needed`,
    html: emailWrapper(`
      <p>Hi Jeff — test send for the <strong>${params.clientName}</strong> distribution is attached.</p>
      <p>Please review and reply <strong>"APPROVED"</strong> when ready to send to the full list of <strong>${params.listSize.toLocaleString()} recipients</strong> on <strong>${params.scheduledDate} at ${params.scheduledTime} ET</strong>.</p>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function bannerLiveEmail(params: {
  clientName: string;
  publication: string;
  startDate: string;
  endDate: string;
  campaignId: string;
  screenshotUrl?: string;
}): { subject: string; html: string } {
  return {
    subject: `${params.clientName} Banner is LIVE on ${params.publication} ✓`,
    html: emailWrapper(`
      <p>Hi Jeff — the banner for <strong>${params.clientName}</strong> is now <strong style="color: #27ae60;">LIVE</strong> on <strong>${params.publication}</strong>.</p>
      <p>Campaign runs <strong>${params.startDate}</strong> through <strong>${params.endDate}</strong>.</p>
      ${params.screenshotUrl
        ? `<p><img src="${params.screenshotUrl}" alt="Live banner screenshot" style="max-width: 100%; border: 2px solid #27ae60; border-radius: 4px;"></p>`
        : ''
      }
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function campaignEndedEmailJeff(params: {
  clientName: string;
  publication: string;
  endDate: string;
  impressions: number;
  clicks: number;
  ctr: number;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `${params.clientName} Campaign Ended — Final Stats`,
    html: emailWrapper(`
      <p>Hi Jeff — the <strong>${params.clientName}</strong> campaign on <strong>${params.publication}</strong> has ended as scheduled on <strong>${params.endDate}</strong>.</p>
      <table style="border-collapse: collapse; width: 100%; margin: 16px 0;">
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Impressions</td><td style="padding: 8px 12px;">${params.impressions.toLocaleString()}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Clicks</td><td style="padding: 8px 12px;">${params.clicks.toLocaleString()}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">CTR</td><td style="padding: 8px 12px;">${(params.ctr * 100).toFixed(2)}%</td></tr>
      </table>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function campaignEndedEmailRyan(params: {
  clientName: string;
  publication: string;
  endDate: string;
  impressions: number;
  clicks: number;
  ctr: number;
  campaignId: string;
  agreedRate: number;
  invoiceId?: string;
  invoiceStatus?: string;
}): { subject: string; html: string } {
  return {
    subject: `${params.clientName} Campaign Ended — Final Stats + Financial`,
    html: emailWrapper(`
      <p>The <strong>${params.clientName}</strong> campaign on <strong>${params.publication}</strong> has ended as scheduled on <strong>${params.endDate}</strong>.</p>
      <table style="border-collapse: collapse; width: 100%; margin: 16px 0;">
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Impressions</td><td style="padding: 8px 12px;">${params.impressions.toLocaleString()}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Clicks</td><td style="padding: 8px 12px;">${params.clicks.toLocaleString()}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">CTR</td><td style="padding: 8px 12px;">${(params.ctr * 100).toFixed(2)}%</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold; color: #2c3e50;">Revenue</td><td style="padding: 8px 12px; font-weight: bold; color: #27ae60;">$${params.agreedRate.toFixed(2)}</td></tr>
        ${params.invoiceId ? `<tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Invoice</td><td style="padding: 8px 12px;">${params.invoiceId} — ${params.invoiceStatus || 'unknown'}</td></tr>` : ''}
      </table>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function invoiceCreatedEmail(params: {
  clientName: string;
  campaignDescription: string;
  amount: number;
  invoiceNumber: string;
  dueDate: string;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `Invoice Created — ${params.clientName} ${params.campaignDescription}`,
    html: emailWrapper(`
      <p>Invoice created in MoonInvoice:</p>
      <table style="border-collapse: collapse; width: 100%; margin: 16px 0;">
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Invoice #</td><td style="padding: 8px 12px;">${params.invoiceNumber}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Client</td><td style="padding: 8px 12px;">${params.clientName}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Description</td><td style="padding: 8px 12px;">${params.campaignDescription}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Amount</td><td style="padding: 8px 12px; font-weight: bold; color: #27ae60;">$${params.amount.toFixed(2)}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Due Date</td><td style="padding: 8px 12px;">${params.dueDate}</td></tr>
      </table>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function ioReminderEmail(params: {
  clientName: string;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `Insertion Order Needed — ${params.clientName} Campaign`,
    html: emailWrapper(`
      <p>Hi Jeff — I need a signed insertion order before the <strong>${params.clientName}</strong> campaign can go live.</p>
      <p>Can you attach it to your reply? Once I have it I'll proceed with deployment.</p>
      <p><em>Note: If this campaign does not require an IO, reply with "NO IO NEEDED" and I'll proceed.</em></p>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function newsletterPreviewEmail(params: {
  publication: string;
  scheduledDate: string;
  issueNumber?: number;
}): { subject: string; html: string } {
  return {
    subject: `${params.publication} Newsletter Preview — Approval Needed`,
    html: emailWrapper(`
      <p>Hi Jeff — the <strong>${params.publication}</strong> bi-weekly newsletter${params.issueNumber ? ` (Issue #${params.issueNumber})` : ''} is ready for <strong>${params.scheduledDate}</strong>.</p>
      <p>Preview is attached. <strong>Reply "APPROVED"</strong> to send on Thursday at 11am ET, or let me know any changes.</p>
    `),
  };
}

export function newsletterReminderEmail(params: {
  publication: string;
  scheduledDate: string;
}): { subject: string; html: string } {
  return {
    subject: `⏰ ${params.publication} Newsletter Needs Approval by 5pm`,
    html: emailWrapper(`
      <p><strong>Reminder:</strong> The <strong>${params.publication}</strong> newsletter needs approval by <strong>5pm today</strong> to go out Thursday at 11am.</p>
      <p>Preview is attached. Reply "APPROVED" to confirm.</p>
    `),
  };
}

export function distributionScheduledEmail(params: {
  clientName: string;
  listSize: number;
  scheduledDate: string;
  scheduledTime: string;
  campaignId: string;
}): { subject: string; html: string } {
  return {
    subject: `${params.clientName} Distribution Scheduled`,
    html: emailWrapper(`
      <p>Distribution for <strong>${params.clientName}</strong> is scheduled for <strong>${params.scheduledDate} at ${params.scheduledTime} ET</strong> to <strong>${params.listSize.toLocaleString()} recipients</strong>.</p>
      <p>I'll send you a delivery report once complete.</p>
      <p style="font-size: 12px; color: #888;">Campaign ID: ${params.campaignId}</p>
    `),
  };
}

export function postSendReportEmailJeff(params: {
  clientName: string;
  sendDate: string;
  sent: number;
  delivered: number;
  bounced: number;
  unsubscribed: number;
  opens: number;
  uniqueOpens: number;
  openRate: number;
  clicks: number;
  uniqueClicks: number;
  clickRate: number;
  topLinks: { url: string; clicks: number }[];
}): { subject: string; html: string } {
  const topLinksHtml = params.topLinks.slice(0, 5)
    .map((l, i) => `<tr${i % 2 === 0 ? ' style="background: #f5f5f5;"' : ''}><td style="padding: 6px 12px;">${i + 1}. ${l.url}</td><td style="padding: 6px 12px;">${l.clicks}</td></tr>`)
    .join('');

  return {
    subject: `${params.clientName} Distribution Report — ${params.sendDate}`,
    html: emailWrapper(`
      <p>Here's the delivery report for the <strong>${params.clientName}</strong> distribution sent on <strong>${params.sendDate}</strong>.</p>
      <table style="border-collapse: collapse; width: 100%; margin: 16px 0;">
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Sent</td><td style="padding: 8px 12px;">${params.sent.toLocaleString()}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Delivered</td><td style="padding: 8px 12px;">${params.delivered.toLocaleString()}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Bounced</td><td style="padding: 8px 12px;">${params.bounced.toLocaleString()}</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Unsubscribed</td><td style="padding: 8px 12px;">${params.unsubscribed.toLocaleString()}</td></tr>
        <tr style="background: #f5f5f5;"><td style="padding: 8px 12px; font-weight: bold;">Opens (Unique)</td><td style="padding: 8px 12px;">${params.uniqueOpens.toLocaleString()} (${(params.openRate * 100).toFixed(1)}%)</td></tr>
        <tr><td style="padding: 8px 12px; font-weight: bold;">Clicks (Unique)</td><td style="padding: 8px 12px;">${params.uniqueClicks.toLocaleString()} (${(params.clickRate * 100).toFixed(1)}%)</td></tr>
      </table>
      ${topLinksHtml ? `<p><strong>Top Clicked Links:</strong></p><table style="border-collapse: collapse; width: 100%;">${topLinksHtml}</table>` : ''}
    `),
  };
}

export function jeffWelcomeEmail(): { subject: string; html: string; to: string; cc: string } {
  return {
    to: 'jeff@avbeat.com',
    cc: 'ryan.salazar@relevantmediaproperties.com',
    subject: 'Your New Ad Ops System is Ready',
    html: emailWrapper(`
      <p>Hi Jeff — your new advertising operations system is ready. Here's how to use it:</p>
      <h3 style="color: #2c3e50; margin-top: 20px;">BANNER ADS</h3>
      <p>Email <a href="mailto:adops@avbeat.com">adops@avbeat.com</a> with the banner image attached and tell me: which publication, which placement, the click-through URL, and the campaign dates. I'll handle the rest and send you a screenshot for approval before anything goes live.</p>
      <h3 style="color: #2c3e50; margin-top: 20px;">EMAIL DISTRIBUTIONS</h3>
      <p>Email <a href="mailto:adops@avbeat.com">adops@avbeat.com</a> with the HTML file attached along with the subject line, send date, and recipient list. I'll send you a test email for approval before sending to the full list.</p>
      <h3 style="color: #2c3e50; margin-top: 20px;">INSERTION ORDERS</h3>
      <p>Please attach the signed IO to your campaign email. I'll store it automatically and create the invoice.</p>
      <p style="margin-top: 20px;">Questions? Just reply to this email and I'll take care of everything.</p>
    `),
  };
}
