/** Ouvre le client mail par défaut (Outlook, Apple Mail, etc.) via mailto: */

const MAILTO_SAFE_LEN = 1800;

export type MailtoPayload = {
  to: string;
  subject: string;
  body: string;
};

export type MailtoResult =
  | { ok: true; href: string }
  | { ok: false; reason: "no_email" | "invalid_email" | "too_long"; message: string };

function isValidEmail(email: string): boolean {
  // Simple check — enough to avoid clearly broken mailto targets
  return /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email);
}

function truncateBody(body: string, maxLen: number): string {
  if (body.length <= maxLen) return body;
  return `${body.slice(0, Math.max(0, maxLen - 20)).trimEnd()}\n\n[…]`;
}

/** Construit une URL mailto: sûre (encodage, longueur limitée). */
export function buildMailtoHref(payload: MailtoPayload): MailtoResult {
  const to = payload.to.trim();
  if (!to) {
    return {
      ok: false,
      reason: "no_email",
      message: "Aucune adresse email n'est renseignée pour ce client.",
    };
  }
  if (!isValidEmail(to)) {
    return {
      ok: false,
      reason: "invalid_email",
      message: `L'adresse email du client semble invalide : ${to}`,
    };
  }

  const subject = payload.subject.trim();
  let body = payload.body.trim();

  // Reserve space for mailto: + address + subject encoding overhead
  const overhead =
    `mailto:${to}?subject=${encodeURIComponent(subject)}&body=`.length + 40;
  const maxBodyChars = Math.max(400, MAILTO_SAFE_LEN - overhead);
  body = truncateBody(body, maxBodyChars);

  const href = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(body)}`;

  if (href.length > 2000) {
    // Last resort: shorter body
    const shortBody = truncateBody(body, 600);
    const shortHref = `mailto:${to}?subject=${encodeURIComponent(subject)}&body=${encodeURIComponent(shortBody)}`;
    if (shortHref.length > 2000) {
      return {
        ok: false,
        reason: "too_long",
        message:
          "Le message est trop long pour mailto:. Exportez le PDF, puis composez l'email manuellement.",
      };
    }
    return { ok: true, href: shortHref };
  }

  return { ok: true, href };
}

/**
 * Déclenche l'ouverture du client mail.
 * Préfère un clic sur <a> (mieux supporté qu'un assignement de location,
 * notamment avec Outlook / certains navigateurs).
 */
export function openMailClient(payload: MailtoPayload): MailtoResult {
  const result = buildMailtoHref(payload);
  if (!result.ok) return result;

  try {
    const a = document.createElement("a");
    a.href = result.href;
    a.target = "_self";
    a.rel = "noopener noreferrer";
    a.style.display = "none";
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
  } catch {
    try {
      window.location.href = result.href;
    } catch {
      return {
        ok: false,
        reason: "too_long",
        message:
          "Impossible d'ouvrir le client mail. Exportez le PDF et composez l'email manuellement.",
      };
    }
  }

  return result;
}

export function factureEmailCopy(opts: {
  numeroLabel: string;
  clientNom: string;
  montant: string;
  emetteurNom: string;
  conditionsPaiement?: string;
}): { subject: string; body: string } {
  const subject = `Facture ${opts.numeroLabel} — ${opts.clientNom}`;
  const lines = [
    "Bonjour,",
    "",
    `Veuillez trouver la facture ${opts.numeroLabel} concernant ${opts.clientNom}, pour un montant de ${opts.montant} TTC.`,
    "",
    "Joignez le PDF exporté depuis Facture-online (bouton « Exporter en PDF »).",
  ];
  if (opts.conditionsPaiement?.trim()) {
    lines.push("", `Conditions de paiement : ${opts.conditionsPaiement.trim()}`);
  }
  lines.push("", "Cordialement,", opts.emetteurNom);
  return { subject, body: lines.join("\n") };
}

export function devisEmailCopy(opts: {
  numeroLabel: string;
  clientNom: string;
  montant: string;
  emetteurNom: string;
  validite?: string;
}): { subject: string; body: string } {
  const subject = `Devis ${opts.numeroLabel} — ${opts.clientNom}`;
  const lines = [
    "Bonjour,",
    "",
    `Veuillez trouver le devis ${opts.numeroLabel} concernant ${opts.clientNom}, pour un montant de ${opts.montant} TTC.`,
  ];
  if (opts.validite) {
    lines.push(`Validité : ${opts.validite}.`);
  }
  lines.push(
    "",
    "Joignez le PDF exporté depuis Facture-online (bouton « Exporter en PDF »).",
    "",
    "Cordialement,",
    opts.emetteurNom,
  );
  return { subject, body: lines.join("\n") };
}
