// backend/src/services/email.js
import { Resend } from 'resend';

const resend = new Resend(process.env.RESEND_API_KEY);

const t = {
  en: {
    verify: { subject: 'Verify your Content Machine account', greeting: 'Welcome to Content Machine!' },
    welcome: { subject: 'You\'re in! Content Machine is ready', greeting: 'Your pipeline is live!' },
    paymentFailed: { subject: 'Payment failed — action required', greeting: 'We couldn\'t process your payment' },
    reset: { subject: 'Reset your password', greeting: 'Password reset requested' },
  },
  ro: {
    verify: { subject: 'Verifică contul tău Content Machine', greeting: 'Bun venit la Content Machine!' },
    welcome: { subject: 'Ești înăuntru! Content Machine e pregătit', greeting: 'Pipeline-ul tău este activ!' },
    paymentFailed: { subject: 'Plata a eșuat — acțiune necesară', greeting: 'Nu am putut procesa plata ta' },
    reset: { subject: 'Resetează parola', greeting: 'Resetare parolă solicitată' },
  }
};

function layout(content) {
  return `<!DOCTYPE html>
<html>
<head><meta charset="utf-8"><style>
  body { font-family: -apple-system, sans-serif; background: #f5f5f5; margin: 0; padding: 40px 0; }
  .card { max-width: 560px; margin: 0 auto; background: white; border-radius: 12px; overflow: hidden; }
  .header { background: #0f172a; padding: 32px; text-align: center; }
  .header h1 { color: #10b981; font-size: 20px; margin: 0; letter-spacing: -0.5px; }
  .body { padding: 40px 32px; }
  .body p { color: #374151; line-height: 1.6; font-size: 15px; }
  .btn { display: inline-block; background: #10b981; color: white; text-decoration: none; padding: 12px 28px; border-radius: 8px; font-weight: 600; font-size: 15px; margin: 16px 0; }
  .footer { padding: 24px 32px; border-top: 1px solid #f0f0f0; color: #9ca3af; font-size: 13px; }
</style></head>
<body>
<div class="card">
  <div class="header"><h1>⚡ Content Machine</h1></div>
  <div class="body">${content}</div>
  <div class="footer">Content Machine — AI-powered content pipeline</div>
</div>
</body></html>`;
}

const templates = {
  'verify-email': ({ name, token, locale }) => {
    const l = locale === 'ro' ? 'ro' : 'en';
    const url = `${process.env.APP_URL}/verify-email?token=${token}`;
    const text = l === 'ro'
      ? `<h2>Bun venit, ${name}!</h2><p>Dă click pe butonul de mai jos pentru a-ți verifica adresa de email și a activa contul tău Content Machine.</p><a href="${url}" class="btn">Verifică Email</a><p>Link-ul expiră în 24 de ore.</p>`
      : `<h2>Welcome, ${name}!</h2><p>Click the button below to verify your email and activate your Content Machine account.</p><a href="${url}" class="btn">Verify Email</a><p>Link expires in 24 hours.</p>`;
    return { subject: t[l].verify.subject, html: layout(text) };
  },
  'welcome-paid': ({ name, planId, locale }) => {
    const l = locale === 'ro' ? 'ro' : 'en';
    const text = l === 'ro'
      ? `<h2>Ești activ, ${name}! 🚀</h2><p>Abonamentul tău <strong>${planId}</strong> este acum activ. Mergi la dashboard și rulează primul tău pipeline.</p><a href="${process.env.APP_URL}/dashboard" class="btn">Deschide Dashboard</a>`
      : `<h2>You're live, ${name}! 🚀</h2><p>Your <strong>${planId}</strong> subscription is now active. Head to your dashboard and run your first pipeline.</p><a href="${process.env.APP_URL}/dashboard" class="btn">Open Dashboard</a>`;
    return { subject: t[l].welcome.subject, html: layout(text) };
  },
  'payment-failed': ({ name, locale }) => {
    const l = locale === 'ro' ? 'ro' : 'en';
    const text = l === 'ro'
      ? `<h2>Hei ${name},</h2><p>Plata ta a eșuat și contul tău este momentan suspendat. Actualizează metoda de plată pentru a continua.</p><a href="${process.env.APP_URL}/dashboard/billing" class="btn">Actualizează Plata</a>`
      : `<h2>Hey ${name},</h2><p>Your payment failed and your account is temporarily suspended. Update your payment method to continue.</p><a href="${process.env.APP_URL}/dashboard/billing" class="btn">Update Payment</a>`;
    return { subject: t[l].paymentFailed.subject, html: layout(text) };
  },
  'reset-password': ({ name, token, locale }) => {
    const l = locale === 'ro' ? 'ro' : 'en';
    const url = `${process.env.APP_URL}/reset-password?token=${token}`;
    const text = l === 'ro'
      ? `<h2>Resetare parolă</h2><p>Hei ${name}, am primit o cerere de resetare a parolei.</p><a href="${url}" class="btn">Resetează Parola</a><p>Link-ul expiră în 1 oră. Dacă nu tu ai solicitat acest lucru, ignoră acest email.</p>`
      : `<h2>Password Reset</h2><p>Hey ${name}, we received a password reset request.</p><a href="${url}" class="btn">Reset Password</a><p>Link expires in 1 hour. If you didn't request this, ignore this email.</p>`;
    return { subject: t[l].reset.subject, html: layout(text) };
  },
};

export async function sendEmail({ to, template, data, subject, html }) {
  try {
    let emailSubject = subject;
    let emailHtml = html;

    if (template && templates[template]) {
      const rendered = templates[template](data || {});
      emailSubject = rendered.subject;
      emailHtml = rendered.html;
    }

    await resend.emails.send({
      from: `${process.env.EMAIL_FROM_NAME} <${process.env.EMAIL_FROM}>`,
      to,
      subject: emailSubject,
      html: emailHtml,
    });
  } catch (err) {
    // Don't throw — email failure shouldn't break the request
    console.error('Email send error:', err.message);
  }
}
