// src/inquiry-notifications/email-template.ts

export interface EmailTemplateData {
  type: string;
  inquiry_ref: string;
  company_name: string;
  old_status: string;
  new_status: string;
  message: string;
  timestamp: string;
  pdf_url?: string;
  docx_url?: string;
  inquiry_type?: string;
  auditor_name?: string;
  previous_cert_no?: string;
  cert_body?: string; // ✅ NEW
  audit_stage?: string; // ✅ NEW
  submitted_by_name?: string; // ✅ NEW
  submitted_by_email?: string; // ✅ NEW
  notes?: string;
}

interface TypeStyle {
  color: string;
  bg: string;
  label: string;
}

const TYPE_CONFIG: { [key: string]: TypeStyle } = {
  NEW_INQUIRY: { color: '#1E40AF', bg: '#EFF6FF', label: 'New Inquiry' },
  IN_REVIEW: { color: '#5B21B6', bg: '#F5F3FF', label: 'In Review' },
  DRAFT_READY: { color: '#0F766E', bg: '#F0FDFA', label: 'Draft Ready' },
  CHANGES_REQUESTED: {
    color: '#991B1B',
    bg: '#FEF2F2',
    label: 'Changes Requested',
  },
  CLIENT_CONFIRMED: {
    color: '#065F46',
    bg: '#F0FDF4',
    label: 'Client Confirmed',
  },
  FINAL_ISSUED: { color: '#0C4A6E', bg: '#F0F9FF', label: 'Final Issued' },
};

// Color constants
const BRAND = '#0F4C5C';
const BRAND_LIGHT = '#E6EEF0';
const TEXT = '#1A1A1A';
const MUTED = '#6B7280';
const BORDER = '#E5E7EB';
const PAGE_BG = '#F4F5F7';

