import emailjs from '@emailjs/browser';
import { doc, getDoc, setDoc, onSnapshot } from 'firebase/firestore';
import { db } from '../lib/firebase';
import { OrderRecord, generateTrackingLink } from './orderService';
import { getBankDetails } from './bankService';

export interface EmailConfig {
  // Primary Account
  publicKey: string;
  serviceId: string;
  templateId: string;
  primaryLimit?: number;
  primaryUsed?: number;

  // Secondary Fallback Account
  enableSecondary?: boolean;
  secondaryPublicKey?: string;
  secondaryServiceId?: string;
  secondaryTemplateId?: string;
  secondaryLimit?: number;
  secondaryUsed?: number;

  // Dedicated Newsletter EmailJS Account
  useSeparateNewsletterAccount?: boolean;
  newsletterPublicKey?: string;
  newsletterServiceId?: string;
  newsletterTemplateId?: string;
  newsletterLimit?: number;
  newsletterUsed?: number;

  adminEmail: string;
}

const env = (import.meta as any).env || {};

export function sanitizeAdminEmail(emailStr?: string): string {
  if (!emailStr) return '';
  const legacyEmails = [
    'timenlife00@gmail.com',
    'azaancreatixcel@gmail.com',
    'bhattimz@gmail.com',
    'orders@timenlife.com',
  ];

  const parsed = emailStr
    .split(/[,;\s]+/)
    .map((e) => e.trim().toLowerCase())
    .filter((e) => e.includes('@'));

  // If parsed list matches the 4 legacy hardcoded defaults, ignore them so emails are only sent to explicitly added admin emails
  const isExactLegacy4 =
    parsed.length === 4 && legacyEmails.every((leg) => parsed.includes(leg));

  if (isExactLegacy4) {
    return '';
  }

  return parsed.join(', ');
}

export const HARDCODED_ADMIN_EMAILS: string[] = [];

export const DEFAULT_EMAIL_CONFIG: EmailConfig = {
  publicKey: env.VITE_EMAILJS_PUBLIC_KEY || 'R9sYorZX3DTqi59Pk',
  serviceId: env.VITE_EMAILJS_SERVICE_ID || 'service_toz6uzv',
  templateId: env.VITE_EMAILJS_TEMPLATE_ID || 'template_sgcoqkp',
  primaryLimit: 200,
  primaryUsed: 0,

  enableSecondary: false,
  secondaryPublicKey: '',
  secondaryServiceId: '',
  secondaryTemplateId: '',
  secondaryLimit: 200,
  secondaryUsed: 0,

  useSeparateNewsletterAccount: true,
  newsletterPublicKey: env.VITE_NEWSLETTER_EMAILJS_PUBLIC_KEY || '',
  newsletterServiceId: env.VITE_NEWSLETTER_EMAILJS_SERVICE_ID || '',
  newsletterTemplateId: env.VITE_NEWSLETTER_EMAILJS_TEMPLATE_ID || '',
  newsletterLimit: 200,
  newsletterUsed: 0,

  adminEmail: sanitizeAdminEmail(env.VITE_ADMIN_EMAIL || ''),
};

export function getCombinedAdminEmails(configEmail?: string): string[] {
  const set = new Set<string>();
  const rawSource = configEmail !== undefined ? configEmail : DEFAULT_EMAIL_CONFIG.adminEmail;
  const emailSource = sanitizeAdminEmail(rawSource);

  if (emailSource) {
    emailSource
      .split(/[,;\s]+/)
      .map((e) => e.trim().toLowerCase())
      .filter((e) => e.includes('@'))
      .forEach((e) => set.add(e));
  }

  return Array.from(set);
}

const SETTINGS_COLLECTION = 'settings';
const EMAIL_DOC_ID = 'emailConfig';

// Get current config from local storage or defaults
export function getStoredEmailConfig(): EmailConfig {
  try {
    const saved = localStorage.getItem('tnl_email_config');
    if (saved) {
      const parsed = JSON.parse(saved);
      return {
        ...DEFAULT_EMAIL_CONFIG,
        ...parsed,
        adminEmail: sanitizeAdminEmail(parsed.adminEmail),
        primaryLimit: typeof parsed.primaryLimit === 'number' ? parsed.primaryLimit : 200,
        primaryUsed: typeof parsed.primaryUsed === 'number' ? parsed.primaryUsed : 0,
        enableSecondary: Boolean(parsed.enableSecondary),
        secondaryLimit: typeof parsed.secondaryLimit === 'number' ? parsed.secondaryLimit : 200,
        secondaryUsed: typeof parsed.secondaryUsed === 'number' ? parsed.secondaryUsed : 0,
        useSeparateNewsletterAccount: parsed.useSeparateNewsletterAccount !== false,
        newsletterLimit: typeof parsed.newsletterLimit === 'number' ? parsed.newsletterLimit : 200,
        newsletterUsed: typeof parsed.newsletterUsed === 'number' ? parsed.newsletterUsed : 0,
      };
    }
  } catch (err) {
    console.warn('Error reading local email config:', err);
  }
  return { ...DEFAULT_EMAIL_CONFIG };
}

// Save local
export function saveEmailConfigLocal(config: EmailConfig): void {
  try {
    localStorage.setItem('tnl_email_config', JSON.stringify(config));
  } catch (err) {
    console.warn('Error saving local email config:', err);
  }
}

// Increment email usage counter
export async function incrementEmailUsage(account: 'primary' | 'secondary' | 'newsletter'): Promise<void> {
  const current = getStoredEmailConfig();
  if (account === 'primary') {
    current.primaryUsed = (current.primaryUsed || 0) + 1;
  } else if (account === 'secondary') {
    current.secondaryUsed = (current.secondaryUsed || 0) + 1;
  } else if (account === 'newsletter') {
    current.newsletterUsed = (current.newsletterUsed || 0) + 1;
  }
  saveEmailConfigLocal(current);

  try {
    const docRef = doc(db, SETTINGS_COLLECTION, EMAIL_DOC_ID);
    const fieldToIncrement =
      account === 'primary' ? 'primaryUsed' : account === 'secondary' ? 'secondaryUsed' : 'newsletterUsed';
    const val =
      account === 'primary'
        ? current.primaryUsed
        : account === 'secondary'
        ? current.secondaryUsed
        : current.newsletterUsed;
    await setDoc(docRef, { [fieldToIncrement]: val }, { merge: true });
  } catch (err) {
    console.warn('Could not sync email usage increment to Firestore:', err);
  }
}

