export interface EmailTemplateDetail {
  label: string;
  value: string;
}

export interface EmailTemplateInput {
  preheader: string;
  eyebrow: string;
  title: string;
  introHtml: string;
  action?: { label: string; url: string } | null;
  detailRows?: EmailTemplateDetail[];
  outroHtml?: string;
  footerNote?: string;
}

const SITE_URL = "https://tiketrack.com";
const HEADER_IMAGE_URL = `${SITE_URL}/brand/tiketrack-email-header.png`;
const BRAND_NAME_DARK_URL = `${SITE_URL}/brand/tiketrack-name-dark.png`;
const BRAND_NAME_LIGHT_URL = `${SITE_URL}/brand/tiketrack-name-light.png`;
const BRAND_ICON_URL = `${SITE_URL}/brand/tiketrack-icon.png`;

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

export function plainTextToEmailHtml(value: string): string {
  const escaped = escapeHtml(value.trim());
  const withLinks = escaped.replace(/(https?:\/\/[^\s<]+)/gu, '<a href="$1">$1</a>');
  return withLinks
    .split(/\n{2,}/u)
    .map((paragraph) => `<p>${paragraph.replace(/\n/gu, "<br />")}</p>`)
    .join("");
}

function renderDetailRows(rows: EmailTemplateDetail[] = []): string {
  if (!rows.length) return "";
  return `
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:separate;margin-top:24px;">
      ${rows.map((row) => `
        <tr><td style="padding:0 0 10px;">
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="border-collapse:separate;border:1px solid #d8e6e7;border-radius:14px;background:#f6fbfb;">
            <tr><td style="padding:15px 16px;">
              <div style="font-size:11px;line-height:1.4;letter-spacing:.13em;text-transform:uppercase;color:#51717b;font-weight:700;">${escapeHtml(row.label)}</div>
              <div style="margin-top:5px;font-size:16px;line-height:1.45;color:#102b45;font-weight:700;word-break:break-word;">${escapeHtml(row.value)}</div>
            </td></tr>
          </table>
        </td></tr>`).join("")}
    </table>`;
}

