/**
 * Modèles d'e-mails transactionnels PyramidCom.
 *
 * Le fichier est volontairement indépendant de Nodemailer et de la base de
 * données : les routes peuvent l'utiliser avec n'importe quel transport.
 * Les styles sont en ligne pour rester fiables dans Gmail, Outlook et Apple
 * Mail. Les urls de liens doivent toujours être absolues.
 */

export type EmailTemplate = {
  html: string;
  text: string;
};

export type EmailLink = {
  label: string;
  href: string;
};

export type PyramidComSignatureInput = {
  siteUrl: string;
  name?: string;
  role?: string;
  email?: string;
  phone?: string;
};

type BaseTemplateInput = {
  siteUrl: string;
  preheader?: string;
  title: string;
  greeting?: string;
  intro: string;
  paragraphs?: string[];
  details?: Array<{ label: string; value: string }>;
  action?: EmailLink;
  signature?: Omit<PyramidComSignatureInput, "siteUrl">;
};

const BRAND = {
  violet: "#61287f",
  violetDark: "#241d2d",
  orange: "#f7941d",
  ink: "#1e1b26",
  muted: "#665f70",
  paper: "#f7f6f9",
  border: "#e7e1eb",
  white: "#ffffff",
};

export function escapeEmailHtml(value: unknown): string {
  return String(value ?? "")
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/\"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

function normalizedSiteUrl(siteUrl: string) {
  return siteUrl.trim().replace(/\/+$/, "") || "https://pyramidcom.fr";
}

function safeHref(href: string) {
  try {
    const parsed = new URL(href);
    return parsed.protocol === "https:" || parsed.protocol === "http:" || parsed.protocol === "mailto:"
      ? parsed.href
      : "";
  } catch {
    return "";
  }
}

function detailsTable(details: BaseTemplateInput["details"] = []) {
  if (!details.length) return "";
  const rows = details.map(({ label, value }) => `
    <tr>
      <td style="padding:9px 12px;border-bottom:1px solid ${BRAND.border};font-family:Arial,Helvetica,sans-serif;font-size:12px;line-height:18px;letter-spacing:.03em;text-transform:uppercase;color:${BRAND.muted};width:38%;">${escapeEmailHtml(label)}</td>
      <td style="padding:9px 12px;border-bottom:1px solid ${BRAND.border};font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:20px;font-weight:700;color:${BRAND.ink};">${escapeEmailHtml(value)}</td>
    </tr>`).join("");
  return `<table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="margin:23px 0 4px;border:1px solid ${BRAND.border};border-radius:8px;border-collapse:separate;overflow:hidden;background:${BRAND.white};">${rows}</table>`;
}

function actionButton(action?: EmailLink) {
  if (!action) return "";
  const href = safeHref(action.href);
  if (!href) return "";
  return `<table role="presentation" cellspacing="0" cellpadding="0" style="margin:27px 0 25px;"><tr><td style="border-radius:6px;background:${BRAND.violet};"><a href="${escapeEmailHtml(href)}" style="display:inline-block;padding:14px 21px;font-family:Arial,Helvetica,sans-serif;font-size:14px;font-weight:700;color:#ffffff;text-decoration:none;">${escapeEmailHtml(action.label)}&nbsp; →</a></td></tr></table>`;
}

/** Signature HTML compatible clients mail, à stocker/réutiliser depuis le CMS. */
export function pyramidComEmailSignature(input: PyramidComSignatureInput): EmailTemplate {
  const site = normalizedSiteUrl(input.siteUrl);
  const name = input.name?.trim() || "L’équipe PyramidCom";
  const role = input.role?.trim() || "Fabricant d’enseignes & communication visuelle";
  const email = input.email?.trim() || "projets@pyramidcom.fr";
  const phone = input.phone?.trim() || "06 04 41 04 49";
  const telHref = phone.replace(/[^+\d]/g, "");
  const html = `
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;max-width:560px;margin-top:28px;border:1px solid #ded6e2;border-radius:12px;border-collapse:separate;border-spacing:0;overflow:hidden;background:#ffffff;font-family:Arial,Helvetica,sans-serif;color:${BRAND.ink};box-shadow:0 5px 16px rgba(36,29,45,.07);">
      <tr><td colspan="2" height="5" style="height:5px;line-height:5px;font-size:0;background:${BRAND.orange};">&nbsp;</td></tr>
      <tr>
        <td width="35%" align="center" style="width:35%;padding:25px 18px;vertical-align:middle;background:${BRAND.violetDark};">
          <a href="${escapeEmailHtml(site)}" style="display:inline-block;text-decoration:none;"><img src="${escapeEmailHtml(`${site}/logo-white.png`)}" alt="PyramidCom" width="148" style="display:block;width:148px;max-width:100%;height:auto;border:0;outline:none;text-decoration:none;"></a>
          <div style="margin-top:15px;font-size:8px;line-height:12px;font-weight:700;letter-spacing:.18em;color:#f5a746;text-transform:uppercase;white-space:nowrap;">Fabrication française</div>
        </td>
        <td width="65%" style="width:65%;padding:22px 24px 20px;vertical-align:middle;background:#ffffff;">
          <div style="font-size:18px;line-height:22px;font-weight:800;letter-spacing:-.02em;color:${BRAND.ink};">${escapeEmailHtml(name)}</div>
          <div style="margin-top:4px;font-size:9px;line-height:14px;font-weight:800;letter-spacing:.11em;color:${BRAND.violet};text-transform:uppercase;">${escapeEmailHtml(role)}</div>
          <div style="width:38px;height:2px;margin:13px 0 11px;background:${BRAND.orange};font-size:0;line-height:0;">&nbsp;</div>
          <div style="font-size:11px;line-height:18px;color:${BRAND.muted};">
            <a href="mailto:${escapeEmailHtml(email)}" style="font-weight:700;color:${BRAND.ink};text-decoration:none;">${escapeEmailHtml(email)}</a>
            <span style="padding:0 6px;color:#c8becd;">|</span>
            <a href="tel:${escapeEmailHtml(telHref)}" style="font-weight:700;color:${BRAND.ink};text-decoration:none;white-space:nowrap;">${escapeEmailHtml(phone)}</a>
          </div>
          <div style="margin-top:2px;font-size:10px;line-height:16px;color:#7b7381;">35T Rue du Dr Eugène Jacquot · 90400 Danjoutin</div>
          <div style="margin-top:7px;font-size:10px;line-height:15px;font-weight:800;letter-spacing:.08em;text-transform:uppercase;"><a href="${escapeEmailHtml(site)}" style="color:${BRAND.orange};text-decoration:none;">pyramidcom.fr&nbsp; ↗</a></div>
        </td>
      </tr>
      <tr><td colspan="2" style="padding:8px 18px;background:#f7f4f8;border-top:1px solid #ebe5ee;font-size:8px;line-height:12px;letter-spacing:.08em;color:#8a818f;text-align:center;text-transform:uppercase;">Enseignes lumineuses · Signalétique · Communication visuelle · Déploiements réseaux</td></tr>
    </table>`;
  const text = [
    [name, role].filter(Boolean).join(" · "),
    "SAS PYRAMID COM · Fabricant d’enseignes & communication visuelle",
    `${email} · ${phone}`,
    "35T Rue du Dr Eugène Jacquot · 90400 Danjoutin",
    site,
  ].filter(Boolean).join("\n");
  return { html, text };
}

/** Gabarit commun de tous les messages transactionnels. */
export function pyramidComEmailLayout(input: BaseTemplateInput): EmailTemplate {
  const site = normalizedSiteUrl(input.siteUrl);
  const greeting = input.greeting ? `<p style="margin:0 0 16px;font-family:Arial,Helvetica,sans-serif;font-size:16px;line-height:25px;color:${BRAND.ink};">${escapeEmailHtml(input.greeting)}</p>` : "";
  const paragraphs = (input.paragraphs || []).filter(Boolean).map((paragraph) =>
    `<p style="margin:0 0 14px;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:24px;color:${BRAND.muted};">${escapeEmailHtml(paragraph)}</p>`,
  ).join("");
  const signature = pyramidComEmailSignature({ siteUrl: site, ...input.signature });
  const body = [input.greeting, input.intro, ...(input.paragraphs || []), input.details?.length ? "Détails :" : "", ...(input.details || []).map((detail) => `${detail.label} : ${detail.value}`), input.action ? `${input.action.label} : ${input.action.href}` : "", "", signature.text]
    .filter(Boolean).join("\n");
  const html = `<!doctype html>
<html lang="fr"><head><meta name="viewport" content="width=device-width, initial-scale=1.0"><meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><title>${escapeEmailHtml(input.title)}</title></head>
<body style="margin:0;padding:0;background:${BRAND.paper};">
  <div style="display:none;max-height:0;overflow:hidden;mso-hide:all;color:transparent;opacity:0;">${escapeEmailHtml(input.preheader || input.intro)}</div>
  <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="width:100%;background:${BRAND.paper};margin:0;padding:0;"><tr><td align="center" style="padding:26px 12px;">
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="max-width:640px;margin:0 auto;background:${BRAND.white};border-radius:12px;overflow:hidden;box-shadow:0 4px 18px rgba(36,29,45,.08);">
      <tr><td style="padding:25px 30px 21px;background:${BRAND.violetDark};border-bottom:5px solid ${BRAND.orange};"><a href="${escapeEmailHtml(site)}" style="text-decoration:none;"><img src="${escapeEmailHtml(`${site}/logo-white.png`)}" alt="PyramidCom" width="156" style="display:block;width:156px;height:auto;border:0;outline:none;text-decoration:none;"></a></td></tr>
      <tr><td style="padding:34px 30px 20px;">
        <div style="font-family:Arial,Helvetica,sans-serif;font-size:11px;line-height:16px;font-weight:700;letter-spacing:.12em;color:${BRAND.orange};text-transform:uppercase;">PYRAMIDCOM · SUIVI DE PROJET</div>
        <h1 style="margin:8px 0 20px;font-family:Arial,Helvetica,sans-serif;font-size:26px;line-height:33px;font-weight:800;color:${BRAND.ink};">${escapeEmailHtml(input.title)}</h1>
        ${greeting}
        <p style="margin:0 0 14px;font-family:Arial,Helvetica,sans-serif;font-size:15px;line-height:24px;color:${BRAND.muted};">${escapeEmailHtml(input.intro)}</p>
        ${paragraphs}
        ${detailsTable(input.details)}
        ${actionButton(input.action)}
        ${signature.html}
      </td></tr>
      <tr><td style="padding:18px 30px 24px;border-top:1px solid ${BRAND.border};font-family:Arial,Helvetica,sans-serif;font-size:11px;line-height:17px;color:${BRAND.muted};">Ce message concerne votre dossier PyramidCom. Pour toute question, répondez simplement à cet e-mail.</td></tr>
    </table>
  </td></tr></table>
</body></html>`;
  return { html, text: body };
}

export function requestReceiptEmail(input: {
  siteUrl: string; name: string; reference: string; projectLabel: string; details?: BaseTemplateInput["details"];
}): EmailTemplate {
  return pyramidComEmailLayout({
    ...input,
    title: "Votre demande a bien été reçue",
    greeting: `Bonjour ${input.name},`,
    intro: `Nous avons bien reçu votre demande ${input.reference} concernant ${input.projectLabel}.`,
    paragraphs: ["Notre équipe vérifie les éléments techniques et revient vers vous avec votre devis et votre BAT."],
    details: [{ label: "Référence dossier", value: input.reference }, ...(input.details || [])],
  });
}

export function internalRequestNotificationEmail(input: {
  siteUrl: string; reference: string; clientName: string; clientEmail: string; company?: string; projectLabel: string; details?: BaseTemplateInput["details"];
}): EmailTemplate {
  return pyramidComEmailLayout({
    ...input,
    title: `Nouvelle demande · ${input.reference}`,
    intro: `Une nouvelle demande vient d’être reçue pour ${input.projectLabel}.`,
    details: [
      { label: "Client", value: input.clientName },
      { label: "E-mail", value: input.clientEmail },
      ...(input.company ? [{ label: "Société", value: input.company }] : []),
      { label: "Référence", value: input.reference },
      ...(input.details || []),
    ],
    action: { label: "Ouvrir l’administration", href: `${normalizedSiteUrl(input.siteUrl)}/admin` },
  });
}

export function quoteBatEmail(input: {
  siteUrl: string; name: string; reference: string; projectLabel: string; totalHt: string; validityDays: number; batUrl: string;
}): EmailTemplate {
  return pyramidComEmailLayout({
    ...input,
    title: "Votre devis et BAT sont prêts",
    greeting: `Bonjour ${input.name},`,
    intro: `Nous avons préparé le devis ${input.reference} pour ${input.projectLabel}.`,
    paragraphs: ["Consultez le devis, téléchargez le BAT, puis signez-le ou demandez une correction depuis votre espace privé."],
    details: [
      { label: "Montant total", value: `${input.totalHt} HT` },
      { label: "Validité", value: `${input.validityDays} jours` },
      { label: "Référence", value: input.reference },
    ],
    action: { label: "Consulter mon devis et BAT", href: input.batUrl },
  });
}

export function batDecisionEmail(input: {
  siteUrl: string; name: string; reference: string; projectLabel: string; status: "accepted" | "changes_requested"; note?: string; batUrl?: string;
}): EmailTemplate {
  const accepted = input.status === "accepted";
  return pyramidComEmailLayout({
    ...input,
    title: accepted ? "Votre BAT est validé" : "Votre correction est enregistrée",
    greeting: `Bonjour ${input.name},`,
    intro: accepted
      ? `Votre signature et votre validation du BAT ${input.reference} ont bien été enregistrées.`
      : `Votre demande de correction du BAT ${input.reference} a bien été transmise à notre équipe.`,
    paragraphs: [accepted
      ? "Notre équipe peut désormais préparer la mise en fabrication."
      : "Nous vous avertirons dès qu’une nouvelle version sera disponible sur votre lien privé.",
    ...(input.note ? [`Votre message : ${input.note}`] : [])],
    details: [{ label: "Référence", value: input.reference }, { label: "Projet", value: input.projectLabel }],
    action: input.batUrl ? { label: "Ouvrir mon BAT", href: input.batUrl } : undefined,
  });
}

export function resellerInviteEmail(input: {
  siteUrl: string; contactName: string; company: string; accountUrl: string;
}): EmailTemplate {
  return pyramidComEmailLayout({
    ...input,
    title: "Votre compte professionnel est activé",
    greeting: `Bonjour ${input.contactName},`,
    intro: `Le compte revendeur de ${input.company} est maintenant approuvé.`,
    paragraphs: ["Retrouvez vos tarifs professionnels et l’historique de vos projets depuis votre espace privé.", "Conservez ce lien de manière confidentielle."],
    action: { label: "Accéder à mon compte pro", href: input.accountUrl },
  });
}

export function turkishWorkshopEmail(input: {
  siteUrl: string; reference: string; workshopUrl: string; vectorUrl?: string; files?: EmailLink[];
}): EmailTemplate {
  const extraFiles = (input.files || []).filter((file) => safeHref(file.href));
  const links = [
    `Türkçe atölye formu: ${input.workshopUrl}`,
    ...(input.vectorUrl ? [`SVG gerçek ölçekte: ${input.vectorUrl}`] : []),
    ...extraFiles.map((file) => `${file.label}: ${file.href}`),
  ];
  const site = normalizedSiteUrl(input.siteUrl);
  const htmlLinks = [
    { label: "Türkçe atölye formu", href: input.workshopUrl },
    ...(input.vectorUrl ? [{ label: "SVG gerçek ölçekte", href: input.vectorUrl }] : []),
    ...extraFiles,
  ].filter((link) => safeHref(link.href)).map((link) => `<li style="margin:0 0 8px;"><a href="${escapeEmailHtml(safeHref(link.href))}" style="color:${BRAND.violet};font-weight:700;text-decoration:underline;">${escapeEmailHtml(link.label)}</a></li>`).join("");
  const text = [
    "Merhaba,", "", `Üretim dosyası / Fiche de fabrication : ${input.reference}`,
    ...links, "", "Lütfen üretime başlamadan önce profil, ölçüler ve dosyaları kontrol edin.",
    "Merci de contrôler le profil, les dimensions et les fichiers avant fabrication.", "", pyramidComEmailSignature({ siteUrl: site }).text,
  ].join("\n");
  const layout = pyramidComEmailLayout({
    siteUrl: site,
    title: `Üretim dosyası · ${input.reference}`,
    greeting: "Merhaba,",
    intro: `Üretim dosyası / Fiche de fabrication : ${input.reference}`,
    paragraphs: ["Lütfen üretime başlamadan önce profil, ölçüler ve dosyaları kontrol edin.", "Merci de contrôler le profil, les dimensions et les fichiers avant fabrication."],
    action: { label: "Türkçe atölye formu", href: input.workshopUrl },
  });
  return {
    text,
    html: layout.html.replace("</td></tr>\n      <tr><td style=\"padding:18px", `<div style="margin:4px 0 24px;font-family:Arial,Helvetica,sans-serif;font-size:14px;line-height:21px;color:${BRAND.ink};"><b>Dosyalar / Fichiers :</b><ul style="padding-left:19px;margin:10px 0;">${htmlLinks}</ul></div></td></tr>\n      <tr><td style="padding:18px`),
  };
}