// Reset email usage counter
export async function resetEmailCounter(account: 'primary' | 'secondary' | 'newsletter'): Promise<void> {
  const current = getStoredEmailConfig();
  if (account === 'primary') {
    current.primaryUsed = 0;
  } else if (account === 'secondary') {
    current.secondaryUsed = 0;
  } else if (account === 'newsletter') {
    current.newsletterUsed = 0;
  }
  saveEmailConfigLocal(current);

  try {
    const docRef = doc(db, SETTINGS_COLLECTION, EMAIL_DOC_ID);
    const fieldToReset =
      account === 'primary' ? 'primaryUsed' : account === 'secondary' ? 'secondaryUsed' : 'newsletterUsed';
    await setDoc(docRef, { [fieldToReset]: 0 }, { merge: true });
  } catch (err) {
    console.warn('Could not sync email counter reset to Firestore:', err);
  }
}

// Fetch active email config from Firestore (or fallback to local/default)
export async function getActiveEmailConfig(): Promise<EmailConfig> {
  try {
    const docRef = doc(db, SETTINGS_COLLECTION, EMAIL_DOC_ID);
    const snap = await getDoc(docRef);
    if (snap.exists()) {
      const data = snap.data() as Partial<EmailConfig>;
      const merged: EmailConfig = {
        publicKey: data.publicKey || DEFAULT_EMAIL_CONFIG.publicKey,
        serviceId: data.serviceId || DEFAULT_EMAIL_CONFIG.serviceId,
        templateId: data.templateId || DEFAULT_EMAIL_CONFIG.templateId,
        primaryLimit: typeof data.primaryLimit === 'number' ? data.primaryLimit : 200,
        primaryUsed: typeof data.primaryUsed === 'number' ? data.primaryUsed : 0,

        enableSecondary: Boolean(data.enableSecondary),
        secondaryPublicKey: data.secondaryPublicKey || '',
        secondaryServiceId: data.secondaryServiceId || '',
        secondaryTemplateId: data.secondaryTemplateId || '',
        secondaryLimit: typeof data.secondaryLimit === 'number' ? data.secondaryLimit : 200,
        secondaryUsed: typeof data.secondaryUsed === 'number' ? data.secondaryUsed : 0,

        useSeparateNewsletterAccount: data.useSeparateNewsletterAccount !== false,
        newsletterPublicKey: data.newsletterPublicKey || '',
        newsletterServiceId: data.newsletterServiceId || '',
        newsletterTemplateId: data.newsletterTemplateId || '',
        newsletterLimit: typeof data.newsletterLimit === 'number' ? data.newsletterLimit : 200,
        newsletterUsed: typeof data.newsletterUsed === 'number' ? data.newsletterUsed : 0,

        adminEmail: sanitizeAdminEmail(data.adminEmail),
      };
      saveEmailConfigLocal(merged);
      if (merged.publicKey) {
        emailjs.init(merged.publicKey);
      }
      return merged;
    }
  } catch (err) {
    console.warn('Error fetching email config from Firestore:', err);
  }
  return getStoredEmailConfig();
}

// Save email config to Firestore
export async function saveEmailConfig(config: EmailConfig): Promise<void> {
  saveEmailConfigLocal(config);
  try {
    const docRef = doc(db, SETTINGS_COLLECTION, EMAIL_DOC_ID);
    await setDoc(docRef, JSON.parse(JSON.stringify(config)), { merge: true });
    if (config.publicKey) {
      emailjs.init(config.publicKey);
    }
  } catch (err) {
    console.error('Failed to save email config to Firestore:', err);
    throw err;
  }
}

// Subscribe to real-time changes
export function subscribeToEmailConfig(callback: (config: EmailConfig) => void) {
  const docRef = doc(db, SETTINGS_COLLECTION, EMAIL_DOC_ID);
  
  const unsub = onSnapshot(
    docRef,
    (snapshot) => {
      if (snapshot.exists()) {
        const data = snapshot.data() as Partial<EmailConfig>;
        const merged: EmailConfig = {
          publicKey: data.publicKey || DEFAULT_EMAIL_CONFIG.publicKey,
          serviceId: data.serviceId || DEFAULT_EMAIL_CONFIG.serviceId,
          templateId: data.templateId || DEFAULT_EMAIL_CONFIG.templateId,
          primaryLimit: typeof data.primaryLimit === 'number' ? data.primaryLimit : 200,
          primaryUsed: typeof data.primaryUsed === 'number' ? data.primaryUsed : 0,

          enableSecondary: Boolean(data.enableSecondary),
          secondaryPublicKey: data.secondaryPublicKey || '',
          secondaryServiceId: data.secondaryServiceId || '',
          secondaryTemplateId: data.secondaryTemplateId || '',
          secondaryLimit: typeof data.secondaryLimit === 'number' ? data.secondaryLimit : 200,
          secondaryUsed: typeof data.secondaryUsed === 'number' ? data.secondaryUsed : 0,

          useSeparateNewsletterAccount: data.useSeparateNewsletterAccount !== false,
          newsletterPublicKey: data.newsletterPublicKey || '',
          newsletterServiceId: data.newsletterServiceId || '',
          newsletterTemplateId: data.newsletterTemplateId || '',
          newsletterLimit: typeof data.newsletterLimit === 'number' ? data.newsletterLimit : 200,
          newsletterUsed: typeof data.newsletterUsed === 'number' ? data.newsletterUsed : 0,

          adminEmail: sanitizeAdminEmail(data.adminEmail),
        };
        saveEmailConfigLocal(merged);
        if (merged.publicKey) {
          emailjs.init(merged.publicKey);
        }
        callback(merged);
      } else {
        callback(getStoredEmailConfig());
      }
    },
    (err) => {
      console.warn('Real-time listener error for email config:', err);
      callback(getStoredEmailConfig());
    }
  );

  return unsub;
}

/**
 * Smart EmailJS Sender for Newsletter Campaigns.
 * Uses dedicated Newsletter EmailJS account credentials if provided.
 * Falls back to order accounts if separate newsletter account is disabled or unconfigured.
 */
export async function sendNewsletterSmartEmail(
  templateParams: Record<string, any>,
  customConfig?: EmailConfig
): Promise<boolean> {
  const config = customConfig || (await getActiveEmailConfig());

  const nEnabled = config.useSeparateNewsletterAccount !== false;
  const nKey = config.newsletterPublicKey?.trim();
  const nService = config.newsletterServiceId?.trim();
  const nTemplate = config.newsletterTemplateId?.trim();
  const nLimit = typeof config.newsletterLimit === 'number' && config.newsletterLimit >= 0 ? config.newsletterLimit : 200;
  const nUsed = config.newsletterUsed || 0;
  const nHasQuota = nLimit === 0 || nUsed < nLimit;

  if (nEnabled && nKey && nService && nTemplate && nHasQuota) {
    try {
      emailjs.init(nKey);
      await emailjs.send(nService, nTemplate, templateParams, nKey);
      await incrementEmailUsage('newsletter');
      console.log(`[Newsletter EmailJS Success] Sent to ${templateParams.to_email || 'recipient'}. Usage: ${nUsed + 1}/${nLimit}`);
      return true;
    } catch (err) {
      console.warn('Dedicated Newsletter EmailJS account failed/error:', err, 'Falling back to main order EmailJS credentials...');
    }
  } else if (nEnabled && nKey && nService && nTemplate && !nHasQuota) {
    console.warn(`Newsletter EmailJS account limit reached (${nUsed}/${nLimit}). Falling back to main order credentials.`);
  }

  // Fallback to order email accounts
  return await sendSmartEmail(templateParams, config);
}

