/**
 * Trial Emails Service
 *
 * Handles all trial-related email notifications including:
 * - Trial ending reminders (3 days, 1 day)
 * - Payment failed notifications (attempts 1-3 with retry info)
 * - Subscription active confirmations (trial to paid conversion)
 * - Trial expired notifications
 *
 * Features:
 * - Beautiful responsive HTML templates with green gradient theme
 * - RTL (Arabic) and LTR (English) support
 * - Multi-currency support (GBP, USD, EUR, QAR, AED, SAR)
 * - Idempotency tracking via billing_history to prevent duplicate emails
 * - Plain text alternatives for all templates
 *
 * @module services/trial-emails
 */

import { sendEmail } from '@/lib/email';
import { logger } from '@/lib/logger';
import { billingAdapter } from '@/lib/adapters/billing';
import { subscriptionsAdapter } from '@/lib/adapters/subscriptions';

// ============================================
// INTERFACES
// ============================================

export interface TrialEndingEmailParams {
  userEmail: string;
  userName: string;
  daysRemaining: 1 | 3;
  trialEndDate: Date;
  planName: string;
  amount: number;
  currency: string;
  subscriptionId?: string;
  customerId?: string;
  lang?: 'en' | 'ar';
}

export interface PaymentFailedEmailParams {
  userEmail: string;
  userName: string;
  amount: number;
  currency: string;
  failureReason?: string;
  retryDate?: Date;
  attemptCount: number;
  subscriptionId: string;
  customerId: string;
  lang?: 'en' | 'ar';
}

export interface SubscriptionActiveEmailParams {
  userEmail: string;
  userName: string;
  planName: string;
  amount: number;
  currency: string;
  nextBillingDate: Date;
  subscriptionId: string;
  customerId: string;
  lang?: 'en' | 'ar';
}

export interface TrialExpiredEmailParams {
  userEmail: string;
  userName: string;
  planName: string;
  amount: number;
  currency: string;
  subscriptionId?: string;
  customerId?: string;
  lang?: 'en' | 'ar';
}

export interface PaymentMethodMissingEmailParams {
  userEmail: string;
  userName: string;
  trialEndDate: Date;
  planName: string;
  amount: number;
  currency: string;
  lang?: 'en' | 'ar';
}

// ============================================
// CURRENCY HELPER
// ============================================

/**
 * Format currency amount with proper symbol
 */
function formatCurrency(amount: number, currency: string): string {
  const currencyMap: Record<string, { symbol: string; position: 'prefix' | 'suffix' }> = {
    gbp: { symbol: '\u00A3', position: 'prefix' },
    usd: { symbol: '$', position: 'prefix' },
    eur: { symbol: '\u20AC', position: 'prefix' },
    qar: { symbol: 'QAR', position: 'suffix' },
    aed: { symbol: 'AED', position: 'suffix' },
    sar: { symbol: 'SAR', position: 'suffix' },
  };

  const currencyConfig = currencyMap[currency.toLowerCase()] || {
    symbol: currency.toUpperCase(),
    position: 'suffix',
  };

  const formattedAmount = amount.toFixed(2);

  if (currencyConfig.position === 'prefix') {
    return `${currencyConfig.symbol}${formattedAmount}`;
  }
  return `${formattedAmount} ${currencyConfig.symbol}`;
}

// ============================================
// BASE TEMPLATE STYLES
// ============================================

