export interface ReportApprovedEmailContext {
  recipientName: string;
  approverName: string;
  companyName: string;
  reportNo: string;
  stageLabel: string;
  standardName: string;
  auditDate: string;
  conclusion: string;
  ncMajor: number;
  ncMinor: number;
  ncObs: number;
  approvedAt: string;
  version: number;
  attachmentName: string;
  reviewUrl: string;
}

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

/**
 * Notification to the auditor (and the report's submitter): the report has been approved.
 * Carries the final PDF. Table-based, inline styles, MSO fallback for the button.
 */
export function buildReportApprovedEmail(ctx: ReportApprovedEmailContext): string {
  const BRAND = '#4a0080';
  const ACCENT = '#16a34a';
  const SOFT = '#dcfce7';
  const INK = '#0f172a';
  const MUTED = '#64748b';
  const BORDER = '#e2e8f0';
  const FONT = "'Segoe UI',Arial,sans-serif";

  const ncTotal = ctx.ncMajor + ctx.ncMinor + ctx.ncObs;
  const findings = ncTotal
    ? `${ctx.ncMajor} Major · ${ctx.ncMinor} Minor · ${ctx.ncObs} Observation(s)`
    : 'No non-conformities recorded';

  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)],
    ['Audit Date', esc(ctx.auditDate)],
    ['Conclusion', esc(ctx.conclusion)],
    ['Findings', esc(findings)],
    ['Approved By', esc(ctx.approverName)],
    ['Approved On', esc(ctx.approvedAt)],
    ['Version', `v${esc(ctx.version)} (final)`],
  ];

  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;word-break:break-word;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" />
  <meta http-equiv="X-UA-Compatible" content="IE=edge" />
  <title>Audit Report Approved</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};">
                Report Approved · Final
              </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
                approved by <strong style="color:${INK};">${esc(ctx.approverName)}</strong>. The final, approved
                version is attached as a PDF and is no longer marked as a draft.
              </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:12px 16px;background:#f0fdf4;border:1px dashed #86efac;border-radius:8px;font-size:13px;color:${INK};font-family:${FONT};">
                    <strong>Attached:</strong> ${esc(ctx.attachmentName)} <span style="color:${MUTED};">(final PDF + Word)</span>
                  </td>
                </tr>
              </table>

              <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
                <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="${esc(ctx.reviewUrl)}" 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;">View Audit</center>
                    </v:roundrect>
                    <![endif]-->
                    <!--[if !mso]><!-->
                    <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};">
                      View Audit &rarr;
                    </a>
                    <!--<![endif]-->
                  </td>
                </tr>
              </table>

              <p style="margin:24px 0 22px;font-size:12px;color:${MUTED};line-height:1.6;">
                Approved on ${esc(ctx.approvedAt)}. This is an automated notification from Quality Registrar Systems.
              </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 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>`;
}