/**
 * Smart EmailJS Sender with automatic fallback and limit deduction.
 * Tries primary credentials first. If primary quota is reached or fails, automatically switches to secondary account.
 */
export async function sendSmartEmail(
  templateParams: Record<string, any>,
  customConfig?: EmailConfig
): Promise<boolean> {
  const config = customConfig || (await getActiveEmailConfig());

  // 1. Primary Account check
  const pKey = config.publicKey?.trim();
  const pService = config.serviceId?.trim();
  const pTemplate = config.templateId?.trim();
  const pLimit = typeof config.primaryLimit === 'number' && config.primaryLimit >= 0 ? config.primaryLimit : 200;
  const pUsed = config.primaryUsed || 0;
  const pHasQuota = pLimit === 0 || pUsed < pLimit; // 0 means unlimited

  if (pKey && pService && pTemplate && pHasQuota) {
    try {
      emailjs.init(pKey);
      await emailjs.send(pService, pTemplate, templateParams, pKey);
      await incrementEmailUsage('primary');
      console.log(`[EmailJS Primary Success] Sent to ${templateParams.to_email || 'recipient'}. Usage: ${pUsed + 1}/${pLimit}`);
      return true;
    } catch (err) {
      console.warn('Primary EmailJS account failed/error:', err, 'Falling back to secondary email account...');
    }
  } else if (!pHasQuota) {
    console.warn(`Primary EmailJS account limit reached (${pUsed}/${pLimit}). Switching to secondary account.`);
  }

  // 2. Secondary Fallback Account check
  const sEnabled = Boolean(config.enableSecondary);
  const sKey = config.secondaryPublicKey?.trim();
  const sService = config.secondaryServiceId?.trim();
  const sTemplate = config.secondaryTemplateId?.trim();
  const sLimit = typeof config.secondaryLimit === 'number' && config.secondaryLimit >= 0 ? config.secondaryLimit : 200;
  const sUsed = config.secondaryUsed || 0;
  const sHasQuota = sLimit === 0 || sUsed < sLimit;

  if (sEnabled && sKey && sService && sTemplate && sHasQuota) {
    try {
      emailjs.init(sKey);
      await emailjs.send(sService, sTemplate, templateParams, sKey);
      await incrementEmailUsage('secondary');
      console.log(`[EmailJS Secondary Success] Sent to ${templateParams.to_email || 'recipient'}. Usage: ${sUsed + 1}/${sLimit}`);
      return true;
    } catch (err) {
      console.error('Secondary EmailJS account failed as well:', err);
    }
  } else if (sEnabled && !sHasQuota) {
    console.warn(`Secondary EmailJS account limit reached (${sUsed}/${sLimit}).`);
  }

  return false;
}

// Initialize EmailJS on module load
const initialConfig = getStoredEmailConfig();
if (initialConfig.publicKey) {
  emailjs.init(initialConfig.publicKey);
}

// Helper to format currency
const formatPKR = (num: number) => `Rs ${num.toLocaleString('en-PK')}`;

// HTML Helper to generate products table for emails
function generateProductTableHTML(items: OrderRecord['items']): string {
  let rows = '';
  items.forEach((item) => {
    rows += `
      <tr style="border-bottom: 1px solid #eeeeee;">
        <td style="padding: 10px; vertical-align: middle;">
          ${item.image ? `<img src="${item.image}" alt="${item.productName}" style="width: 50px; height: 50px; object-fit: cover; border-radius: 8px; border: 1px solid #e2e8f0;" />` : ''}
        </td>
        <td style="padding: 10px; font-family: sans-serif; font-size: 13px; color: #1e293b;">
          <strong>${item.productName}</strong>
          ${item.strength ? `<br/><span style="font-size: 11px; color: #64748b;">Strength: ${item.strength}</span>` : ''}
          ${item.packing ? `<br/><span style="font-size: 11px; color: #64748b;">Packing: ${item.packing}</span>` : ''}
        </td>
        <td style="padding: 10px; text-align: center; font-family: sans-serif; font-size: 13px; color: #1e293b;">
          ${item.quantity}
        </td>
        <td style="padding: 10px; text-align: right; font-family: sans-serif; font-size: 13px; color: #1e293b;">
          ${formatPKR(item.unitPrice)}
        </td>
        <td style="padding: 10px; text-align: right; font-family: sans-serif; font-size: 13px; color: #C81E3D; font-weight: bold;">
          ${formatPKR(item.totalPrice)}
        </td>
      </tr>
    `;
  });

  return `
    <table style="width: 100%; border-collapse: collapse; margin-top: 15px; margin-bottom: 15px; background-color: #ffffff;">
      <thead>
        <tr style="background-color: #1C1814; color: #ffffff; font-family: sans-serif; font-size: 12px; text-transform: uppercase;">
          <th style="padding: 10px; text-align: left;">Image</th>
          <th style="padding: 10px; text-align: left;">Product</th>
          <th style="padding: 10px; text-align: center;">Qty</th>
          <th style="padding: 10px; text-align: right;">Unit Price</th>
          <th style="padding: 10px; text-align: right;">Total</th>
        </tr>
      </thead>
      <tbody>
        ${rows}
      </tbody>
    </table>
  `;
}

