import nodemailer from 'nodemailer';
import fs from 'fs';
import path from 'path';
import { fileURLToPath } from 'url';

const __filename = fileURLToPath(import.meta.url);
const __dirname = path.dirname(__filename);


// Cache logos as base64 data URIs so they're inlined in the HTML email
let dashcaddyLogoDataUri = null;
let samiahmedLogoDataUri = null;

function loadLogo(filename) {
  const assetsDir = path.join(__dirname, '..', 'assets');
  const filepath = path.join(assetsDir, filename);
  if (!fs.existsSync(filepath)) return null;
  const buf = fs.readFileSync(filepath);
  const ext = path.extname(filename).slice(1).toLowerCase();
  const mime = ext === 'jpg' || ext === 'jpeg' ? 'image/jpeg' : `image/${ext}`;
  return `data:${mime};base64,${buf.toString('base64')}`;
}


let transporter = null;
function getTransporter() {
  if (transporter) return transporter;
  transporter = nodemailer.createTransport({
    host: process.env.SMTP_HOST || '127.0.0.1',
    port: parseInt(process.env.SMTP_PORT || '25', 10),
    secure: process.env.SMTP_SECURE === 'true',
    auth: process.env.SMTP_USERNAME ? {
      user: process.env.SMTP_USERNAME,
      pass: process.env.SMTP_PASSWORD
    } : undefined,
    connectionTimeout: 10000,
    greetingTimeout: 10000,
    socketTimeout: 20000,
    tls: { rejectUnauthorized: process.env.SMTP_TLS_REJECT_UNAUTHORIZED !== 'false' }
  });
  return transporter;
}

function formatDate(iso) {
  if (!iso) return 'N/A';
  return new Date(iso).toLocaleString('en-US', {
    timeZone: 'America/Los_Angeles',
    year: 'numeric',
    month: 'long',
    day: 'numeric',
    hour: 'numeric',
    minute: '2-digit',
    hour12: true,
    timeZoneName: 'short'
  });
}

function planLabel(planCode, durationDays) {
  if (durationDays) return `${durationDays} days`;
  return planCode;
}

/**
 * Send the license key email to the customer. Called after every payment
 * (initial purchase or renewal extension).
 */
