// Templates HTML + texte pour les emails transactionnels.
//
// Style email-safe : table-based layout, inline styles, max 600 px, palette
// derived de la charte (papier creme + stone-900 + bronze). Pas de webfonts
// custom : on retombe sur system-ui + Georgia pour rester compatible Outlook.

import { BRAND_NAME, BRAND_DOMAIN } from "@/lib/brand";

export type ContactSubmission = {
  firstName: string;
  lastName: string;
  company: string;
  email: string;
  reason: string;
  message: string;
};

// Couleurs duplicate des tokens globals.css (les emails ne lisent pas le CSS).
const C = {
  paper: "#faf7f2",
  card: "#ffffff",
  text: "#1c1917",
  muted: "#44403c",
  faint: "#78716c",
  border: "rgba(28, 25, 23, 0.10)",
  accent: "#92400e",
  accentSoft: "#fef3c7",
};

/** Echappe les caracteres dangereux pour HTML (XSS basique sur user content). */
function esc(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;")
    .replace(/'/g, "&#39;");
}

/** Convertit les retours ligne en <br> apres escape (pour conserver le formattage user). */
function nl2br(s: string): string {
  return esc(s).replace(/\r?\n/g, "<br>");
}

// =====================================================================
// Notification interne : prevenir l'agence qu'une demande arrive.
// =====================================================================

export function contactNotificationSubject(s: ContactSubmission): string {
  return `Nouveau contact : ${s.firstName} ${s.lastName} (${s.company})`;
}

export function contactNotificationText(s: ContactSubmission): string {
  return `Nouvelle demande de contact via ${BRAND_DOMAIN}

De : ${s.firstName} ${s.lastName}
Entreprise : ${s.company}
Email : ${s.email}
Motif : ${s.reason}

Message :
${s.message}

---
Repondez directement a cet email pour ecrire au prospect (Reply-To : ${s.email}).
`;
}

export function contactNotificationHtml(s: ContactSubmission): string {
  const fullName = `${esc(s.firstName)} ${esc(s.lastName)}`;
  return `<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Nouveau contact</title>
</head>
<body style="margin:0;padding:0;background:${C.paper};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;color:${C.text};">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:${C.paper};padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:${C.card};border:1px solid ${C.border};border-radius:12px;overflow:hidden;">
          <tr>
            <td style="padding:24px 32px;border-bottom:1px solid ${C.border};">
              <div style="font-size:11px;letter-spacing:1.8px;text-transform:uppercase;color:${C.faint};font-weight:600;">
                ${esc(BRAND_NAME)} &middot; Nouveau contact
              </div>
              <div style="margin-top:8px;font-family:Georgia,serif;font-size:24px;line-height:1.2;color:${C.text};font-weight:500;">
                ${fullName}
              </div>
              <div style="margin-top:4px;font-size:14px;color:${C.muted};">
                ${esc(s.company)}
              </div>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 32px;">
              <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                <tr>
                  <td style="padding:8px 0;border-bottom:1px solid ${C.border};font-size:14px;">
                    <span style="color:${C.faint};display:inline-block;width:90px;">Email</span>
                    <a href="mailto:${esc(s.email)}" style="color:${C.accent};text-decoration:none;">${esc(s.email)}</a>
                  </td>
                </tr>
                <tr>
                  <td style="padding:8px 0;border-bottom:1px solid ${C.border};font-size:14px;">
                    <span style="color:${C.faint};display:inline-block;width:90px;">Motif</span>
                    <span style="color:${C.text};">${esc(s.reason)}</span>
                  </td>
                </tr>
              </table>
              <div style="margin-top:24px;padding:16px;background:${C.paper};border:1px solid ${C.border};border-radius:8px;">
                <div style="font-size:11px;letter-spacing:1.8px;text-transform:uppercase;color:${C.faint};font-weight:600;margin-bottom:8px;">
                  Message
                </div>
                <div style="font-size:15px;line-height:1.6;color:${C.text};">
                  ${nl2br(s.message)}
                </div>
              </div>
            </td>
          </tr>
          <tr>
            <td style="padding:16px 32px;background:${C.paper};border-top:1px solid ${C.border};font-size:12px;color:${C.faint};">
              Repondez directement a cet email pour ecrire au prospect.
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

// =====================================================================
// Confirmation au prospect : "on a bien recu votre message".
// =====================================================================

export function contactConfirmationSubject(): string {
  return `On a bien recu votre message - ${BRAND_NAME}`;
}

export function contactConfirmationText(s: ContactSubmission): string {
  return `Bonjour ${s.firstName},

Merci pour votre message. Nous l'avons bien recu et nous vous repondons rapidement, du lundi au vendredi.

En attendant, vous pouvez retrouver toutes les informations sur nos offres et notre fonctionnement sur https://${BRAND_DOMAIN}/essentiel et https://${BRAND_DOMAIN}/tarifs.

A tres vite,
L'equipe ${BRAND_NAME}

---
${BRAND_NAME} - Atelier web francais
https://${BRAND_DOMAIN}
`;
}

// =====================================================================
// Welcome client : compte provisionne par l'agence, l'utilisateur recoit
// ses identifiants pour se connecter au portail.
// =====================================================================

export type WelcomeClientData = {
  contactName: string;
  companyName: string;
  email: string;
  /** Mot de passe genere par l'agence. Le client est invite a le changer. */
  temporaryPassword: string;
  /** URL du portail (ex: https://app.agence-novelia.fr ou /connexion). */
  loginUrl: string;
};

export function welcomeClientSubject(d: WelcomeClientData): string {
  return `Bienvenue chez ${BRAND_NAME}, ${d.contactName}. Voici vos acces.`;
}

export function welcomeClientText(d: WelcomeClientData): string {
  return `Bonjour ${d.contactName},

Votre espace client ${BRAND_NAME} est ouvert. Vous y retrouverez les chiffres de votre site, vos factures, vos demandes de support et vos parametres.

Vos identifiants :
  Email : ${d.email}
  Mot de passe : ${d.temporaryPassword}

Connectez-vous : ${d.loginUrl}

Important : ce mot de passe a ete genere pour vous. Changez-le des votre premiere connexion dans Parametres > Profil > Securite.

Si vous avez des questions, repondez directement a cet email, on vous repond rapidement.

A bientot,
L'equipe ${BRAND_NAME}

---
${BRAND_NAME} - Atelier web francais
https://${BRAND_DOMAIN}
`;
}

export function welcomeClientHtml(d: WelcomeClientData): string {
  return `<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Bienvenue chez ${esc(BRAND_NAME)}</title>
</head>
<body style="margin:0;padding:0;background:${C.paper};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;color:${C.text};">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:${C.paper};padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:${C.card};border:1px solid ${C.border};border-radius:12px;overflow:hidden;">
          <tr>
            <td style="padding:32px 32px 16px;">
              <div style="display:inline-block;padding:6px 10px;background:#1c1917;border:1px solid ${C.accent};border-radius:6px;color:#fafaf9;font-family:Georgia,serif;font-size:13px;font-weight:500;">
                ${esc(BRAND_NAME)}
              </div>
              <h1 style="margin:24px 0 0;font-family:Georgia,serif;font-size:28px;line-height:1.2;color:${C.text};font-weight:500;">
                Bienvenue, ${esc(d.contactName)}.
              </h1>
              <p style="margin:12px 0 0;font-size:15px;color:${C.muted};">
                Votre espace client pour ${esc(d.companyName)} est ouvert.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding:16px 32px 24px;font-size:16px;line-height:1.6;color:${C.text};">
              <p style="margin:16px 0;color:${C.muted};">
                Vous y retrouverez les chiffres de votre site, vos factures, vos demandes de support et vos parametres.
              </p>
              <div style="margin-top:24px;padding:20px;background:${C.paper};border:1px solid ${C.border};border-radius:8px;">
                <div style="font-size:11px;letter-spacing:1.8px;text-transform:uppercase;color:${C.faint};font-weight:600;margin-bottom:12px;">
                  Vos identifiants
                </div>
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
                  <tr>
                    <td style="padding:6px 0;font-size:14px;color:${C.muted};width:90px;">Email</td>
                    <td style="padding:6px 0;font-size:14px;color:${C.text};font-family:'SFMono-Regular',Consolas,monospace;">${esc(d.email)}</td>
                  </tr>
                  <tr>
                    <td style="padding:6px 0;font-size:14px;color:${C.muted};">Mot de passe</td>
                    <td style="padding:6px 0;font-size:14px;color:${C.text};font-family:'SFMono-Regular',Consolas,monospace;letter-spacing:0.5px;">${esc(d.temporaryPassword)}</td>
                  </tr>
                </table>
              </div>
              <div style="margin-top:24px;text-align:center;">
                <a href="${esc(d.loginUrl)}" style="display:inline-block;padding:12px 24px;background:${C.accent};color:#ffffff;text-decoration:none;border-radius:6px;font-size:15px;font-weight:600;">
                  Acceder a mon espace
                </a>
              </div>
              <p style="margin:24px 0 0;font-size:13px;color:${C.faint};line-height:1.5;">
                Ce mot de passe a ete genere pour vous. Changez-le des votre premiere connexion dans Parametres &middot; Profil &middot; Securite.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 32px;background:${C.paper};border-top:1px solid ${C.border};">
              <p style="margin:0;font-size:13px;color:${C.faint};line-height:1.5;">
                Si vous avez des questions, repondez directement a cet email.<br>
                ${esc(BRAND_NAME)} &middot; <a href="https://${BRAND_DOMAIN}" style="color:${C.faint};text-decoration:underline;">${esc(BRAND_DOMAIN)}</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

// =====================================================================
// Password reset : utilise par Better Auth via sendResetPassword callback.
// =====================================================================

export type ResetPasswordData = {
  name: string | null;
  email: string;
  resetUrl: string;
};

export function resetPasswordSubject(): string {
  return `Reinitialiser votre mot de passe ${BRAND_NAME}`;
}

export function resetPasswordText(d: ResetPasswordData): string {
  const greeting = d.name ? `Bonjour ${d.name},` : "Bonjour,";
  return `${greeting}

Vous avez demande a reinitialiser votre mot de passe ${BRAND_NAME}.

Cliquez sur le lien ci-dessous pour definir un nouveau mot de passe :
${d.resetUrl}

Ce lien est valable 1 heure. Si vous n'avez pas demande cette reinitialisation, ignorez cet email, votre mot de passe restera inchange.

L'equipe ${BRAND_NAME}

---
${BRAND_NAME}
https://${BRAND_DOMAIN}
`;
}

export function resetPasswordHtml(d: ResetPasswordData): string {
  const greeting = d.name ? `Bonjour ${esc(d.name)},` : "Bonjour,";
  return `<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>Reinitialiser votre mot de passe</title>
</head>
<body style="margin:0;padding:0;background:${C.paper};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;color:${C.text};">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:${C.paper};padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:${C.card};border:1px solid ${C.border};border-radius:12px;overflow:hidden;">
          <tr>
            <td style="padding:32px 32px 16px;">
              <div style="display:inline-block;padding:6px 10px;background:#1c1917;border:1px solid ${C.accent};border-radius:6px;color:#fafaf9;font-family:Georgia,serif;font-size:13px;font-weight:500;">
                ${esc(BRAND_NAME)}
              </div>
              <h1 style="margin:24px 0 0;font-family:Georgia,serif;font-size:24px;line-height:1.3;color:${C.text};font-weight:500;">
                Reinitialiser votre mot de passe
              </h1>
            </td>
          </tr>
          <tr>
            <td style="padding:8px 32px 24px;font-size:16px;line-height:1.6;color:${C.text};">
              <p style="margin:16px 0;">${greeting}</p>
              <p style="margin:16px 0;color:${C.muted};">
                Vous avez demande a reinitialiser votre mot de passe ${esc(BRAND_NAME)}. Cliquez sur le bouton ci-dessous pour en definir un nouveau.
              </p>
              <div style="margin-top:24px;text-align:center;">
                <a href="${esc(d.resetUrl)}" style="display:inline-block;padding:12px 24px;background:${C.accent};color:#ffffff;text-decoration:none;border-radius:6px;font-size:15px;font-weight:600;">
                  Definir un nouveau mot de passe
                </a>
              </div>
              <p style="margin:24px 0 0;font-size:13px;color:${C.faint};line-height:1.5;">
                Ce lien est valable 1 heure. Si vous n'avez pas demande cette reinitialisation, ignorez cet email, votre mot de passe restera inchange.
              </p>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 32px;background:${C.paper};border-top:1px solid ${C.border};">
              <p style="margin:0;font-size:13px;color:${C.faint};line-height:1.5;">
                ${esc(BRAND_NAME)} &middot; <a href="https://${BRAND_DOMAIN}" style="color:${C.faint};text-decoration:underline;">${esc(BRAND_DOMAIN)}</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}

export function contactConfirmationHtml(s: ContactSubmission): string {
  return `<!doctype html>
<html lang="fr">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>On a bien recu votre message</title>
</head>
<body style="margin:0;padding:0;background:${C.paper};font-family:-apple-system,BlinkMacSystemFont,'Segoe UI',Roboto,sans-serif;color:${C.text};">
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:${C.paper};padding:32px 16px;">
    <tr>
      <td align="center">
        <table role="presentation" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;background:${C.card};border:1px solid ${C.border};border-radius:12px;overflow:hidden;">
          <tr>
            <td style="padding:32px 32px 16px;">
              <div style="display:inline-block;padding:6px 10px;background:#1c1917;border:1px solid ${C.accent};border-radius:6px;color:#fafaf9;font-family:Georgia,serif;font-size:13px;font-weight:500;">
                ${esc(BRAND_NAME)}
              </div>
              <h1 style="margin:24px 0 0;font-family:Georgia,serif;font-size:28px;line-height:1.2;color:${C.text};font-weight:500;">
                Bonjour ${esc(s.firstName)},
              </h1>
            </td>
          </tr>
          <tr>
            <td style="padding:8px 32px 24px;font-size:16px;line-height:1.6;color:${C.text};">
              <p style="margin:16px 0;">
                Merci pour votre message. Nous l'avons bien recu et nous vous repondons rapidement, du lundi au vendredi.
              </p>
              <p style="margin:16px 0;color:${C.muted};">
                En attendant, voici deux pages utiles pour mieux nous connaitre :
              </p>
              <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin-top:16px;">
                <tr>
                  <td style="padding:4px 0;">
                    <a href="https://${BRAND_DOMAIN}/essentiel" style="color:${C.accent};text-decoration:none;font-weight:600;font-size:14px;">
                      &rarr; Tout ce qui est inclus dans l'abonnement
                    </a>
                  </td>
                </tr>
                <tr>
                  <td style="padding:4px 0;">
                    <a href="https://${BRAND_DOMAIN}/tarifs" style="color:${C.accent};text-decoration:none;font-weight:600;font-size:14px;">
                      &rarr; Les tarifs detailles
                    </a>
                  </td>
                </tr>
              </table>
            </td>
          </tr>
          <tr>
            <td style="padding:24px 32px;background:${C.paper};border-top:1px solid ${C.border};">
              <p style="margin:0;font-size:13px;color:${C.faint};line-height:1.5;">
                ${esc(BRAND_NAME)} &middot; Atelier web francais<br>
                <a href="https://${BRAND_DOMAIN}" style="color:${C.faint};text-decoration:underline;">${esc(BRAND_DOMAIN)}</a>
              </p>
            </td>
          </tr>
        </table>
      </td>
    </tr>
  </table>
</body>
</html>`;
}