function generateBankDetailsHTML(order: OrderRecord): string {
  if (order.paymentMethod === 'QR Payment') {
    const defaultBank = getBankDetails();
    let bankName = defaultBank.bankName;
    let accountTitle = defaultBank.accountTitle;
    let accountNumber = defaultBank.accountNumber;
    let iban = defaultBank.iban;

    if (order.bankDetailsUsed) {
      const matchBank = order.bankDetailsUsed.match(/Bank Name:\s*([^\n]+)/i);
      const matchTitle = order.bankDetailsUsed.match(/Account Title:\s*([^\n]+)/i);
      const matchAcc = order.bankDetailsUsed.match(/Account Number:\s*([^\n]+)/i);
      const matchIban = order.bankDetailsUsed.match(/IBAN:\s*([^\n]+)/i);
      if (matchBank) bankName = matchBank[1].trim();
      if (matchTitle) accountTitle = matchTitle[1].trim();
      if (matchAcc) accountNumber = matchAcc[1].trim();
      if (matchIban) iban = matchIban[1].trim();
    }

    return `
      <div style="background: #F0FDF4; border: 2px solid #86EFAC; border-radius: 12px; padding: 18px; margin: 20px 0; font-size: 13px; color: #166534;">
        <h4 style="margin: 0 0 10px 0; font-size: 15px; color: #15803D; font-weight: bold; border-bottom: 1px dashed #86EFAC; padding-bottom: 6px;">
          📲 QR Payment Details (${bankName})
        </h4>
        <div style="line-height: 1.8; color: #166534; font-size: 13px;">
          <div><strong>Bank Name:</strong> ${bankName}</div>
          <div><strong>Account Title:</strong> ${accountTitle}</div>
          <div><strong>Account #:</strong> <span style="font-family: monospace; font-weight: bold; font-size: 14px; color: #047857;">${accountNumber}</span></div>
          <div><strong>IBAN:</strong> <span style="font-family: monospace; font-weight: bold; font-size: 13px; color: #047857;">${iban}</span></div>
          <div><strong>QR Payment Amount:</strong> <span style="font-weight: bold; color: #047857;">${formatPKR(order.qrPaymentAmount || order.totals.grandTotal)}</span></div>
          <div><strong>Payment Status:</strong> <span style="display: inline-block; padding: 3px 10px; background: #FEF3C7; color: #92400E; font-weight: bold; border-radius: 9999px; font-size: 12px; margin-top: 4px;">${order.paymentStatus || 'Pending Verification'}</span></div>
          <div style="margin-top: 10px; padding: 10px; background: #DCFCE7; border-radius: 8px; font-size: 12px; color: #14532D;">
            ✓ Payment proof screenshot has been submitted and attached to your order record. Admin will verify before dispatch.
          </div>
        </div>
      </div>
    `;
  }

  if (order.paymentMethod !== 'Bank Transfer' && !order.paymentMethod?.toLowerCase().includes('bank')) {
    return '';
  }

  const bank = getBankDetails();

  return `
    <div style="background: #FFFBEB; border: 2px solid #FCD34D; border-radius: 12px; padding: 18px; margin: 20px 0; font-size: 13px; color: #92400E;">
      <h4 style="margin: 0 0 10px 0; font-size: 15px; color: #B45309; font-weight: bold; border-bottom: 1px dashed #FCD34D; padding-bottom: 6px;">
        🏦 Direct Bank Transfer Account Details
      </h4>
      <div style="line-height: 1.8; color: #78350F; font-size: 13px;">
        <div><strong>Bank Name:</strong> ${bank.bankName}</div>
        <div><strong>Account Title:</strong> ${bank.accountTitle}</div>
        <div><strong>Account Number:</strong> <span style="font-family: monospace; font-size: 14px; font-weight: bold; color: #991B1B;">${bank.accountNumber}</span></div>
        <div><strong>IBAN:</strong> <span style="font-family: monospace; font-size: 13px; font-weight: bold; color: #991B1B;">${bank.iban}</span></div>
        ${bank.instructions ? `<div style="margin-top: 10px; padding-top: 8px; border-top: 1px dashed #FCD34D; color: #92400E;"><strong>Payment Instructions:</strong> ${bank.instructions}</div>` : ''}
      </div>
      ${order.bankDetailsUsed && !order.bankDetailsUsed.includes(bank.accountNumber) ? `
      <div style="margin-top: 10px; padding: 10px; background: #FEF3C7; border-radius: 6px; font-size: 12px; font-family: monospace; color: #78350F; white-space: pre-wrap;">
        ${order.bankDetailsUsed}
      </div>` : ''}
    </div>
  `;
}

