export interface ReportReturnedEmailContext {
  recipientName: string;
  actorName: string;
  companyName: string;
  reportNo: string;
  stageLabel: string;
  standardName: string;
  reason: string;
  action: 'returned' | 'reopened';   // "returned for correction" or "reopened"
  version: number;
  actedAt: string;
  reviewUrl: string;
}

const esc = (v: unknown): string =>
  String(v ?? '')
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;');

export function buildReportReturnedEmail(ctx: ReportReturnedEmailContext): string {
  const BRAND = '#4a0080';
  const ACCENT = '#d97706';
  const SOFT = '#fef3c7';
  const INK = '#0f172a';
  const MUTED = '#64748b';
  const BORDER = '#e2e8f0';
  const FONT = "'Segoe UI',Arial,sans-serif";

  const heading = ctx.action === 'reopened' ? 'Report Reopened for Correction' : 'Report Returned for Correction';
  const verb = ctx.action === 'reopened' ? 'reopened' : 'returned for correction';

  const rows: Array<[string, string]> = [
    ['Report No.', `<span style="font-family:'Courier New',monospace;">${esc(ctx.reportNo)}</span>`],
    ['Company', esc(ctx.companyName)],
    ['Standard(s)', esc(ctx.standardName)],
    ['Audit Type', esc(ctx.stageLabel)],
    ['Version', `v${esc(ctx.version)}`],
    ['By', esc(ctx.actorName)],
    ['Date', esc(ctx.actedAt)],
  ];

  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;font-family:${FONT};">${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;font-family:${FONT};">${value}</td>
          </tr>`,
    )
    .join('');

  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" />
  <title>${heading}</title>
</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};">

          <tr>
            <td style="background:${SOFT};border-top:3px solid ${ACCENT};padding:12px 32px;">
              <span style="display:inline-block;background:${ACCENT};color:#ffffff;font-size:11px;font-weight:700;padding:5px 12px;border-radius:20px;text-transform:uppercase;letter-spacing:0.05em;font-family:${FONT};">
                Correction Required
              </span>
            </td>
          </tr>

          <tr>
            <td style="padding:30px 32px 8px;font-family:${FONT};">
              <p style="margin:0 0 14px;font-size:15px;color:${INK};">
                Dear <strong>${esc(ctx.recipientName)}</strong>,
              </p>
              <p style="margin:0 0 22px;font-size:14px;color:${MUTED};line-height:1.7;">
                The audit report for <strong style="color:${INK};">${esc(ctx.companyName)}</strong> has been ${verb} by
                <strong style="color:${INK};">${esc(ctx.actorName)}</strong>. Please review the comments below and update the report.
              </p>

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

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-top:18px;">
                <tr>
                  <td style="padding:14px 16px;background:#fffbeb;border-left:4px solid ${ACCENT};border-radius:6px;font-size:13px;color:#92400e;line-height:1.6;font-family:${FONT};">
                    <strong>Reason:</strong> ${esc(ctx.reason)}
                  </td>
                </tr>
              </table>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <tr>
                  <td align="center" style="padding:28px 0 4px;">
                    <a href="${esc(ctx.reviewUrl)}" 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:${FONT};">
                      Open Report &rarr;
                    </a>
                  </td>
                </tr>
              </table>
              <p style="margin:24px 0 22px;font-size:12px;color:${MUTED};">${heading}: ${esc(ctx.actedAt)}</p>
            </td>
          </tr>

          <tr>
            <td style="background:#f8fafc;border-top:1px solid ${BORDER};padding:16px 32px;font-family:${FONT};">
              <p style="margin:0;font-size:11px;color:#94a3b8;line-height:1.6;">
                Quality Registrar Systems also collaborates with ASCB, 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>`;
}