// Email templates for Spanglish platform
// These are the default templates that get seeded into the database

export interface EmailVariable {
  name: string;
  description: string;
  example: string;
}

export interface DefaultTemplate {
  name: string;
  slug: string;
  subject: string;
  subjectEs: string;
  bodyHtml: string;
  bodyHtmlEs: string;
  bodyText: string;
  bodyTextEs: string;
  description: string;
  variables: EmailVariable[];
  isSystem: boolean;
}

// Common variables available in all templates
export const commonVariables: EmailVariable[] = [
  { name: 'siteName', description: 'Website name', example: 'Spanglish' },
  { name: 'siteUrl', description: 'Website URL', example: 'https://spanglish.com' },
  { name: 'currentYear', description: 'Current year', example: '2026' },
  { name: 'supportEmail', description: 'Support email address', example: 'hello@spanglish.com' },
];

// Booking-specific variables
export const bookingVariables: EmailVariable[] = [
  { name: 'attendeeName', description: 'Attendee full name', example: 'John Doe' },
  { name: 'attendeeEmail', description: 'Attendee email', example: 'john@example.com' },
  { name: 'ticketId', description: 'Unique ticket ID', example: 'TKT-ABC123' },
  { name: 'qrCode', description: 'QR code for check-in', example: 'data:image/png;base64,...' },
  { name: 'ticketPdfUrl', description: 'URL to download ticket PDF', example: 'https://api.spanglish.com/api/tickets/abc123/pdf' },
  { name: 'eventTitle', description: 'Event title', example: 'Spanglish Night - January Edition' },
  { name: 'eventDate', description: 'Event date formatted', example: 'January 28, 2026' },
  { name: 'eventTime', description: 'Event time', example: '7:00 PM' },
  { name: 'eventLocation', description: 'Event location', example: 'Casa Cultural, Asunción' },
  { name: 'eventLocationUrl', description: 'Google Maps link', example: 'https://maps.google.com/...' },
  { name: 'eventPrice', description: 'Event price with currency', example: '50,000 PYG' },
];

// Payment-specific variables
export const paymentVariables: EmailVariable[] = [
  { name: 'paymentAmount', description: 'Payment amount with currency', example: '50,000 PYG' },
  { name: 'paymentMethod', description: 'Payment method used', example: 'Lightning' },
  { name: 'paymentReference', description: 'Payment reference ID', example: 'PAY-XYZ789' },
  { name: 'paymentDate', description: 'Payment date', example: 'January 28, 2026' },
];

// Payment instructions variables (for manual payment methods)
export const paymentInstructionsVariables: EmailVariable[] = [
  { name: 'tpagoLink', description: 'TPago payment link', example: 'https://tpago.com.py/...' },
  { name: 'bankName', description: 'Bank name', example: 'Banco Itaú' },
  { name: 'bankAccountHolder', description: 'Account holder name', example: 'Spanglish SRL' },
  { name: 'bankAccountNumber', description: 'Bank account number', example: '1234567890' },
  { name: 'bankAlias', description: 'Bank alias or phone', example: '0981-123-456' },
  { name: 'bankPhone', description: 'Bank phone number', example: '0981-123-456' },
];

// Base HTML wrapper for all emails
export const baseEmailWrapper = `
<!DOCTYPE html>
<html lang="{{lang}}">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>{{subject}}</title>
  <style>
    body {
      font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, Oxygen, Ubuntu, sans-serif;
      line-height: 1.6;
      color: #333;
      margin: 0;
      padding: 0;
      background-color: #f5f5f5;
    }
    .container {
      max-width: 600px;
      margin: 0 auto;
      background-color: #ffffff;
    }
    .header {
      background-color: #1a1a1a;
      padding: 24px;
      text-align: center;
    }
    .header img {
      max-height: 40px;
      width: auto;
    }
    .content {
      padding: 32px 24px;
    }
    .content h2 {
      color: #1a1a1a;
      margin-top: 0;
    }
    .event-card {
      background-color: #f9f9f9;
      border-radius: 8px;
      padding: 20px;
      margin: 20px 0;
    }
    .event-card h3 {
      margin-top: 0;
      color: #1a1a1a;
    }
    .event-detail {
      display: flex;
      margin: 8px 0;
    }
    .event-detail strong {
      min-width: 80px;
      color: #666;
    }
    .ticket-box {
      background-color: #f4d03f;
      border-radius: 8px;
      padding: 16px;
      text-align: center;
      margin: 20px 0;
    }
    .ticket-box p {
      margin: 4px 0;
      font-weight: 600;
      color: #1a1a1a;
    }
    .ticket-id {
      font-size: 20px;
      font-family: monospace;
      letter-spacing: 2px;
    }
    .btn {
      display: inline-block;
      background-color: #f4d03f;
      color: #1a1a1a;
      text-decoration: none;
      padding: 12px 24px;
      border-radius: 6px;
      font-weight: 600;
      margin: 16px 0;
    }
    .btn:hover {
      background-color: #e6c230;
    }
    .footer {
      background-color: #f5f5f5;
      padding: 24px;
      text-align: center;
      font-size: 14px;
      color: #666;
    }
    .footer a {
      color: #333;
    }
    .qr-code {
      text-align: center;
      margin: 20px 0;
    }
    .qr-code img {
      max-width: 150px;
      height: auto;
    }
    .divider {
      height: 1px;
      background-color: #eee;
      margin: 24px 0;
    }
    .note {
      background-color: #fff9e6;
      border-left: 4px solid #f4d03f;
      padding: 12px 16px;
      margin: 16px 0;
      font-size: 14px;
    }
    @media (max-width: 600px) {
      .content {
        padding: 24px 16px;
      }
    }
  </style>
</head>
<body>
  <div class="container">
    <div class="header">
      <img src="{{siteUrl}}/images/logo-spanglish.png" alt="Spanglish" />
    </div>
    <div class="content">
      {{content}}
    </div>
    <div class="footer">
      <p>{{siteName}} - Language Exchange Community in Asunción</p>
      <p><a href="{{siteUrl}}">{{siteUrl}}</a></p>
      <p>Questions? Contact us at <a href="mailto:{{supportEmail}}">{{supportEmail}}</a></p>
      <p>&copy; {{currentYear}} {{siteName}}. All rights reserved.</p>
    </div>
  </div>
</body>
</html>
`;

