import { baseTemplate, heading, BRAND_COLORS as C } from './base.js';

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

function sectionHeader(label: string, accentColor: string) {
  return `<tr>
    <td colspan="2" style="background-color:${accentColor};color:#ffffff;padding:10px 16px;font-weight:600;border-radius:8px 8px 0 0;font-size:14px;letter-spacing:0.02em;">
      ${label}
    </td>
  </tr>`;
}

function row(label: string, value: string, isLast = false) {
  const border = isLast ? '' : `border-bottom:1px solid ${C.border};`;
  return `<tr>
    <td style="padding:10px 16px;${border}font-weight:500;color:${C.textMuted};width:40%;font-size:13px;">${label}</td>
    <td style="padding:10px 16px;${border}color:${C.textPrimary};font-size:14px;">${value}</td>
  </tr>`;
}

export function newClientAdminEmail(data: {
  clienteNombre: string;
  clienteRfc: string;
  adminEmail: string;
  adminNombre: string;
  tempPassword: string | null | undefined;
  databaseName: string;
  plan: string;
}): string {
  return baseTemplate(`
    ${heading('Nuevo cliente registrado')}
    <p style="color:${C.textPrimary};margin:0 0 24px;">
      Se ha dado de alta un nuevo cliente en Horux 360. Detalles:
    </p>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;border:1px solid ${C.border};border-radius:8px;overflow:hidden;">
      ${sectionHeader('Datos del cliente', C.primary)}
      ${row('Empresa', `<strong>${escapeHtml(data.clienteNombre)}</strong>`)}
      ${row('RFC', `<span style="font-family:monospace;">${escapeHtml(data.clienteRfc)}</span>`)}
      ${row('Plan', escapeHtml(data.plan), true)}
    </table>

    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;border:1px solid ${C.border};border-radius:8px;overflow:hidden;">
      ${sectionHeader('Credenciales del usuario', C.secondary)}
      ${row('Nombre', escapeHtml(data.adminNombre))}
      ${row('Email', `<span style="font-family:monospace;">${escapeHtml(data.adminEmail)}</span>`)}
      ${row('Contraseña temporal', `<code style="background-color:${C.bgLight};padding:4px 10px;border-radius:6px;font-size:13px;color:#dc2626;border:1px solid ${C.border};">${escapeHtml(data.tempPassword || 'N/A - usuario ya existía')}</code>`, true)}
    </table>

    <div style="background-color:#fef2f2;border-left:4px solid #ef4444;border-radius:8px;padding:12px 16px;margin:0 0 16px;">
      <p style="margin:0;color:#991b1b;font-size:13px;">
        <strong>⚠️ Confidencial:</strong> este correo contiene credenciales. No lo reenvíes ni lo compartas.
      </p>
    </div>
  `);
}
