export interface ReportSubmittedEmailContext {
  recipientName: string;      // "Ms. Julie" or "Team"
  auditorName: string;
  auditorTitle?: string;
  auditorEmail: string;
  auditorPhone?: string;
  companyName: string;
  reportNo: string;
  stageLabel: string;         // "Surveillance", "Stage 2 (Initial)", ...
  standardName: string;
  auditDate: string;          // dd-mm-yyyy
  leadAuditor: string;
  conclusion: string;         // e.g. "Complies with exception of minor NC(s)"
  ncMajor: number;
  ncMinor: number;
  ncObs: number;
  submittedAt: string;        // formatted date-time
  attachmentName: string;     // "SV-2026-000037.pdf"
  reviewUrl: string;
  isDraftWatermark?: boolean;
   approveUrl?: string;   // ← add this line
}

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

/**
 * Coordinator notification: an audit report has been submitted for approval.
 * Table-based, inline styles, MSO fallback for the CTA. Matches the QRS audit email family.
 */
export function buildReportSubmittedEmail(ctx: ReportSubmittedEmailContext): 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 ncTotal = ctx.ncMajor + ctx.ncMinor + ctx.ncObs;
  const ncSummary = 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)],
    ['Lead Auditor', esc(ctx.leadAuditor)],
    ['Conclusion', esc(ctx.conclusion)],
    ['Findings', esc(ncSummary)],
    ['Submitted', esc(ctx.submittedAt)],
  ];

  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('');

  const draftNote = ctx.isDraftWatermark
    ? `<p style="margin:12px 0 0;font-size:12px;color:${MUTED};line-height:1.6;">The attached PDF is marked <strong>DRAFT</strong> until the report is approved.</p>`
    : '';

  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 Submitted for Approval</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};">

          <!-- Status strip -->
          <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};">
                Action Required · Report for Approval
              </span>
            </td>
          </tr>

          <!-- Body -->
          <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;">
                <strong style="color:${INK};">${esc(ctx.auditorName)}</strong>${ctx.auditorTitle ? `, ${esc(ctx.auditorTitle)},` : ''}
                has submitted the audit report for <strong style="color:${INK};">${esc(ctx.companyName)}</strong>
                for your review and approval. The full report is attached as a PDF.
              </p>

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

              <!-- Attachment -->
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-top:18px;">
                <tr>
                  <td style="padding:12px 16px;background:#f8fafc;border:1px dashed #cbd5e1;border-radius:8px;font-size:13px;color:${INK};font-family:${FONT};">
                    <strong>Attached:</strong> ${esc(ctx.attachmentName)} <span style="color:${MUTED};">(PDF + Word)</span>
                  </td>
                </tr>
              </table>
              ${draftNote}

              <!-- CTA -->
              <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;">Review Report</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};">
                      Review Report &rarr;
                    </a>
                    <!--<![endif]-->
                  </td>
                </tr>
              </table>

              <!-- Sender signature -->
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-top:26px;border-top:1px solid ${BORDER};">
                <tr>
                  <td style="padding:18px 0 22px;font-family:${FONT};">
                    <p style="margin:0;font-size:13px;color:${INK};font-weight:700;">${esc(ctx.auditorName)}</p>
                    ${ctx.auditorTitle ? `<p style="margin:2px 0 0;font-size:12px;color:${MUTED};">${esc(ctx.auditorTitle)}</p>` : ''}
                    <p style="margin:2px 0 0;font-size:12px;color:${MUTED};">
                      <a href="mailto:${esc(ctx.auditorEmail)}" style="color:${BRAND};text-decoration:none;">${esc(ctx.auditorEmail)}</a>
                      ${ctx.auditorPhone ? ` · ${esc(ctx.auditorPhone)}` : ''}
                    </p>
                  </td>
                </tr>
              </table>
            </td>
          </tr>

          <!-- Footer -->
          <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>`;
}