// 1. Send Order Confirmation Email
export async function sendOrderConfirmationEmail(order: OrderRecord): Promise<boolean> {
  const config = await getActiveEmailConfig();
  if (config.publicKey) {
    emailjs.init(config.publicKey);
  }

  const productsHtml = generateProductTableHTML(order.items);
  const bankDetailsHtml = generateBankDetailsHTML(order);

  const emailHtml = `
    <div style="font-family: Arial, sans-serif; max-width: 650px; margin: 0 auto; background: #FFFDFB; border: 1px solid #E8D9CC; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <div style="background: #1C1814; color: #ffffff; padding: 24px; text-align: center; border-bottom: 3px solid #C81E3D;">
        <h1 style="margin: 0; font-size: 24px; color: #fef3c7; letter-spacing: 1px;">TIME N LIFE</h1>
        <p style="margin: 4px 0 0 0; font-size: 12px; color: #fde68a;">Official Order Booking Confirmation</p>
      </div>

      <div style="padding: 24px; color: #334155;">
        <p style="font-size: 16px; margin-top: 0;">Dear <strong>${order.customer.name}</strong>,</p>
        <p style="font-size: 14px; line-height: 1.5; color: #475569;">
          Thank you for your order! We have received your booking and it is now being prepared. Below are your complete order details:
        </p>

        <div style="background: #FAF5F0; border: 1px solid #F2E5D9; border-radius: 12px; padding: 16px; margin: 20px 0; font-size: 13px;">
          <div style="margin-bottom: 6px;"><strong>Order Reference #:</strong> <span style="color: #C81E3D; font-weight: bold;">${order.id}</span></div>
          <div style="margin-bottom: 6px;"><strong>Order Date:</strong> ${new Date(order.createdAt).toLocaleString('en-PK')}</div>
          <div style="margin-bottom: 6px;"><strong>Payment Method:</strong> <span style="color: #991B1B; font-weight: bold;">${order.paymentMethod === 'QR Payment' ? 'QR Payment (Raast / Bank Transfer)' : order.paymentMethod === 'Bank Transfer' ? 'Direct Bank Transfer' : 'Cash on Delivery (COD)'}</span></div>
          <div style="margin-bottom: 6px;"><strong>Customer Phone:</strong> ${order.customer.phone}</div>
          <div style="margin-bottom: 6px;"><strong>Shipping Address:</strong> ${order.customer.address}, ${order.customer.city}, ${order.customer.province || 'Pakistan'}</div>
          ${order.customer.notes ? `<div><strong>Notes:</strong> ${order.customer.notes}</div>` : ''}
        </div>

        ${bankDetailsHtml}

        <h3 style="font-size: 15px; color: #1e293b; border-bottom: 2px solid #C81E3D; padding-bottom: 6px; margin-top: 25px;">Ordered Products Summary</h3>
        ${productsHtml}

        <div style="background: #FFF8F6; border: 1px solid #FECDD3; border-radius: 12px; padding: 16px; text-align: right; margin-top: 20px;">
          <p style="margin: 4px 0; font-size: 13px; color: #64748b;">Subtotal: <strong>${formatPKR(order.totals.subtotal)}</strong></p>
          <p style="margin: 4px 0; font-size: 13px; color: #64748b;">Shipping: <strong>${formatPKR(order.totals.shippingCharges)}</strong></p>
          ${
            order.totals.discount > 0
              ? `<p style="margin: 4px 0; font-size: 13px; color: #16a34a; font-weight: bold;">Coupon Discount ${order.totals.couponCode ? `(${order.totals.couponCode})` : ''}: -${formatPKR(order.totals.discount)}</p>`
              : ''
          }
          <p style="margin: 8px 0 0 0; font-size: 18px; color: #C81E3D; font-weight: bold;">Grand Total: ${formatPKR(order.totals.grandTotal)}</p>
        </div>

        <div style="text-align: center; margin-top: 30px;">
          <a href="https://timenlife.com" style="display: inline-block; background: #C81E3D; color: #ffffff; text-decoration: none; padding: 12px 24px; border-radius: 8px; font-weight: bold; font-size: 14px;">
            Visit Time N Life Store
          </a>
        </div>
      </div>

      <div style="background: #1C1814; color: #94a3b8; padding: 16px; text-align: center; font-size: 12px; border-top: 1px solid #334155;">
        <p style="margin: 0;">Time N Life - Your Ultimate Choice for Online Shopping</p>
        <p style="margin: 4px 0 0 0; font-size: 11px;">Email: info@timenlife.com | Phone: +92 333 4344003</p>
      </div>
    </div>
  `;

  let successCustomer = false;
  let successAdmin = false;

  // Send to Customer
  try {
    const templateParamsCustomer = {
      to_email: order.customer.email,
      to_name: order.customer.name,
      name: 'Time N Life',
      email: 'info@timenlife.com',
      from_name: 'Time N Life',
      reply_to: 'info@timenlife.com',
      order_id: order.id,
      order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
      total_amount: formatPKR(order.totals.grandTotal),
      subject: `Order Confirmation #${order.id} - Time N Life`,
      message: emailHtml,
      message_html: emailHtml,
    };
    successCustomer = await sendSmartEmail(templateParamsCustomer, config);
  } catch (err) {
    console.warn('Failed sending confirmation email to customer:', err);
  }

  // Send to Admin Emails (Guaranteed hardcoded emails + any config emails)
  const adminEmailsList = getCombinedAdminEmails(config.adminEmail);
  console.log('Sending New Order Alert to Admin Emails:', adminEmailsList);

  const adminPromises = adminEmailsList.map(async (adminEmail) => {
    try {
      const templateParamsAdmin = {
        to_email: adminEmail,
        to_name: 'Time N Life Admin',
        name: 'Time N Life',
        email: 'info@timenlife.com',
        from_name: 'Time N Life',
        reply_to: 'info@timenlife.com',
        order_id: order.id,
        order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
        total_amount: formatPKR(order.totals.grandTotal),
        subject: `New Order Alert #${order.id} from ${order.customer.name}`,
        message: emailHtml,
        message_html: emailHtml,
      };
      const res = await sendSmartEmail(templateParamsAdmin, config);
      console.log(`New order alert sent to admin (${adminEmail}):`, res);
      return res;
    } catch (err) {
      console.warn(`Failed sending confirmation email to admin (${adminEmail}):`, err);
      return false;
    }
  });

  const adminResults = await Promise.allSettled(adminPromises);
  if (adminResults.some((r) => r.status === 'fulfilled' && r.value === true)) {
    successAdmin = true;
  }

  return successCustomer || successAdmin;
}

// 2. Send Processing Email
export async function sendProcessingEmail(order: OrderRecord): Promise<boolean> {
  const config = await getActiveEmailConfig();

  const bankDetailsHtml = generateBankDetailsHTML(order);

  const emailHtml = `
    <div style="font-family: Arial, sans-serif; max-width: 650px; margin: 0 auto; background: #FFFDFB; border: 1px solid #E8D9CC; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <div style="background: #1C1814; color: #ffffff; padding: 24px; text-align: center; border-bottom: 3px solid #3b82f6;">
        <h1 style="margin: 0; font-size: 24px; color: #fef3c7;">TIME N LIFE</h1>
        <p style="margin: 4px 0 0 0; font-size: 12px; color: #93c5fd;">Status Update: Processing</p>
      </div>

      <div style="padding: 24px; color: #334155;">
        <p style="font-size: 16px; margin-top: 0;">Dear <strong>${order.customer.name}</strong>,</p>
        <p style="font-size: 14px; line-height: 1.5; color: #475569;">
          Great news! Your order <strong>#${order.id}</strong> is now being <strong>PROCESSED</strong> by our warehouse team.
        </p>

        <div style="background: #EFF6FF; border: 1px solid #BFDBFE; border-radius: 12px; padding: 16px; margin: 20px 0; font-size: 13px; color: #1e3a8a;">
          <p style="margin: 0; font-weight: bold;">What happens next?</p>
          <p style="margin: 6px 0 0 0;">Our fulfillment team is performing quality checks and carefully packing your items. Once handed over to our courier partner, you will receive a dispatch notification with your tracking details.</p>
        </div>

        <div style="background: #FAF5F0; border: 1px solid #F2E5D9; border-radius: 12px; padding: 16px; font-size: 13px;">
          <p style="margin: 0 0 6px 0;"><strong>Order ID:</strong> ${order.id}</p>
          <p style="margin: 0 0 6px 0;"><strong>Total Payable:</strong> ${formatPKR(order.totals.grandTotal)}</p>
          <p style="margin: 0 0 6px 0;"><strong>Payment Method:</strong> ${order.paymentMethod === 'Bank Transfer' ? 'Direct Bank Transfer' : 'Cash on Delivery (COD)'}</p>
          <p style="margin: 0;"><strong>Shipping Address:</strong> ${order.customer.address}, ${order.customer.city}</p>
        </div>

        ${bankDetailsHtml}

        <p style="font-size: 14px; margin-top: 25px; color: #475569;">
          Thank you for choosing Time N Life!
        </p>
      </div>

      <div style="background: #1C1814; color: #94a3b8; padding: 16px; text-align: center; font-size: 12px;">
        <p style="margin: 0;">Time N Life Customer Care | info@timenlife.com</p>
      </div>
    </div>
  `;

  let successCustomer = false;
  let successAdmin = false;

  try {
    const templateParams = {
      to_email: order.customer.email,
      to_name: order.customer.name,
      name: 'Time N Life',
      email: 'info@timenlife.com',
      from_name: 'Time N Life',
      reply_to: 'info@timenlife.com',
      order_id: order.id,
      order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
      total_amount: formatPKR(order.totals.grandTotal),
      subject: `Order #${order.id} is now Processing - Time N Life`,
      message: emailHtml,
      message_html: emailHtml,
    };
    successCustomer = await sendSmartEmail(templateParams, config);
  } catch (err) {
    console.warn('Failed sending processing email to customer:', err);
  }

  // Also send Processing Alert copy to all Admin Emails
  const adminEmailsList = getCombinedAdminEmails(config.adminEmail);
  const adminPromises = adminEmailsList.map(async (adminEmail) => {
    try {
      const templateParamsAdmin = {
        to_email: adminEmail,
        to_name: 'Time N Life Admin',
        name: 'Time N Life',
        email: 'info@timenlife.com',
        from_name: 'Time N Life',
        reply_to: 'info@timenlife.com',
        order_id: order.id,
        order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
        total_amount: formatPKR(order.totals.grandTotal),
        subject: `[Processing Order Alert] #${order.id} from ${order.customer.name}`,
        message: emailHtml,
        message_html: emailHtml,
      };
      return await sendSmartEmail(templateParamsAdmin, config);
    } catch (err) {
      console.warn(`Failed sending processing email copy to admin (${adminEmail}):`, err);
      return false;
    }
  });

  const adminResults = await Promise.allSettled(adminPromises);
  if (adminResults.some((r) => r.status === 'fulfilled' && r.value === true)) {
    successAdmin = true;
  }

  return successCustomer || successAdmin;
}

