export type NewsletterEmailTemplate = {
  subject: string;
  textBody: string;
  htmlBody: string;
};

type ConfirmTemplateInput = {
  label: string;
  confirmUrl: string;
  unsubscribeUrl: string;
};

type ManageTemplateInput = {
  label: string;
  manageUrl: string;
  expiresHours: number;
};

type AdminLoginTemplateInput = {
  loginUrl: string;
  expiresMinutes: number;
};

function escapeHtml(value: string): string {
  return value.replace(/[&<>"']/g, (char) => {
    switch (char) {
      case '&':
        return '&amp;';
      case '<':
        return '&lt;';
      case '>':
        return '&gt;';
      case '"':
        return '&quot;';
      case "'":
        return '&#39;';
      default:
        return char;
    }
  });
}

function renderLayout({
  title,
  preheader,
  content
}: {
  title: string;
  preheader: string;
  content: string;
}): string {
  return `<!doctype html>
<html lang="en">
  <head>
    <meta charset="utf-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />
    <title>${escapeHtml(title)}</title>
  </head>
  <body style="margin:0; background:#121212; color:#e6e6e6; font-family:ui-sans-serif, system-ui, -apple-system, Segoe UI, Roboto, Helvetica, Arial, sans-serif; line-height:1.6;">
    <div style="display:none; max-height:0; overflow:hidden; opacity:0; color:transparent;">
      ${escapeHtml(preheader)}
    </div>
    <table role="presentation" width="100%" cellspacing="0" cellpadding="0" style="background:#121212; padding:32px 16px;">
      <tr>
        <td align="center">
          <table role="presentation" width="560" cellspacing="0" cellpadding="0" style="max-width:560px; width:100%; background:#1f1f1f; border:1px solid rgba(255,255,255,0.08); border-radius:16px; padding:24px;">
            <tr>
              <td style="font-size:20px; font-weight:600; letter-spacing:0.02em; color:#ffffff;">
                ${escapeHtml(title)}
              </td>
            </tr>
            <tr>
              <td style="padding-top:16px; font-size:15px; color:#e6e6e6;">
                ${content}
              </td>
            </tr>
            <tr>
              <td style="padding-top:20px; font-size:12px; color:rgba(230,230,230,0.7);">
                If you did not request this, you can ignore this email.
              </td>
            </tr>
          </table>
        </td>
      </tr>
    </table>
  </body>
</html>`;
}

export function buildConfirmEmail({
  label,
  confirmUrl,
  unsubscribeUrl
}: ConfirmTemplateInput): NewsletterEmailTemplate {
  const subject = `Confirm your ${label} subscription`;
  const textBody = `Confirm your ${label} subscription:\n\n${confirmUrl}\n\nIf you did not request this, you can ignore this email.\n\nUnsubscribe:\n${unsubscribeUrl}`;
  const content = `
    <p style="margin:0 0 16px;">You are almost subscribed to ${escapeHtml(label)} updates.</p>
    <p style="margin:0 0 16px;">
      <a href="${escapeHtml(confirmUrl)}" style="display:inline-block; background:#b78a3c; color:#ffffff; text-decoration:none; padding:10px 18px; border-radius:999px;">
        Confirm subscription
      </a>
    </p>
    <p style="margin:12px 0 0;">
      <a href="${escapeHtml(
        unsubscribeUrl
      )}" style="display:inline-block; background:transparent; color:#ffffff; text-decoration:none; padding:10px 16px; border-radius:999px; border:1px solid rgba(255,255,255,0.4);">
        Unsubscribe
      </a>
    </p>
  `;
  const htmlBody = renderLayout({
    title: `Confirm your ${label} subscription`,
    preheader: subject,
    content
  });
  return { subject, textBody, htmlBody };
}

export function buildManageEmail({
  label,
  manageUrl,
  expiresHours
}: ManageTemplateInput): NewsletterEmailTemplate {
  const subject = `Manage your ${label} subscriptions`;
  const textBody = `Use this secure link to manage your ${label} subscriptions:\n\n${manageUrl}\n\nThis link expires in ${expiresHours} hours.`;
  const content = `
    <p style="margin:0 0 16px;">Use this secure link to manage your ${escapeHtml(label)} subscriptions.</p>
    <p style="margin:0 0 16px;">
      <a href="${escapeHtml(manageUrl)}" style="display:inline-block; background:#b78a3c; color:#ffffff; text-decoration:none; padding:10px 18px; border-radius:999px;">
        Manage subscriptions
      </a>
    </p>
    <p style="margin:0; font-size:13px; color:rgba(230,230,230,0.8);">This link expires in ${expiresHours} hours.</p>
  `;
  const htmlBody = renderLayout({
    title: `Manage your ${label} subscriptions`,
    preheader: subject,
    content
  });
  return { subject, textBody, htmlBody };
}

export function buildAdminLoginEmail({
  loginUrl,
  expiresMinutes
}: AdminLoginTemplateInput): NewsletterEmailTemplate {
  const subject = 'Your CULTSCALE admin login link';
  const textBody = `Use this secure link to access the CULTSCALE admin dashboard:\n\n${loginUrl}\n\nThis link expires in ${expiresMinutes} minutes.`;
  const content = `
    <p style="margin:0 0 16px;">Use this secure link to access the CULTSCALE admin dashboard.</p>
    <p style="margin:0 0 16px;">
      <a href="${escapeHtml(loginUrl)}" style="display:inline-block; background:#b78a3c; color:#ffffff; text-decoration:none; padding:10px 18px; border-radius:999px;">
        Open admin dashboard
      </a>
    </p>
    <p style="margin:0; font-size:13px; color:rgba(230,230,230,0.8);">This link expires in ${expiresMinutes} minutes.</p>
  `;
  const htmlBody = renderLayout({
    title: 'Admin login',
    preheader: subject,
    content
  });
  return { subject, textBody, htmlBody };
}
