/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * CLIENT PORTAL EMAIL TEMPLATES — Premium QRS Branded Edition
 *
 * Professional, mobile-responsive HTML emails.
 * All styles are inline (Gmail / Outlook safe).
 * QRS logo loaded from https://crm.qrs.ae/qrslogo.jpg
 * ═══════════════════════════════════════════════════════════════════════════════
 */

// ── Brand tokens (single source of truth) ───────────────────────────────────
const BRAND = {
  name: 'Quality Registrar Systems',
  short: 'QRS',
  platform: 'Audit & Certification Platform',
  tagline: 'Empowering continual improvement for your business',
  logo: 'https://crm.qrs.ae/qrslogo.jpg',
  color: {
    primary: '#1a1054',      // QRS deep purple
    primaryMid: '#4a0080',   // mid purple
    accent: '#7c3aed',       // violet
    gold: '#d4a843',         // QRS gold accent
    success: '#059669',
    successBg: '#ecfdf5',
    warning: '#d97706',
    warningBg: '#fffbeb',
    danger: '#dc2626',
    dangerBg: '#fef2f2',
    text: '#1e293b',
    textLight: '#64748b',
    textMuted: '#94a3b8',
    bg: '#f4f2f7',
    bgCard: '#ffffff',
    border: '#e2e8f0',
    borderLight: '#f1f5f9',
  },
  support: 'support@qrsyst.com',
  website: 'https://crm.qrsyst.com',
  year: new Date().getFullYear(),
};

