/**
 * Notification Email Templates Service
 *
 * Generates professional, bilingual (Arabic/English) email templates
 * for all notification types in the Mawidi platform.
 *
 * @module lib/services/notification-templates.service
 */

import type {
  NotificationEmailTemplate,
  PreferencesConfirmationData,
  BookingNotificationData,
  ReminderNotificationData,
  PaymentReceiptData,
  SecurityAlertData,
  WeeklyReportData,
  PreferenceChange,
} from '@/lib/types/notification.types';

const BASE_URL = process.env.NEXT_PUBLIC_BASE_URL || 'https://mawidi.com';

/**
 * Email configuration
 */
const EMAIL_CONFIG = {
  brandName: 'Mawidi',
  brandTaglineEn: 'Smart Appointment Management',
  brandTaglineAr: 'منصة إدارة المواعيد الذكية',
  supportEmail: 'support@mawidi.com',
  companyYear: new Date().getFullYear(),
} as const;

/**
 * Notification Templates Service Class
 */
class NotificationTemplatesService {
  /**
   * Generate preferences confirmation email
   */
  createPreferencesConfirmationEmail(
    data: PreferencesConfirmationData
  ): NotificationEmailTemplate {
    const isAr = data.language === 'ar';

    const subject = isAr
      ? 'تم تحديث إعدادات الإشعارات الخاصة بك - Mawidi'
      : 'Your notification preferences have been updated - Mawidi';

    const html = this.generatePreferencesConfirmationHTML(data, isAr);
    const text = this.generatePreferencesConfirmationText(data, isAr);

    return { subject, html, text };
  }

  /**
   * Generate new booking notification email
   */
  createBookingNotificationEmail(
    data: BookingNotificationData
  ): NotificationEmailTemplate {
    const isAr = data.language === 'ar';

    const subject = isAr
      ? `حجز جديد: ${data.customerName} - ${data.service}`
      : `New Booking: ${data.customerName} - ${data.service}`;

    const html = this.generateBookingNotificationHTML(data, isAr);
    const text = this.generateBookingNotificationText(data, isAr);

    return { subject, html, text };
  }

  /**
   * Generate appointment reminder email
   */
  createReminderEmail(data: ReminderNotificationData): NotificationEmailTemplate {
    const isAr = data.language === 'ar';

    const subject = isAr
      ? `تذكير: موعدك بعد ${data.hoursUntil} ساعات`
      : `Reminder: Your appointment in ${data.hoursUntil} hours`;

    const html = this.generateReminderHTML(data, isAr);
    const text = this.generateReminderText(data, isAr);

    return { subject, html, text };
  }

  /**
   * Generate payment receipt email
   */
  createPaymentReceiptEmail(data: PaymentReceiptData): NotificationEmailTemplate {
    const isAr = data.language === 'ar';
    const formattedAmount = this.formatCurrency(data.amount, data.currency, isAr);

    const subject = isAr
      ? `إيصال دفع: ${formattedAmount} - Mawidi`
      : `Payment Receipt: ${formattedAmount} - Mawidi`;

    const html = this.generatePaymentReceiptHTML(data, isAr);
    const text = this.generatePaymentReceiptText(data, isAr);

    return { subject, html, text };
  }

  /**
   * Generate security alert email
   */
  createSecurityAlertEmail(data: SecurityAlertData): NotificationEmailTemplate {
    const isAr = data.language === 'ar';
    const alertTitle = this.getSecurityAlertTitle(data.alertType, isAr);

    const subject = isAr
      ? `تنبيه أمني: ${alertTitle} - Mawidi`
      : `Security Alert: ${alertTitle} - Mawidi`;

    const html = this.generateSecurityAlertHTML(data, isAr);
    const text = this.generateSecurityAlertText(data, isAr);

    return { subject, html, text };
  }

  /**
   * Generate weekly report email
   */
  createWeeklyReportEmail(data: WeeklyReportData): NotificationEmailTemplate {
    const isAr = data.language === 'ar';
    const dateRange = this.formatDateRange(data.periodStart, data.periodEnd, isAr);

    const subject = isAr
      ? `تقريرك الأسبوعي: ${dateRange} - Mawidi`
      : `Your Weekly Report: ${dateRange} - Mawidi`;

    const html = this.generateWeeklyReportHTML(data, isAr);
    const text = this.generateWeeklyReportText(data, isAr);

    return { subject, html, text };
  }

