import nodemailer from "nodemailer";

function esc(str = "") {
  return String(str)
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}

function buildHtmlMail(form) {
  const when = new Date().toLocaleString("pl-PL");
  const offerText = (form.offerSummary || "").trim()

  return `<!DOCTYPE html>
<html lang="pl">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1.0"/>
  <title>Nowa wiadomość – FUZ</title>
</head>
<body style="margin:0;padding:0;background:#f5f7fa;font-family:Arial,Helvetica,sans-serif;">
  <table width="100%" cellpadding="0" cellspacing="0" role="presentation" style="background:#f5f7fa;">
    <tr>
      <td align="center" style="padding:24px;">
        <table width="600" cellpadding="0" cellspacing="0" role="presentation"
               style="background:#ffffff;border-radius:14px;overflow:hidden;box-shadow:0 8px 24px rgba(0,0,0,0.08);">
          
          <!-- Header -->
          <tr>
            <td style="background:#0066ff;color:#ffffff;padding:20px 24px;">
              <div style="font-size:12px;opacity:0.9;margin-bottom:6px;">FUZ • Formularz kontaktowy</div>
              <div style="font-size:20px;font-weight:700;line-height:1.2;">📩 Nowa wiadomość</div>
            </td>
          </tr>

          <!-- Content -->
          <tr>
            <td style="padding:24px;">
              <div style="font-size:14px;color:#111827;margin-bottom:14px;">
                Poniżej szczegóły zgłoszenia:
              </div>

              <table width="100%" cellpadding="0" cellspacing="0" role="presentation"
                     style="font-size:14px;color:#111827;border-collapse:collapse;">
                <tr>
                  <td style="padding:8px 0;width:160px;color:#374151;"><strong>Imię</strong></td>
                  <td style="padding:8px 0;">${esc(form.firstName)}</td>
                </tr>
                <tr>
                  <td style="padding:8px 0;color:#374151;"><strong>Nazwisko</strong></td>
                  <td style="padding:8px 0;">${esc(form.lastName)}</td>
                </tr>
                <tr>
                  <td style="padding:8px 0;color:#374151;"><strong>Email</strong></td>
                  <td style="padding:8px 0;">
                    <a href="mailto:${esc(form.email)}" style="color:#0066ff;text-decoration:none;">
                      ${esc(form.email)}
                    </a>
                  </td>
                </tr>
                <tr>
                  <td style="padding:8px 0;color:#374151;"><strong>Telefon</strong></td>
                  <td style="padding:8px 0;">${esc(form.phone)}</td>
                </tr>
                <tr>
                  <td style="padding:8px 0;color:#374151;"><strong>Temat</strong></td>
                  <td style="padding:8px 0;">${esc(form.subject)}</td>
                </tr>
              </table>

              <div style="height:1px;background:#e5e7eb;margin:18px 0;"></div>

              <div style="font-size:14px;color:#111827;margin:0 0 8px;font-weight:700;">
                Wiadomość:
              </div>

              <div style="font-size:14px;color:#111827;white-space:pre-line;line-height:1.6;
                          background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:14px;">
                ${esc(form.message)}
              </div>

              ${offerText ? `
                <div style="font-size:14px;color:#111827;margin:8px 0;font-weight:700;">
                  Wybrana oferta:
                </div>

                <div style="font-size:14px;color:#111827;white-space:pre-line;line-height:1.6;
                            background:#f8fafc;border:1px solid #e5e7eb;border-radius:12px;padding:14px;">
                  ${esc(offerText)}
                </div>
              ` : ``}

              <div style="margin-top:16px;font-size:12px;color:#6b7280;">
                Wysłano: ${when}
              </div>
            </td>
          </tr>

          <!-- Footer -->
          <tr>
            <td style="background:#f1f5f9;padding:14px 24px;font-size:12px;color:#6b7280;">
              To jest automatyczna wiadomość wygenerowana przez formularz na stronie FUZ.
            </td>
          </tr>

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

export async function POST({ request }) {
  try {
    const form = await request.json();

    // (opcjonalnie) prosta walidacja minimum:
    if (!form?.email || !form?.message) {
      return new Response(JSON.stringify({ ok: false, error: "Brak danych" }), {
        status: 400,
        headers: { "Content-Type": "application/json" },
      });
    }

    const transporter = nodemailer.createTransport({
      host: import.meta.env.SMTP_HOST,
      port: Number(import.meta.env.SMTP_PORT),
      secure: true,
      auth: {
        user: import.meta.env.SMTP_USER,
        pass: import.meta.env.SMTP_PASS,
      },
      // Uwaga: lepiej NIE wyłączać TLS w prod, ale zostawiam zgodnie z Twoją wersją
      tls: { rejectUnauthorized: false },
    });

    const subject = `FUZ: wiadomość od ${form.firstName || ""} ${form.lastName || ""}`.trim();

    const text = `
Imię: ${form.firstName || ""}
Nazwisko: ${form.lastName || ""}
Email: ${form.email || ""}
Telefon: ${form.phone || ""}
Temat: ${form.subject || ""}

Wiadomość:
${form.message || ""}
`.trim();

    const html = buildHtmlMail(form);

    await transporter.sendMail({
      from: `"${import.meta.env.SMTP_FROM_NAME}" <${import.meta.env.SMTP_USER}>`,
      to: import.meta.env.SMTP_TO,
      subject,
      text,
      html,
      replyTo: form.email ? String(form.email) : undefined,
    });

    return new Response(JSON.stringify({ ok: true }), {
      status: 200,
      headers: { "Content-Type": "application/json" },
    });
  } catch (error) {
    console.error("MAIL ERROR:", error);

    return new Response(JSON.stringify({ ok: false }), {
      status: 500,
      headers: { "Content-Type": "application/json" },
    });
  }
}