// 3. Send Dispatch Email
export async function sendDispatchEmail(order: OrderRecord): Promise<boolean> {
  const config = await getActiveEmailConfig();

  const courier = order.courierInfo?.courierName || 'Leopards';
  const trackingNumber = order.courierInfo?.trackingNumber || 'PENDING';

  // Always compute dynamic tracking link using generateTrackingLink
  const trackingLink = generateTrackingLink(courier, trackingNumber);
  const productsHtml = generateProductTableHTML(order.items);

  const emailHtml = `
    <div style="font-family: Arial, sans-serif; max-width: 650px; margin: 0 auto; background: #FFFDFB; border: 1px solid #E8D9CC; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <div style="background: #1C1814; color: #ffffff; padding: 24px; text-align: center; border-bottom: 3px solid #10b981;">
        <h1 style="margin: 0; font-size: 24px; color: #fef3c7;">TIME N LIFE</h1>
        <p style="margin: 4px 0 0 0; font-size: 12px; color: #a7f3d0;">Your Order Has Been Dispatched! 🚚</p>
      </div>

      <div style="padding: 24px; color: #334155;">
        <p style="font-size: 16px; margin-top: 0;">Dear <strong>${order.customer.name}</strong>,</p>
        <p style="font-size: 14px; line-height: 1.5; color: #475569;">
          Your order <strong>#${order.id}</strong> has been handed over to <strong>${courier} Courier</strong> and is on its way to your delivery address!
        </p>

        <div style="background: #ECFDF5; border: 2px solid #10B981; border-radius: 12px; padding: 20px; text-align: center; margin: 20px 0;">
          <h3 style="margin: 0 0 8px 0; color: #065f46; font-size: 16px;">Couriers Tracking Information</h3>
          <p style="margin: 0 0 4px 0; font-size: 14px; color: #1e293b;">Courier Service: <strong>${courier}</strong></p>
          <p style="margin: 0 0 16px 0; font-size: 16px; color: #C81E3D; font-family: monospace; font-weight: bold;">
            Tracking Number (CN): ${trackingNumber}
          </p>
          ${
            trackingLink !== '#'
              ? `<a href="${trackingLink}" target="_blank" style="display: inline-block; background: #10B981; color: #ffffff; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-weight: bold; font-size: 14px;">
                  Track Package Online
                </a>`
              : ''
          }
        </div>

        <h3 style="font-size: 15px; color: #1e293b; border-bottom: 2px solid #C81E3D; padding-bottom: 6px; margin-top: 25px;">Dispatched Items</h3>
        ${productsHtml}

        <div style="background: #FAF5F0; border: 1px solid #F2E5D9; border-radius: 12px; padding: 16px; margin-top: 20px; font-size: 13px;">
          <p style="margin: 0 0 6px 0;"><strong>Delivery Address:</strong> ${order.customer.address}, ${order.customer.city}</p>
          <p style="margin: 0; font-weight: bold; color: #1e293b;">Total Amount Payable upon Delivery (COD): ${formatPKR(order.totals.grandTotal)}</p>
        </div>

        <p style="font-size: 14px; margin-top: 25px; color: #475569;">
          Please keep the exact cash amount ready upon delivery.
        </p>
      </div>

      <div style="background: #1C1814; color: #94a3b8; padding: 16px; text-align: center; font-size: 12px;">
        <p style="margin: 0;">Time N Life Customer Service | Phone: +92 333 4344003</p>
      </div>
    </div>
  `;

  let successCustomer = false;
  let successAdmin = false;

  // 1. Send to Customer
  try {
    const templateParams = {
      to_email: order.customer.email,
      to_name: order.customer.name,
      name: 'Time N Life',
      email: 'info@timenlife.com',
      from_name: 'Time N Life',
      reply_to: 'info@timenlife.com',
      order_id: order.id,
      order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
      total_amount: formatPKR(order.totals.grandTotal),
      subject: `Order #${order.id} Dispatched via ${courier} - Time N Life`,
      message: emailHtml,
      message_html: emailHtml,
    };
    successCustomer = await sendSmartEmail(templateParams, config);
  } catch (err) {
    console.warn('Failed sending dispatch email to customer:', err);
  }

  // 2. Send copy to Configured Admin Emails only
  const adminEmailsList = getCombinedAdminEmails(config.adminEmail);
  const adminPromises = adminEmailsList.map(async (adminEmail) => {
    try {
      const templateParamsAdmin = {
        to_email: adminEmail,
        to_name: 'Time N Life Admin',
        name: 'Time N Life',
        email: 'info@timenlife.com',
        from_name: 'Time N Life',
        reply_to: 'info@timenlife.com',
        order_id: order.id,
        order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
        total_amount: formatPKR(order.totals.grandTotal),
        subject: `[Admin Alert - Dispatched] Order #${order.id} (${order.customer.name}) via ${courier}`,
        message: emailHtml,
        message_html: emailHtml,
      };
      return await sendSmartEmail(templateParamsAdmin, config);
    } catch (err) {
      console.warn(`Failed sending dispatch email copy to admin (${adminEmail}):`, err);
      return false;
    }
  });

  const adminResults = await Promise.allSettled(adminPromises);
  if (adminResults.some((r) => r.status === 'fulfilled' && r.value === true)) {
    successAdmin = true;
  }

  return successCustomer || successAdmin;
}