const baseStyles = `
  body {
    font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, 'Helvetica Neue', Arial, sans-serif;
    line-height: 1.6;
    color: #1f2937;
    margin: 0;
    padding: 0;
    background-color: #f3f4f6;
    -webkit-font-smoothing: antialiased;
    -moz-osx-font-smoothing: grayscale;
  }
  .wrapper {
    width: 100%;
    background-color: #f3f4f6;
    padding: 40px 20px;
    box-sizing: border-box;
  }
  .container {
    max-width: 600px;
    margin: 0 auto;
    background: #ffffff;
    border-radius: 16px;
    overflow: hidden;
    box-shadow: 0 4px 20px rgba(0, 0, 0, 0.08);
  }
  .header {
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: white;
    padding: 48px 32px;
    text-align: center;
  }
  .header-icon {
    font-size: 56px;
    margin-bottom: 16px;
    display: block;
  }
  .header h1 {
    margin: 0;
    font-size: 28px;
    font-weight: 700;
    letter-spacing: -0.5px;
  }
  .header p {
    margin: 12px 0 0 0;
    opacity: 0.95;
    font-size: 16px;
    font-weight: 400;
  }
  .content {
    padding: 40px 32px;
  }
  .greeting {
    font-size: 18px;
    font-weight: 500;
    color: #1f2937;
    margin-bottom: 24px;
  }
  .message {
    font-size: 15px;
    color: #4b5563;
    margin-bottom: 24px;
    line-height: 1.7;
  }
  .info-box {
    background: #f0fdf4;
    border-left: 4px solid #10b981;
    padding: 24px;
    margin: 24px 0;
    border-radius: 0 12px 12px 0;
  }
  .info-box h3 {
    margin: 0 0 16px 0;
    color: #065f46;
    font-size: 16px;
    font-weight: 600;
  }
  .info-row {
    display: flex;
    justify-content: space-between;
    padding: 10px 0;
    border-bottom: 1px solid #dcfce7;
    font-size: 14px;
  }
  .info-row:last-child {
    border-bottom: none;
  }
  .info-row .label {
    color: #6b7280;
  }
  .info-row .value {
    font-weight: 600;
    color: #065f46;
  }
  .cta-button {
    display: inline-block;
    padding: 16px 40px;
    background: linear-gradient(135deg, #10b981 0%, #059669 100%);
    color: #ffffff !important;
    text-decoration: none;
    border-radius: 10px;
    font-weight: 600;
    font-size: 16px;
    margin: 24px 0;
    box-shadow: 0 4px 14px rgba(16, 185, 129, 0.35);
    transition: transform 0.2s, box-shadow 0.2s;
  }
  .cta-button:hover {
    transform: translateY(-2px);
    box-shadow: 0 6px 20px rgba(16, 185, 129, 0.4);
  }
  .footer {
    background: #f9fafb;
    padding: 32px;
    text-align: center;
    border-top: 1px solid #e5e7eb;
  }
  .footer-text {
    font-size: 13px;
    color: #6b7280;
    margin: 8px 0;
  }
  .footer-link {
    color: #10b981;
    text-decoration: none;
    font-weight: 500;
  }
  .warning-header {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
  }
  .danger-header {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
  }
  .warning-box {
    background: #fef3c7;
    border-left: 4px solid #f59e0b;
    padding: 24px;
    margin: 24px 0;
    border-radius: 0 12px 12px 0;
  }
  .warning-box h3 {
    margin: 0 0 12px 0;
    color: #92400e;
    font-size: 16px;
    font-weight: 600;
  }
  .warning-box p {
    margin: 8px 0;
    color: #b45309;
    font-size: 14px;
  }
  .danger-box {
    background: #fef2f2;
    border-left: 4px solid #ef4444;
    padding: 24px;
    margin: 24px 0;
    border-radius: 0 12px 12px 0;
  }
  .danger-box h3 {
    margin: 0 0 12px 0;
    color: #991b1b;
    font-size: 16px;
    font-weight: 600;
  }
  .danger-box p {
    margin: 8px 0;
    color: #b91c1c;
    font-size: 14px;
  }
  .countdown-box {
    background: linear-gradient(135deg, #fef3c7 0%, #fde68a 100%);
    border: 2px solid #f59e0b;
    border-radius: 16px;
    padding: 32px;
    margin: 32px 0;
    text-align: center;
  }
  .countdown-number {
    font-size: 72px;
    font-weight: 800;
    color: #d97706;
    line-height: 1;
    margin: 0;
  }
  .countdown-label {
    font-size: 18px;
    color: #92400e;
    font-weight: 600;
    margin-top: 12px;
    text-transform: uppercase;
    letter-spacing: 2px;
  }
  .countdown-urgent {
    background: linear-gradient(135deg, #fef2f2 0%, #fecaca 100%);
    border-color: #ef4444;
  }
  .countdown-urgent .countdown-number {
    color: #dc2626;
  }
  .countdown-urgent .countdown-label {
    color: #991b1b;
  }
  .steps-list {
    margin: 24px 0;
    padding: 0;
    list-style: none;
  }
  .steps-list li {
    padding: 12px 0 12px 40px;
    position: relative;
    font-size: 15px;
    color: #4b5563;
  }
  .steps-list li::before {
    content: attr(data-step);
    position: absolute;
    left: 0;
    top: 50%;
    transform: translateY(-50%);
    width: 28px;
    height: 28px;
    background: #10b981;
    color: white;
    border-radius: 50%;
    display: flex;
    align-items: center;
    justify-content: center;
    font-weight: 600;
    font-size: 14px;
  }
  .danger-button {
    background: linear-gradient(135deg, #ef4444 0%, #dc2626 100%);
    box-shadow: 0 4px 14px rgba(239, 68, 68, 0.35);
  }
  .warning-button {
    background: linear-gradient(135deg, #f59e0b 0%, #d97706 100%);
    box-shadow: 0 4px 14px rgba(245, 158, 11, 0.35);
  }
  @media only screen and (max-width: 600px) {
    .container {
      border-radius: 0;
    }
    .header {
      padding: 32px 24px;
    }
    .header h1 {
      font-size: 24px;
    }
    .content {
      padding: 32px 24px;
    }
    .cta-button {
      display: block;
      text-align: center;
    }
    .countdown-number {
      font-size: 56px;
    }
  }
`;

// RTL-specific styles for Arabic - exported for future RTL email templates
export const rtlStyles = `
  .info-box {
    border-left: none;
    border-right: 4px solid #10b981;
    border-radius: 12px 0 0 12px;
  }
  .warning-box {
    border-left: none;
    border-right: 4px solid #f59e0b;
    border-radius: 12px 0 0 12px;
  }
  .danger-box {
    border-left: none;
    border-right: 4px solid #ef4444;
    border-radius: 12px 0 0 12px;
  }
  .steps-list li {
    padding: 12px 40px 12px 0;
  }
  .steps-list li::before {
    left: auto;
    right: 0;
  }
`;

// ============================================
// TRIAL EMAILS SERVICE CLASS
// ============================================

export class TrialEmailsService {
  private readonly appUrl: string;