  // =============================================
  // Private Template Generation Methods
  // =============================================

  private getBaseStyles(): string {
    return `
      <style>
        * { margin: 0; padding: 0; box-sizing: border-box; }
        body {
          font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Arial, sans-serif;
          line-height: 1.6;
          color: #1f2937;
          background: #f3f4f6;
        }
        .email-wrapper { background: #f3f4f6; padding: 40px 20px; }
        .container {
          max-width: 600px;
          margin: 0 auto;
          background: #ffffff;
          border-radius: 16px;
          overflow: hidden;
          box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
        }
        .header {
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: #ffffff;
          padding: 30px;
          text-align: center;
        }
        .logo { font-size: 28px; font-weight: 800; margin-bottom: 8px; }
        .header-subtitle { font-size: 14px; opacity: 0.9; }
        .content { padding: 30px; }
        .greeting { font-size: 18px; font-weight: 600; margin-bottom: 20px; }
        .message { font-size: 15px; color: #4b5563; margin-bottom: 20px; line-height: 1.7; }
        .highlight-box {
          background: #f0fdf4;
          border: 1px solid #10b981;
          border-radius: 12px;
          padding: 20px;
          margin: 20px 0;
        }
        .cta-button {
          display: inline-block;
          background: linear-gradient(135deg, #10b981 0%, #059669 100%);
          color: white !important;
          padding: 14px 28px;
          text-decoration: none;
          border-radius: 10px;
          font-weight: 600;
          margin: 20px 0;
        }
        .footer {
          background: #f9fafb;
          padding: 20px 30px;
          text-align: center;
          border-top: 1px solid #e5e7eb;
        }
        .footer-text { color: #6b7280; font-size: 12px; margin: 5px 0; }
        .metric-card {
          background: white;
          border: 1px solid #e5e7eb;
          border-radius: 10px;
          padding: 15px;
          margin: 10px 0;
        }
        .metric-value { font-size: 24px; font-weight: 700; color: #10b981; }
        .metric-label { font-size: 12px; color: #6b7280; }
        .change-positive { color: #10b981; }
        .change-negative { color: #ef4444; }
        .alert-box {
          background: #fef3c7;
          border-left: 4px solid #f59e0b;
          padding: 15px;
          margin: 20px 0;
          border-radius: 8px;
        }
        .security-alert {
          background: #fef2f2;
          border-left: 4px solid #ef4444;
        }
        table { width: 100%; border-collapse: collapse; }
        td { padding: 8px 0; }
      </style>
    `;
  }

