import { NextRequest, NextResponse } from "next/server";
import nodemailer from "nodemailer";

export async function POST(req: NextRequest) {
  try {
    const { to, articleTitle, articleUrl, articleExcerpt, note } = await req.json();

    if (!to || !articleTitle || !articleUrl) {
      return NextResponse.json({ error: "Missing required fields" }, { status: 400 });
    }

    const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
    if (!emailRegex.test(to)) {
      return NextResponse.json({ error: "Invalid email address" }, { status: 400 });
    }

    const transporter = nodemailer.createTransport({
      host: process.env.SMTP_HOST,
      port: Number(process.env.SMTP_PORT) || 587,
      secure: false,
      auth: {
        user: process.env.SMTP_USER,
        pass: process.env.SMTP_PASS,
      },
    });

    const noteHtml = note
      ? `<div style="background:#1a1a1a;border-left:3px solid #1D4ED8;padding:12px 16px;margin-bottom:20px;border-radius:2px;">
           <p style="margin:0;color:#aaa;font-size:14px;font-style:italic;">"${note}"</p>
         </div>`
      : "";

    const html = `<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0" />
  <title>Article shared with you — AV Beat</title>
</head>
<body style="margin:0;padding:0;background:#0d0d0d;font-family:Arial,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" style="background:#0d0d0d;padding:32px 16px;">
    <tr>
      <td align="center">
        <table width="600" cellpadding="0" cellspacing="0" style="max-width:600px;width:100%;background:#111;border:1px solid #222;border-radius:4px;overflow:hidden;">
          <!-- Header -->
          <tr>
            <td style="background:#0a0a0a;border-bottom:1px solid #1a1a1a;padding:20px 28px;">
              <p style="margin:0;color:#1D4ED8;font-size:11px;font-weight:700;letter-spacing:3px;text-transform:uppercase;">AV Beat</p>
            </td>
          </tr>
          <!-- Body -->
          <tr>
            <td style="padding:28px;">
              <p style="margin:0 0 8px;color:#555;font-size:11px;text-transform:uppercase;letter-spacing:2px;">Someone shared an article with you</p>
              ${noteHtml}
              <p style="margin:0 0 6px;color:#1D4ED8;font-size:10px;font-weight:700;text-transform:uppercase;letter-spacing:2px;">NEWS</p>
              <h1 style="margin:0 0 12px;color:#f0f0f0;font-size:22px;font-weight:700;line-height:1.3;">${articleTitle}</h1>
              <p style="margin:0 0 24px;color:#999;font-size:14px;line-height:1.6;">${articleExcerpt}</p>
              <a href="${articleUrl}" style="display:inline-block;background:#1D4ED8;color:#fff;text-decoration:none;font-size:13px;font-weight:700;padding:12px 24px;border-radius:2px;letter-spacing:1px;text-transform:uppercase;">Read Article</a>
            </td>
          </tr>
          <!-- Footer -->
          <tr>
            <td style="background:#0a0a0a;border-top:1px solid #1a1a1a;padding:16px 28px;">
              <p style="margin:0;color:#444;font-size:11px;">You received this because someone shared a AV Beat article with you.</p>
              <p style="margin:6px 0 0;color:#333;font-size:11px;">© ${new Date().getFullYear()} AV Beat. All rights reserved.</p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;

    await transporter.sendMail({
      from: `"${process.env.SMTP_FROM_NAME || "AV Beat"}" <${process.env.SMTP_FROM_EMAIL}>`,
      to,
      subject: `Shared article: ${articleTitle}`,
      html,
    });

    return NextResponse.json({ success: true });
  } catch (err) {
    console.error("[share-email] Error:", err);
    return NextResponse.json({ error: "Failed to send email" }, { status: 500 });
  }
}