// Helper to format raw message content (converting plain text into HTML paragraphs if not already HTML)
function formatBodyContent(rawContent: string): string {
  if (!rawContent) return '';
  // If content contains explicit HTML tags, use as is
  if (/<[a-z][\s\S]*>/i.test(rawContent)) {
    return rawContent;
  }
  // Convert plain text paragraphs & line breaks into clean HTML
  return rawContent
    .split(/\n\s*\n/)
    .map((paragraph) => {
      const cleanPara = paragraph.trim().replace(/\n/g, '<br/>');
      if (!cleanPara) return '';
      return `<p style="margin: 0 0 16px 0; font-size: 14px; line-height: 1.7; color: #334155;">${cleanPara}</p>`;
    })
    .filter(Boolean)
    .join('');
}

// 4. Generate Responsive HTML Newsletter Template
export function generateNewsletterHTML(params: {
  title: string;
  content: string;
  buttonLabel?: string;
  buttonUrl?: string;
  featuredImage?: string;
  useRawHtml?: boolean;
}): string {
  const { title, content, buttonLabel, buttonUrl, featuredImage, useRawHtml } = params;

  // If raw HTML mode is selected OR content starts with HTML markup tags, return raw user code directly with ZERO added header or footer
  if (useRawHtml || /^\s*<!DOCTYPE|^\s*<html|^\s*<body|^\s*<table|^\s*<!--/i.test(content)) {
    return content || '<p style="font-family: Arial, sans-serif; padding: 20px; color: #64748b;">Write or paste your custom HTML template code here...</p>';
  }

  const formattedContent = formatBodyContent(content);

  const buttonHtml = buttonLabel && buttonUrl
    ? `<div style="text-align: center; margin: 32px 0 24px 0;">
        <a href="${buttonUrl}" target="_blank" style="display: inline-block; background-color: #C81E3D; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 10px; font-weight: bold; font-size: 14px; letter-spacing: 0.5px; box-shadow: 0 4px 12px rgba(200, 30, 61, 0.25);">
          ${buttonLabel}
        </a>
       </div>`
    : '';

  const heroImageHtml = featuredImage
    ? `<div style="width: 100%; overflow: hidden; border-radius: 12px; margin-bottom: 24px; border: 1px solid #E8D9CC;">
        <img src="${featuredImage}" alt="${title}" style="width: 100%; height: auto; max-height: 380px; object-fit: cover; display: block;" />
       </div>`
    : '';

  return `<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>${title}</title>
</head>
<body style="margin: 0; padding: 20px 10px; background-color: #F8F5F2; font-family: Arial, 'Helvetica Neue', Helvetica, sans-serif; -webkit-font-smoothing: antialiased;">
  <table role="presentation" width="100%" border="0" cellspacing="0" cellpadding="0">
    <tr>
      <td align="center">
        <div style="max-width: 620px; width: 100%; background: #FFFFFF; border: 1px solid #E8D9CC; border-radius: 16px; overflow: hidden; box-shadow: 0 6px 18px rgba(0,0,0,0.06); text-align: left;">
          
          <!-- BRAND HEADER -->
          <div style="background-color: #1C1814; padding: 28px 20px; text-align: center; border-bottom: 4px solid #C81E3D;">
            <img src="https://timenlife.com/wp-content/uploads/2025/01/TimeNLifeLogo-300x300-1.png" alt="Time N Life" style="width: 70px; height: 70px; margin-bottom: 10px; border-radius: 50%; border: 2px solid #C81E3D; object-fit: cover;" />
            <h1 style="margin: 0; font-size: 24px; font-family: Georgia, 'Times New Roman', serif; letter-spacing: 1.5px; color: #FFFFFF; text-transform: uppercase;">TIME N LIFE</h1>
            <p style="margin: 6px 0 0 0; font-size: 11px; color: #F8D0BD; text-transform: uppercase; letter-spacing: 2px; font-weight: 600;">Pure, Natural & Organic Choice</p>
          </div>

          <!-- MAIN CONTENT CONTAINER -->
          <div style="padding: 32px 28px; color: #334155; line-height: 1.7;">
            
            ${heroImageHtml}

            <h2 style="color: #1E293B; font-size: 22px; font-family: Georgia, 'Times New Roman', serif; margin-top: 0; margin-bottom: 20px; border-bottom: 2px solid #F2E5D9; padding-bottom: 10px; font-weight: bold;">
              ${title || 'Time N Life Updates'}
            </h2>

            <div style="font-size: 14px; color: #334155; line-height: 1.7; margin-bottom: 20px;">
              ${formattedContent || '<p style="color: #94a3b8; font-style: italic;">Write your message content in the admin composer...</p>'}
            </div>

            ${buttonHtml}

          </div>

          <!-- BRAND FOOTER -->
          <div style="background-color: #14110F; color: #94A3B8; padding: 28px 20px; text-align: center; font-size: 12px; border-top: 1px solid #281D17;">
            
            <!-- Social Icons -->
            <div style="margin-bottom: 18px; font-size: 12px;">
              <a href="https://www.facebook.com/TimeNLifeShop" target="_blank" style="color: #F8D0BD; text-decoration: none; margin: 0 10px; font-weight: bold;">Facebook</a> •
              <a href="https://www.instagram.com/timenlifeshop" target="_blank" style="color: #F8D0BD; text-decoration: none; margin: 0 10px; font-weight: bold;">Instagram</a> •
              <a href="https://www.linkedin.com/timenlifeshop" target="_blank" style="color: #F8D0BD; text-decoration: none; margin: 0 10px; font-weight: bold;">LinkedIn</a> •
              <a href="https://www.youtube.com/@timenlifeshop" target="_blank" style="color: #F8D0BD; text-decoration: none; margin: 0 10px; font-weight: bold;">YouTube</a>
            </div>

            <p style="margin: 0; color: #E2E8F0; font-weight: bold; font-size: 13px;">Time N Life - Natural & Organic Products</p>
            <p style="margin: 4px 0 14px 0; color: #94A3B8;">Website: <a href="https://timenlife.com" style="color: #F8D0BD; text-decoration: none; font-weight: 600;">timenlife.com</a> | Helpline: +92 333 4344003</p>

            <div style="border-top: 1px solid #281D17; padding-top: 14px; margin-top: 14px;">
              <p style="margin: 0; font-size: 11px; color: #64748B;">
                You received this email because you subscribed to Time N Life newsletters.<br/>
                <a href="https://timenlife.com/#unsubscribe" style="color: #C81E3D; text-decoration: underline;">Click here to Unsubscribe</a>
              </p>

              <p style="margin: 10px 0 0 0; font-size: 10px; color: #475569;">
                © ${new Date().getFullYear()} Time N Life. All rights reserved.
              </p>
            </div>

          </div>

        </div>
      </td>
    </tr>
  </table>
</body>
</html>
  `;
}