// ── Shared wrapper (header + footer) ────────────────────────────────────────
function emailShell(content: string, preheader: string = ''): string {
  return `
<!DOCTYPE html>
<html lang="en" 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>${BRAND.name}</title>
  <!--[if mso]><style>table,td{font-family:Arial,Helvetica,sans-serif!important}</style><![endif]-->
</head>
<body style="margin:0;padding:0;background-color:${BRAND.color.bg};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,'Helvetica Neue',Arial,sans-serif;-webkit-font-smoothing:antialiased;">
  <div style="display:none;font-size:1px;color:${BRAND.color.bg};line-height:1px;max-height:0;max-width:0;opacity:0;overflow:hidden;">${preheader}</div>

  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background-color:${BRAND.color.bg};">
    <tr><td align="center" style="padding:32px 16px;">

      <table role="presentation" width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background-color:${BRAND.color.bgCard};border-radius:16px;overflow:hidden;box-shadow:0 1px 3px rgba(0,0,0,0.06),0 4px 16px rgba(0,0,0,0.04);">

        <!-- ═══ Header with QRS Logo ═══ -->
        <tr>
          <td style="background:linear-gradient(135deg,${BRAND.color.primary} 0%,${BRAND.color.primaryMid} 50%,${BRAND.color.accent} 100%);padding:28px 48px 24px;text-align:center;">
            <img src="${BRAND.logo}" alt="${BRAND.name}" width="180" style="display:block;margin:0 auto 14px;max-width:180px;height:auto;" />
            <div style="font-size:12px;color:rgba(255,255,255,0.65);letter-spacing:0.8px;font-weight:500;">${BRAND.platform.toUpperCase()}</div>
          </td>
        </tr>

        <!-- ═══ Gold accent line ═══ -->
        <tr><td style="height:3px;background:linear-gradient(90deg,${BRAND.color.gold},${BRAND.color.accent},${BRAND.color.gold});"></td></tr>

        <!-- ═══ Body ═══ -->
        <tr>
          <td style="padding:0;">
            ${content}
          </td>
        </tr>

        <!-- ═══ Footer ═══ -->
        <tr>
          <td style="padding:24px 48px;background:${BRAND.color.borderLight};border-top:1px solid ${BRAND.color.border};text-align:center;">
            <img src="${BRAND.logo}" alt="${BRAND.short}" width="80" style="display:block;margin:0 auto 10px;max-width:80px;height:auto;opacity:0.5;" />
            <div style="font-size:11px;color:${BRAND.color.textMuted};line-height:1.8;">
              &copy; ${BRAND.year} ${BRAND.name}. All rights reserved.<br/>
              This is an automated message from the ${BRAND.platform}.<br/>
              <a href="mailto:${BRAND.support}" style="color:${BRAND.color.primaryMid};text-decoration:none;">${BRAND.support}</a> &middot;
              <a href="${BRAND.website}" style="color:${BRAND.color.primaryMid};text-decoration:none;">${BRAND.website}</a>
            </div>
          </td>
        </tr>

      </table>

    </td></tr>
  </table>
</body>
</html>`.trim();
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 1. CLIENT INVITE EMAIL
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function clientInviteEmailTemplate(
  clientName: string,
  companyName: string,
  inviteLink: string,
  expiresInDays: number = 7,
): string {
  const body = `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:32px 48px 0;">
          <div style="font-size:22px;font-weight:700;color:${BRAND.color.text};line-height:1.3;">Welcome to the Client Portal</div>
          <div style="height:3px;width:40px;background:${BRAND.color.gold};border-radius:2px;margin-top:12px;"></div>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 0;font-size:15px;color:${BRAND.color.text};line-height:1.7;">
          <p style="margin:0 0 14px;">Hi <strong>${clientName}</strong>,</p>
          <p style="margin:0 0 20px;">You have been invited to access the <strong>${BRAND.name}</strong> Client Portal where you can track your company&rsquo;s audit progress, review findings, and download digital certificates &mdash; all in real time.</p>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:0 48px;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border:1px solid ${BRAND.color.border};border-radius:10px;">
            <tr>
              <td style="padding:16px 20px;">
                <div style="font-size:11px;font-weight:600;color:${BRAND.color.textMuted};text-transform:uppercase;letter-spacing:0.8px;">Company</div>
                <div style="font-size:15px;font-weight:700;color:${BRAND.color.text};margin-top:4px;">${companyName}</div>
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center" style="padding:28px 48px 4px;">
          <table role="presentation" cellpadding="0" cellspacing="0">
            <tr>
              <td style="background:linear-gradient(135deg,${BRAND.color.primary},${BRAND.color.primaryMid},${BRAND.color.accent});border-radius:10px;box-shadow:0 4px 14px rgba(74,0,128,0.35);">
                <a href="${inviteLink}" target="_blank" style="display:inline-block;padding:14px 40px;font-size:15px;font-weight:700;color:#ffffff;text-decoration:none;letter-spacing:0.3px;">
                  Access Client Portal &rarr;
                </a>
              </td>
            </tr>
          </table>
          <div style="font-size:12px;color:${BRAND.color.textMuted};margin-top:12px;">Link expires in ${expiresInDays} days</div>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr><td style="padding:24px 48px 0;"><div style="border-top:1px solid ${BRAND.color.border};"></div></td></tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 0;">
          <div style="font-size:13px;font-weight:700;color:${BRAND.color.text};text-transform:uppercase;letter-spacing:0.5px;margin-bottom:16px;">What you get access to</div>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="padding:0 40px;">
      <tr>
        <td width="50%" style="padding:8px;vertical-align:top;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:8px;">
            <tr><td style="padding:14px 16px;">
              <div style="font-size:18px;margin-bottom:6px;">📋</div>
              <div style="font-size:13px;font-weight:600;color:${BRAND.color.text};">Audit Schedules</div>
              <div style="font-size:12px;color:${BRAND.color.textLight};margin-top:2px;">View upcoming &amp; past audits</div>
            </td></tr>
          </table>
        </td>
        <td width="50%" style="padding:8px;vertical-align:top;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:8px;">
            <tr><td style="padding:14px 16px;">
              <div style="font-size:18px;margin-bottom:6px;">📊</div>
              <div style="font-size:13px;font-weight:600;color:${BRAND.color.text};">Live Progress</div>
              <div style="font-size:12px;color:${BRAND.color.textLight};margin-top:2px;">Track audits in real time</div>
            </td></tr>
          </table>
        </td>
      </tr>
      <tr>
        <td width="50%" style="padding:8px;vertical-align:top;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:8px;">
            <tr><td style="padding:14px 16px;">
              <div style="font-size:18px;margin-bottom:6px;">📄</div>
              <div style="font-size:13px;font-weight:600;color:${BRAND.color.text};">Reports &amp; Findings</div>
              <div style="font-size:12px;color:${BRAND.color.textLight};margin-top:2px;">Access all audit reports</div>
            </td></tr>
          </table>
        </td>
        <td width="50%" style="padding:8px;vertical-align:top;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:8px;">
            <tr><td style="padding:14px 16px;">
              <div style="font-size:18px;margin-bottom:6px;">🏆</div>
              <div style="font-size:13px;font-weight:600;color:${BRAND.color.text};">Digital Certificates</div>
              <div style="font-size:12px;color:${BRAND.color.textLight};margin-top:2px;">Download &amp; verify anytime</div>
            </td></tr>
          </table>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr><td style="padding:24px 48px 0;"><div style="border-top:1px solid ${BRAND.color.border};"></div></td></tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 0;">
          <div style="font-size:13px;font-weight:700;color:${BRAND.color.text};text-transform:uppercase;letter-spacing:0.5px;margin-bottom:16px;">How to login</div>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:0 48px;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:10px;"><tr>
            <td width="32" valign="top"><div style="width:28px;height:28px;border-radius:8px;background:${BRAND.color.primaryMid};color:#fff;font-size:13px;font-weight:700;line-height:28px;text-align:center;">1</div></td>
            <td style="padding-left:12px;font-size:14px;color:${BRAND.color.text};line-height:1.6;">Click <strong>&ldquo;Access Client Portal&rdquo;</strong> above</td>
          </tr></table>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:10px;"><tr>
            <td width="32" valign="top"><div style="width:28px;height:28px;border-radius:8px;background:${BRAND.color.primaryMid};color:#fff;font-size:13px;font-weight:700;line-height:28px;text-align:center;">2</div></td>
            <td style="padding-left:12px;font-size:14px;color:${BRAND.color.text};line-height:1.6;">Enter your email address</td>
          </tr></table>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:10px;"><tr>
            <td width="32" valign="top"><div style="width:28px;height:28px;border-radius:8px;background:${BRAND.color.primaryMid};color:#fff;font-size:13px;font-weight:700;line-height:28px;text-align:center;">3</div></td>
            <td style="padding-left:12px;font-size:14px;color:${BRAND.color.text};line-height:1.6;">Enter the verification code sent to your email</td>
          </tr></table>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-bottom:4px;"><tr>
            <td width="32" valign="top"><div style="width:28px;height:28px;border-radius:8px;background:${BRAND.color.success};color:#fff;font-size:13px;font-weight:700;line-height:28px;text-align:center;">✓</div></td>
            <td style="padding-left:12px;font-size:14px;color:${BRAND.color.text};line-height:1.6;">You&rsquo;re in! Access your dashboard</td>
          </tr></table>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:28px 48px;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:8px;">
            <tr><td style="padding:14px 18px;">
              <div style="font-size:12px;color:${BRAND.color.textMuted};margin-bottom:6px;">If the button doesn&rsquo;t work, copy this link:</div>
              <div style="font-size:12px;color:${BRAND.color.primaryMid};word-break:break-all;line-height:1.5;">${inviteLink}</div>
            </td></tr>
          </table>
        </td>
      </tr>
    </table>
  `;

  return emailShell(body, `You've been invited to track audits for ${companyName} on ${BRAND.name}.`);
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 2. OTP VERIFICATION EMAIL
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function clientOtpEmailTemplate(
  otpCode: string,
  expiryMinutes: number = 10,
): string {
  const digits = otpCode.split('');
  const digitBoxes = digits
    .map(
      (d) =>
        `<td style="width:48px;height:56px;background:${BRAND.color.borderLight};border:2px solid ${BRAND.color.border};border-radius:10px;text-align:center;font-size:26px;font-weight:700;color:${BRAND.color.primary};font-family:'Courier New',monospace;letter-spacing:1px;">${d}</td>`,
    )
    .join(`<td style="width:8px;"></td>`);

  const body = `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:32px 48px 0;text-align:center;">
          <div style="font-size:22px;font-weight:700;color:${BRAND.color.text};line-height:1.3;">Verification Code</div>
          <div style="font-size:14px;color:${BRAND.color.textLight};margin-top:8px;">Enter this code to access your ${BRAND.name} Client Portal</div>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center" style="padding:32px 48px 8px;">
          <table role="presentation" cellpadding="0" cellspacing="0"><tr>${digitBoxes}</tr></table>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td align="center" style="padding:8px 48px 0;">
          <table role="presentation" cellpadding="0" cellspacing="0" style="background:${BRAND.color.warningBg};border-radius:8px;">
            <tr><td style="padding:10px 20px;font-size:13px;color:${BRAND.color.warning};font-weight:600;">
              ⏱ This code expires in ${expiryMinutes} minutes
            </td></tr>
          </table>
        </td>
      </tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr><td style="padding:28px 48px 0;"><div style="border-top:1px solid ${BRAND.color.border};"></div></td></tr>
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 32px;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.borderLight};border-radius:10px;">
            <tr><td style="padding:18px 20px;">
              <div style="font-size:12px;font-weight:700;color:${BRAND.color.text};margin-bottom:8px;">🔒 Security Notice</div>
              <div style="font-size:12px;color:${BRAND.color.textLight};line-height:1.7;">
                &bull; Never share this code with anyone<br/>
                &bull; ${BRAND.name} will never ask for your code by phone<br/>
                &bull; If you did not request this code, please ignore this email
              </div>
            </td></tr>
          </table>
        </td>
      </tr>
    </table>
  `;

  return emailShell(body, `Your verification code is ${otpCode}. It expires in ${expiryMinutes} minutes.`);
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 3. OTP SMS TEMPLATE
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function clientOtpSmsTemplate(otp: string, expiryMinutes: number = 10): string {
  return `[${BRAND.short}] Your login code is: ${otp}\n\nExpires in ${expiryMinutes} minutes. Do not share this code.`;
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 4. RESEND OTP SMS TEMPLATE
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function resendOtpSmsTemplate(otp: string, expiryMinutes: number = 10): string {
  return `[${BRAND.short}] Your new login code is: ${otp}\n\nExpires in ${expiryMinutes} minutes. Do not share this code.`;
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 5. LOGIN CONFIRMATION EMAIL
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function clientLoginConfirmationEmailTemplate(
  clientName: string,
  loginTime: Date,
  ipAddress?: string,
): string {
  const body = `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:32px 48px 0;">
          <div style="font-size:22px;font-weight:700;color:${BRAND.color.text};line-height:1.3;">Login Successful</div>
          <div style="height:3px;width:40px;background:${BRAND.color.success};border-radius:2px;margin-top:12px;"></div>
        </td>
      </tr>
    </table>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px;">
          <p style="margin:0 0 16px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">Hi <strong>${clientName}</strong>,</p>
          <p style="margin:0 0 20px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">Your account was successfully logged into the ${BRAND.name} Client Portal.</p>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.successBg};border:1px solid #a7f3d0;border-radius:10px;">
            <tr><td style="padding:18px 20px;">
              <div style="font-size:12px;font-weight:700;color:${BRAND.color.success};margin-bottom:8px;">Login Details</div>
              <div style="font-size:13px;color:${BRAND.color.text};line-height:1.8;">
                <strong>Time:</strong> ${loginTime.toLocaleString('en-GB', { dateStyle: 'medium', timeStyle: 'short' })}<br/>
                ${ipAddress ? `<strong>IP:</strong> ${ipAddress}<br/>` : ''}
              </div>
            </td></tr>
          </table>
          <p style="margin:20px 0 0;font-size:13px;color:${BRAND.color.textLight};line-height:1.6;">
            If this was not you, please contact us immediately at
            <a href="mailto:${BRAND.support}" style="color:${BRAND.color.primaryMid};text-decoration:none;font-weight:600;">${BRAND.support}</a>
          </p>
        </td>
      </tr>
    </table>
  `;
  return emailShell(body, `Successful login to your ${BRAND.name} Client Portal.`);
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 6. INVITE LINK EXPIRED
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function inviteLinkExpiredEmailTemplate(clientName: string, companyName: string): string {
  const body = `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:32px 48px 0;">
          <div style="font-size:22px;font-weight:700;color:${BRAND.color.text};line-height:1.3;">Invite Link Expired</div>
          <div style="height:3px;width:40px;background:${BRAND.color.warning};border-radius:2px;margin-top:12px;"></div>
        </td>
      </tr>
    </table>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 32px;">
          <p style="margin:0 0 14px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">Hi <strong>${clientName}</strong>,</p>
          <p style="margin:0 0 20px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">
            Your invitation to the Client Portal for <strong>${companyName}</strong> has expired.
            Invitation links are valid for 7 days.
          </p>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.warningBg};border:1px solid #fde68a;border-radius:10px;">
            <tr><td style="padding:18px 20px;">
              <div style="font-size:13px;color:${BRAND.color.warning};line-height:1.6;">
                Please contact your coordinator or email
                <a href="mailto:${BRAND.support}" style="color:${BRAND.color.primaryMid};text-decoration:none;font-weight:600;">${BRAND.support}</a>
                to request a new invite.
              </div>
            </td></tr>
          </table>
        </td>
      </tr>
    </table>
  `;
  return emailShell(body, `Your invite to ${companyName}'s portal has expired.`);
}


/**
 * ═══════════════════════════════════════════════════════════════════════════════
 * 7. ACCESS DISABLED NOTIFICATION
 * ═══════════════════════════════════════════════════════════════════════════════
 */
export function clientAccessDisabledEmailTemplate(
  clientName: string,
  companyName: string,
): string {
  const body = `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:32px 48px 0;">
          <div style="font-size:22px;font-weight:700;color:${BRAND.color.text};line-height:1.3;">Portal Access Update</div>
          <div style="height:3px;width:40px;background:${BRAND.color.danger};border-radius:2px;margin-top:12px;"></div>
        </td>
      </tr>
    </table>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0">
      <tr>
        <td style="padding:24px 48px 32px;">
          <p style="margin:0 0 14px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">Hi <strong>${clientName}</strong>,</p>
          <p style="margin:0 0 20px;font-size:15px;color:${BRAND.color.text};line-height:1.7;">
            Your access to the Client Portal for <strong>${companyName}</strong> has been temporarily disabled by an administrator.
          </p>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="background:${BRAND.color.dangerBg};border:1px solid #fecaca;border-radius:10px;">
            <tr><td style="padding:18px 20px;">
              <div style="font-size:13px;color:${BRAND.color.danger};line-height:1.6;">
                If you believe this was done in error, please contact your coordinator or email
                <a href="mailto:${BRAND.support}" style="color:${BRAND.color.primaryMid};text-decoration:none;font-weight:600;">${BRAND.support}</a>.
              </div>
            </td></tr>
          </table>
        </td>
      </tr>
    </table>
  `;
  return emailShell(body, `Your portal access for ${companyName} has been updated.`);
}