  constructor() {
    this.appUrl = process.env.NEXT_PUBLIC_APP_URL || 'https://app.mawidi.com';
  }

  /**
   * Escape HTML special characters to prevent XSS attacks
   * Used for user-provided content that will be interpolated into HTML templates
   */
  private escapeHtml(str: string): string {
    return str
      .replace(/&/g, '&amp;')
      .replace(/</g, '&lt;')
      .replace(/>/g, '&gt;')
      .replace(/"/g, '&quot;')
      .replace(/'/g, '&#039;');
  }

  /**
   * Get combined styles for email templates with RTL support
   * Applies RTL styles when lang is 'ar' (Arabic)
   */
  private getStyles(lang: 'en' | 'ar' = 'en'): string {
    return lang === 'ar' ? baseStyles + rtlStyles : baseStyles;
  }

  /**
   * Get HTML attributes for body element based on language
   */
  private getBodyAttrs(lang: 'en' | 'ar' = 'en'): { dir: string; htmlLang: string } {
    return {
      dir: lang === 'ar' ? 'rtl' : 'ltr',
      htmlLang: lang,
    };
  }

  // ============================================
  // IDEMPOTENCY TRACKING
  // ============================================

  /**
   * Check if email has already been sent for this event
   */
  private async hasEmailBeenSent(
    subscriptionId: string,
    eventType: string
  ): Promise<boolean> {
    try {
      const existing = await billingAdapter.billingHistory.findFirst({
        where: {
          subscriptionId,
          event: eventType,
        },
        orderBy: { createdAt: 'desc' },
      });

      return !!existing;
    } catch (error) {
      logger.error('Error checking email idempotency', error, {
        subscriptionId,
        eventType,
      });
      // Fail open - allow sending if we can't check
      return false;
    }
  }

  /**
   * Record that email was sent
   */
  private async recordEmailSent(
    params: {
      subscriptionId?: string;
      customerId?: string;
      eventType: string;
      email: string;
      currency: string;
      metadata?: Record<string, unknown>;
    }
  ): Promise<void> {
    try {
      const { createId } = await import('@paralleldrive/cuid2');

      await billingAdapter.billingHistory.create({
        data: {
          id: createId(),
          customerId: params.customerId || 'system',
          subscriptionId: params.subscriptionId || null,
          event: params.eventType,
          amount: 0,
          currency: params.currency.toLowerCase(),
          metadata: {
            type: 'email_notification',
            email: params.email,
            sentAt: new Date().toISOString(),
            ...params.metadata,
          },
        },
      });

      logger.info('Email notification recorded in billing_history', {
        eventType: params.eventType,
        subscriptionId: params.subscriptionId,
      });
    } catch (error) {
      logger.error('Failed to record email in billing_history', error, {
        eventType: params.eventType,
        subscriptionId: params.subscriptionId,
      });
      // Don't throw - email was sent, just logging failed
    }
  }

  // ============================================
  // EMAIL METHODS
  // ============================================

  /**
   * Send trial ending reminder email (3 days or 1 day before)
   * Includes idempotency check to prevent duplicate sends
   *
   * @param params - Email parameters
   * @param externalSubscriptionId - Optional subscription ID for idempotency (overrides params.subscriptionId)
   */
  async sendTrialEndingEmail(
    params: TrialEndingEmailParams,
    externalSubscriptionId?: string
  ): Promise<boolean> {
    const { userEmail, daysRemaining, currency, subscriptionId: paramsSubId, customerId, trialEndDate, planName, amount } = params;
    const subscriptionId = externalSubscriptionId || paramsSubId;

    const eventType = `trial_reminder_${daysRemaining}d`;

    // Idempotency check
    if (subscriptionId) {
      const alreadySent = await this.hasEmailBeenSent(subscriptionId, eventType);
      if (alreadySent) {
        logger.info('Trial ending email already sent (idempotency check)', {
          subscriptionId,
          daysRemaining,
        });
        return false;
      }
    }

    const subject = daysRemaining === 1
      ? 'Your Free Trial Ends Tomorrow - Action Required'
      : 'Your Free Trial Ends in 3 Days - Mawidi';

    const html = this.generateTrialEndingHTML(params);
    const text = this.generateTrialEndingText(params);

    try {
      const success = await sendEmail(userEmail, { subject, html, text });

      if (success && subscriptionId) {
        await this.recordEmailSent({
          subscriptionId,
          customerId,
          eventType,
          email: userEmail,
          currency,
          metadata: {
            daysRemaining,
            trialEndDate: trialEndDate.toISOString(),
            planName,
            amount,
          },
        });
      }

      logger.info('Trial ending email sent', {
        daysRemaining,
        subscriptionId,
      });

      return success;
    } catch (error) {
      logger.error('Failed to send trial ending email', error, {
        subscriptionId,
        daysRemaining,
      });
      return false;
    }
  }

  /**
   * Send payment failed notification email
   * Includes retry information and attempt count
   */
  async sendPaymentFailedEmail(params: PaymentFailedEmailParams): Promise<boolean> {
    const { userEmail, amount, currency, failureReason, retryDate, attemptCount, subscriptionId, customerId } = params;

    const eventType = `payment_failed_${attemptCount}`;

    // Idempotency check
    const alreadySent = await this.hasEmailBeenSent(subscriptionId, eventType);
    if (alreadySent) {
      logger.info('Payment failed email already sent (idempotency check)', {
        subscriptionId,
        attemptCount,
      });
      return false;
    }

    const isFinal = attemptCount >= 3;
    const subject = isFinal
      ? 'Subscription Suspended - Final Payment Attempt Failed - Mawidi'
      : `Payment Failed (Attempt ${attemptCount}/3) - Action Required - Mawidi`;

    const html = this.generatePaymentFailedHTML(params);
    const text = this.generatePaymentFailedText(params);

    try {
      const success = await sendEmail(userEmail, { subject, html, text });

      if (success) {
        await this.recordEmailSent({
          subscriptionId,
          customerId,
          eventType,
          email: userEmail,
          currency,
          metadata: {
            attemptCount,
            failureReason,
            retryDate: retryDate?.toISOString(),
            amount,
            isFinal,
          },
        });
      }

      logger.info('Payment failed email sent', {
        attemptCount,
        subscriptionId,
        isFinal,
      });

      return success;
    } catch (error) {
      logger.error('Failed to send payment failed email', error, {
        subscriptionId,
        attemptCount,
      });
      return false;
    }
  }

  /**
   * Send subscription active email (trial converted to paid)
   */
  async sendSubscriptionActiveEmail(params: SubscriptionActiveEmailParams): Promise<boolean> {
    const { userEmail, planName, amount, currency, nextBillingDate, subscriptionId, customerId } = params;

    const eventType = 'subscription_activated';

    // Idempotency check
    const alreadySent = await this.hasEmailBeenSent(subscriptionId, eventType);
    if (alreadySent) {
      logger.info('Subscription active email already sent (idempotency check)', {
        subscriptionId,
      });
      return false;
    }

    const subject = 'Welcome to Mawidi - Your Subscription is Now Active!';

    const html = this.generateSubscriptionActiveHTML(params);
    const text = this.generateSubscriptionActiveText(params);

    try {
      const success = await sendEmail(userEmail, { subject, html, text });

      if (success) {
        await this.recordEmailSent({
          subscriptionId,
          customerId,
          eventType,
          email: userEmail,
          currency,
          metadata: {
            planName,
            amount,
            nextBillingDate: nextBillingDate.toISOString(),
          },
        });
      }

      logger.info('Subscription active email sent', {
        subscriptionId,
        planName,
      });

      return success;
    } catch (error) {
      logger.error('Failed to send subscription active email', error, {
        subscriptionId,
      });
      return false;
    }
  }

  /**
   * Send trial expired email (no payment method, trial ended)
   */
  async sendTrialExpiredEmail(params: TrialExpiredEmailParams): Promise<boolean> {
    const { userEmail, planName, amount, currency, subscriptionId, customerId } = params;

    const eventType = 'trial_expired';

    // Idempotency check
    if (subscriptionId) {
      const alreadySent = await this.hasEmailBeenSent(subscriptionId, eventType);
      if (alreadySent) {
        logger.info('Trial expired email already sent (idempotency check)', {
          subscriptionId,
        });
        return false;
      }
    }

    const subject = 'Your Trial Has Expired - Reactivate Your Mawidi Account';

    const html = this.generateTrialExpiredHTML(params);
    const text = this.generateTrialExpiredText(params);

    try {
      const success = await sendEmail(userEmail, { subject, html, text });

      if (success && subscriptionId) {
        await this.recordEmailSent({
          subscriptionId,
          customerId,
          eventType,
          email: userEmail,
          currency,
          metadata: {
            planName,
            amount,
          },
        });
      }

      logger.info('Trial expired email sent', {
        subscriptionId,
        planName,
      });

      return success;
    } catch (error) {
      logger.error('Failed to send trial expired email', error, {
        subscriptionId,
      });
      return false;
    }
  }

  /**
   * Check if a subscription has a payment method attached
   *
   * @param stripeSubscriptionId - The Stripe subscription ID
   * @returns boolean indicating if payment method exists
   */
  async hasPaymentMethod(stripeSubscriptionId: string): Promise<boolean> {
    try {
      const subscription = await subscriptionsAdapter.findUnique({
        where: { stripeSubscriptionId },
        select: { paymentMethodId: true },
      });

      return !!subscription?.paymentMethodId;
    } catch (error) {
      logger.error('Failed to check payment method', error, {
        stripeSubscriptionId,
      });
      return false;
    }
  }

  /**
   * Send payment method missing warning email
   * Sent when trial is ending but no payment method is on file
   */
  async sendPaymentMethodMissingEmail(params: PaymentMethodMissingEmailParams): Promise<boolean> {
    const { userEmail, userName, trialEndDate, planName, amount, currency, lang = 'en' } = params;

    const subject = 'Action Required: Add Payment Method Before Trial Ends - Mawidi';
    const formattedAmount = formatCurrency(amount, currency);
    const formattedDate = trialEndDate.toLocaleDateString(lang === 'ar' ? 'ar-SA' : 'en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
    const { dir, htmlLang } = this.getBodyAttrs(lang);
    const styles = this.getStyles(lang);

    const html = `
<!DOCTYPE html>
<html lang="${htmlLang}" dir="${dir}">
<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>Add Payment Method - Mawidi</title>
  <style>${styles}</style>
</head>
<body dir="${dir}">
  <div class="wrapper">
    <div class="container">
      <div class="header warning-header">
        <span class="header-icon">\u26A0\uFE0F</span>
        <h1>Payment Method Required</h1>
        <p>Add a payment method to continue using Mawidi</p>
      </div>

      <div class="content">
        <p class="greeting">Hello ${this.escapeHtml(userName)},</p>

        <div class="warning-box">
          <h3>\u26A0\uFE0F No Payment Method on File</h3>
          <p>Your trial of <strong>${planName}</strong> ends on <strong>${formattedDate}</strong>, but we don't have a payment method on file.</p>
        </div>

        <p class="message">
          To continue using Mawidi without interruption, please add a payment method before your trial ends.
          Without a valid payment method, your account access will be restricted when the trial expires.
        </p>

        <div class="info-box">
          <h3>\uD83D\uDCB3 Billing Summary</h3>
          <div class="info-row">
            <span class="label">Plan</span>
            <span class="value">${planName}</span>
          </div>
          <div class="info-row">
            <span class="label">Monthly Price</span>
            <span class="value">${formattedAmount}</span>
          </div>
          <div class="info-row">
            <span class="label">Trial Ends</span>
            <span class="value">${formattedDate}</span>
          </div>
        </div>

        <div style="text-align: center;">
          <a href="${this.appUrl}/en/dashboard?tab=billing" class="cta-button warning-button">
            Add Payment Method
          </a>
        </div>

        <p style="color: #6b7280; font-size: 14px; margin-top: 32px;">
          Thank you for choosing Mawidi!<br><br>
          Best regards,<br>
          <strong>The Mawidi Team</strong>
        </p>
      </div>

      <div class="footer">
        <p class="footer-text">This is an automated reminder from Mawidi.</p>
        <p class="footer-text">\u00A9 ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
        <p class="footer-text">
          <a href="mailto:support@mawidi.com" class="footer-link">support@mawidi.com</a>
        </p>
      </div>
    </div>
  </div>
</body>
</html>`;

    const text = `
ACTION REQUIRED: PAYMENT METHOD NEEDED
${'='.repeat(50)}

Hello ${userName},

Your trial of ${planName} ends on ${formattedDate}, but we don't have a payment method on file.

BILLING SUMMARY
---------------
Plan: ${planName}
Monthly Price: ${formattedAmount}
Trial Ends: ${formattedDate}

To continue using Mawidi without interruption, please add a payment method before your trial ends.

Add payment method:
${this.appUrl}/en/dashboard?tab=billing

Thank you for choosing Mawidi!

Best regards,
The Mawidi Team

---
This is an automated reminder from Mawidi.
(c) ${new Date().getFullYear()} Mawidi. All rights reserved.
support@mawidi.com
    `.trim();

    try {
      const success = await sendEmail(userEmail, { subject, html, text });

      logger.info('Payment method missing email sent', {
        userEmail,
        planName,
      });

      return success;
    } catch (error) {
      logger.error('Failed to send payment method missing email', error, {
        userEmail,
      });
      return false;
    }
  }

  // ============================================
  // HTML TEMPLATE GENERATORS
  // ============================================

  private generateTrialEndingHTML(params: TrialEndingEmailParams): string {
    const { userName, daysRemaining, trialEndDate, planName, amount, currency, lang = 'en' } = params;
    const isUrgent = daysRemaining === 1;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedDate = trialEndDate.toLocaleDateString(lang === 'ar' ? 'ar-SA' : 'en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
    const { dir, htmlLang } = this.getBodyAttrs(lang);
    const styles = this.getStyles(lang);

    return `
<!DOCTYPE html>
<html lang="${htmlLang}" dir="${dir}">
<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>Trial Ending Soon - Mawidi</title>
  <style>${styles}</style>
</head>
<body dir="${dir}">
  <div class="wrapper">
    <div class="container">
      <div class="header ${isUrgent ? 'warning-header' : ''}">
        <span class="header-icon">${isUrgent ? '\u23F0' : '\u2699\uFE0F'}</span>
        <h1>Your Trial is Ending ${isUrgent ? 'Tomorrow!' : 'Soon'}</h1>
        <p>Don't lose access to your Mawidi account</p>
      </div>

      <div class="content">
        <p class="greeting">Hello ${this.escapeHtml(userName)},</p>

        <div class="countdown-box ${isUrgent ? 'countdown-urgent' : ''}">
          <p class="countdown-number">${daysRemaining}</p>
          <p class="countdown-label">${daysRemaining === 1 ? 'Day Left' : 'Days Left'}</p>
        </div>

        <p class="message">
          Your free trial of <strong>${planName}</strong> ends on <strong>${formattedDate}</strong>.
          ${isUrgent
            ? 'This is your final reminder before your trial expires!'
            : 'Ensure you have a payment method on file to continue using Mawidi without interruption.'}
        </p>

        <div class="info-box">
          <h3>\uD83D\uDCB3 Billing Summary</h3>
          <div class="info-row">
            <span class="label">Plan</span>
            <span class="value">${planName}</span>
          </div>
          <div class="info-row">
            <span class="label">Monthly Price</span>
            <span class="value">${formattedAmount}</span>
          </div>
          <div class="info-row">
            <span class="label">First Billing Date</span>
            <span class="value">${formattedDate}</span>
          </div>
        </div>

        <p class="message">
          <strong>What happens next?</strong><br>
          When your trial ends, your payment method will be charged ${formattedAmount}/month.
          You can update your payment method or cancel anytime from your billing settings.
        </p>

        <div style="text-align: center;">
          <a href="${this.appUrl}/en/dashboard?tab=billing" class="cta-button ${isUrgent ? 'warning-button' : ''}">
            Manage Subscription
          </a>
        </div>

        <p style="color: #6b7280; font-size: 14px; margin-top: 32px;">
          Thank you for choosing Mawidi!<br><br>
          Best regards,<br>
          <strong>The Mawidi Team</strong>
        </p>
      </div>

      <div class="footer">
        <p class="footer-text">This is an automated reminder from Mawidi.</p>
        <p class="footer-text">\u00A9 ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
        <p class="footer-text">
          <a href="mailto:support@mawidi.com" class="footer-link">support@mawidi.com</a>
        </p>
      </div>
    </div>
  </div>
</body>
</html>`;
  }

  private generatePaymentFailedHTML(params: PaymentFailedEmailParams): string {
    const { userName, amount, currency, failureReason, retryDate, attemptCount, lang = 'en' } = params;
    const isFinal = attemptCount >= 3;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedRetryDate = retryDate
      ? retryDate.toLocaleDateString(lang === 'ar' ? 'ar-SA' : 'en-US', { month: 'long', day: 'numeric', year: 'numeric' })
      : null;
    const { dir, htmlLang } = this.getBodyAttrs(lang);
    const styles = this.getStyles(lang);

    return `
<!DOCTYPE html>
<html lang="${htmlLang}" dir="${dir}">
<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>Payment Failed - Mawidi</title>
  <style>${styles}</style>
</head>
<body dir="${dir}">
  <div class="wrapper">
    <div class="container">
      <div class="header danger-header">
        <span class="header-icon">${isFinal ? '\u26A0\uFE0F' : '\u274C'}</span>
        <h1>${isFinal ? 'Subscription Suspended' : 'Payment Failed'}</h1>
        <p>Action required to ${isFinal ? 'restore your account' : 'continue your subscription'}</p>
      </div>

      <div class="content">
        <p class="greeting">Hello ${this.escapeHtml(userName)},</p>

        <div class="danger-box">
          <h3>${isFinal ? '\u26A0\uFE0F Account Access Restricted' : '\u274C Payment Could Not Be Processed'}</h3>
          <p><strong>Amount:</strong> ${formattedAmount}</p>
          ${failureReason ? `<p><strong>Reason:</strong> ${failureReason}</p>` : ''}
          <p><strong>Attempt:</strong> ${attemptCount} of 3</p>
        </div>

        ${isFinal ? `
        <p class="message">
          After 3 failed payment attempts, your subscription has been suspended and your account access has been restricted.
          To restore full access to Mawidi, please update your payment method immediately.
        </p>

        <div class="warning-box">
          <h3>\uD83D\uDD12 Your Data is Safe</h3>
          <p>We've preserved all your data and settings. Once you update your payment method, your account will be restored instantly.</p>
        </div>
        ` : `
        <p class="message">
          We were unable to process your payment of ${formattedAmount}. This can happen for various reasons including
          insufficient funds, expired card, or bank security checks.
          ${formattedRetryDate ? `<br><br>We'll automatically retry on <strong>${formattedRetryDate}</strong>.` : ''}
        </p>
        `}

        <p class="message"><strong>What you can do:</strong></p>
        <ul class="steps-list">
          <li data-step="1">Check that your card has sufficient funds</li>
          <li data-step="2">Verify your card hasn't expired</li>
          <li data-step="3">Contact your bank if payments are being blocked</li>
          <li data-step="4">Update your payment method in Mawidi</li>
        </ul>

        <div style="text-align: center;">
          <a href="${this.appUrl}/en/dashboard?tab=billing" class="cta-button danger-button">
            Update Payment Method
          </a>
        </div>

        <p style="color: #6b7280; font-size: 14px; margin-top: 32px;">
          Need help? Our support team is here to assist you.<br><br>
          Best regards,<br>
          <strong>The Mawidi Team</strong>
        </p>
      </div>

      <div class="footer">
        <p class="footer-text">This is an automated notification from Mawidi.</p>
        <p class="footer-text">\u00A9 ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
        <p class="footer-text">
          <a href="mailto:support@mawidi.com" class="footer-link">support@mawidi.com</a>
        </p>
      </div>
    </div>
  </div>
</body>
</html>`;
  }

  private generateSubscriptionActiveHTML(params: SubscriptionActiveEmailParams): string {
    const { userName, planName, amount, currency, nextBillingDate, lang = 'en' } = params;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedDate = nextBillingDate.toLocaleDateString(lang === 'ar' ? 'ar-SA' : 'en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });
    const { dir, htmlLang } = this.getBodyAttrs(lang);
    const styles = this.getStyles(lang);

    return `
<!DOCTYPE html>
<html lang="${htmlLang}" dir="${dir}">
<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>Welcome to Mawidi - Subscription Active</title>
  <style>${styles}</style>
</head>
<body dir="${dir}">
  <div class="wrapper">
    <div class="container">
      <div class="header">
        <span class="header-icon">\u2705</span>
        <h1>Welcome to Mawidi!</h1>
        <p>Your subscription is now active</p>
      </div>

      <div class="content">
        <p class="greeting">Hello ${this.escapeHtml(userName)},</p>

        <p class="message">
          <strong>Congratulations!</strong> Your free trial has ended and your subscription is now active.
          Thank you for choosing Mawidi to manage your clinic appointments.
        </p>

        <div class="info-box">
          <h3>\uD83D\uDCCB Subscription Details</h3>
          <div class="info-row">
            <span class="label">Plan</span>
            <span class="value">${planName}</span>
          </div>
          <div class="info-row">
            <span class="label">Monthly Price</span>
            <span class="value">${formattedAmount}</span>
          </div>
          <div class="info-row">
            <span class="label">Next Billing Date</span>
            <span class="value">${formattedDate}</span>
          </div>
          <div class="info-row">
            <span class="label">Status</span>
            <span class="value" style="color: #10b981;">\u2705 Active</span>
          </div>
        </div>

        <p class="message"><strong>What's included in your plan:</strong></p>
        <ul class="steps-list">
          <li data-step="\u2713">Full access to all Mawidi features</li>
          <li data-step="\u2713">WhatsApp appointment reminders</li>
          <li data-step="\u2713">Multi-language support (English & Arabic)</li>
          <li data-step="\u2713">Priority customer support</li>
          <li data-step="\u2713">Regular updates and new features</li>
        </ul>

        <div style="text-align: center;">
          <a href="${this.appUrl}/en/dashboard" class="cta-button">
            Go to Dashboard
          </a>
        </div>

        <p style="color: #6b7280; font-size: 14px; margin-top: 32px;">
          If you have any questions, our support team is always here to help.<br><br>
          Thank you for your trust in Mawidi!<br><br>
          Best regards,<br>
          <strong>The Mawidi Team</strong>
        </p>
      </div>

      <div class="footer">
        <p class="footer-text">This is a confirmation email from Mawidi.</p>
        <p class="footer-text">\u00A9 ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
        <p class="footer-text">
          <a href="mailto:support@mawidi.com" class="footer-link">support@mawidi.com</a>
        </p>
      </div>
    </div>
  </div>
</body>
</html>`;
  }

  private generateTrialExpiredHTML(params: TrialExpiredEmailParams): string {
    const { userName, planName, amount, currency, lang = 'en' } = params;
    const formattedAmount = formatCurrency(amount, currency);
    const { dir, htmlLang } = this.getBodyAttrs(lang);
    const styles = this.getStyles(lang);

    return `
<!DOCTYPE html>
<html lang="${htmlLang}" dir="${dir}">
<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>Trial Expired - Mawidi</title>
  <style>${styles}</style>
</head>
<body dir="${dir}">
  <div class="wrapper">
    <div class="container">
      <div class="header danger-header">
        <span class="header-icon">\u23F3</span>
        <h1>Your Trial Has Expired</h1>
        <p>Reactivate to continue using Mawidi</p>
      </div>

      <div class="content">
        <p class="greeting">Hello ${this.escapeHtml(userName)},</p>

        <div class="warning-box">
          <h3>\u23F3 Trial Period Ended</h3>
          <p>Your free trial of <strong>${planName}</strong> has expired. Your account access has been restricted until you add a payment method.</p>
        </div>

        <p class="message">
          We noticed you haven't added a payment method during your trial period.
          To continue using Mawidi and all its features, please add a payment method to reactivate your subscription.
        </p>

        <div class="info-box">
          <h3>\uD83D\uDC9A What You're Missing</h3>
          <div class="info-row">
            <span class="label">Plan</span>
            <span class="value">${planName}</span>
          </div>
          <div class="info-row">
            <span class="label">Price</span>
            <span class="value">${formattedAmount}/month</span>
          </div>
          <div class="info-row">
            <span class="label">Features</span>
            <span class="value">Full access to all features</span>
          </div>
        </div>

        <p class="message"><strong>Good news:</strong> Your data has been preserved. Once you reactivate, everything will be exactly as you left it.</p>

        <div style="text-align: center;">
          <a href="${this.appUrl}/en/dashboard?tab=billing&action=reactivate" class="cta-button">
            Reactivate Now
          </a>
        </div>

        <p class="message" style="margin-top: 24px;">
          <strong>Special Offer:</strong> Reactivate within 7 days and we'll add an extra week to your subscription at no additional cost!
        </p>

        <p style="color: #6b7280; font-size: 14px; margin-top: 32px;">
          Questions? We're here to help.<br><br>
          Best regards,<br>
          <strong>The Mawidi Team</strong>
        </p>
      </div>

      <div class="footer">
        <p class="footer-text">This is an automated notification from Mawidi.</p>
        <p class="footer-text">\u00A9 ${new Date().getFullYear()} Mawidi. All rights reserved.</p>
        <p class="footer-text">
          <a href="mailto:support@mawidi.com" class="footer-link">support@mawidi.com</a>
        </p>
      </div>
    </div>
  </div>
</body>
</html>`;
  }

  // ============================================
  // PLAIN TEXT GENERATORS
  // ============================================

  private generateTrialEndingText(params: TrialEndingEmailParams): string {
    const { userName, daysRemaining, trialEndDate, planName, amount, currency } = params;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedDate = trialEndDate.toLocaleDateString('en-US', {
      weekday: 'long',
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    return `
YOUR TRIAL IS ENDING ${daysRemaining === 1 ? 'TOMORROW' : 'SOON'}
${'='.repeat(50)}

Hello ${userName},

Your free trial of ${planName} ends on ${formattedDate}.
${daysRemaining === 1 ? 'This is your final reminder!' : ''}

BILLING SUMMARY
---------------
Plan: ${planName}
Monthly Price: ${formattedAmount}
First Billing Date: ${formattedDate}

What happens next?
When your trial ends, your payment method will be charged ${formattedAmount}/month.
You can update your payment method or cancel anytime from your billing settings.

Manage your subscription:
${this.appUrl}/en/dashboard?tab=billing

Thank you for choosing Mawidi!

Best regards,
The Mawidi Team

---
This is an automated reminder from Mawidi.
(c) ${new Date().getFullYear()} Mawidi. All rights reserved.
support@mawidi.com
    `.trim();
  }

  private generatePaymentFailedText(params: PaymentFailedEmailParams): string {
    const { userName, amount, currency, failureReason, retryDate, attemptCount } = params;
    const isFinal = attemptCount >= 3;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedRetryDate = retryDate
      ? retryDate.toLocaleDateString('en-US', { month: 'long', day: 'numeric', year: 'numeric' })
      : null;

    return `
${isFinal ? 'SUBSCRIPTION SUSPENDED' : 'PAYMENT FAILED'}
${'='.repeat(50)}

Hello ${userName},

${isFinal
  ? 'After 3 failed payment attempts, your subscription has been suspended and your account access has been restricted.'
  : `We were unable to process your payment of ${formattedAmount}.`}

PAYMENT DETAILS
---------------
Amount: ${formattedAmount}
${failureReason ? `Reason: ${failureReason}` : ''}
Attempt: ${attemptCount} of 3

${isFinal
  ? 'To restore full access to Mawidi, please update your payment method immediately.\n\nYour data is safe - we\'ve preserved all your data and settings.'
  : formattedRetryDate
    ? `We'll automatically retry on ${formattedRetryDate}.`
    : ''}

WHAT YOU CAN DO
---------------
1. Check that your card has sufficient funds
2. Verify your card hasn't expired
3. Contact your bank if payments are being blocked
4. Update your payment method in Mawidi

Update payment method:
${this.appUrl}/en/dashboard?tab=billing

Need help? Our support team is here to assist you.

Best regards,
The Mawidi Team

---
This is an automated notification from Mawidi.
(c) ${new Date().getFullYear()} Mawidi. All rights reserved.
support@mawidi.com
    `.trim();
  }

  private generateSubscriptionActiveText(params: SubscriptionActiveEmailParams): string {
    const { userName, planName, amount, currency, nextBillingDate } = params;
    const formattedAmount = formatCurrency(amount, currency);
    const formattedDate = nextBillingDate.toLocaleDateString('en-US', {
      year: 'numeric',
      month: 'long',
      day: 'numeric',
    });

    return `
WELCOME TO MAWIDI!
${'='.repeat(50)}

Hello ${userName},

Congratulations! Your free trial has ended and your subscription is now active.
Thank you for choosing Mawidi to manage your clinic appointments.

SUBSCRIPTION DETAILS
--------------------
Plan: ${planName}
Monthly Price: ${formattedAmount}
Next Billing Date: ${formattedDate}
Status: Active

WHAT'S INCLUDED
---------------
- Full access to all Mawidi features
- WhatsApp appointment reminders
- Multi-language support (English & Arabic)
- Priority customer support
- Regular updates and new features

Go to your dashboard:
${this.appUrl}/en/dashboard

If you have any questions, our support team is always here to help.

Thank you for your trust in Mawidi!

Best regards,
The Mawidi Team

---
This is a confirmation email from Mawidi.
(c) ${new Date().getFullYear()} Mawidi. All rights reserved.
support@mawidi.com
    `.trim();
  }

  private generateTrialExpiredText(params: TrialExpiredEmailParams): string {
    const { userName, planName, amount, currency } = params;
    const formattedAmount = formatCurrency(amount, currency);

    return `
YOUR TRIAL HAS EXPIRED
${'='.repeat(50)}

Hello ${userName},

Your free trial of ${planName} has expired.
Your account access has been restricted until you add a payment method.

WHAT YOU'RE MISSING
-------------------
Plan: ${planName}
Price: ${formattedAmount}/month
Features: Full access to all features

Good news: Your data has been preserved. Once you reactivate,
everything will be exactly as you left it.

SPECIAL OFFER
-------------
Reactivate within 7 days and we'll add an extra week to your
subscription at no additional cost!

Reactivate now:
${this.appUrl}/en/dashboard?tab=billing&action=reactivate

Questions? We're here to help.

Best regards,
The Mawidi Team

---
This is an automated notification from Mawidi.
(c) ${new Date().getFullYear()} Mawidi. All rights reserved.
support@mawidi.com
    `.trim();
  }
}

// ============================================
// SINGLETON EXPORT
// ============================================

export const trialEmailsService = new TrialEmailsService();
export default trialEmailsService;
