export interface AuditEmailContext {
  // For the greeting line ("Dear Ms. Harshani,")
  recipientName: string;

  // Body fields shown in the audit details table
  companyName: string;
  auditeeName: string;
  auditeeContact: string;
  auditeeEmail: string;
  standards: string;
  dateTimeOfAudit: string;
  locationDetails: string;
  certification: string;
  accreditation: string;
  marketingRemarks?: string;

  // Header & intro text vary per event type
  introLine: string;
  subjectPrefix?: string;

  // Status colour for the highlighted accent (yellow / red / green)
  highlightColor?: 'yellow' | 'red' | 'green';

  // Signature block — sender's contact info
  senderName: string;
  senderTitle: string;
  senderPhone: string;
  senderEmail: string;
  senderAddress: string;
  senderWebsite: string;

  // Optional CTA button below the table
  ctaLabel?: string;
  ctaUrl?: string;
}

/**
 * Builds the full HTML email body in the QRS audit format.
 * Table-based, inline-styled, with MSO conditional comments — renders
 * reliably in Outlook (Word engine), Gmail, Apple Mail, and mobile.
 */
export function buildAuditEmail(ctx: AuditEmailContext): string {
  const highlight = ctx.highlightColor ?? 'yellow';

  // Status accent — header band colour + label text
  const theme = {
    yellow: { accent: '#d97706', soft: '#fef3c7', label: 'Audit Request' },
    green: { accent: '#16a34a', soft: '#dcfce7', label: 'Audit Confirmed' },
    red: { accent: '#dc2626', soft: '#fee2e2', label: 'Audit Update' },
  }[highlight];

  const BRAND = '#4a0080';
  const INK = '#0f172a';
  const MUTED = '#64748b';
  const BORDER = '#e2e8f0';

  // Detail rows — label / value pairs
  const rows: Array<[string, string]> = [
    ['Company', ctx.companyName],
    ['Auditee', ctx.auditeeName],
    ['Contact No', ctx.auditeeContact],
    [
      'Email',
      `<a href="mailto:${ctx.auditeeEmail}" style="color:${BRAND};text-decoration:none;">${ctx.auditeeEmail}</a>`,
    ],
    ['Standard(s)', ctx.standards],
    ['Date &amp; Time', ctx.dateTimeOfAudit],
    ['Location', ctx.locationDetails],
    ['Certification', ctx.certification],
    ['Accreditation', ctx.accreditation],
  ];

  const rowsHtml = rows
    .map(
      ([label, value], i) => `
      <tr>
        <td style="padding:11px 16px;background:${i % 2 ? '#ffffff' : '#f8fafc'};border-bottom:1px solid ${BORDER};font-size:12px;font-weight:600;color:${MUTED};text-transform:uppercase;letter-spacing:0.04em;width:38%;vertical-align:top;">
          ${label}
        </td>
        <td style="padding:11px 16px;background:${i % 2 ? '#ffffff' : '#f8fafc'};border-bottom:1px solid ${BORDER};font-size:14px;font-weight:600;color:${INK};vertical-align:top;word-break:break-word;">
          ${value}
        </td>
      </tr>`,
    )
    .join('');

  // Marketing remarks — highlighted callout row
  const remarksRow = ctx.marketingRemarks
    ? `
      <tr>
        <td colspan="2" style="padding:14px 16px;background:${theme.soft};border-bottom:1px solid ${BORDER};">
          <div style="font-size:11px;font-weight:700;color:${theme.accent};text-transform:uppercase;letter-spacing:0.05em;margin-bottom:4px;">Marketing Remarks</div>
          <div style="font-size:13px;color:${INK};line-height:1.6;">${ctx.marketingRemarks}</div>
        </td>
      </tr>`
    : '';

  // Bulletproof CTA button (MSO VML fallback for Outlook)
  const ctaButton =
    ctx.ctaLabel && ctx.ctaUrl
      ? `
      <tr>
        <td align="center" style="padding:28px 0 4px;">
          <!--[if mso]>
          <v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${ctx.ctaUrl}" style="height:44px;v-text-anchor:middle;width:240px;" arcsize="14%" stroke="f" fillcolor="${BRAND}">
            <w:anchorlock/>
            <center style="color:#ffffff;font-family:Segoe UI,Arial,sans-serif;font-size:14px;font-weight:bold;">${ctx.ctaLabel}</center>
          </v:roundrect>
          <![endif]-->
          <!--[if !mso]><!-->
          <a href="${ctx.ctaUrl}" style="display:inline-block;padding:13px 34px;background:${BRAND};color:#ffffff;text-decoration:none;border-radius:6px;font-weight:700;font-size:14px;font-family:'Segoe UI',Arial,sans-serif;">
            ${ctx.ctaLabel} &rarr;
          </a>
          <!--<![endif]-->
        </td>
      </tr>`
      : '';

  const prefix = ctx.subjectPrefix
    ? `<div style="font-size:13px;font-weight:700;color:${theme.accent};margin-bottom:6px;">${ctx.subjectPrefix}</div>`
    : '';

  return `<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width,initial-scale=1.0" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>QRS Audit Notification</title>
  <!--[if mso]>
  <style type="text/css">
    body,table,td,a { font-family: 'Segoe UI', Arial, sans-serif !important; }
  </style>
  <![endif]-->
</head>
<body style="margin:0;padding:0;background:#eef0f2;">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:#eef0f2;">
    <tr>
      <td align="center" style="padding:28px 12px;">

        <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="width:100%;max-width:600px;background:#ffffff;border-radius:10px;overflow:hidden;border:1px solid ${BORDER};">

          <!-- Header band -->
          <!-- Slim status strip (the outer wrapper already shows the QRS header) -->
          <tr>
            <td style="background:${theme.soft};border-top:3px solid ${theme.accent};padding:12px 32px;">
              <span style="display:inline-block;background:${theme.accent};color:#ffffff;font-size:11px;font-weight:700;padding:5px 12px;border-radius:20px;text-transform:uppercase;letter-spacing:0.05em;font-family:'Segoe UI',Arial,sans-serif;">
                ${theme.label}
              </span>
            </td>
          </tr>

          <!-- Body -->
          <tr>
            <td style="padding:30px 32px 8px;font-family:'Segoe UI',Arial,sans-serif;">
              ${prefix}
              <p style="margin:0 0 14px;font-size:15px;color:${INK};">
                Dear <strong>${ctx.recipientName}</strong>,
              </p>
              <p style="margin:0 0 22px;font-size:14px;color:${MUTED};line-height:1.7;">
                ${ctx.introLine}
              </p>

              <!-- Detail card -->
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border:1px solid ${BORDER};border-radius:8px;overflow:hidden;">
                ${rowsHtml}
                ${remarksRow}
              </table>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                ${ctaButton}
              </table>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background:#f8fafc;border-top:1px solid ${BORDER};padding:16px 32px;font-family:'Segoe UI',Arial,sans-serif;">
              <p style="margin:0;font-size:11px;color:#94a3b8;line-height:1.6;">
                Quality Registrar Systems also collaborates with IAS, EIAC, and other international accreditation bodies.
              </p>
              <p style="margin:6px 0 0;font-size:11px;color:#94a3b8;">
                &copy; ${new Date().getFullYear()} Quality Registrar Systems. All rights reserved.
              </p>
            </td>
          </tr>

        </table>

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