  private generatePreferencesConfirmationHTML(
    data: PreferencesConfirmationData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const dashboardUrl = `${BASE_URL}/${lang}/dashboard?tab=settings`;

    const changesHTML = data.changes
      .map((change) => this.formatPreferenceChange(change, isAr))
      .join('');

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr)}
            <div class="content">
              <p class="greeting">${greeting}</p>
              <p class="message">
                ${isAr
                  ? 'تم تحديث إعدادات الإشعارات الخاصة بك بنجاح. فيما يلي ملخص التغييرات:'
                  : 'Your notification preferences have been updated successfully. Here\'s a summary of the changes:'}
              </p>

              <div class="highlight-box">
                <table>
                  ${changesHTML}
                </table>
              </div>

              <div style="text-align: center;">
                <a href="${dashboardUrl}" class="cta-button">
                  ${isAr ? 'عرض الإعدادات' : 'View Settings'}
                </a>
              </div>

              <p class="message" style="color: #6b7280; font-size: 13px;">
                ${isAr
                  ? 'إذا لم تقم بإجراء هذه التغييرات، يرجى الاتصال بالدعم فوراً.'
                  : 'If you didn\'t make these changes, please contact support immediately.'}
              </p>
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generatePreferencesConfirmationText(
    data: PreferencesConfirmationData,
    isAr: boolean
  ): string {
    const greeting = this.getGreeting(data.name, isAr);
    const changesText = data.changes
      .map((change) => this.formatPreferenceChangeText(change, isAr))
      .join('\n');

    return isAr
      ? `${greeting}\n\nتم تحديث إعدادات الإشعارات الخاصة بك:\n\n${changesText}\n\n© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}`
      : `${greeting}\n\nYour notification preferences have been updated:\n\n${changesText}\n\n© ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}`;
  }

  private generateBookingNotificationHTML(
    data: BookingNotificationData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const dashboardUrl = `${BASE_URL}/${lang}/dashboard?tab=bookings`;
    const formattedDate = this.formatDate(data.appointmentDate, isAr);
    const formattedAmount = this.formatCurrency(data.totalAmount * 100, 'QAR', isAr);

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr, '#3b82f6')}
            <div class="content">
              <p class="greeting">${greeting}</p>
              <p class="message">
                ${isAr
                  ? 'لديك حجز جديد! تفاصيل الحجز:'
                  : 'You have a new booking! Here are the details:'}
              </p>

              <div class="highlight-box">
                <table>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'العميل:' : 'Customer:'}</td>
                    <td style="font-weight: 600;">${data.customerName}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'الهاتف:' : 'Phone:'}</td>
                    <td style="font-weight: 600;">${data.customerPhone}</td>
                  </tr>
                  ${data.customerEmail ? `
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'البريد:' : 'Email:'}</td>
                    <td style="font-weight: 600;">${data.customerEmail}</td>
                  </tr>
                  ` : ''}
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'الخدمة:' : 'Service:'}</td>
                    <td style="font-weight: 600;">${data.service}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'التاريخ:' : 'Date:'}</td>
                    <td style="font-weight: 600;">${formattedDate}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'الوقت:' : 'Time:'}</td>
                    <td style="font-weight: 600;">${data.appointmentTime}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'المدة:' : 'Duration:'}</td>
                    <td style="font-weight: 600;">${data.duration} ${isAr ? 'دقيقة' : 'minutes'}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'المبلغ:' : 'Amount:'}</td>
                    <td style="font-weight: 600; color: #10b981;">${formattedAmount}</td>
                  </tr>
                </table>
              </div>

              <div style="text-align: center;">
                <a href="${dashboardUrl}" class="cta-button">
                  ${isAr ? 'عرض الحجز' : 'View Booking'}
                </a>
              </div>
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generateBookingNotificationText(
    data: BookingNotificationData,
    isAr: boolean
  ): string {
    const formattedDate = this.formatDate(data.appointmentDate, isAr);
    const formattedAmount = this.formatCurrency(data.totalAmount * 100, 'QAR', isAr);

    return isAr
      ? `حجز جديد!\n\nالعميل: ${data.customerName}\nالهاتف: ${data.customerPhone}\nالخدمة: ${data.service}\nالتاريخ: ${formattedDate}\nالوقت: ${data.appointmentTime}\nالمبلغ: ${formattedAmount}`
      : `New Booking!\n\nCustomer: ${data.customerName}\nPhone: ${data.customerPhone}\nService: ${data.service}\nDate: ${formattedDate}\nTime: ${data.appointmentTime}\nAmount: ${formattedAmount}`;
  }

  private generateReminderHTML(
    data: ReminderNotificationData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const formattedDate = this.formatDate(data.appointmentDate, isAr);

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr, '#f59e0b')}
            <div class="content">
              <p class="greeting">${greeting}</p>
              <p class="message">
                ${isAr
                  ? `تذكير: لديك موعد قادم بعد ${data.hoursUntil} ساعات.`
                  : `Reminder: You have an upcoming appointment in ${data.hoursUntil} hours.`}
              </p>

              <div class="highlight-box">
                <table>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'العميل:' : 'Customer:'}</td>
                    <td style="font-weight: 600;">${data.customerName}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'الخدمة:' : 'Service:'}</td>
                    <td style="font-weight: 600;">${data.service}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'التاريخ:' : 'Date:'}</td>
                    <td style="font-weight: 600;">${formattedDate}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'الوقت:' : 'Time:'}</td>
                    <td style="font-weight: 600;">${data.appointmentTime}</td>
                  </tr>
                  ${data.meetingLink ? `
                  <tr>
                    <td style="color: #6b7280;">${isAr ? 'رابط الاجتماع:' : 'Meeting Link:'}</td>
                    <td><a href="${data.meetingLink}" style="color: #10b981;">${isAr ? 'انضمام' : 'Join'}</a></td>
                  </tr>
                  ` : ''}
                </table>
              </div>

              ${data.meetingLink ? `
              <div style="text-align: center;">
                <a href="${data.meetingLink}" class="cta-button">
                  ${isAr ? 'انضم للاجتماع' : 'Join Meeting'}
                </a>
              </div>
              ` : ''}
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generateReminderText(
    data: ReminderNotificationData,
    isAr: boolean
  ): string {
    const formattedDate = this.formatDate(data.appointmentDate, isAr);
    return isAr
      ? `تذكير: موعدك بعد ${data.hoursUntil} ساعات\n\nالعميل: ${data.customerName}\nالخدمة: ${data.service}\nالتاريخ: ${formattedDate}\nالوقت: ${data.appointmentTime}${data.meetingLink ? `\nرابط الاجتماع: ${data.meetingLink}` : ''}`
      : `Reminder: Appointment in ${data.hoursUntil} hours\n\nCustomer: ${data.customerName}\nService: ${data.service}\nDate: ${formattedDate}\nTime: ${data.appointmentTime}${data.meetingLink ? `\nMeeting Link: ${data.meetingLink}` : ''}`;
  }

  private generatePaymentReceiptHTML(
    data: PaymentReceiptData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const formattedAmount = this.formatCurrency(data.amount, data.currency, isAr);
    const formattedDate = this.formatDate(data.paymentDate, isAr);
    const dashboardUrl = `${BASE_URL}/${lang}/dashboard?tab=billing`;

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr, '#10b981')}
            <div class="content">
              <p class="greeting">${greeting}</p>
              <p class="message">
                ${isAr
                  ? 'شكراً لك! تم استلام دفعتك بنجاح.'
                  : 'Thank you! Your payment has been received successfully.'}
              </p>

              <div class="highlight-box" style="text-align: center;">
                <p style="font-size: 14px; color: #6b7280; margin-bottom: 10px;">
                  ${isAr ? 'المبلغ المدفوع' : 'Amount Paid'}
                </p>
                <p style="font-size: 32px; font-weight: 700; color: #10b981; margin-bottom: 10px;">
                  ${formattedAmount}
                </p>
                <p style="font-size: 12px; color: #9ca3af;">
                  ${isAr ? 'رقم المرجع:' : 'Reference:'} ${data.stripePaymentIntentId.slice(-8)}
                </p>
              </div>

              <div style="background: #f9fafb; border-radius: 8px; padding: 15px; margin: 20px 0;">
                <table style="width: 100%;">
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'التاريخ:' : 'Date:'}</td>
                    <td style="text-align: right;">${formattedDate}</td>
                  </tr>
                  ${data.cardLastFour ? `
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'طريقة الدفع:' : 'Payment Method:'}</td>
                    <td style="text-align: right;">${data.cardBrand || 'Card'} •••• ${data.cardLastFour}</td>
                  </tr>
                  ` : ''}
                  ${data.description ? `
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'الوصف:' : 'Description:'}</td>
                    <td style="text-align: right;">${data.description}</td>
                  </tr>
                  ` : ''}
                </table>
              </div>

              <div style="text-align: center;">
                <a href="${dashboardUrl}" class="cta-button">
                  ${isAr ? 'عرض سجل المدفوعات' : 'View Payment History'}
                </a>
              </div>
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generatePaymentReceiptText(
    data: PaymentReceiptData,
    isAr: boolean
  ): string {
    const formattedAmount = this.formatCurrency(data.amount, data.currency, isAr);
    const formattedDate = this.formatDate(data.paymentDate, isAr);

    return isAr
      ? `إيصال دفع\n\nالمبلغ: ${formattedAmount}\nالتاريخ: ${formattedDate}\nرقم المرجع: ${data.stripePaymentIntentId.slice(-8)}\n\nشكراً لك!`
      : `Payment Receipt\n\nAmount: ${formattedAmount}\nDate: ${formattedDate}\nReference: ${data.stripePaymentIntentId.slice(-8)}\n\nThank you!`;
  }

  private generateSecurityAlertHTML(
    data: SecurityAlertData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const alertTitle = this.getSecurityAlertTitle(data.alertType, isAr);
    const alertMessage = this.getSecurityAlertMessage(data, isAr);
    const formattedTime = this.formatDateTime(data.eventTime, isAr);

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr, '#ef4444')}
            <div class="content">
              <p class="greeting">${greeting}</p>

              <div class="alert-box security-alert">
                <p style="font-weight: 600; margin-bottom: 10px;">
                  🔒 ${alertTitle}
                </p>
                <p style="color: #6b7280; font-size: 14px;">
                  ${alertMessage}
                </p>
              </div>

              <div style="background: #f9fafb; border-radius: 8px; padding: 15px; margin: 20px 0;">
                <table style="width: 100%;">
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'الوقت:' : 'Time:'}</td>
                    <td style="text-align: right;">${formattedTime}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'عنوان IP:' : 'IP Address:'}</td>
                    <td style="text-align: right;">${data.ipAddress}</td>
                  </tr>
                  ${data.location ? `
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'الموقع:' : 'Location:'}</td>
                    <td style="text-align: right;">${data.location}</td>
                  </tr>
                  ` : ''}
                  ${data.deviceName ? `
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'الجهاز:' : 'Device:'}</td>
                    <td style="text-align: right;">${data.deviceName}</td>
                  </tr>
                  ` : ''}
                </table>
              </div>

              <p class="message" style="font-size: 13px; color: #6b7280;">
                ${isAr
                  ? 'إذا لم تكن أنت من قام بهذا النشاط، يرجى تغيير كلمة المرور فوراً والاتصال بالدعم.'
                  : 'If this wasn\'t you, please change your password immediately and contact support.'}
              </p>

              <div style="text-align: center;">
                <a href="${BASE_URL}/${lang}/dashboard?tab=security" class="cta-button" style="background: #ef4444;">
                  ${isAr ? 'مراجعة إعدادات الأمان' : 'Review Security Settings'}
                </a>
              </div>
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generateSecurityAlertText(
    data: SecurityAlertData,
    isAr: boolean
  ): string {
    const alertTitle = this.getSecurityAlertTitle(data.alertType, isAr);
    const formattedTime = this.formatDateTime(data.eventTime, isAr);

    return isAr
      ? `تنبيه أمني: ${alertTitle}\n\nالوقت: ${formattedTime}\nعنوان IP: ${data.ipAddress}${data.location ? `\nالموقع: ${data.location}` : ''}\n\nإذا لم تكن أنت، يرجى تغيير كلمة المرور فوراً.`
      : `Security Alert: ${alertTitle}\n\nTime: ${formattedTime}\nIP Address: ${data.ipAddress}${data.location ? `\nLocation: ${data.location}` : ''}\n\nIf this wasn't you, please change your password immediately.`;
  }

  private generateWeeklyReportHTML(
    data: WeeklyReportData,
    isAr: boolean
  ): string {
    const direction = isAr ? 'rtl' : 'ltr';
    const lang = isAr ? 'ar' : 'en';
    const greeting = this.getGreeting(data.name, isAr);
    const dateRange = this.formatDateRange(data.periodStart, data.periodEnd, isAr);
    const formattedRevenue = this.formatCurrency(data.payments.totalRevenue, data.payments.currency, isAr);

    return `
      <!DOCTYPE html>
      <html dir="${direction}" lang="${lang}">
      <head>
        <meta charset="UTF-8">
        <meta name="viewport" content="width=device-width, initial-scale=1.0">
        ${this.getBaseStyles()}
      </head>
      <body>
        <div class="email-wrapper">
          <div class="container">
            ${this.getHeader(isAr, '#6366f1')}
            <div class="content">
              <p class="greeting">${greeting}</p>
              <p class="message">
                ${isAr
                  ? `إليك ملخص أداء عملك للأسبوع ${dateRange}:`
                  : `Here's your business performance summary for ${dateRange}:`}
              </p>

              <!-- Metrics Grid -->
              <div style="display: grid; grid-template-columns: 1fr 1fr; gap: 15px; margin: 25px 0;">
                <!-- Appointments -->
                <div class="metric-card">
                  <p class="metric-label">${isAr ? 'الحجوزات الجديدة' : 'New Bookings'}</p>
                  <p class="metric-value">${data.appointments.newBookings}</p>
                  <p style="font-size: 12px;" class="${data.appointments.changePercent >= 0 ? 'change-positive' : 'change-negative'}">
                    ${data.appointments.changePercent >= 0 ? '↑' : '↓'} ${Math.abs(data.appointments.changePercent)}%
                  </p>
                </div>

                <!-- Messages -->
                <div class="metric-card">
                  <p class="metric-label">${isAr ? 'المحادثات' : 'Conversations'}</p>
                  <p class="metric-value">${data.messages.newConversations}</p>
                  <p style="font-size: 12px;" class="${data.messages.changePercent >= 0 ? 'change-positive' : 'change-negative'}">
                    ${data.messages.changePercent >= 0 ? '↑' : '↓'} ${Math.abs(data.messages.changePercent)}%
                  </p>
                </div>

                <!-- Revenue -->
                <div class="metric-card">
                  <p class="metric-label">${isAr ? 'الإيرادات' : 'Revenue'}</p>
                  <p class="metric-value" style="font-size: 20px;">${formattedRevenue}</p>
                  <p style="font-size: 12px;" class="${data.payments.changePercent >= 0 ? 'change-positive' : 'change-negative'}">
                    ${data.payments.changePercent >= 0 ? '↑' : '↓'} ${Math.abs(data.payments.changePercent)}%
                  </p>
                </div>

                <!-- Leads -->
                <div class="metric-card">
                  <p class="metric-label">${isAr ? 'العملاء المحتملون' : 'New Leads'}</p>
                  <p class="metric-value">${data.leads.newLeads}</p>
                  <p style="font-size: 12px;" class="${data.leads.changePercent >= 0 ? 'change-positive' : 'change-negative'}">
                    ${data.leads.changePercent >= 0 ? '↑' : '↓'} ${Math.abs(data.leads.changePercent)}%
                  </p>
                </div>
              </div>

              <!-- Detailed Stats -->
              <div style="background: #f9fafb; border-radius: 8px; padding: 15px; margin: 20px 0;">
                <h4 style="margin-bottom: 10px; color: #374151;">${isAr ? 'تفاصيل إضافية' : 'Additional Details'}</h4>
                <table style="width: 100%; font-size: 14px;">
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'مواعيد قادمة:' : 'Upcoming:'}</td>
                    <td style="text-align: right;">${data.appointments.upcoming}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'مواعيد مكتملة:' : 'Completed:'}</td>
                    <td style="text-align: right;">${data.appointments.completed}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'عملاء محتملون محولون:' : 'Leads Converted:'}</td>
                    <td style="text-align: right;">${data.leads.converted}</td>
                  </tr>
                  <tr>
                    <td style="color: #6b7280; padding: 5px 0;">${isAr ? 'رسائل مستلمة:' : 'Messages Received:'}</td>
                    <td style="text-align: right;">${data.messages.received}</td>
                  </tr>
                </table>
              </div>

              <div style="text-align: center;">
                <a href="${BASE_URL}/${lang}/dashboard" class="cta-button">
                  ${isAr ? 'عرض لوحة التحكم' : 'View Dashboard'}
                </a>
              </div>
            </div>
            ${this.getFooter(isAr)}
          </div>
        </div>
      </body>
      </html>
    `;
  }

  private generateWeeklyReportText(
    data: WeeklyReportData,
    isAr: boolean
  ): string {
    const dateRange = this.formatDateRange(data.periodStart, data.periodEnd, isAr);
    const formattedRevenue = this.formatCurrency(data.payments.totalRevenue, data.payments.currency, isAr);

    return isAr
      ? `تقريرك الأسبوعي: ${dateRange}\n\nالحجوزات الجديدة: ${data.appointments.newBookings}\nالمحادثات: ${data.messages.newConversations}\nالإيرادات: ${formattedRevenue}\nالعملاء المحتملون: ${data.leads.newLeads}`
      : `Your Weekly Report: ${dateRange}\n\nNew Bookings: ${data.appointments.newBookings}\nConversations: ${data.messages.newConversations}\nRevenue: ${formattedRevenue}\nNew Leads: ${data.leads.newLeads}`;
  }

  // =============================================
  // Helper Methods
  // =============================================

  private getHeader(isAr: boolean, color: string = '#10b981'): string {
    return `
      <div class="header" style="background: linear-gradient(135deg, ${color} 0%, ${color}dd 100%);">
        <div class="logo">${EMAIL_CONFIG.brandName}</div>
        <div class="header-subtitle">
          ${isAr ? EMAIL_CONFIG.brandTaglineAr : EMAIL_CONFIG.brandTaglineEn}
        </div>
      </div>
    `;
  }

  private getFooter(isAr: boolean): string {
    return `
      <div class="footer">
        <p class="footer-text">
          ${isAr ? 'هل تحتاج مساعدة؟' : 'Need help?'}
          <a href="mailto:${EMAIL_CONFIG.supportEmail}" style="color: #10b981;">
            ${isAr ? 'تواصل معنا' : 'Contact us'}
          </a>
        </p>
        <p class="footer-text">
          © ${EMAIL_CONFIG.companyYear} ${EMAIL_CONFIG.brandName}.
          ${isAr ? 'جميع الحقوق محفوظة.' : 'All rights reserved.'}
        </p>
      </div>
    `;
  }

  private getGreeting(name: string | undefined, isAr: boolean): string {
    if (!name) {
      return isAr ? 'مرحباً،' : 'Hello,';
    }
    return isAr ? `مرحباً ${name}،` : `Hello ${name},`;
  }

  private getSecurityAlertTitle(alertType: SecurityAlertData['alertType'], isAr: boolean): string {
    const titles: Record<SecurityAlertData['alertType'], { en: string; ar: string }> = {
      new_login: { en: 'New Login Detected', ar: 'تم رصد تسجيل دخول جديد' },
      password_changed: { en: 'Password Changed', ar: 'تم تغيير كلمة المرور' },
      email_changed: { en: 'Email Changed', ar: 'تم تغيير البريد الإلكتروني' },
      suspicious_activity: { en: 'Suspicious Activity', ar: 'نشاط مشبوه' },
      failed_login_attempts: { en: 'Multiple Failed Login Attempts', ar: 'محاولات تسجيل دخول فاشلة متعددة' },
      account_locked: { en: 'Account Locked', ar: 'تم قفل الحساب' },
      new_device: { en: 'New Device Login', ar: 'تسجيل دخول من جهاز جديد' },
      new_location: { en: 'Login from New Location', ar: 'تسجيل دخول من موقع جديد' },
    };
    return isAr ? titles[alertType].ar : titles[alertType].en;
  }

  private getSecurityAlertMessage(data: SecurityAlertData, isAr: boolean): string {
    const messages: Record<SecurityAlertData['alertType'], { en: string; ar: string }> = {
      new_login: {
        en: 'We detected a new login to your account.',
        ar: 'تم رصد تسجيل دخول جديد إلى حسابك.',
      },
      password_changed: {
        en: 'Your password was successfully changed.',
        ar: 'تم تغيير كلمة المرور الخاصة بك بنجاح.',
      },
      email_changed: {
        en: 'Your email address was changed.',
        ar: 'تم تغيير عنوان بريدك الإلكتروني.',
      },
      suspicious_activity: {
        en: 'We detected suspicious activity on your account.',
        ar: 'تم رصد نشاط مشبوه على حسابك.',
      },
      failed_login_attempts: {
        en: `There were ${data.failedAttempts || 'multiple'} failed login attempts.`,
        ar: `تمت ${data.failedAttempts || 'عدة'} محاولات تسجيل دخول فاشلة.`,
      },
      account_locked: {
        en: 'Your account has been temporarily locked for security.',
        ar: 'تم قفل حسابك مؤقتاً لأسباب أمنية.',
      },
      new_device: {
        en: 'Your account was accessed from a new device.',
        ar: 'تم الوصول إلى حسابك من جهاز جديد.',
      },
      new_location: {
        en: 'Your account was accessed from a new location.',
        ar: 'تم الوصول إلى حسابك من موقع جديد.',
      },
    };
    return isAr ? messages[data.alertType].ar : messages[data.alertType].en;
  }

  private formatPreferenceChange(change: PreferenceChange, isAr: boolean): string {
    const settingNames: Record<string, { en: string; ar: string }> = {
      bookings: { en: 'New Bookings', ar: 'الحجوزات الجديدة' },
      reminders: { en: 'Appointment Reminders', ar: 'تذكيرات المواعيد' },
      payments: { en: 'Payment Receipts', ar: 'إيصالات الدفع' },
      marketing: { en: 'Marketing Emails', ar: 'الرسائل التسويقية' },
      security: { en: 'Security Alerts', ar: 'التنبيهات الأمنية' },
      weeklyReport: { en: 'Weekly Report', ar: 'التقرير الأسبوعي' },
      language: { en: 'Language', ar: 'اللغة' },
      timezone: { en: 'Timezone', ar: 'المنطقة الزمنية' },
    };

    const settingName = settingNames[change.setting]
      ? (isAr ? settingNames[change.setting].ar : settingNames[change.setting].en)
      : change.setting;

    const formatValue = (val: boolean | string) => {
      if (typeof val === 'boolean') {
        return isAr
          ? (val ? '✓ مفعل' : '✗ معطل')
          : (val ? '✓ Enabled' : '✗ Disabled');
      }
      return String(val);
    };

    return `
      <tr>
        <td style="color: #374151; padding: 8px 0; font-weight: 500;">${settingName}</td>
        <td style="text-align: ${isAr ? 'left' : 'right'}; color: #10b981;">
          ${formatValue(change.newValue)}
        </td>
      </tr>
    `;
  }

  private formatPreferenceChangeText(change: PreferenceChange, isAr: boolean): string {
    const settingNames: Record<string, { en: string; ar: string }> = {
      bookings: { en: 'New Bookings', ar: 'الحجوزات الجديدة' },
      reminders: { en: 'Appointment Reminders', ar: 'تذكيرات المواعيد' },
      payments: { en: 'Payment Receipts', ar: 'إيصالات الدفع' },
      marketing: { en: 'Marketing Emails', ar: 'الرسائل التسويقية' },
      security: { en: 'Security Alerts', ar: 'التنبيهات الأمنية' },
      weeklyReport: { en: 'Weekly Report', ar: 'التقرير الأسبوعي' },
      language: { en: 'Language', ar: 'اللغة' },
      timezone: { en: 'Timezone', ar: 'المنطقة الزمنية' },
    };

    const settingName = settingNames[change.setting]
      ? (isAr ? settingNames[change.setting].ar : settingNames[change.setting].en)
      : change.setting;

    const formatValue = (val: boolean | string) => {
      if (typeof val === 'boolean') {
        return isAr ? (val ? 'مفعل' : 'معطل') : (val ? 'Enabled' : 'Disabled');
      }
      return String(val);
    };

    return `- ${settingName}: ${formatValue(change.newValue)}`;
  }

  private formatCurrency(amountInCents: number, currency: string, isAr: boolean): string {
    const amount = amountInCents / 100;
    const currencyNames: Record<string, { en: string; ar: string }> = {
      QAR: { en: 'QAR', ar: 'ر.ق' },
      SAR: { en: 'SAR', ar: 'ر.س' },
      AED: { en: 'AED', ar: 'د.إ' },
      USD: { en: 'USD', ar: 'دولار' },
    };
    const currencyLabel = currencyNames[currency]?.[isAr ? 'ar' : 'en'] || currency;
    return isAr
      ? `${amount.toFixed(2)} ${currencyLabel}`
      : `${currencyLabel} ${amount.toFixed(2)}`;
  }

  private formatDate(date: Date, isAr: boolean): string {
    return date.toLocaleDateString(isAr ? 'ar-QA' : 'en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
  }

  private formatDateTime(date: Date, isAr: boolean): string {
    return date.toLocaleString(isAr ? 'ar-QA' : 'en-US', {
      year: 'numeric',
      month: 'short',
      day: 'numeric',
      hour: '2-digit',
      minute: '2-digit',
    });
  }

  private formatDateRange(start: Date, end: Date, isAr: boolean): string {
    const startStr = start.toLocaleDateString(isAr ? 'ar-QA' : 'en-US', { month: 'short', day: 'numeric' });
    const endStr = end.toLocaleDateString(isAr ? 'ar-QA' : 'en-US', { month: 'short', day: 'numeric' });
    return isAr ? `${startStr} - ${endStr}` : `${startStr} - ${endStr}`;
  }
}

/**
 * Singleton instance
 */
export const notificationTemplatesService = new NotificationTemplatesService();