// Default templates
export const defaultTemplates: DefaultTemplate[] = [
  {
    name: 'Booking Confirmation',
    slug: 'booking-confirmation',
    subject: 'Your Spanglish ticket is confirmed 🎉',
    subjectEs: 'Tu entrada de Spanglish está confirmada 🎉',
    bodyHtml: `
      <h2>Your Booking is Confirmed!</h2>
      <p>Hi {{attendeeName}},</p>
      <p>Great news! Your spot for <strong>{{eventTitle}}</strong> has been confirmed. We can't wait to see you there!</p>
      
      <div class="event-card">
        <h3>📅 Event Details</h3>
        <div class="event-detail"><strong>Event:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Time:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Location:</strong> {{eventLocation}}</div>
        {{#if eventLocationUrl}}
        <p><a href="{{eventLocationUrl}}" class="btn">📍 View on Map</a></p>
        {{/if}}
      </div>
      
      <div class="ticket-box">
        <p>Your Ticket ID</p>
        <p class="ticket-id">{{qrCode}}</p>
      </div>
      
      {{#if ticketPdfUrl}}
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{ticketPdfUrl}}" class="btn" style="background-color: #1a1a1a; color: #f4d03f;">📄 Download Your Ticket (PDF)</a>
      </p>
      {{/if}}
      
      <div class="note">
        <strong>💡 Important:</strong> Please arrive 10-15 minutes early for check-in. Show the PDF ticket or this email at the entrance.
      </div>
      
      <p>See you at Spanglish!</p>
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>¡Tu Reserva está Confirmada!</h2>
      <p>Hola {{attendeeName}},</p>
      <p>¡Excelentes noticias! Tu lugar para <strong>{{eventTitle}}</strong> ha sido confirmado. ¡No podemos esperar a verte ahí!</p>
      
      <div class="event-card">
        <h3>📅 Detalles del Evento</h3>
        <div class="event-detail"><strong>Evento:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Hora:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Ubicación:</strong> {{eventLocation}}</div>
        {{#if eventLocationUrl}}
        <p><a href="{{eventLocationUrl}}" class="btn">📍 Ver en el Mapa</a></p>
        {{/if}}
      </div>
      
      <div class="ticket-box">
        <p>Tu ID de Ticket</p>
        <p class="ticket-id">{{qrCode}}</p>
      </div>
      
      {{#if ticketPdfUrl}}
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{ticketPdfUrl}}" class="btn" style="background-color: #1a1a1a; color: #f4d03f;">📄 Descargar Tu Ticket (PDF)</a>
      </p>
      {{/if}}
      
      <div class="note">
        <strong>💡 Importante:</strong> Por favor llega 10-15 minutos antes para el check-in. Muestra el PDF del ticket o este email en la entrada.
      </div>
      
      <p>¡Nos vemos en Spanglish!</p>
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `Your Booking is Confirmed!

Hi {{attendeeName}},

Great news! Your spot for {{eventTitle}} has been confirmed.

Event Details:
- Event: {{eventTitle}}
- Date: {{eventDate}}
- Time: {{eventTime}}
- Location: {{eventLocation}}

Your Ticket ID: {{ticketId}}

Important: Please arrive 10-15 minutes early for check-in. Bring your ticket ID or show this email.

See you at Spanglish!
The Spanglish Team`,
    bodyTextEs: `¡Tu Reserva está Confirmada!

Hola {{attendeeName}},

¡Excelentes noticias! Tu lugar para {{eventTitle}} ha sido confirmado.

Detalles del Evento:
- Evento: {{eventTitle}}
- Fecha: {{eventDate}}
- Hora: {{eventTime}}
- Ubicación: {{eventLocation}}

Tu ID de Ticket: {{ticketId}}

Importante: Por favor llega 10-15 minutos antes para el check-in. Trae tu ID de ticket o muestra este email.

¡Nos vemos en Spanglish!
El Equipo de Spanglish`,
    description: 'Sent automatically when a booking is confirmed after payment',
    variables: [...commonVariables, ...bookingVariables],
    isSystem: true,
  },
  {
    name: 'Payment Receipt',
    slug: 'payment-receipt',
    subject: 'Payment Receipt - Spanglish',
    subjectEs: 'Recibo de Pago - Spanglish',
    bodyHtml: `
      <h2>Payment Received</h2>
      <p>Hi {{attendeeName}},</p>
      <p>Thank you for your payment! Here's your receipt for your records.</p>
      
      <div class="event-card">
        <h3>💳 Payment Details</h3>
        <div class="event-detail"><strong>Amount:</strong> {{paymentAmount}}</div>
        <div class="event-detail"><strong>Method:</strong> {{paymentMethod}}</div>
        <div class="event-detail"><strong>Reference:</strong> {{paymentReference}}</div>
        <div class="event-detail"><strong>Date:</strong> {{paymentDate}}</div>
      </div>
      
      <div class="divider"></div>
      
      <div class="event-card">
        <h3>📅 Event</h3>
        <div class="event-detail"><strong>Event:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Ticket ID:</strong> {{ticketId}}</div>
      </div>
      
      <p>Keep this email as your payment confirmation.</p>
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>Pago Recibido</h2>
      <p>Hola {{attendeeName}},</p>
      <p>¡Gracias por tu pago! Aquí está tu recibo para tus registros.</p>
      
      <div class="event-card">
        <h3>💳 Detalles del Pago</h3>
        <div class="event-detail"><strong>Monto:</strong> {{paymentAmount}}</div>
        <div class="event-detail"><strong>Método:</strong> {{paymentMethod}}</div>
        <div class="event-detail"><strong>Referencia:</strong> {{paymentReference}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{paymentDate}}</div>
      </div>
      
      <div class="divider"></div>
      
      <div class="event-card">
        <h3>📅 Evento</h3>
        <div class="event-detail"><strong>Evento:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>ID de Ticket:</strong> {{ticketId}}</div>
      </div>
      
      <p>Guarda este email como tu confirmación de pago.</p>
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `Payment Received

Hi {{attendeeName}},

Thank you for your payment! Here's your receipt:

Payment Details:
- Amount: {{paymentAmount}}
- Method: {{paymentMethod}}
- Reference: {{paymentReference}}
- Date: {{paymentDate}}

Event: {{eventTitle}}
Date: {{eventDate}}
Ticket ID: {{ticketId}}

Keep this email as your payment confirmation.

The Spanglish Team`,
    bodyTextEs: `Pago Recibido

Hola {{attendeeName}},

¡Gracias por tu pago! Aquí está tu recibo:

Detalles del Pago:
- Monto: {{paymentAmount}}
- Método: {{paymentMethod}}
- Referencia: {{paymentReference}}
- Fecha: {{paymentDate}}

Evento: {{eventTitle}}
Fecha: {{eventDate}}
ID de Ticket: {{ticketId}}

Guarda este email como tu confirmación de pago.

El Equipo de Spanglish`,
    description: 'Sent automatically after payment is processed',
    variables: [...commonVariables, ...bookingVariables, ...paymentVariables],
    isSystem: true,
  },
  {
    name: 'Event Update',
    slug: 'event-update',
    subject: 'Important Update: {{eventTitle}}',
    subjectEs: 'Actualización Importante: {{eventTitle}}',
    bodyHtml: `
      <h2>Important Event Update</h2>
      <p>Hi {{attendeeName}},</p>
      <p>We have an important update regarding <strong>{{eventTitle}}</strong>.</p>
      
      <div class="event-card">
        <h3>📢 Message</h3>
        <p>{{customMessage}}</p>
      </div>
      
      <div class="event-card">
        <h3>📅 Event Details</h3>
        <div class="event-detail"><strong>Event:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Time:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Location:</strong> {{eventLocation}}</div>
      </div>
      
      <p>If you have any questions, please don't hesitate to contact us.</p>
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>Actualización Importante del Evento</h2>
      <p>Hola {{attendeeName}},</p>
      <p>Tenemos una actualización importante sobre <strong>{{eventTitle}}</strong>.</p>
      
      <div class="event-card">
        <h3>📢 Mensaje</h3>
        <p>{{customMessage}}</p>
      </div>
      
      <div class="event-card">
        <h3>📅 Detalles del Evento</h3>
        <div class="event-detail"><strong>Evento:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Hora:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Ubicación:</strong> {{eventLocation}}</div>
      </div>
      
      <p>Si tienes alguna pregunta, no dudes en contactarnos.</p>
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `Important Event Update

Hi {{attendeeName}},

We have an important update regarding {{eventTitle}}.

Message:
{{customMessage}}

Event Details:
- Event: {{eventTitle}}
- Date: {{eventDate}}
- Time: {{eventTime}}
- Location: {{eventLocation}}

If you have any questions, please don't hesitate to contact us.

The Spanglish Team`,
    bodyTextEs: `Actualización Importante del Evento

Hola {{attendeeName}},

Tenemos una actualización importante sobre {{eventTitle}}.

Mensaje:
{{customMessage}}

Detalles del Evento:
- Evento: {{eventTitle}}
- Fecha: {{eventDate}}
- Hora: {{eventTime}}
- Ubicación: {{eventLocation}}

Si tienes alguna pregunta, no dudes en contactarnos.

El Equipo de Spanglish`,
    description: 'Template for sending event updates to attendees (sent manually)',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'customMessage', description: 'Custom message from admin', example: 'The venue has changed...' }
    ],
    isSystem: true,
  },
  {
    name: 'Post-Event Follow-Up',
    slug: 'post-event-followup',
    subject: 'Thanks for joining {{eventTitle}}! 🙏',
    subjectEs: '¡Gracias por asistir a {{eventTitle}}! 🙏',
    bodyHtml: `
      <h2>Thank You for Joining Us!</h2>
      <p>Hi {{attendeeName}},</p>
      <p>Thank you so much for being part of <strong>{{eventTitle}}</strong>! We hope you had a great time practicing languages and meeting new people.</p>
      
      <div class="event-card">
        <h3>💬 Share Your Experience</h3>
        <p>{{customMessage}}</p>
      </div>
      
      {{#if nextEventTitle}}
      <div class="event-card">
        <h3>📅 Next Event</h3>
        <div class="event-detail"><strong>Event:</strong> {{nextEventTitle}}</div>
        <div class="event-detail"><strong>Date:</strong> {{nextEventDate}}</div>
        <p style="text-align: center; margin-top: 16px;">
          <a href="{{nextEventUrl}}" class="btn">Reserve Your Spot</a>
        </p>
      </div>
      {{/if}}
      
      <p>Follow us on social media for updates and photos from the event!</p>
      <p>See you at the next Spanglish!</p>
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>¡Gracias por Unirte!</h2>
      <p>Hola {{attendeeName}},</p>
      <p>¡Muchas gracias por ser parte de <strong>{{eventTitle}}</strong>! Esperamos que hayas pasado un gran momento practicando idiomas y conociendo gente nueva.</p>
      
      <div class="event-card">
        <h3>💬 Comparte tu Experiencia</h3>
        <p>{{customMessage}}</p>
      </div>
      
      {{#if nextEventTitle}}
      <div class="event-card">
        <h3>📅 Próximo Evento</h3>
        <div class="event-detail"><strong>Evento:</strong> {{nextEventTitle}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{nextEventDate}}</div>
        <p style="text-align: center; margin-top: 16px;">
          <a href="{{nextEventUrl}}" class="btn">Reserva tu Lugar</a>
        </p>
      </div>
      {{/if}}
      
      <p>¡Síguenos en redes sociales para actualizaciones y fotos del evento!</p>
      <p>¡Nos vemos en el próximo Spanglish!</p>
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `Thank You for Joining Us!

Hi {{attendeeName}},

Thank you so much for being part of {{eventTitle}}! We hope you had a great time.

{{customMessage}}

Follow us on social media for updates and photos from the event!

See you at the next Spanglish!
The Spanglish Team`,
    bodyTextEs: `¡Gracias por Unirte!

Hola {{attendeeName}},

¡Muchas gracias por ser parte de {{eventTitle}}! Esperamos que hayas pasado un gran momento.

{{customMessage}}

¡Síguenos en redes sociales para actualizaciones y fotos del evento!

¡Nos vemos en el próximo Spanglish!
El Equipo de Spanglish`,
    description: 'Template for post-event follow-up emails (sent manually)',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'customMessage', description: 'Custom message from admin', example: 'We would love to hear your feedback!' },
      { name: 'nextEventTitle', description: 'Next event title (optional)', example: 'Spanglish Night - February' },
      { name: 'nextEventDate', description: 'Next event date (optional)', example: 'February 25, 2026' },
      { name: 'nextEventUrl', description: 'Next event booking URL (optional)', example: 'https://spanglish.com/book/...' },
    ],
    isSystem: true,
  },
  {
    name: 'Custom Email',
    slug: 'custom-email',
    subject: '{{customSubject}}',
    subjectEs: '{{customSubject}}',
    bodyHtml: `
      <h2>{{customTitle}}</h2>
      <p>Hi {{attendeeName}},</p>
      
      <div class="event-card">
        {{customMessage}}
      </div>
      
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>{{customTitle}}</h2>
      <p>Hola {{attendeeName}},</p>
      
      <div class="event-card">
        {{customMessage}}
      </div>
      
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `{{customTitle}}

Hi {{attendeeName}},

{{customMessage}}

The Spanglish Team`,
    bodyTextEs: `{{customTitle}}

Hola {{attendeeName}},

{{customMessage}}

El Equipo de Spanglish`,
    description: 'Blank template for fully custom emails',
    variables: [
      ...commonVariables,
      { name: 'attendeeName', description: 'Recipient name', example: 'John Doe' },
      { name: 'customSubject', description: 'Email subject', example: 'Special Announcement' },
      { name: 'customTitle', description: 'Email title/heading', example: 'Special Announcement' },
      { name: 'customMessage', description: 'Email body content (supports HTML)', example: '<p>Your message here...</p>' },
    ],
    isSystem: true,
  },
  {
    name: 'Payment Instructions - TPago',
    slug: 'payment-instructions-tpago',
    subject: 'Complete your payment for Spanglish',
    subjectEs: 'Completa tu pago para Spanglish',
    bodyHtml: `
      <h2>You're Almost In! 🎉</h2>
      <p>Hi {{attendeeName}},</p>
      <p>To complete your booking for:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>📍 Location:</strong> {{eventLocation}}</div>
        <div class="event-detail"><strong>💰 Amount:</strong> {{paymentAmount}}</div>
      </div>
      
      <p>Please complete your payment using TPago at the link below:</p>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{tpagoLink}}" class="btn" style="background-color: #3b82f6;">👉 Pay with Card</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        If the button doesn't work: <a href="{{tpagoLink}}" style="color: #3b82f6; word-break: break-all;">{{tpagoLink}}</a>
      </p>
      
      <div class="note" style="background-color: #fef3c7; border-left-color: #f59e0b;">
        <strong>Important - Manual Verification Process:</strong><br>
        Please make sure you complete the payment before clicking "I have paid".<br>
        The Spanglish team will review the payment manually.<br>
        <strong>Your booking is only confirmed after you receive a confirmation email from us.</strong>
      </div>
      
      <div class="note">
        <strong>After completing the payment:</strong><br>
        Return to the website and click <strong>"I have paid"</strong> or click the button below to notify us.
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">✓ I Have Paid</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        Or use this link: <a href="{{bookingUrl}}" style="color: #f59e0b; word-break: break-all;">{{bookingUrl}}</a>
      </p>
      
      <p>If you have any questions, just reply to this email.</p>
      <p>See you soon,<br>Spanglish</p>
    `,
    bodyHtmlEs: `
      <h2>¡Ya Casi Estás! 🎉</h2>
      <p>Hola {{attendeeName}},</p>
      <p>Para completar tu reserva para:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>📍 Ubicación:</strong> {{eventLocation}}</div>
        <div class="event-detail"><strong>💰 Monto:</strong> {{paymentAmount}}</div>
      </div>
      
      <p>Por favor completa tu pago usando TPago en el siguiente enlace:</p>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{tpagoLink}}" class="btn" style="background-color: #3b82f6;">👉 Pagar con Tarjeta</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        Si el botón no funciona: <a href="{{tpagoLink}}" style="color: #3b82f6; word-break: break-all;">{{tpagoLink}}</a>
      </p>
      
      <div class="note" style="background-color: #fef3c7; border-left-color: #f59e0b;">
        <strong>Importante - Proceso de Verificación Manual:</strong><br>
        Por favor asegúrate de completar el pago antes de hacer clic en "Ya pagué".<br>
        El equipo de Spanglish revisará el pago manualmente.<br>
        <strong>Tu reserva solo será confirmada después de que recibas un email de confirmación de nuestra parte.</strong>
      </div>
      
      <div class="note">
        <strong>Después de completar el pago:</strong><br>
        Vuelve al sitio web y haz clic en <strong>"Ya pagué"</strong> o haz clic en el botón de abajo para notificarnos.
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">✓ Ya Pagué</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        O usa este enlace: <a href="{{bookingUrl}}" style="color: #f59e0b; word-break: break-all;">{{bookingUrl}}</a>
      </p>
      
      <p>Si tienes alguna pregunta, simplemente responde a este email.</p>
      <p>¡Nos vemos pronto!<br>Spanglish</p>
    `,
    bodyText: `You're Almost In!

Hi {{attendeeName}},

To complete your booking for:

{{eventTitle}}
📅 Date: {{eventDate}}
📍 Location: {{eventLocation}}
💰 Amount: {{paymentAmount}}

Please complete your payment using TPago at the link below:

👉 Pay with card: {{tpagoLink}}

⚠️ IMPORTANT - Manual Verification Process:
Please make sure you complete the payment before clicking "I have paid".
The Spanglish team will review the payment manually.
Your booking is only confirmed after you receive a confirmation email from us.

After completing the payment, return to the website and click "I have paid" or use this link to notify us:

{{bookingUrl}}

If you have any questions, just reply to this email.

See you soon,
Spanglish`,
    bodyTextEs: `¡Ya Casi Estás!

Hola {{attendeeName}},

Para completar tu reserva para:

{{eventTitle}}
📅 Fecha: {{eventDate}}
📍 Ubicación: {{eventLocation}}
💰 Monto: {{paymentAmount}}

Por favor completa tu pago usando TPago en el siguiente enlace:

👉 Pagar con tarjeta: {{tpagoLink}}

⚠️ IMPORTANTE - Proceso de Verificación Manual:
Por favor asegúrate de completar el pago antes de hacer clic en "Ya pagué".
El equipo de Spanglish revisará el pago manualmente.
Tu reserva solo será confirmada después de que recibas un email de confirmación de nuestra parte.

Después de completar el pago, vuelve al sitio web y haz clic en "Ya pagué" o usa este enlace para notificarnos:

{{bookingUrl}}

Si tienes alguna pregunta, simplemente responde a este email.

¡Nos vemos pronto!
Spanglish`,
    description: 'Sent when user selects TPago payment and clicks continue to payment',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'paymentAmount', description: 'Payment amount with currency', example: '50,000 PYG' },
      { name: 'tpagoLink', description: 'TPago payment link', example: 'https://tpago.com.py/...' },
      { name: 'bookingUrl', description: 'URL to return to payment page', example: 'https://spanglish.com/booking/abc123?step=payment' },
    ],
    isSystem: true,
  },
  {
    name: 'Payment Instructions - Bank Transfer',
    slug: 'payment-instructions-bank-transfer',
    subject: 'Bank transfer details for your Spanglish booking',
    subjectEs: 'Datos de transferencia para tu reserva en Spanglish',
    bodyHtml: `
      <h2>Thanks for Joining Spanglish! 🙂</h2>
      <p>Hi {{attendeeName}},</p>
      <p>Here are the bank transfer details for your booking:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>💰 Amount:</strong> {{paymentAmount}}</div>
      </div>
      
      <div class="event-card" style="background-color: #ecfdf5; border: 1px solid #10b981;">
        <h3 style="color: #059669; margin-top: 0;">🏦 Bank Transfer Details</h3>
        {{#if bankName}}
        <div class="event-detail"><strong>Bank:</strong> {{bankName}}</div>
        {{/if}}
        {{#if bankAccountHolder}}
        <div class="event-detail"><strong>Account Holder:</strong> {{bankAccountHolder}}</div>
        {{/if}}
        {{#if bankAccountNumber}}
        <div class="event-detail"><strong>Account Number:</strong> <span style="font-family: monospace;">{{bankAccountNumber}}</span></div>
        {{/if}}
        {{#if bankAlias}}
        <div class="event-detail"><strong>Alias:</strong> {{bankAlias}}</div>
        {{/if}}
        {{#if bankPhone}}
        <div class="event-detail"><strong>Phone:</strong> {{bankPhone}}</div>
        {{/if}}
        <div class="event-detail"><strong>Reference:</strong> <span style="font-family: monospace; background: #fff; padding: 2px 6px; border-radius: 4px;">{{paymentReference}}</span></div>
      </div>
      
      <div class="note" style="background-color: #fef3c7; border-left-color: #f59e0b;">
        <strong>Important - Manual Verification Process:</strong><br>
        Please make sure you complete the payment before clicking "I have paid".<br>
        The Spanglish team will review the payment manually.<br>
        <strong>Your booking is only confirmed after you receive a confirmation email from us.</strong>
      </div>
      
      <div class="note">
        <strong>After making the transfer:</strong><br>
        Return to the website and click <strong>"I have paid"</strong> or click the button below to notify us.
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">✓ I Have Paid</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        Or use this link: <a href="{{bookingUrl}}" style="color: #f59e0b; word-break: break-all;">{{bookingUrl}}</a>
      </p>
      
      <p>If you need help, reply to this email.</p>
      <p>See you at the event,<br>Spanglish</p>
    `,
    bodyHtmlEs: `
      <h2>¡Gracias por unirte a Spanglish! 🙂</h2>
      <p>Hola {{attendeeName}},</p>
      <p>Aquí están los datos de transferencia para tu reserva:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>💰 Monto:</strong> {{paymentAmount}}</div>
      </div>
      
      <div class="event-card" style="background-color: #ecfdf5; border: 1px solid #10b981;">
        <h3 style="color: #059669; margin-top: 0;">🏦 Datos de Transferencia</h3>
        {{#if bankName}}
        <div class="event-detail"><strong>Banco:</strong> {{bankName}}</div>
        {{/if}}
        {{#if bankAccountHolder}}
        <div class="event-detail"><strong>Titular:</strong> {{bankAccountHolder}}</div>
        {{/if}}
        {{#if bankAccountNumber}}
        <div class="event-detail"><strong>Nro. Cuenta:</strong> <span style="font-family: monospace;">{{bankAccountNumber}}</span></div>
        {{/if}}
        {{#if bankAlias}}
        <div class="event-detail"><strong>Alias:</strong> {{bankAlias}}</div>
        {{/if}}
        {{#if bankPhone}}
        <div class="event-detail"><strong>Teléfono:</strong> {{bankPhone}}</div>
        {{/if}}
        <div class="event-detail"><strong>Referencia:</strong> <span style="font-family: monospace; background: #fff; padding: 2px 6px; border-radius: 4px;">{{paymentReference}}</span></div>
      </div>
      
      <div class="note" style="background-color: #fef3c7; border-left-color: #f59e0b;">
        <strong>Importante - Proceso de Verificación Manual:</strong><br>
        Por favor asegúrate de completar el pago antes de hacer clic en "Ya pagué".<br>
        El equipo de Spanglish revisará el pago manualmente.<br>
        <strong>Tu reserva solo será confirmada después de que recibas un email de confirmación de nuestra parte.</strong>
      </div>
      
      <div class="note">
        <strong>Después de realizar la transferencia:</strong><br>
        Vuelve al sitio web y haz clic en <strong>"Ya pagué"</strong> o haz clic en el botón de abajo para notificarnos.
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">✓ Ya Pagué</a>
      </p>
      <p style="text-align: center; font-size: 12px; color: #6b7280; margin-top: -16px;">
        O usa este enlace: <a href="{{bookingUrl}}" style="color: #f59e0b; word-break: break-all;">{{bookingUrl}}</a>
      </p>
      
      <p>Si necesitas ayuda, responde a este email.</p>
      <p>¡Nos vemos en el evento!<br>Spanglish</p>
    `,
    bodyText: `Thanks for Joining Spanglish!

Hi {{attendeeName}},

Here are the bank transfer details for your booking:

{{eventTitle}}
📅 Date: {{eventDate}}
💰 Amount: {{paymentAmount}}

Bank Transfer Details:
- Bank: {{bankName}}
- Account Holder: {{bankAccountHolder}}
- Account Number: {{bankAccountNumber}}
- Alias: {{bankAlias}}
- Phone: {{bankPhone}}
- Reference: {{paymentReference}}

⚠️ IMPORTANT - Manual Verification Process:
Please make sure you complete the payment before clicking "I have paid".
The Spanglish team will review the payment manually.
Your booking is only confirmed after you receive a confirmation email from us.

After making the transfer, return to the website and click "I have paid" or use this link to notify us:

{{bookingUrl}}

If you need help, reply to this email.

See you at the event,
Spanglish`,
    bodyTextEs: `¡Gracias por unirte a Spanglish!

Hola {{attendeeName}},

Aquí están los datos de transferencia para tu reserva:

{{eventTitle}}
📅 Fecha: {{eventDate}}
💰 Monto: {{paymentAmount}}

Datos de Transferencia:
- Banco: {{bankName}}
- Titular: {{bankAccountHolder}}
- Nro. Cuenta: {{bankAccountNumber}}
- Alias: {{bankAlias}}
- Teléfono: {{bankPhone}}
- Referencia: {{paymentReference}}

⚠️ IMPORTANTE - Proceso de Verificación Manual:
Por favor asegúrate de completar el pago antes de hacer clic en "Ya pagué".
El equipo de Spanglish revisará el pago manualmente.
Tu reserva solo será confirmada después de que recibas un email de confirmación de nuestra parte.

Después de completar el pago, vuelve al sitio web y haz clic en "Ya pagué" o usa este enlace para notificarnos:

{{bookingUrl}}

Si necesitas ayuda, responde a este email.

¡Nos vemos en el evento!
Spanglish`,
    description: 'Sent when user selects bank transfer payment and clicks continue to payment',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'paymentAmount', description: 'Payment amount with currency', example: '50,000 PYG' },
      { name: 'paymentReference', description: 'Unique payment reference', example: 'SPG-ABC123' },
      { name: 'bankName', description: 'Bank name', example: 'Banco Itaú' },
      { name: 'bankAccountHolder', description: 'Account holder name', example: 'Spanglish SRL' },
      { name: 'bankAccountNumber', description: 'Bank account number', example: '1234567890' },
      { name: 'bankAlias', description: 'Bank alias', example: 'spanglish.py' },
      { name: 'bankPhone', description: 'Bank phone number', example: '0981-123-456' },
      { name: 'bookingUrl', description: 'URL to return to payment page', example: 'https://spanglish.com/booking/abc123?step=payment' },
    ],
    isSystem: true,
  },
  {
    name: 'Payment Reminder',
    slug: 'payment-reminder',
    subject: 'Reminder: Complete your payment for Spanglish',
    subjectEs: 'Recordatorio: Completa tu pago para Spanglish',
    bodyHtml: `
      <h2>Payment Reminder</h2>
      <p>Hi {{attendeeName}},</p>
      <p>We wanted to follow up on your booking for <strong>{{eventTitle}}</strong>.</p>
      <p>We haven't been able to locate your payment yet. To receive your ticket and confirm your spot, please complete your payment.</p>
      
      <div class="event-card">
        <h3>📅 Event Details</h3>
        <div class="event-detail"><strong>Event:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Time:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Location:</strong> {{eventLocation}}</div>
        <div class="event-detail"><strong>Amount Due:</strong> {{paymentAmount}}</div>
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">Complete Payment</a>
      </p>
      
      <div class="note">
        <strong>Already paid?</strong><br>
        If you have already completed your payment and believe this is an error, please reply to this email with your payment details (date, amount, and method used) and we'll be happy to look into it.
      </div>
      
      <p>We hope to see you at the event!</p>
      <p>The Spanglish Team</p>
    `,
    bodyHtmlEs: `
      <h2>Recordatorio de Pago</h2>
      <p>Hola {{attendeeName}},</p>
      <p>Queríamos dar seguimiento a tu reserva para <strong>{{eventTitle}}</strong>.</p>
      <p>Aún no hemos podido localizar tu pago. Para recibir tu entrada y confirmar tu lugar, por favor completa tu pago.</p>
      
      <div class="event-card">
        <h3>📅 Detalles del Evento</h3>
        <div class="event-detail"><strong>Evento:</strong> {{eventTitle}}</div>
        <div class="event-detail"><strong>Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>Hora:</strong> {{eventTime}}</div>
        <div class="event-detail"><strong>Ubicación:</strong> {{eventLocation}}</div>
        <div class="event-detail"><strong>Monto a Pagar:</strong> {{paymentAmount}}</div>
      </div>
      
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{bookingUrl}}" class="btn">Completar Pago</a>
      </p>
      
      <div class="note">
        <strong>¿Ya pagaste?</strong><br>
        Si ya completaste tu pago y crees que esto es un error, por favor responde a este correo con los detalles de tu pago (fecha, monto y método utilizado) y con gusto lo revisaremos.
      </div>
      
      <p>¡Esperamos verte en el evento!</p>
      <p>El Equipo de Spanglish</p>
    `,
    bodyText: `Payment Reminder

Hi {{attendeeName}},

We wanted to follow up on your booking for {{eventTitle}}.

We haven't been able to locate your payment yet. To receive your ticket and confirm your spot, please complete your payment.

Event Details:
- Event: {{eventTitle}}
- Date: {{eventDate}}
- Time: {{eventTime}}
- Location: {{eventLocation}}
- Amount Due: {{paymentAmount}}

Complete your payment here: {{bookingUrl}}

Already paid?
If you have already completed your payment and believe this is an error, please reply to this email with your payment details (date, amount, and method used) and we'll be happy to look into it.

We hope to see you at the event!
The Spanglish Team`,
    bodyTextEs: `Recordatorio de Pago

Hola {{attendeeName}},

Queríamos dar seguimiento a tu reserva para {{eventTitle}}.

Aún no hemos podido localizar tu pago. Para recibir tu entrada y confirmar tu lugar, por favor completa tu pago.

Detalles del Evento:
- Evento: {{eventTitle}}
- Fecha: {{eventDate}}
- Hora: {{eventTime}}
- Ubicación: {{eventLocation}}
- Monto a Pagar: {{paymentAmount}}

Completa tu pago aquí: {{bookingUrl}}

¿Ya pagaste?
Si ya completaste tu pago y crees que esto es un error, por favor responde a este correo con los detalles de tu pago (fecha, monto y método utilizado) y con gusto lo revisaremos.

¡Esperamos verte en el evento!
El Equipo de Spanglish`,
    description: 'Sent to remind attendees to complete their pending payment',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'paymentAmount', description: 'Payment amount with currency', example: '50,000 PYG' },
      { name: 'bookingUrl', description: 'URL to complete payment', example: 'https://spanglish.com/booking/abc123?step=payment' },
    ],
    isSystem: true,
  },
  {
    name: 'Payment Rejected',
    slug: 'payment-rejected',
    subject: 'Payment not found for your Spanglish booking',
    subjectEs: 'No encontramos el pago de tu reserva en Spanglish',
    bodyHtml: `
      <h2>About Your Booking</h2>
      <p>Hi {{attendeeName}},</p>
      <p>Thanks for your interest in Spanglish.</p>
      <p>Unfortunately, we were unable to find or confirm the payment for your booking for:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Date:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>📍 Location:</strong> {{eventLocation}}</div>
      </div>
      
      <p>Because of this, the booking has been cancelled.</p>
      
      <div class="note">
        <strong>Did you already pay?</strong><br>
        If you believe this was a mistake or if you have already made the payment, please reply to this email and we'll be happy to check it with you.
      </div>
      
      <p>You're always welcome to make a new booking if spots are still available.</p>
      
      {{#if newBookingUrl}}
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{newBookingUrl}}" class="btn">Make a New Booking</a>
      </p>
      {{/if}}
      
      <p>Warm regards,<br>Spanglish</p>
    `,
    bodyHtmlEs: `
      <h2>Sobre Tu Reserva</h2>
      <p>Hola {{attendeeName}},</p>
      <p>Gracias por tu interés en Spanglish.</p>
      <p>Lamentablemente, no pudimos encontrar o confirmar el pago de tu reserva para:</p>
      
      <div class="event-card">
        <h3>{{eventTitle}}</h3>
        <div class="event-detail"><strong>📅 Fecha:</strong> {{eventDate}}</div>
        <div class="event-detail"><strong>📍 Ubicación:</strong> {{eventLocation}}</div>
      </div>
      
      <p>Por esta razón, la reserva ha sido cancelada.</p>
      
      <div class="note">
        <strong>¿Ya realizaste el pago?</strong><br>
        Si crees que esto fue un error o si ya realizaste el pago, por favor responde a este correo y con gusto lo revisaremos contigo.
      </div>
      
      <p>Siempre eres bienvenido/a a hacer una nueva reserva si aún hay lugares disponibles.</p>
      
      {{#if newBookingUrl}}
      <p style="text-align: center; margin: 24px 0;">
        <a href="{{newBookingUrl}}" class="btn">Hacer una Nueva Reserva</a>
      </p>
      {{/if}}
      
      <p>Saludos cordiales,<br>Spanglish</p>
    `,
    bodyText: `About Your Booking

Hi {{attendeeName}},

Thanks for your interest in Spanglish.

Unfortunately, we were unable to find or confirm the payment for your booking for:

{{eventTitle}}
📅 Date: {{eventDate}}
📍 Location: {{eventLocation}}

Because of this, the booking has been cancelled.

If you believe this was a mistake or if you have already made the payment, please reply to this email and we'll be happy to check it with you.

You're always welcome to make a new booking if spots are still available.

Warm regards,
Spanglish`,
    bodyTextEs: `Sobre Tu Reserva

Hola {{attendeeName}},

Gracias por tu interés en Spanglish.

Lamentablemente, no pudimos encontrar o confirmar el pago de tu reserva para:

{{eventTitle}}
📅 Fecha: {{eventDate}}
📍 Ubicación: {{eventLocation}}

Por esta razón, la reserva ha sido cancelada.

Si crees que esto fue un error o si ya realizaste el pago, por favor responde a este correo y con gusto lo revisaremos contigo.

Siempre eres bienvenido/a a hacer una nueva reserva si aún hay lugares disponibles.

Saludos cordiales,
Spanglish`,
    description: 'Sent when admin rejects a TPago or Bank Transfer payment',
    variables: [
      ...commonVariables, 
      ...bookingVariables,
      { name: 'newBookingUrl', description: 'URL to make a new booking (optional)', example: 'https://spanglish.com/book/event123' },
    ],
    isSystem: true,
  },
];

// Escape HTML-significant characters so substituted variable values can't inject markup.
function escapeHtmlValue(value: string): string {
  return value
    .replace(/&/g, '&amp;')
    .replace(/</g, '&lt;')
    .replace(/>/g, '&gt;')
    .replace(/"/g, '&quot;')
    .replace(/'/g, '&#x27;');
}

// Helper function to replace template variables.
// When `escapeHtml` is true (HTML rendering contexts), substituted *values* are
// HTML-escaped to prevent stored-XSS via attacker-influenced variables (e.g. event
// location, attendee name). The template markup itself is never escaped. Subjects and
// plain-text bodies pass `escapeHtml=false` so they don't show literal entities.
export function replaceTemplateVariables(
  template: string,
  variables: Record<string, any>,
  escapeHtml: boolean = false
): string {
  let result = template;
  
  // Handle conditional blocks {{#if variable}}...{{/if}}
  const conditionalRegex = /\{\{#if\s+(\w+)\}\}([\s\S]*?)\{\{\/if\}\}/g;
  result = result.replace(conditionalRegex, (match, varName, content) => {
    return variables[varName] ? content : '';
  });
  
  // Replace simple variables {{variable}}
  const variableRegex = /\{\{(\w+)\}\}/g;
  result = result.replace(variableRegex, (match, varName) => {
    if (variables[varName] === undefined) return match;
    const raw = String(variables[varName]);
    return escapeHtml ? escapeHtmlValue(raw) : raw;
  });
  
  return result;
}

// Helper to wrap content in the base template.
// `content` is treated as trusted HTML (it is the already-rendered body). The wrapper's
// own variables (subject, year, etc.) are HTML-escaped on substitution.
export function wrapInBaseTemplate(content: string, variables: Record<string, any>): string {
  const wrappedContent = baseEmailWrapper.replace('{{content}}', () => content);
  return replaceTemplateVariables(wrappedContent, variables, true);
}

// Get all available variables for a template by slug
export function getTemplateVariables(slug: string): EmailVariable[] {
  const template = defaultTemplates.find(t => t.slug === slug);
  return template?.variables || commonVariables;
}