export function renderTikeTrackEmailTemplate(input: EmailTemplateInput): string {
  const action = input.action
    ? `<table role="presentation" cellpadding="0" cellspacing="0" style="margin:26px 0 10px;"><tr><td bgcolor="#0aa88f" style="border-radius:12px;background:#0aa88f;"><a href="${escapeHtml(input.action.url)}" style="display:inline-block;padding:15px 22px;color:#ffffff;text-decoration:none;font-size:16px;line-height:1;font-weight:700;">${escapeHtml(input.action.label)} <span style="font-size:20px;padding-left:7px;">&#8594;</span></a></td></tr></table>`
    : "";

  return `<!doctype html>
<html lang="es"><head>
  <meta charset="utf-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1" />
  <meta name="x-apple-disable-message-reformatting" />
  <meta name="color-scheme" content="light dark" />
  <meta name="supported-color-schemes" content="light dark" />
  <title>${escapeHtml(input.title)} | TikeTrack</title>
  <style>
    html,body{margin:0!important;padding:0!important;width:100%!important;background:#edf5f6;color:#102b45} body,table,td{font-family:Arial,Helvetica,sans-serif} table{border-spacing:0} img{border:0;outline:none;text-decoration:none} p{margin:0 0 14px} a{color:#078b80;font-weight:700}.email-bg{background:#edf5f6}.shell{width:100%;max-width:680px}.header-card{background:#06243b}.content-card{background:#fff}.footer{background:#06243b}.brand-name-dark{display:none}.brand-name-light{display:block}.title{font-size:31px;line-height:1.15;color:#102b45;margin:0}.intro,.content{font-size:16px;line-height:1.65;color:#45606d}@media(prefers-color-scheme:dark){.email-bg{background:#071b2b!important}.header-card{background:#06243b!important}.brand-name-dark{display:none!important}.brand-name-light{display:block!important}.content-card{background:#ffffff!important}.title{color:#102b45!important}.intro,.content{color:#45606d!important}}@media only screen and (max-width:620px){.outer-pad{padding:12px 7px 28px!important}.header-pad{padding:19px 20px!important}.card-pad{padding:27px 22px!important}.footer-pad{padding:24px 22px!important}.title{font-size:26px!important}.header-card{border-radius:18px 18px 0 0!important}.header-illustration{max-width:118px!important}.meta-cell{display:block!important;width:100%!important;padding:0 0 14px!important}}
  </style>
</head><body>
  <div style="display:none;max-height:0;overflow:hidden;opacity:0;color:transparent;mso-hide:all;">${escapeHtml(input.preheader)}</div>
  <table role="presentation" width="100%" cellpadding="0" cellspacing="0" class="email-bg" style="width:100%;background:#edf5f6;"><tr><td align="center" class="outer-pad" style="padding:28px 12px 42px;">
    <table role="presentation" width="680" cellpadding="0" cellspacing="0" class="shell" style="width:100%;max-width:680px;">
      <tr><td class="header-card header-pad" style="background:#06243b;border-radius:22px 22px 0 0;padding:22px 30px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr>
          <td style="vertical-align:middle;padding-right:12px;">
            <a href="${SITE_URL}" style="text-decoration:none;">
              <table role="presentation" cellpadding="0" cellspacing="0"><tr>
                <td style="vertical-align:top;padding-right:12px;"><img src="${BRAND_ICON_URL}" alt="Icono de TikeTrack" width="78" style="display:block;width:78px;max-width:78px;height:auto;" /></td>
                <td style="vertical-align:top;">
                  <img class="brand-name-dark" src="${BRAND_NAME_DARK_URL}" alt="tiketrack" width="190" style="display:none;width:190px;max-width:190px;height:auto;" /><img class="brand-name-light" src="${BRAND_NAME_LIGHT_URL}" alt="tiketrack" width="190" style="display:block;width:190px;max-width:190px;height:auto;" />
                  <div style="margin-top:6px;font-family:Helvetica,Arial,sans-serif;font-size:14px;line-height:1.3;font-weight:700;white-space:nowrap;"><span style="color:#ffffff;">Tus garantías,</span> <span style="color:#4de0d0;">siempre contigo</span></div>
                </td>
              </tr></table>
            </a>
          </td>
          <td width="38%" align="right" style="width:38%;vertical-align:middle;"><a href="${SITE_URL}" style="text-decoration:none;"><img class="header-illustration" src="${HEADER_IMAGE_URL}" alt="Gestiona tus garantías con TikeTrack" width="210" style="display:block;width:100%;max-width:210px;height:auto;" /></a></td>
        </tr></table>
      </td></tr>
      <tr><td style="height:5px;line-height:5px;font-size:0;background:#12bda9;background:linear-gradient(90deg,#06b9a3 0%,#37e0d0 50%,#1499d4 100%);">&nbsp;</td></tr>
      <tr><td class="content-card card-pad" style="background:#ffffff;padding:38px 42px 30px;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td>
          <div style="font-size:11px;line-height:1.4;letter-spacing:.18em;text-transform:uppercase;color:#078b80;font-weight:700;">${escapeHtml(input.eyebrow)}</div>
          <h1 class="title" style="margin:12px 0 0;font-size:31px;line-height:1.15;color:#102b45;">${escapeHtml(input.title)}</h1>
          <div class="intro" style="margin-top:18px;font-size:16px;line-height:1.65;color:#45606d;">${input.introHtml}</div>
          ${action}
          ${renderDetailRows(input.detailRows)}
          ${input.outroHtml ? `<div class="content" style="margin-top:18px;font-size:15px;line-height:1.65;color:#45606d;">${input.outroHtml}</div>` : ""}
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" style="margin-top:24px;border-collapse:separate;border:1px solid #d9e8e7;border-radius:14px;background:#f2fbfa;"><tr><td style="padding:15px 17px;font-size:13px;line-height:1.55;color:#52707a;"><strong style="color:#102b45;">&#128274;&nbsp; Mensaje seguro de TikeTrack</strong><br />${escapeHtml(input.footerNote ?? "Este aviso se ha generado conforme a tus preferencias de notificación.")}</td></tr></table>
        </td></tr></table>
      </td></tr>
      <tr><td class="footer footer-pad" style="background:#06243b;border-radius:0 0 22px 22px;padding:26px 34px;color:#d8edf1;">
        <table role="presentation" width="100%" cellpadding="0" cellspacing="0"><tr><td align="center" style="text-align:center;"><a href="${SITE_URL}" style="display:inline-block;color:#ffffff;text-decoration:none;font-size:25px;line-height:1.2;font-weight:700;">tiketrack.com</a></td></tr></table>
        <div style="height:1px;background:#26516a;margin:20px 0 14px;"></div><div style="font-size:11px;line-height:1.55;color:#9cbcc5;">Este mensaje se ha generado automáticamente desde TikeTrack. No respondas a este correo.</div>
      </td></tr>
    </table>
  </td></tr></table>
</body></html>`;
}