// 5. Send Payment Verification Status Email to Customer and Admins
export async function sendPaymentStatusNotificationEmail(
  order: OrderRecord,
  newPaymentStatus: 'Pending Verification' | 'Payment Verified' | 'Payment Rejected'
): Promise<boolean> {
  const config = await getActiveEmailConfig();
  if (config.publicKey) {
    emailjs.init(config.publicKey);
  }

  const productsHtml = generateProductTableHTML(order.items);
  let statusBadgeBg = '#FEF3C7';
  let statusBadgeText = '#92400E';
  let statusBadgeBorder = '#F59E0B';
  let statusHeadline = 'Payment Status Update';
  let statusExplanation = '';

  if (newPaymentStatus === 'Payment Verified') {
    statusBadgeBg = '#D1FAE5';
    statusBadgeText = '#065F46';
    statusBadgeBorder = '#10B981';
    statusHeadline = 'Payment Verified Successfully! ✅';
    statusExplanation = `Great news! Your payment of <strong>${formatPKR(order.totals.grandTotal)}</strong> for Order <strong>#${order.id}</strong> has been successfully verified. Your order is now confirmed and being prepared for processing and dispatch.`;
  } else if (newPaymentStatus === 'Payment Rejected') {
    statusBadgeBg = '#FEE2E2';
    statusBadgeText = '#991B1B';
    statusBadgeBorder = '#EF4444';
    statusHeadline = 'Payment Verification Issue ⚠️';
    statusExplanation = `We were unable to verify the payment proof uploaded for Order <strong>#${order.id}</strong>. Please check your transaction details or contact our support team with your payment receipt.`;
  } else {
    statusBadgeBg = '#FEF3C7';
    statusBadgeText = '#92400E';
    statusBadgeBorder = '#F59E0B';
    statusHeadline = 'Payment Verification Pending ⏳';
    statusExplanation = `Your payment proof for Order <strong>#${order.id}</strong> has been received and is currently under review by our accounts team. We will notify you as soon as verification is complete.`;
  }

  const emailHtml = `
    <div style="font-family: Arial, sans-serif; max-width: 650px; margin: 0 auto; background: #FFFDFB; border: 1px solid #E8D9CC; border-radius: 16px; overflow: hidden; box-shadow: 0 4px 12px rgba(0,0,0,0.05);">
      <div style="background: #1C1814; color: #ffffff; padding: 24px; text-align: center; border-bottom: 3px solid ${statusBadgeBorder};">
        <h1 style="margin: 0; font-size: 24px; color: #fef3c7;">TIME N LIFE</h1>
        <p style="margin: 4px 0 0 0; font-size: 13px; color: #f8d0bd; font-weight: bold;">${statusHeadline}</p>
      </div>

      <div style="padding: 24px; color: #334155;">
        <p style="font-size: 16px; margin-top: 0;">Dear <strong>${order.customer.name}</strong>,</p>
        
        <div style="background: ${statusBadgeBg}; border: 2px solid ${statusBadgeBorder}; border-radius: 12px; padding: 18px; text-align: center; margin: 16px 0;">
          <h3 style="margin: 0 0 6px 0; color: ${statusBadgeText}; font-size: 16px;">
            Payment Status: ${newPaymentStatus}
          </h3>
          <p style="margin: 0; font-size: 13px; color: #1e293b; line-height: 1.5;">
            ${statusExplanation}
          </p>
        </div>

        <div style="background: #FAF5F0; border: 1px solid #F2E5D9; border-radius: 12px; padding: 16px; margin: 16px 0; font-size: 13px;">
          <p style="margin: 0 0 6px 0;"><strong>Order ID:</strong> #${order.id}</p>
          <p style="margin: 0 0 6px 0;"><strong>Payment Method:</strong> ${order.paymentMethod}</p>
          <p style="margin: 0 0 6px 0;"><strong>Total Amount:</strong> ${formatPKR(order.totals.grandTotal)}</p>
          <p style="margin: 0;"><strong>Delivery Address:</strong> ${order.customer.address}, ${order.customer.city}</p>
        </div>

        <h3 style="font-size: 15px; color: #1e293b; border-bottom: 2px solid #C81E3D; padding-bottom: 6px; margin-top: 20px;">Order Summary</h3>
        ${productsHtml}

        <p style="font-size: 13px; margin-top: 25px; color: #475569;">
          If you have any questions regarding your payment or order, please reply to this email or contact our customer support line.
        </p>
      </div>

      <div style="background: #1C1814; color: #94a3b8; padding: 16px; text-align: center; font-size: 12px;">
        <p style="margin: 0;">Time N Life Customer Support | Helpline: +92 333 4344003 | timenlife.com</p>
      </div>
    </div>
  `;

  let successCustomer = false;
  let successAdmin = false;

  // 1. Send to Customer
  try {
    const templateParams = {
      to_email: order.customer.email,
      to_name: order.customer.name,
      name: 'Time N Life',
      email: 'info@timenlife.com',
      from_name: 'Time N Life',
      reply_to: 'info@timenlife.com',
      order_id: order.id,
      order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
      total_amount: formatPKR(order.totals.grandTotal),
      subject: `[Payment Update] Order #${order.id} - ${newPaymentStatus}`,
      message: emailHtml,
      message_html: emailHtml,
    };
    successCustomer = await sendSmartEmail(templateParams, config);
  } catch (err) {
    console.warn('Failed sending payment status email to customer:', err);
  }

  // 2. Send copy to all Admin Emails configured
  const adminEmailsList = getCombinedAdminEmails(config.adminEmail);
  const adminPromises = adminEmailsList.map(async (adminEmail) => {
    try {
      const templateParamsAdmin = {
        to_email: adminEmail,
        to_name: 'Time N Life Admin',
        name: 'Time N Life',
        email: 'info@timenlife.com',
        from_name: 'Time N Life',
        reply_to: 'info@timenlife.com',
        order_id: order.id,
        order_date: new Date(order.createdAt).toLocaleDateString('en-PK'),
        total_amount: formatPKR(order.totals.grandTotal),
        subject: `[Admin Alert - Payment ${newPaymentStatus}] Order #${order.id} (${order.customer.name})`,
        message: emailHtml,
        message_html: emailHtml,
      };
      return await sendSmartEmail(templateParamsAdmin, config);
    } catch (err) {
      console.warn(`Failed sending payment status email to admin (${adminEmail}):`, err);
      return false;
    }
  });

  const adminResults = await Promise.allSettled(adminPromises);
  if (adminResults.some((r) => r.status === 'fulfilled' && r.value === true)) {
    successAdmin = true;
  }

  return successCustomer || successAdmin;
}