// Strip emojis for clean professional look
function cleanText(text: string): string {
  return text
    .replace(
      /[\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|[\u{2700}-\u{27BF}]/gu,
      '',
    )
    .trim();
}

// Format inquiry type (NEW → "New", RE_CERTIFICATION → "Re Certification")
function formatType(t: string | undefined): string {
  if (!t) return '—';
  return t
    .replace(/_/g, ' ')
    .toLowerCase()
    .replace(/\b\w/g, (c) => c.toUpperCase());
}

// ✅ NEW — Build a professional structured headline with proper typography hierarchy
function buildHeadline(event: EmailTemplateData, cleanMessage: string): string {
  const ref = event.inquiry_ref;
  const submitter = event.submitted_by_name;
  const company = event.company_name;

  // Detect the action verb from the message (submitted / updated / approved / etc.)
  let action = 'Update';
  const lower = cleanMessage.toLowerCase();
  if (lower.includes('submitted')) action = 'New inquiry submitted';
  else if (lower.includes('approved')) action = 'Inquiry approved';
  else if (lower.includes('confirmed')) action = 'Inquiry confirmed';
  else if (lower.includes('issued')) action = 'Final certificate issued';
  else if (lower.includes('changes requested')) action = 'Changes requested';
  else if (lower.includes('draft')) action = 'Draft ready for review';
  else if (lower.includes('review')) action = 'Inquiry under review';
  else action = cleanMessage.split('.')[0]; // fallback to first sentence

  // Eyebrow line (small, uppercase, muted) — context above the headline
  const eyebrow = `<p style="margin:0 0 6px 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:${MUTED};text-transform:uppercase;letter-spacing:1.5px;">${ref}</p>`;

  // Main headline — clean, balanced, professional weight
  const headline = `<h2 style="margin:0 0 10px 0;font-family:Georgia,'Times New Roman',Times,serif;font-size:22px;font-weight:normal;color:${TEXT};line-height:30px;letter-spacing:-0.3px;">${action}</h2>`;

  // Sub-line — company + submitter context in lighter weight
  const parts: string[] = [];
  if (company) {
    parts.push(
      `<span style="color:${TEXT};font-weight:bold;">${company}</span>`,
    );
  }
  if (submitter) {
    parts.push(`submitted by <span style="color:${TEXT};">${submitter}</span>`);
  }
  const subline = parts.length
    ? `<p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:14px;color:${MUTED};line-height:20px;">${parts.join(' &middot; ')}</p>`
    : '';

  return `${eyebrow}${headline}${subline}`;
}
// Outlook-safe button
function vmlButton(href: string, label: string, bg: string): string {
  return `<!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" xmlns:w="urn:schemas-microsoft-com:office:word" href="${href}" style="height:44px;v-text-anchor:middle;width:220px;" arcsize="6%" stroke="f" fillcolor="${bg}"><w:anchorlock/><center style="color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:13px;font-weight:bold;letter-spacing:0.5px;">${label}</center></v:roundrect><![endif]--><!--[if !mso]><!--><a href="${href}" style="background-color:${bg};border:1px solid ${bg};color:#ffffff;display:inline-block;font-family:Arial,Helvetica,sans-serif;font-size:13px;font-weight:bold;line-height:44px;text-align:center;text-decoration:none;width:220px;letter-spacing:0.5px;-webkit-text-size-adjust:none;mso-hide:all;">${label}</a><!--<![endif]-->`;
}

// Build a single details table row
function detailRow(
  label: string,
  value: string,
  mono: boolean,
  isLast: boolean,
): string {
  const borderStyle = isLast ? '' : `border-bottom:1px solid ${BORDER};`;
  const valueFont = mono
    ? `font-family:'Courier New',Courier,monospace;`
    : `font-family:Arial,Helvetica,sans-serif;`;
  return `<tr><td width="40%" style="padding:14px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:${MUTED};${borderStyle}">${label}</td><td style="padding:14px 0;${valueFont}font-size:13px;color:${TEXT};font-weight:bold;${borderStyle}text-align:right;">${value}</td></tr>`;
}

// ✅ NEW — Special row that renders the value as a colored badge (for cert_body / audit_stage)
function badgeRow(
  label: string,
  value: string,
  badgeColor: string,
  badgeBg: string,
  isLast: boolean,
): string {
  const borderStyle = isLast ? '' : `border-bottom:1px solid ${BORDER};`;
  const badgeHtml = `<span style="display:inline-block;background-color:${badgeBg};color:${badgeColor};font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;letter-spacing:0.5px;padding:3px 10px;border-radius:10px;text-transform:uppercase;">${value}</span>`;
  return `<tr><td width="40%" style="padding:14px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:${MUTED};${borderStyle}">${label}</td><td style="padding:14px 0;font-size:13px;${borderStyle}text-align:right;">${badgeHtml}</td></tr>`;
}

export function buildEmailHtmlTemplate(event: EmailTemplateData): string {
  const cfg = TYPE_CONFIG[event.type] || {
    color: '#374151',
    bg: '#F3F4F6',
    label: event.type,
  };
  const appUrl = process.env.APP_URL || 'http://localhost:3011';

  const date = new Date(event.timestamp).toLocaleString('en-GB', {
    day: '2-digit',
    month: 'short',
    year: 'numeric',
    hour: '2-digit',
    minute: '2-digit',
    hour12: false,
  });

  const cleanMessage = cleanText(event.message);

  // Status display
  const statusHtml = event.old_status
    ? `<span style="color:${MUTED};font-family:Arial,Helvetica,sans-serif;">${event.old_status}</span>&nbsp;&nbsp;&rarr;&nbsp;&nbsp;<span style="color:${TEXT};font-weight:bold;font-family:Arial,Helvetica,sans-serif;">${event.new_status}</span>`
    : `<span style="color:${TEXT};font-weight:bold;font-family:Arial,Helvetica,sans-serif;">${event.new_status}</span>`;

  // Build all detail rows (only render rows that have values)
  const detailRows: string[] = [];
  detailRows.push(
    detailRow('Reference Number', event.inquiry_ref, true, false),
  );
  detailRows.push(detailRow('Company', event.company_name, false, false));

  // ✅ NEW — Certification Body badge (purple if QRS, teal if TQS)
  if (event.cert_body) {
    const isQrs = event.cert_body.toUpperCase() === 'QRS';
    detailRows.push(
      badgeRow(
        'Certification Body',
        event.cert_body,
        isQrs ? '#7c3aed' : '#0f766e', // text color
        isQrs ? '#f5f3ff' : '#f0fdfa', // bg color
        false,
      ),
    );
  }

  // ✅ NEW — Audit Stage badge (always purple/lavender for visibility)
  if (event.audit_stage) {
    detailRows.push(
      badgeRow('Audit Stage', event.audit_stage, '#6d28d9', '#ede9fe', false),
    );
  }

  if (event.inquiry_type) {
    detailRows.push(
      detailRow(
        'Certification Type',
        formatType(event.inquiry_type),
        false,
        false,
      ),
    );
  }
  if (event.auditor_name) {
    detailRows.push(detailRow('Auditor', event.auditor_name, false, false));
  }
  // ✅ NEW — Submitter info
  if (event.submitted_by_name) {
    detailRows.push(
      detailRow('Submitted By', event.submitted_by_name, false, false),
    );
  }
  if (event.submitted_by_email) {
    detailRows.push(
      detailRow('Submitter Email', event.submitted_by_email, false, false),
    );
  }
  if (event.previous_cert_no) {
    detailRows.push(
      detailRow('Previous Cert. No.', event.previous_cert_no, true, false),
    );
  }
  // Status row (with normal font)
  detailRows.push(
    `<tr><td width="40%" style="padding:14px 0;font-family:Arial,Helvetica,sans-serif;font-size:12px;color:${MUTED};border-bottom:1px solid ${BORDER};">Status</td><td style="padding:14px 0;font-size:13px;border-bottom:1px solid ${BORDER};text-align:right;">${statusHtml}</td></tr>`,
  );
  // Notification Date (last row, no bottom border)
  detailRows.push(detailRow('Notification Date', date, false, true));

  // Download buttons
  const pdfBlock = event.pdf_url
    ? `<td align="center" style="padding:0 6px 8px 0;">${vmlButton(`${appUrl}${event.pdf_url}`, 'DOWNLOAD PDF', BRAND)}</td>`
    : '';
  const docxBlock = event.docx_url
    ? `<td align="center" style="padding:0 0 8px 6px;">${vmlButton(`${appUrl}${event.docx_url}`, 'DOWNLOAD WORD', '#374151')}</td>`
    : '';

  const downloadSection =
    event.pdf_url || event.docx_url
      ? `<tr><td bgcolor="#ffffff" style="padding:0 40px 24px 40px;"><p style="margin:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:${MUTED};text-transform:uppercase;letter-spacing:1px;">Documents Available</p><table border="0" cellpadding="0" cellspacing="0"><tr>${pdfBlock}${docxBlock}</tr></table><p style="margin:8px 0 0 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};line-height:16px;">Secure links valid for 30 days. Authentication required for access.</p></td></tr>`
      : '';
// ✅ NEW — Notes section (only rendered when notes exist)
  const rawNotes = event.notes ? cleanText(event.notes) : '';
  const safeNotes = rawNotes
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;');
  const notesSection = safeNotes
    ? `<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:0 40px 24px 40px;">
<p style="margin:0 0 10px 0;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;color:${MUTED};text-transform:uppercase;letter-spacing:1.2px;">Notes</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>
<td bgcolor="#F9FAFB" style="background-color:#F9FAFB;border:1px solid ${BORDER};border-left:3px solid ${BRAND};padding:14px 16px;">
<p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:13px;color:${TEXT};line-height:20px;white-space:pre-line;">${safeNotes}</p>
</td>
</tr></table>
</td></tr>`
    : '';
  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" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta http-equiv="Content-Type" content="text/html; 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 Certification</title>
<!--[if mso]><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch><o:AllowPNG/></o:OfficeDocumentSettings></xml><style>table, td, div, h1, h2, p, a {font-family: Arial, Helvetica, sans-serif !important;} table {border-collapse: collapse !important;}</style><![endif]-->
<style type="text/css">
body, table, td, p, a, li, blockquote {-webkit-text-size-adjust:100%; -ms-text-size-adjust:100%;}
table, td {mso-table-lspace:0pt; mso-table-rspace:0pt;}
img {-ms-interpolation-mode:bicubic; border:0; height:auto; line-height:100%; outline:none; text-decoration:none;}
body {margin:0 !important; padding:0 !important; width:100% !important;}
</style>
</head>
<body bgcolor="${PAGE_BG}" style="margin:0;padding:0;background-color:${PAGE_BG};">
<div style="display:none;max-height:0;overflow:hidden;mso-hide:all;font-size:1px;line-height:1px;color:${PAGE_BG};">${cfg.label} &middot; ${event.inquiry_ref} &middot; ${event.company_name}</div>
<table border="0" cellpadding="0" cellspacing="0" width="100%" bgcolor="${PAGE_BG}" style="background-color:${PAGE_BG};">
<tr><td align="center" style="padding:40px 12px;">
<!--[if (gte mso 9)|(IE)]><table align="center" border="0" cellspacing="0" cellpadding="0" width="620"><tr><td align="center" valign="top" width="620"><![endif]-->
<table align="center" border="0" cellpadding="0" cellspacing="0" width="620" style="max-width:620px;width:100%;background-color:#ffffff;border:1px solid ${BORDER};">
<tr><td bgcolor="${BRAND}" style="background-color:${BRAND};font-size:0;line-height:0;height:4px;">&nbsp;</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:32px 40px 24px 40px;border-bottom:1px solid ${BORDER};">
<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>
<td valign="middle" align="left">
<h1 style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:20px;font-weight:bold;color:${BRAND};letter-spacing:0.5px;line-height:24px;">QRS CERTIFICATION</h1>
<p style="margin:4px 0 0 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};letter-spacing:1px;text-transform:uppercase;">Inquiry Management System</p>
</td>
<td valign="middle" align="right" style="font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};">${date}</td>
</tr></table>
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:28px 40px 0 40px;">
<table border="0" cellpadding="0" cellspacing="0"><tr>
<td bgcolor="${cfg.bg}" style="background-color:${cfg.bg};padding:5px 12px;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;color:${cfg.color};text-transform:uppercase;letter-spacing:1.2px;">${cfg.label}</td>
</tr></table>
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:14px 40px 8px 40px;">
${buildHeadline(event, cleanMessage)}
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:0 40px 24px 40px;">
<p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:13px;color:${MUTED};line-height:20px;">The following inquiry has been updated. Please review the details below and take any necessary action.</p>
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:0 40px 8px 40px;">
<p style="margin:0 0 10px 0;font-family:Arial,Helvetica,sans-serif;font-size:10px;font-weight:bold;color:${MUTED};text-transform:uppercase;letter-spacing:1.2px;">Inquiry Details</p>
<table border="0" cellpadding="0" cellspacing="0" width="100%" style="border-top:1px solid ${BORDER};">
${detailRows.join('')}
</table>
</td></tr>
${notesSection}
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;font-size:0;line-height:0;height:24px;">&nbsp;</td></tr>
${downloadSection}
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:0 40px 36px 40px;" align="left">
<p style="margin:0 0 14px 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;color:${MUTED};text-transform:uppercase;letter-spacing:1.2px;">Action Required</p>
${vmlButton(`${appUrl}/modules/inquiries`, 'ACCESS PORTAL', BRAND)}
<p style="margin:14px 0 0 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};line-height:16px;">Sign in to your QRS account to view full inquiry details and complete any pending actions.</p>
</td></tr>
<tr><td bgcolor="${BRAND_LIGHT}" style="background-color:${BRAND_LIGHT};padding:18px 40px;border-top:1px solid ${BORDER};border-bottom:1px solid ${BORDER};">
<table border="0" cellpadding="0" cellspacing="0" width="100%"><tr>
<td valign="top" width="24" style="padding-right:12px;"><span style="display:inline-block;width:18px;height:18px;line-height:18px;text-align:center;background-color:${BRAND};color:#ffffff;font-family:Arial,Helvetica,sans-serif;font-size:11px;font-weight:bold;">i</span></td>
<td valign="top"><p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${TEXT};line-height:16px;"><strong>Security notice:</strong> This is an automated message from QRS Certification. We will never ask for your password, OTP, or sensitive information via email. If you did not expect this notification, please contact your administrator immediately.</p></td>
</tr></table>
</td></tr>
<tr><td bgcolor="#ffffff" style="background-color:#ffffff;padding:24px 40px;">
<p style="margin:0 0 8px 0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};line-height:16px;">This message was sent to you because you are a registered participant in the QRS Certification system. This is a system-generated email — please do not reply.</p>
<p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:11px;color:${MUTED};line-height:16px;">For assistance, contact <a href="mailto:coordinator@iicc.ae" style="color:${BRAND};text-decoration:none;font-weight:bold;">coordinator@iicc.ae</a></p>
</td></tr>
<tr><td bgcolor="#F9FAFB" style="background-color:#F9FAFB;padding:18px 40px;border-top:1px solid ${BORDER};">
<p style="margin:0;font-family:Arial,Helvetica,sans-serif;font-size:10px;color:${MUTED};line-height:14px;letter-spacing:0.2px;">&copy; ${new Date().getFullYear()} QRS Certification. All rights reserved.<br/>This communication is confidential and intended solely for the addressee. If you have received this email in error, please notify the sender and delete all copies.</p>
</td></tr>
</table>
<!--[if (gte mso 9)|(IE)]></td></tr></table><![endif]-->
</td></tr></table>
</body></html>`;
}
