'use strict';

const nodemailer = require('nodemailer');

let transporter = null;

function getTransporter() {
  if (transporter) return transporter;
  transporter = nodemailer.createTransport({
    host:   process.env.SMTP_HOST || 'smtp.sendgrid.net',
    port:   parseInt(process.env.SMTP_PORT || '587'),
    secure: process.env.SMTP_PORT === '465',
    auth: {
      user: process.env.SMTP_USER,
      pass: process.env.SMTP_PASS,
    },
  });
  return transporter;
}

// ── Email Templates ───────────────────────────────────────────────
const TEMPLATES = {
  verify_email: (d) => ({
    subject: 'Verify your ChainPay account',
    html: `
    <div style="font-family:Arial,sans-serif;max-width:560px;margin:0 auto;background:#fff;">
      <div style="background:#0a0f1e;padding:24px 32px;border-radius:12px 12px 0 0;">
        <div style="font-size:20px;font-weight:800;color:#fff;">⚡ ChainPay</div>
      </div>
      <div style="padding:32px;border:1px solid #eee;border-top:none;border-radius:0 0 12px 12px;">
        <h2 style="color:#0a0f1e;margin:0 0 12px;">Verify your email</h2>
        <p style="color:#555;line-height:1.6;">Hi ${d.name},<br><br>Thanks for signing up at chainpay.store. Click below to verify your email address.</p>
        <a href="https://chainpay.store/verify?token=${d.token}" style="display:inline-block;background:#ff6b2b;color:#fff;padding:12px 28px;border-radius:9px;font-weight:700;text-decoration:none;margin:16px 0;">Verify Email →</a>
        <p style="font-size:12px;color:#aaa;margin-top:16px;">If you didn't sign up, ignore this email. Link expires in 24 hours.</p>
      </div>
    </div>`,
  }),

  reset_password: (d) => ({
    subject: 'Reset your ChainPay password',
    html: `
    <div style="font-family:Arial,sans-serif;max-width:560px;margin:0 auto;background:#fff;">
      <div style="background:#0a0f1e;padding:24px 32px;border-radius:12px 12px 0 0;">
        <div style="font-size:20px;font-weight:800;color:#fff;">⚡ ChainPay</div>
      </div>
      <div style="padding:32px;border:1px solid #eee;border-top:none;border-radius:0 0 12px 12px;">
        <h2 style="color:#0a0f1e;">Reset your password</h2>
        <p style="color:#555;line-height:1.6;">Hi ${d.name},<br><br>We received a password reset request. Click below to set a new password.</p>
        <a href="https://chainpay.store/reset-password?token=${d.token}" style="display:inline-block;background:#ff6b2b;color:#fff;padding:12px 28px;border-radius:9px;font-weight:700;text-decoration:none;margin:16px 0;">Reset Password →</a>
        <p style="font-size:12px;color:#aaa;">Link expires in 1 hour. Didn't request this? Ignore it.</p>
      </div>
    </div>`,
  }),

  license_created: (d) => ({
    subject: '🎉 Your ChainPay Pro License is ready',
    html: `
    <div style="font-family:Arial,sans-serif;max-width:560px;margin:0 auto;background:#fff;">
      <div style="background:#0a0f1e;padding:24px 32px;border-radius:12px 12px 0 0;">
        <div style="font-size:20px;font-weight:800;color:#fff;">⚡ ChainPay</div>
      </div>
      <div style="padding:32px;border:1px solid #eee;border-top:none;border-radius:0 0 12px 12px;">
        <h2 style="color:#059669;margin-bottom:12px;">🎉 Pro License Activated</h2>
        <p style="color:#555;line-height:1.6;">Your ChainPay Pro license is ready. Paste the key below into <strong>WooCommerce → ChainPay → License</strong>.</p>
        <div style="background:#f8f8f8;border:1.5px solid #e0e0e0;border-radius:8px;padding:14px 16px;margin:16px 0;">
          <div style="font-size:11px;color:#888;margin-bottom:6px;text-transform:uppercase;letter-spacing:.5px;">Your License Key</div>
          <div style="font-family:monospace;font-size:14px;font-weight:700;color:#0a0f1e;word-break:break-all;">${d.license_key}</div>
        </div>
        <div style="background:#f0fdf4;border:1px solid #bbf7d0;border-radius:8px;padding:12px 16px;margin-bottom:16px;">
          <strong style="color:#166534;">Plan:</strong> ${d.plan.toUpperCase()} &nbsp;·&nbsp;
          <strong style="color:#166534;">Expires:</strong> ${d.expires}
        </div>
        <ul style="color:#555;font-size:14px;line-height:1.8;padding-left:18px;">
          <li>All 14 cryptocurrencies unlocked</li>
          <li>0.25% platform fee (vs 1.0% free)</li>
          <li>Unlimited orders</li>
          <li>Smart routing + webhooks + full API</li>
        </ul>
        <a href="https://chainpay.store/dashboard" style="display:inline-block;background:#ff6b2b;color:#fff;padding:12px 28px;border-radius:9px;font-weight:700;text-decoration:none;margin-top:16px;">Go to Dashboard →</a>
        <p style="font-size:12px;color:#aaa;margin-top:16px;">30-day money-back guarantee. Questions? support@chainpay.store</p>
      </div>
    </div>`,
  }),

  payment_confirmed_admin: (d) => ({
    subject: `Payment confirmed — ${d.amount} ${d.coin}`,
    html: `
    <div style="font-family:Arial,sans-serif;max-width:560px;margin:0 auto;background:#fff;">
      <div style="background:#0a0f1e;padding:24px 32px;border-radius:12px 12px 0 0;">
        <div style="font-size:20px;font-weight:800;color:#fff;">⚡ ChainPay</div>
      </div>
      <div style="padding:32px;border:1px solid #eee;border-top:none;border-radius:0 0 12px 12px;">
        <h2 style="color:#059669;">✅ Payment Confirmed</h2>
        <p style="color:#555;">Invoice <code style="font-family:monospace;">${d.invoice_id}</code> has been confirmed.</p>
        <table style="width:100%;border-collapse:collapse;font-size:14px;margin-top:12px;">
          <tr><td style="padding:8px 0;color:#888;width:120px;">Amount</td><td style="font-weight:700;">${d.amount} ${d.coin}</td></tr>
          <tr><td style="padding:8px 0;color:#888;">TX Hash</td><td style="font-family:monospace;font-size:12px;word-break:break-all;">${d.tx_hash}</td></tr>
        </table>
        <a href="https://chainpay.store/dashboard" style="display:inline-block;background:#ff6b2b;color:#fff;padding:10px 24px;border-radius:9px;font-weight:700;text-decoration:none;margin-top:16px;">View Dashboard →</a>
      </div>
    </div>`,
  }),
};

// ── Send email ────────────────────────────────────────────────────
async function sendEmail({ to, subject, template, data, html: rawHtml }) {
  const from = `${process.env.EMAIL_FROM_NAME || 'ChainPay'} <${process.env.EMAIL_FROM || 'noreply@chainpay.store'}>`;

  let finalHtml  = rawHtml || '';
  let finalSubject = subject || '';

  if (template && TEMPLATES[template]) {
    const tpl    = TEMPLATES[template](data || {});
    finalHtml    = tpl.html;
    finalSubject = tpl.subject || subject;
  }

  const mailOptions = {
    from,
    to,
    subject: finalSubject,
    html:    finalHtml,
    text:    finalHtml.replace(/<[^>]+>/g, ''), // auto-generate plain text
  };

  if (process.env.NODE_ENV === 'development' || !process.env.SMTP_USER) {
    console.log(`[EMAIL] Would send to ${to}: ${finalSubject}`);
    return { messageId: 'dev_' + Date.now() };
  }

  const info = await getTransporter().sendMail(mailOptions);
  console.log(`[EMAIL] Sent to ${to}: ${info.messageId}`);
  return info;
}

module.exports = { sendEmail };