export async function sendLicenseEmail({ to, code, durationDays, planCode, expiresAt, extended = false }) {
  // Lazy-load logos as inline data URIs
  if (!dashcaddyLogoDataUri) dashcaddyLogoDataUri = loadLogo('dashcaddy-logo.jpg');
  if (!samiahmedLogoDataUri) samiahmedLogoDataUri = loadLogo('samiahmed7777-logo.png');

  const dashcaddyLogo = dashcaddyLogoDataUri
    ? `<img src="${dashcaddyLogoDataUri}" alt="DashCaddy" width="360" style="display: block; margin: 0 auto;" />`
    : `<h1 style="color: #6d28d9; margin: 0; text-align: center;">DashCaddy</h1>`;

  const samiahmedLogo = samiahmedLogoDataUri
    ? `<img src="${samiahmedLogoDataUri}" alt="A product by samiahmed7777" width="110" style="display: block; margin: 0 auto; opacity: 0.85;" />`
    : `<span style="font-size: 12px; color: #64748b;">a product by samiahmed7777</span>`;

  const subject = extended
    ? `Your DashCaddy Premium license has been extended (${durationDays} days added)`
    : `Your DashCaddy Premium license key`;
  const text = [
    extended ? 'Your DashCaddy Premium license has been extended.' : 'Thank you for purchasing DashCaddy Premium.',
    '',
    `License key: ${code}`,
    `Plan: ${planLabel(planCode, durationDays)}`,
    `License valid until: ${formatDate(expiresAt)}`,
    '',
    'To activate: paste this license key into your DashCaddy dashboard at Admin → License.',
    '',
    'Need help? Reply to this email or visit https://dashcaddy.net/about',
    '',
    '— DashCaddy'
  ].join('\n');

  const html = `
    <!DOCTYPE html>
    <html>
    <head>
      <meta charset="utf-8" />
      <meta name="viewport" content="width=device-width, initial-scale=1" />
    </head>
    <body style="margin: 0; padding: 0; background: #f1f5f9; font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;">
      <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="background: #f1f5f9; padding: 32px 16px;">
        <tr>
          <td align="center">
            <table role="presentation" width="600" cellspacing="0" cellpadding="0" border="0" style="max-width: 600px; background: #ffffff; border-radius: 12px; overflow: hidden; box-shadow: 0 1px 3px rgba(15, 23, 42, 0.08);">

              <!-- HEADER: DashCaddy logo -->
              <tr>
                <td style="padding: 32px 32px 24px 32px; text-align: center; background: #ffffff;">
                    ${dashcaddyLogo}
                </td>
              </tr>

              <!-- BODY -->
              <tr>
                <td style="padding: 8px 40px 16px 40px;">
                    <h2 style="color: #0f172a; font-size: 22px; font-weight: 600; margin: 0 0 12px 0;">
                      ${extended ? 'License extended' : 'Welcome to DashCaddy Premium'}
                    </h2>
                    <p style="color: #334155; font-size: 15px; line-height: 1.55; margin: 0 0 24px 0;">
                      ${extended
                        ? 'Your DashCaddy Premium license has been extended. Same key, more time.'
                        : 'Thank you for purchasing DashCaddy Premium. Your license key is below.'}
                    </p>

                    <div style="background: linear-gradient(135deg, #f5f3ff 0%, #ede9fe 100%); padding: 24px; border-radius: 10px; margin: 0 0 24px 0; text-align: center; border: 1px solid #ddd6fe;">
                      <div style="font-family: 'SF Mono', Menlo, Consolas, monospace; font-size: 22px; font-weight: 700; color: #4c1d95; letter-spacing: 3px; line-height: 1.4;">
                        ${code}
                      </div>
                      <div style="color: #6d28d9; font-size: 12px; text-transform: uppercase; letter-spacing: 2px; margin-top: 10px; font-weight: 600;">
                        Your License Key
                      </div>
                    </div>

                    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0" style="margin: 0 0 24px 0;">
                      <tr>
                        <td style="padding: 8px 0; color: #64748b; font-size: 13px; width: 140px;">Plan</td>
                        <td style="padding: 8px 0; color: #0f172a; font-size: 14px; font-weight: 500;">${planLabel(planCode, durationDays)}</td>
                      </tr>
                      <tr>
                        <td style="padding: 8px 0; color: #64748b; font-size: 13px;">${extended ? 'New expiration' : 'License valid until'}</td>
                        <td style="padding: 8px 0; color: #0f172a; font-size: 14px; font-weight: 500;">${formatDate(expiresAt)}</td>
                      </tr>
                    </table>

                    <p style="color: #334155; font-size: 15px; line-height: 1.55; margin: 0 0 24px 0;">
                      To activate, paste this license key into your DashCaddy dashboard at <strong>Admin → License</strong>.
                    </p>

                    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" border="0">
                      <tr>
                        <td align="center">
                          <a href="https://dashcaddy.net/docs/premium" style="display: inline-block; background: #6d28d9; color: #ffffff; text-decoration: none; padding: 14px 32px; border-radius: 8px; font-size: 15px; font-weight: 600;">View Activation Guide</a>
                        </td>
                      </tr>
                    </table>
                </td>
              </tr>

              <!-- HELP -->
              <tr>
                <td style="padding: 16px 40px 32px 40px;">
                    <hr style="margin: 0 0 24px 0; border: none; border-top: 1px solid #e2e8f0;" />
                    <p style="color: #64748b; font-size: 13px; line-height: 1.5; margin: 0; text-align: center;">
                      Need help? Reply to this email or visit <a href="https://dashcaddy.net/about" style="color: #6d28d9; text-decoration: none;">dashcaddy.net/about</a>
                    </p>
                </td>
              </tr>

              <!-- FOOTER: samiahmed7777 "A product by" -->
              <tr>
                <td style="background: #f8fafc; padding: 24px 32px; text-align: center; border-top: 1px solid #e2e8f0;">
                    <p style="color: #94a3b8; font-size: 11px; text-transform: uppercase; letter-spacing: 2px; margin: 0 0 12px 0; font-weight: 600;">
                      A Product By
                    </p>
                    ${samiahmedLogo}
                </td>
              </tr>

            </table>
          </td>
        </tr>
      </table>
    </body>
    </html>
  `;

  try {
    const t = getTransporter();
    await t.sendMail({
      from: process.env.SMTP_FROM || 'licenses@dashcaddy.net',
      to,
      subject,
      text,
      html
    });
    return { delivered: true, via: 'smtp' };
  } catch (err) {
    console.error('Email delivery failed:', err.message);
    return { delivered: false, error: err.message };
  }
}