/**
 * Email Template Service
 * Manages email templates for campaigns and transactional emails
 */

export interface EmailTemplate {
  id: string;
  name: string;
  subject: string;
  htmlContent: string;
  textContent?: string;
  variables: string[];
  category: 'campaign' | 'transactional' | 'promotional';
  createdAt: Date;
  updatedAt: Date;
}

/**
 * Default email templates
 */
export const DEFAULT_TEMPLATES: Record<string, EmailTemplate> = {
  // Campaign templates
  welcome_campaign: {
    id: 'welcome_campaign',
    name: 'Welcome Campaign',
    subject: 'Welcome to CoinKrazy! 🎰',
    htmlContent: `
      <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
          <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #6366f1;">Welcome to CoinKrazy!</h1>
            <p>Hi {{firstName}},</p>
            <p>We're thrilled to have you join our community of players. Get ready for an exciting gaming experience with:</p>
            <ul>
              <li>🎮 Hundreds of exciting games</li>
              <li>💰 Generous welcome bonuses</li>
              <li>🏆 Daily rewards and tournaments</li>
              <li>⭐ VIP perks and exclusive offers</li>
            </ul>
            <p><a href="{{loginUrl}}" style="background-color: #6366f1; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Start Playing Now</a></p>
            <p>Best regards,<br/>The CoinKrazy Team</p>
          </div>
        </body>
      </html>
    `,
    variables: ['firstName', 'loginUrl'],
    category: 'campaign',
    createdAt: new Date(),
    updatedAt: new Date(),
  },

  // Promotional template
  promotional_offer: {
    id: 'promotional_offer',
    name: 'Promotional Offer',
    subject: '🎁 Special Offer Just for You!',
    htmlContent: `
      <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
          <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #f59e0b;">{{offerTitle}}</h1>
            <p>Hi {{firstName}},</p>
            <p>{{offerDescription}}</p>
            <div style="background-color: #f59e0b; color: white; padding: 20px; border-radius: 5px; text-align: center; margin: 20px 0;">
              <h2>{{offerAmount}}</h2>
              <p>Use code: <strong>{{promoCode}}</strong></p>
            </div>
            <p><a href="{{claimUrl}}" style="background-color: #f59e0b; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Claim Offer</a></p>
            <p style="font-size: 12px; color: #999;">Offer expires on {{expiryDate}}</p>
          </div>
        </body>
      </html>
    `,
    variables: ['firstName', 'offerTitle', 'offerDescription', 'offerAmount', 'promoCode', 'claimUrl', 'expiryDate'],
    category: 'promotional',
    createdAt: new Date(),
    updatedAt: new Date(),
  },

  // Transactional templates
  password_reset: {
    id: 'password_reset',
    name: 'Password Reset',
    subject: 'Reset Your CoinKrazy Password',
    htmlContent: `
      <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
          <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1>Password Reset Request</h1>
            <p>Hi {{firstName}},</p>
            <p>We received a request to reset your password. Click the link below to create a new password:</p>
            <p><a href="{{resetLink}}" style="background-color: #6366f1; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Reset Password</a></p>
            <p style="font-size: 12px; color: #999;">This link expires in 24 hours.</p>
            <p>If you didn't request this, please ignore this email.</p>
          </div>
        </body>
      </html>
    `,
    variables: ['firstName', 'resetLink'],
    category: 'transactional',
    createdAt: new Date(),
    updatedAt: new Date(),
  },

  email_verification: {
    id: 'email_verification',
    name: 'Email Verification',
    subject: 'Verify Your CoinKrazy Email',
    htmlContent: `
      <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
          <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1>Email Verification</h1>
            <p>Hi {{firstName}},</p>
            <p>Please verify your email address to complete your CoinKrazy account setup:</p>
            <p><a href="{{verificationLink}}" style="background-color: #10b981; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Verify Email</a></p>
            <p style="font-size: 12px; color: #999;">Or copy this code: <strong>{{verificationCode}}</strong></p>
          </div>
        </body>
      </html>
    `,
    variables: ['firstName', 'verificationLink', 'verificationCode'],
    category: 'transactional',
    createdAt: new Date(),
    updatedAt: new Date(),
  },

  // Engagement template
  re_engagement: {
    id: 're_engagement',
    name: 'Re-engagement Campaign',
    subject: 'We Miss You! Come Back and Claim Your Bonus 🎁',
    htmlContent: `
      <html>
        <body style="font-family: Arial, sans-serif; color: #333;">
          <div style="max-width: 600px; margin: 0 auto; padding: 20px;">
            <h1 style="color: #6366f1;">We Miss You, {{firstName}}!</h1>
            <p>It's been a while since we've seen you at CoinKrazy. We'd love to have you back!</p>
            <div style="background-color: #f3f4f6; padding: 20px; border-radius: 5px; margin: 20px 0;">
              <h2>Welcome Back Bonus</h2>
              <p>{{bonusAmount}} in free credits waiting for you!</p>
            </div>
            <p><a href="{{loginUrl}}" style="background-color: #6366f1; color: white; padding: 10px 20px; text-decoration: none; border-radius: 5px; display: inline-block;">Log In Now</a></p>
            <p>Offer valid until {{expiryDate}}</p>
          </div>
        </body>
      </html>
    `,
    variables: ['firstName', 'bonusAmount', 'loginUrl', 'expiryDate'],
    category: 'promotional',
    createdAt: new Date(),
    updatedAt: new Date(),
  },
};

/**
 * Get template by ID
 */
export function getTemplate(templateId: string): EmailTemplate | undefined {
  return DEFAULT_TEMPLATES[templateId];
}

/**
 * Render template with variables
 */
export function renderTemplate(
  template: EmailTemplate,
  variables: Record<string, string>
): { subject: string; htmlContent: string } {
  let subject = template.subject;
  let htmlContent = template.htmlContent;

  // Replace all variables in subject and content
  Object.entries(variables).forEach(([key, value]) => {
    const placeholder = `{{${key}}}`;
    subject = subject.replace(new RegExp(placeholder, 'g'), value);
    htmlContent = htmlContent.replace(new RegExp(placeholder, 'g'), value);
  });

  return { subject, htmlContent };
}

/**
 * Validate template variables
 */
export function validateTemplateVariables(
  template: EmailTemplate,
  variables: Record<string, string>
): { valid: boolean; missing: string[] } {
  const missing = template.variables.filter((v) => !variables[v]);

  return {
    valid: missing.length === 0,
    missing,
  };
}

/**
 * Get all templates
 */
export function getAllTemplates(): EmailTemplate[] {
  return Object.values(DEFAULT_TEMPLATES);
}

/**
 * Get templates by category
 */
export function getTemplatesByCategory(
  category: 'campaign' | 'transactional' | 'promotional'
): EmailTemplate[] {
  return Object.values(DEFAULT_TEMPLATES).filter((t) => t.category === category);
}
