<?php
/**
 * EmailTemplateHelper
 *
 * Shared Nexa-branded email template builder.
 * Produces table-based HTML that renders consistently across Gmail,
 * Outlook, Apple Mail, and dark/light theme variants.
 *
 * Brand palette (from Nexa Brandbook):
 *   Iron Gray   #30302D   — logo / dark text
 *   Illuminating Yellow #FFEF34 — primary brand accent
 *   Analytic Violet #6D6090 — secondary
 *   Deep Green  #007878   — CyberSight product color
 *   Cyber Gray  #F2F2F2   — light backgrounds
 *   Typography: Space Grotesk (fallback: Arial)
 */

class EmailTemplateHelper {

    /**
     * Wrap an email body section inside the full Nexa branded shell.
     *
     * @param string $subject    Email subject (shown in header)
     * @param string $headerIcon Short emoji or text icon for the header badge (optional)
     * @param string $innerHtml  The main content block (already table-based HTML)
     * @param string $footerNote Optional extra footer line
     * @return string            Complete HTML document
     */
    public static function wrap(
        string $subject,
        string $innerHtml,
        string $footerNote = '',
        string $headerSubtitle = 'Nexa CyberSight'
    ): string {
        $year = date('Y');
        $safeSubject = htmlspecialchars($subject, ENT_QUOTES, 'UTF-8');
        $safeSubtitle = htmlspecialchars($headerSubtitle, ENT_QUOTES, 'UTF-8');
        $footerExtra = $footerNote !== ''
            ? '<p style="margin:0 0 10px;font-size:12px;color:#6D6090;">' . htmlspecialchars($footerNote, ENT_QUOTES, 'UTF-8') . '</p>'
            : '';

        return <<<HTML
<!DOCTYPE html>
<html lang="en" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light only">
<meta name="supported-color-schemes" content="light only">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{$safeSubject}</title>
<!--[if mso]>
<noscript>
<xml>
<o:OfficeDocumentSettings>
<o:PixelsPerInch>96</o:PixelsPerInch>
</o:OfficeDocumentSettings>
</xml>
</noscript>
<style>table,td,th{font-family:Arial,'Helvetica Neue',Helvetica,sans-serif!important}a{color:#007878!important}</style>
<![endif]-->
<style>
  @media only screen and (max-width:620px) {
    .email-container { width:100% !important; }
    .content-pad { padding:20px 18px !important; }
    .header-pad { padding:22px 18px !important; }
  }
  body, table, td, p, a { -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%; }
  body { margin:0 !important; padding:0 !important; width:100% !important; }
  img { border:0; line-height:100%; outline:none; text-decoration:none; -ms-interpolation-mode:bicubic; }
</style>
</head>
<body style="margin:0;padding:0;background-color:#F2F2F2;font-family:'Space Grotesk',Arial,'Helvetica Neue',Helvetica,sans-serif;-webkit-font-smoothing:antialiased;-moz-osx-font-smoothing:grayscale;">

<!-- Background wrapper -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F2F2F2;">
<tr><td align="center" style="padding:36px 16px;">

<!-- Email container -->
<table role="presentation" class="email-container" width="600" cellpadding="0" cellspacing="0" border="0" style="max-width:600px;width:100%;background-color:#ffffff;border-radius:12px;overflow:hidden;box-shadow:0 4px 24px rgba(48,48,45,0.08);">

  <!-- ======= HEADER ======= -->
  <tr>
    <td class="header-pad" style="background-color:#30302D;padding:28px 32px;text-align:center;">
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
        <tr>
          <td align="center">
            <!-- Nexa wordmark in yellow -->
            <h1 style="margin:0 0 2px;font-size:24px;font-weight:700;color:#FFEF34;letter-spacing:0.08em;text-transform:uppercase;">NEXA</h1>
            <p style="margin:0 0 12px;font-size:11px;font-weight:500;color:#F2F2F2;letter-spacing:0.15em;text-transform:uppercase;opacity:0.7;">CYBERSIGHT</p>
          </td>
        </tr>
        <tr>
          <td align="center">
            <!-- Yellow accent line -->
            <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
              <td style="width:48px;height:3px;background-color:#FFEF34;border-radius:2px;font-size:0;line-height:0;">&nbsp;</td>
            </tr></table>
          </td>
        </tr>
        <tr>
          <td align="center" style="padding-top:14px;">
            <p style="margin:0;font-size:16px;font-weight:600;color:#ffffff;line-height:1.3;">{$safeSubject}</p>
          </td>
        </tr>
      </table>
    </td>
  </tr>

  <!-- ======= BODY ======= -->
  <tr>
    <td class="content-pad" style="padding:28px 32px 8px;">
      {$innerHtml}
    </td>
  </tr>

  <!-- ======= FOOTER ======= -->
  <tr>
    <td style="padding:20px 32px 24px;text-align:center;border-top:1px solid #F2F2F2;">
      {$footerExtra}
      <p style="margin:0 0 4px;font-size:11px;color:#9ca3af;">This is an automated message from Nexa CyberSight.</p>
      <p style="margin:0;font-size:11px;color:#c5c5c5;">&copy; {$year} Nexa &mdash; wearenexa.com</p>
    </td>
  </tr>

</table>
<!-- /Email container -->

</td></tr>
</table>
<!-- /Background wrapper -->

</body>
</html>
HTML;
    }

    // ── Pre-built email types ────────────────────────────────────────────

    /**
     * Welcome / new user email.
     */
    public static function welcomeEmail(string $username, string $firstName, string $resetLink): string {
        $eName = htmlspecialchars($firstName ?: $username, ENT_QUOTES, 'UTF-8');
        $eUser = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
        $eLink = htmlspecialchars($resetLink, ENT_QUOTES, 'UTF-8');

        $inner = <<<HTML
<!-- Greeting -->
<p style="margin:0 0 18px;font-size:15px;color:#30302D;line-height:1.6;">
  Hello <strong>{$eName}</strong>, welcome to <strong style="color:#007878;">Nexa CyberSight</strong>.
</p>

<!-- Info card -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F2F2F2;border-radius:8px;border-left:4px solid #007878;margin-bottom:20px;">
  <tr><td style="padding:18px 22px;">
    <p style="margin:0 0 10px;font-size:14px;color:#30302D;line-height:1.5;">Your account has been created. Here are your details:</p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="padding:6px 0;font-size:13px;color:#6D6090;width:100px;">Username</td>
        <td style="padding:6px 0;font-size:14px;font-weight:600;color:#30302D;">{$eUser}</td>
      </tr>
    </table>
  </td></tr>
</table>

<!-- CTA button -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
  <tr><td align="center">
    <table role="presentation" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="background-color:#007878;border-radius:8px;text-align:center;">
          <!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{$eLink}" style="height:44px;v-text-anchor:middle;width:260px;" arcsize="18%" fillcolor="#007878" stroke="f"><center style="color:#ffffff;font-family:Arial,sans-serif;font-size:14px;font-weight:bold;">Set up your password</center></v:roundrect><![endif]-->
          <a href="{$eLink}" target="_blank" style="display:inline-block;background-color:#007878;color:#ffffff;font-family:'Space Grotesk',Arial,sans-serif;font-size:14px;font-weight:600;text-decoration:none;padding:12px 36px;border-radius:8px;line-height:1.4;mso-hide:all;">Set up your password</a>
        </td>
      </tr>
    </table>
  </td></tr>
</table>

<p style="margin:0 0 6px;font-size:12px;color:#9ca3af;text-align:center;">If the button doesn't work, copy and paste this link into your browser:</p>
<p style="margin:0 0 20px;font-size:12px;color:#007878;text-align:center;word-break:break-all;">{$eLink}</p>

<!-- Security note -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#FFEF34;border-radius:8px;">
  <tr><td style="padding:14px 20px;">
    <p style="margin:0;font-size:13px;color:#30302D;line-height:1.5;font-weight:500;">If you did not expect this invitation, you can safely ignore this message.</p>
  </td></tr>
</table>
HTML;

        return self::wrap('Welcome to Nexa CyberSight', $inner);
    }

    /**
     * Welcome email — plain text fallback.
     */
    public static function welcomeEmailPlain(string $username, string $firstName, string $resetLink): string {
        $name = $firstName ?: $username;
        return "Welcome to Nexa CyberSight\n\n"
             . "Hello {$name},\n\n"
             . "Your account has been created.\n"
             . "Username: {$username}\n\n"
             . "To set up your password, visit the following link:\n{$resetLink}\n\n"
             . "If you did not expect this invitation, you can safely ignore this message.\n\n"
             . "— Nexa CyberSight";
    }

    /**
     * Monitoring alert email.
     */
    public static function monitoringAlertEmail(
        string $userName,
        string $domain,
        int $newFindings,
        int $totalFindings
    ): string {
        $eDomain = htmlspecialchars($domain, ENT_QUOTES, 'UTF-8');
        $eName   = htmlspecialchars($userName, ENT_QUOTES, 'UTF-8');
        $plural  = $newFindings !== 1 ? 's' : '';

        $inner = <<<HTML
<!-- Greeting -->
<p style="margin:0 0 18px;font-size:15px;color:#30302D;line-height:1.6;">
  Hello <strong>{$eName}</strong>, our monitoring system has detected new credential findings.
</p>

<!-- Alert summary card -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="border-left:4px solid #FFEF34;background-color:#F2F2F2;border-radius:8px;margin-bottom:20px;">
  <tr><td style="padding:20px 24px;">
    <h2 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#30302D;">{$newFindings} new finding{$plural} for {$eDomain}</h2>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="padding:8px 0;border-bottom:1px solid #e0e0de;font-size:13px;color:#6D6090;">Monitored asset</td>
        <td style="padding:8px 0;border-bottom:1px solid #e0e0de;font-size:14px;font-weight:700;color:#30302D;text-align:right;">{$eDomain}</td>
      </tr>
      <tr>
        <td style="padding:8px 0;border-bottom:1px solid #e0e0de;font-size:13px;color:#6D6090;">New findings since last check</td>
        <td style="padding:8px 0;border-bottom:1px solid #e0e0de;font-size:20px;font-weight:800;color:#007878;text-align:right;">{$newFindings}</td>
      </tr>
      <tr>
        <td style="padding:8px 0;font-size:13px;color:#6D6090;">Total findings to date</td>
        <td style="padding:8px 0;font-size:14px;font-weight:700;color:#30302D;text-align:right;">{$totalFindings}</td>
      </tr>
    </table>
  </td></tr>
</table>

<!-- How to investigate -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F2F2F2;border:1px solid #e0e0de;border-radius:8px;margin-bottom:20px;">
  <tr><td style="padding:20px 24px;">
    <h3 style="margin:0 0 14px;font-size:11px;font-weight:700;color:#007878;text-transform:uppercase;letter-spacing:0.12em;">How to investigate</h3>
    <table role="presentation" cellpadding="0" cellspacing="0" border="0">
      <tr><td style="padding:4px 0;font-size:14px;color:#30302D;line-height:1.6;">1. Log into the <strong>CyberSight</strong> platform</td></tr>
      <tr><td style="padding:4px 0;font-size:14px;color:#30302D;line-height:1.6;">2. Go to the <strong>Dashboard</strong></td></tr>
      <tr><td style="padding:4px 0;font-size:14px;color:#30302D;line-height:1.6;">3. Search for <strong style="color:#007878;">{$eDomain}</strong> using:</td></tr>
      <tr><td style="padding:5px 0 4px 16px;font-size:13px;color:#30302D;line-height:1.6;">&bull; <strong>Fetch credentials</strong> &mdash; leaked email/password combos</td></tr>
      <tr><td style="padding:4px 0 4px 16px;font-size:13px;color:#30302D;line-height:1.6;">&bull; <strong>Creds by domain</strong> &mdash; credentials from URLs matching this domain</td></tr>
      <tr><td style="padding:4px 0 4px 16px;font-size:13px;color:#30302D;line-height:1.6;">&bull; <strong>Illicit networks</strong> &mdash; dark web mentions</td></tr>
    </table>
  </td></tr>
</table>
HTML;

        return self::wrap(
            "Monitoring Alert: {$newFindings} new finding{$plural} for {$domain}",
            $inner,
            'Manage your monitoring preferences in Profile > Monitoring & Alerts.'
        );
    }

    /**
     * Monitoring alert — plain text fallback.
     */
    public static function monitoringAlertEmailPlain(
        string $userName,
        string $domain,
        int $newFindings,
        int $totalFindings
    ): string {
        return "Nexa CyberSight — Monitoring Alert\n\n"
             . "Hello {$userName},\n\n"
             . "New findings detected for {$domain}\n"
             . "New findings: {$newFindings}\n"
             . "Total findings: {$totalFindings}\n\n"
             . "To investigate:\n"
             . "1. Log into the CyberSight platform\n"
             . "2. Go to the Dashboard\n"
             . "3. Search for \"{$domain}\" using Fetch credentials or Creds by domain\n\n"
             . "Manage your monitoring preferences in Profile > Monitoring & Alerts.\n\n"
             . "— Nexa CyberSight";
    }

    /**
     * Password reset email.
     */
    public static function passwordResetEmail(string $username, string $resetLink): string {
        $eUser = htmlspecialchars($username, ENT_QUOTES, 'UTF-8');
        $eLink = htmlspecialchars($resetLink, ENT_QUOTES, 'UTF-8');

        $inner = <<<HTML
<!-- Greeting -->
<p style="margin:0 0 18px;font-size:15px;color:#30302D;line-height:1.6;">
  Hello <strong>{$eUser}</strong>, we received a request to reset your password.
</p>

<!-- Info card -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#F2F2F2;border-radius:8px;border-left:4px solid #007878;margin-bottom:20px;">
  <tr><td style="padding:18px 22px;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="padding:6px 0;font-size:13px;color:#6D6090;width:100px;">Username</td>
        <td style="padding:6px 0;font-size:14px;font-weight:600;color:#30302D;">{$eUser}</td>
      </tr>
      <tr>
        <td style="padding:6px 0;font-size:13px;color:#6D6090;">Expires</td>
        <td style="padding:6px 0;font-size:14px;font-weight:600;color:#30302D;">60 minutes</td>
      </tr>
    </table>
  </td></tr>
</table>

<!-- CTA button -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:20px;">
  <tr><td align="center">
    <table role="presentation" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td style="background-color:#007878;border-radius:8px;text-align:center;">
          <!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{$eLink}" style="height:44px;v-text-anchor:middle;width:260px;" arcsize="18%" fillcolor="#007878" stroke="f"><center style="color:#ffffff;font-family:Arial,sans-serif;font-size:14px;font-weight:bold;">Reset your password</center></v:roundrect><![endif]-->
          <a href="{$eLink}" target="_blank" style="display:inline-block;background-color:#007878;color:#ffffff;font-family:'Space Grotesk',Arial,sans-serif;font-size:14px;font-weight:600;text-decoration:none;padding:12px 36px;border-radius:8px;line-height:1.4;mso-hide:all;">Reset your password</a>
        </td>
      </tr>
    </table>
  </td></tr>
</table>

<p style="margin:0 0 6px;font-size:12px;color:#9ca3af;text-align:center;">If the button doesn't work, copy and paste this link into your browser:</p>
<p style="margin:0 0 20px;font-size:12px;color:#007878;text-align:center;word-break:break-all;">{$eLink}</p>

<!-- Security note -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background-color:#FFEF34;border-radius:8px;">
  <tr><td style="padding:14px 20px;">
    <p style="margin:0;font-size:13px;color:#30302D;line-height:1.5;font-weight:500;">If you did not request this password reset, you can safely ignore this message. Your password will remain unchanged.</p>
  </td></tr>
</table>
HTML;

        return self::wrap('Reset Your Password', $inner);
    }

    /**
     * Password reset — plain text fallback.
     */
    public static function passwordResetEmailPlain(string $username, string $resetLink): string {
        return "Nexa CyberSight — Password Reset\n\n"
             . "Hello {$username},\n\n"
             . "To reset your password, visit the following link:\n{$resetLink}\n\n"
             . "Username: {$username}\n"
             . "This link is valid for 60 minutes.\n\n"
             . "If you did not request this change, please ignore this message.\n\n"
             . "— Nexa CyberSight";
    }

    // ── Free Exposure Report ──────────────────────────────────────────

    /**
     * Free exposure report email — premium branded design.
     */
    /** Path to the brand logo asset shipped with the codebase. */
    public const BRAND_LOGO_PATH = __DIR__ . '/../assets/email_logo.png';

    /**
     * Content-ID used to reference the inline-attached logo from the HTML.
     * Senders MUST call $mail->addEmbeddedImage(self::BRAND_LOGO_PATH,
     * self::BRAND_LOGO_CID, 'logo.png', 'base64', 'image/png') for the
     * <img src="cid:..."> tag to resolve in the recipient's client.
     */
    public const BRAND_LOGO_CID = 'nx-logo';

    /**
     * Returns the `cid:` URI used by the email HTML. The actual image is
     * attached as MIME by the sender. CID embedding is the only approach
     * that renders reliably in Gmail (data URIs are stripped) and Outlook.
     */
    public static function brandLogoSrc(): string
    {
        return 'cid:' . self::BRAND_LOGO_CID;
    }

    // ─── Tier 1 helpers ────────────────────────────────────────────────────

    /**
     * Build the inbox-facing subject line. Severity-led with emoji + count.
     * Phase A — T1.2.
     */
    public static function exposureReportSubject(string $domain, int $total, string $lang = '', string $variant = 'A'): string
    {
        if ($lang === '' || !in_array($lang, ['es', 'en', 'pt'], true)) {
            $lang = self::reportLang($domain);
        }
        $S = self::reportStrings($lang);

        // Variant A — severity-led emoji prefix (current default)
        // Variant B — domain-led, severity in parenthesis (T3.6 A/B test)
        if ($total === 0) {
            return $variant === 'B'
                ? $domain . ' — ' . $S['subject_clean']
                : $S['subject_clean'] . ' — ' . $domain;
        }
        $tier = $total <= 50 ? 'low' : ($total <= 500 ? 'mod' : ($total <= 5000 ? 'high' : 'critical'));
        $emoji = ['low' => '⚠', 'mod' => '⚠', 'high' => '⛔', 'critical' => '🚨'][$tier];
        $body  = sprintf($S['subject_' . $tier], number_format($total));
        return $variant === 'B'
            ? sprintf('[%s] %s — %s', $domain, $body, $emoji)
            : sprintf('%s %s — %s', $emoji, $body, $domain);
    }

    /**
     * Append UTM tracking params to a URL. Phase A — T1.6.
     */
    public static function addUtm(string $url, string $content): string
    {
        $sep = (strpos($url, '?') === false) ? '?' : '&';
        $params = http_build_query([
            'utm_source'   => 'email',
            'utm_medium'   => 'transactional',
            'utm_campaign' => 'free_exposure_report',
            'utm_content'  => $content,
        ]);
        return $url . $sep . $params;
    }

    /**
     * Pick language by domain TLD. Phase A — T2.2.
     * `.br/.pt`        → pt-br
     * `.com/.us/.io/.ai/.uk/.co` → en
     * default          → es (LATAM hispanoparlante)
     */
    public static function reportLang(string $domain): string
    {
        $domain = strtolower(trim($domain));
        if (preg_match('/\.(br|pt)$/', $domain))                          return 'pt';
        if (preg_match('/\.(com|us|io|ai|uk|co|net|org)(\.[a-z]+)?$/', $domain) &&
            !preg_match('/\.(com|net|org|gob|gub)\.(uy|ar|cl|mx|pe|co|br|ec|bo|ve|py|cr|gt|sv|hn|ni|pa|do|pr|cu)$/', $domain)) {
            return 'en';
        }
        return 'es';
    }

    /**
     * i18n string bundle. Phase A — T2.2.
     */
    private static function reportStrings(string $lang): array
    {
        $bundles = [
            'es' => [
                'subject_clean'    => '✓ Sin exposición detectada',
                'subject_low'      => '%s credenciales expuestas',
                'subject_mod'      => '%s credenciales comprometidas',
                'subject_high'     => '%s credenciales comprometidas — alta exposición',
                'subject_critical' => '%s credenciales filtradas — exposición crítica',
                'preheader_clean'  => 'Tu dominio no aparece en nuestras bases de inteligencia. Revisá la verificación.',
                'preheader_found'  => '%s credenciales encontradas. Revisá el desglose por tipo de cuenta y la fortaleza de las contraseñas.',
                'tldr_clean'       => 'No detectamos credenciales comprometidas vinculadas a tu dominio.',
                'tldr_low'         => 'Encontramos exposición baja — conviene atender los hallazgos en los próximos días.',
                'tldr_mod'         => 'Exposición moderada. Recomendamos rotar contraseñas críticas y forzar MFA.',
                'tldr_high'        => 'Exposición alta. Acción inmediata recomendada en cuentas privilegiadas.',
                'tldr_critical'    => 'Exposición crítica. Tratá esto como un incidente activo y acelerá rotación + MFA.',
                'severity_clean'   => 'SIN EXPOSICIÓN DETECTADA',
                'severity_low'     => 'EXPOSICIÓN BAJA',
                'severity_mod'     => 'EXPOSICIÓN MODERADA',
                'severity_high'    => 'EXPOSICIÓN ALTA',
                'severity_critical'=> 'EXPOSICIÓN CRÍTICA',
                'badge'            => 'REPORTE DE INTELIGENCIA DE CREDENCIALES',
                'title'            => 'Reporte de Exposición',
                'generated_on'     => 'Generado el',
                'updated_chip'     => 'Datos actualizados',
                'hero_label'       => 'CREDENCIALES COMPROMETIDAS',
                'kpi_emp'          => 'EMPLEADOS',
                'kpi_third'        => 'TERCEROS',
                'kpi_cust'         => 'CLIENTES',
                'kpi_emp_sub'      => 'Cuentas @%s',
                'kpi_third_sub'    => 'Servicios externos',
                'kpi_cust_sub'     => 'Cuentas de usuarios',
                'strength_title'   => 'ANÁLISIS DE CONTRASEÑAS',
                'strength_subtitle'=> 'Fortaleza de las %s contraseñas analizadas',
                'strength_weak'    => 'DÉBILES + MUY DÉBILES',
                'strength_lbl_vw'  => 'Muy débil',
                'strength_lbl_w'   => 'Débil',
                'strength_lbl_m'   => 'Media',
                'strength_lbl_s'   => 'Fuerte',
                'whatdo_title'     => 'PRÓXIMOS PASOS RECOMENDADOS',
                'whatdo_step1'     => 'Forzar rotación inmediata de contraseñas para empleados con cuentas comprometidas.',
                'whatdo_step2'     => 'Habilitar MFA obligatoria en todos los servicios SaaS y webmail.',
                'whatdo_step3'     => 'Escanear endpoints de empleados afectados por posibles infecciones de stealer.',
                'whatdo_step4'     => 'Activar monitoreo continuo para alertas en tiempo real ante nuevos compromisos.',
                'cta_kicker'       => '¿LISTO PARA ACTUAR?',
                'cta_title'        => 'Conocé el',
                'cta_title_hl'     => 'panorama completo',
                'cta_sub'          => 'Cada usuario. Cada contraseña. Cada fuente. Plus stealer logs, monitoreo continuo e inteligencia LATAM-native.',
                'cta_primary'      => 'Ver cada credencial →',
                'cta_secondary'    => 'Hablar con un especialista',
                'cta_pdf'          => 'Descargar reporte en PDF',
                'social_proof'     => '%s organizaciones ya consultaron este dominio',
                'understand'       => 'ENTENDIENDO TUS RESULTADOS',
                'edu_emp'          => 'Empleados — emails @%s encontrados en bases de filtraciones y mercados de la dark web.',
                'edu_third'        => 'Terceros — credenciales de empleados reutilizadas en servicios externos (SaaS, redes sociales, etc.).',
                'edu_cust'         => 'Clientes — usuarios que acceden a tu dominio capturados por stealer logs.',
                'trust_kicker'     => 'Confiado por agencias de gobierno · bancos · fintechs · fuerzas de defensa',
                'footer_legal'     => 'Este reporte fue generado a partir de datos de filtraciones disponibles públicamente. No se accedieron ni descifraron credenciales durante este análisis.',
                'footer_byline'    => 'by Nexa Cybersecurity',
                'footer_unsub'     => 'Este es un email transaccional único. Política de privacidad',
            ],
            'en' => [
                'subject_clean'    => '✓ No exposure detected',
                'subject_low'      => '%s credentials exposed',
                'subject_mod'      => '%s credentials compromised',
                'subject_high'     => '%s credentials compromised — high exposure',
                'subject_critical' => '%s credentials leaked — critical exposure',
                'preheader_clean'  => 'Your domain does not appear in our intelligence sources. Review the verification details.',
                'preheader_found'  => '%s credentials found. Review the breakdown by account type and password strength.',
                'tldr_clean'       => 'We did not detect compromised credentials tied to your domain.',
                'tldr_low'         => 'Low exposure detected — review and address findings within a few days.',
                'tldr_mod'         => 'Moderate exposure. Rotate critical passwords and enforce MFA.',
                'tldr_high'        => 'High exposure. Immediate action recommended on privileged accounts.',
                'tldr_critical'    => 'Critical exposure. Treat this as an active incident — accelerate rotation + MFA.',
                'severity_clean'   => 'NO EXPOSURE DETECTED',
                'severity_low'     => 'LOW EXPOSURE',
                'severity_mod'     => 'MODERATE EXPOSURE',
                'severity_high'    => 'HIGH EXPOSURE',
                'severity_critical'=> 'CRITICAL EXPOSURE',
                'badge'            => 'CREDENTIAL INTELLIGENCE REPORT',
                'title'            => 'Exposure Report',
                'generated_on'     => 'Generated on',
                'updated_chip'     => 'Data updated',
                'hero_label'       => 'COMPROMISED CREDENTIALS',
                'kpi_emp'          => 'EMPLOYEES',
                'kpi_third'        => 'THIRD PARTIES',
                'kpi_cust'         => 'CUSTOMERS',
                'kpi_emp_sub'      => '@%s accounts',
                'kpi_third_sub'    => 'External services',
                'kpi_cust_sub'     => 'User accounts',
                'strength_title'   => 'PASSWORD ANALYSIS',
                'strength_subtitle'=> 'Strength of %s passwords analyzed',
                'strength_weak'    => 'WEAK + VERY WEAK',
                'strength_lbl_vw'  => 'Very weak',
                'strength_lbl_w'   => 'Weak',
                'strength_lbl_m'   => 'Medium',
                'strength_lbl_s'   => 'Strong',
                'whatdo_title'     => 'RECOMMENDED NEXT STEPS',
                'whatdo_step1'     => 'Force immediate password rotation for employees with compromised accounts.',
                'whatdo_step2'     => 'Enable mandatory MFA across all SaaS and webmail services.',
                'whatdo_step3'     => 'Scan endpoints of affected employees for active stealer infections.',
                'whatdo_step4'     => 'Activate continuous monitoring for real-time alerts on new compromises.',
                'cta_kicker'       => 'READY TO ACT?',
                'cta_title'        => 'See the',
                'cta_title_hl'     => 'full picture',
                'cta_sub'          => 'Every user. Every password. Every source. Plus stealer logs, 24/7 monitoring and LATAM-native threat intelligence.',
                'cta_primary'      => 'See every credential →',
                'cta_secondary'    => 'Talk to a specialist',
                'cta_pdf'          => 'Download PDF report',
                'social_proof'     => '%s organizations have queried this domain',
                'understand'       => 'UNDERSTANDING YOUR RESULTS',
                'edu_emp'          => 'Employees — @%s emails found in leak databases and dark-web markets.',
                'edu_third'        => 'Third parties — employee credentials reused on external services (SaaS, social, etc.).',
                'edu_cust'         => 'Customers — users accessing your domain captured by stealer logs.',
                'trust_kicker'     => 'Trusted by government agencies · banks · fintechs · defense forces',
                'footer_legal'     => 'This report was generated from publicly-available breach data. No credentials were accessed or decrypted during this analysis.',
                'footer_byline'    => 'by Nexa Cybersecurity',
                'footer_unsub'     => 'This is a one-shot transactional email. Privacy policy',
            ],
            'pt' => [
                'subject_clean'    => '✓ Sem exposição detectada',
                'subject_low'      => '%s credenciais expostas',
                'subject_mod'      => '%s credenciais comprometidas',
                'subject_high'     => '%s credenciais comprometidas — exposição alta',
                'subject_critical' => '%s credenciais vazadas — exposição crítica',
                'preheader_clean'  => 'Seu domínio não aparece em nossas fontes de inteligência. Revise os detalhes da verificação.',
                'preheader_found'  => '%s credenciais encontradas. Revise o detalhamento por tipo de conta e a força das senhas.',
                'tldr_clean'       => 'Não detectamos credenciais comprometidas vinculadas ao seu domínio.',
                'tldr_low'         => 'Exposição baixa — vale a pena tratar nos próximos dias.',
                'tldr_mod'         => 'Exposição moderada. Recomendamos girar senhas críticas e forçar MFA.',
                'tldr_high'        => 'Exposição alta. Ação imediata recomendada em contas privilegiadas.',
                'tldr_critical'    => 'Exposição crítica. Trate como incidente ativo — acelere rotação + MFA.',
                'severity_clean'   => 'SEM EXPOSIÇÃO DETECTADA',
                'severity_low'     => 'EXPOSIÇÃO BAIXA',
                'severity_mod'     => 'EXPOSIÇÃO MODERADA',
                'severity_high'    => 'EXPOSIÇÃO ALTA',
                'severity_critical'=> 'EXPOSIÇÃO CRÍTICA',
                'badge'            => 'RELATÓRIO DE INTELIGÊNCIA DE CREDENCIAIS',
                'title'            => 'Relatório de Exposição',
                'generated_on'     => 'Gerado em',
                'updated_chip'     => 'Dados atualizados',
                'hero_label'       => 'CREDENCIAIS COMPROMETIDAS',
                'kpi_emp'          => 'FUNCIONÁRIOS',
                'kpi_third'        => 'TERCEIROS',
                'kpi_cust'         => 'CLIENTES',
                'kpi_emp_sub'      => 'Contas @%s',
                'kpi_third_sub'    => 'Serviços externos',
                'kpi_cust_sub'     => 'Contas de usuários',
                'strength_title'   => 'ANÁLISE DE SENHAS',
                'strength_subtitle'=> 'Força das %s senhas analisadas',
                'strength_weak'    => 'FRACAS + MUITO FRACAS',
                'strength_lbl_vw'  => 'Muito fraca',
                'strength_lbl_w'   => 'Fraca',
                'strength_lbl_m'   => 'Média',
                'strength_lbl_s'   => 'Forte',
                'whatdo_title'     => 'PRÓXIMOS PASSOS RECOMENDADOS',
                'whatdo_step1'     => 'Forçar rotação imediata de senhas para funcionários com contas comprometidas.',
                'whatdo_step2'     => 'Habilitar MFA obrigatória em todos os SaaS e webmails.',
                'whatdo_step3'     => 'Escanear endpoints dos funcionários afetados em busca de infecções de stealer.',
                'whatdo_step4'     => 'Ativar monitoramento contínuo para alertas em tempo real.',
                'cta_kicker'       => 'PRONTO PARA AGIR?',
                'cta_title'        => 'Veja o',
                'cta_title_hl'     => 'panorama completo',
                'cta_sub'          => 'Cada usuário. Cada senha. Cada fonte. Plus stealer logs, monitoramento 24/7 e inteligência nativa LATAM.',
                'cta_primary'      => 'Ver cada credencial →',
                'cta_secondary'    => 'Falar com um especialista',
                'cta_pdf'          => 'Baixar relatório em PDF',
                'social_proof'     => '%s organizações já consultaram este domínio',
                'understand'       => 'ENTENDENDO SEUS RESULTADOS',
                'edu_emp'          => 'Funcionários — emails @%s encontrados em bases de vazamentos e mercados da dark web.',
                'edu_third'        => 'Terceiros — credenciais de funcionários reutilizadas em serviços externos (SaaS, redes sociais, etc.).',
                'edu_cust'         => 'Clientes — usuários acessando seu domínio capturados por stealer logs.',
                'trust_kicker'     => 'Confiado por agências de governo · bancos · fintechs · forças de defesa',
                'footer_legal'     => 'Este relatório foi gerado a partir de dados de vazamentos publicamente disponíveis. Nenhuma credencial foi acessada ou descriptografada durante esta análise.',
                'footer_byline'    => 'by Nexa Cybersecurity',
                'footer_unsub'     => 'Este é um email transacional único. Política de privacidade',
            ],
        ];
        return $bundles[$lang] ?? $bundles['es'];
    }

    /**
     * Pick severity bucket. Returns assoc with key/color/icon/label/tldr.
     */
    private static function severity(int $total, array $S): array
    {
        if ($total === 0)        return ['key' => 'clean',    'color' => '#00B36A', 'icon' => '&#x2713;', 'label' => $S['severity_clean'],    'tldr' => $S['tldr_clean']];
        if ($total <= 50)        return ['key' => 'low',      'color' => '#FFEF34', 'icon' => '&#x26A0;', 'label' => $S['severity_low'],      'tldr' => $S['tldr_low']];
        if ($total <= 500)       return ['key' => 'mod',      'color' => '#FE7833', 'icon' => '&#x26A0;', 'label' => $S['severity_mod'],      'tldr' => $S['tldr_mod']];
        if ($total <= 5000)      return ['key' => 'high',     'color' => '#E5484D', 'icon' => '&#x26D4;', 'label' => $S['severity_high'],     'tldr' => $S['tldr_high']];
        return                          ['key' => 'critical', 'color' => '#E5484D', 'icon' => '&#x1F6A8;','label' => $S['severity_critical'], 'tldr' => $S['tldr_critical']];
    }

    /**
     * Render strength bars for any number of buckets in one cohesive section.
     * Used by exposureReportEmail. T1.4.
     *
     * @param array<string, array{data: array, label: string, sub: string, accent: string}> $blocks
     * @param array $S            i18n strings bundle
     * @param string $sevColor    severity color for the highlight ring
     */
    private static function renderStrengthSection(array $blocks, array $S, string $sevColor): string
    {
        // Filter blocks with no usable data
        $blocks = array_filter($blocks, static function ($b) {
            return (int) ($b['data']['total_pass'] ?? 0) > 0;
        });
        if (!$blocks) {
            return '';
        }

        $rows = '';
        foreach ($blocks as $key => $block) {
            $totalPass = (int) ($block['data']['total_pass'] ?? 0);
            $tw = $block['data']['too_weak'] ?? ['qty' => 0, 'perc' => 0];
            $wk = $block['data']['weak']     ?? ['qty' => 0, 'perc' => 0];
            $md = $block['data']['medium']   ?? ['qty' => 0, 'perc' => 0];
            $st = $block['data']['strong']   ?? ['qty' => 0, 'perc' => 0];
            $weakPct = round((float)($tw['perc'] ?? 0) + (float)($wk['perc'] ?? 0), 1);
            $accent = $block['accent'];
            $label = htmlspecialchars($block['label'], ENT_QUOTES, 'UTF-8');
            $sub   = htmlspecialchars($block['sub'],   ENT_QUOTES, 'UTF-8');

            $twPerc = (float)($tw['perc'] ?? 0);
            $wkPerc = (float)($wk['perc'] ?? 0);
            $mdPerc = (float)($md['perc'] ?? 0);
            $stPerc = (float)($st['perc'] ?? 0);

            $lblVw = htmlspecialchars($S['strength_lbl_vw'], ENT_QUOTES, 'UTF-8');
            $lblW  = htmlspecialchars($S['strength_lbl_w'],  ENT_QUOTES, 'UTF-8');
            $lblM  = htmlspecialchars($S['strength_lbl_m'],  ENT_QUOTES, 'UTF-8');
            $lblS  = htmlspecialchars($S['strength_lbl_s'],  ENT_QUOTES, 'UTF-8');
            $weakLbl = htmlspecialchars($S['strength_weak'], ENT_QUOTES, 'UTF-8');

            $rows .= <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="t-card-bg" bgcolor="#FFFFFF" style="margin:0 0 10px;background-color:#FFFFFF;border:1px solid #E5E7EB;border-left:3px solid {$accent};border-radius:10px;">
  <tr><td style="padding:14px 18px;">
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr>
        <td>
          <p style="margin:0 0 1px;font-size:9px;font-weight:700;color:{$accent};letter-spacing:0.12em;text-transform:uppercase;">{$label}</p>
          <p class="t-fg-faint" style="margin:0;font-size:11px;color:#6B7280;">{$totalPass} {$sub}</p>
        </td>
        <td align="right" valign="middle">
          <p style="margin:0;font-size:18px;font-weight:800;color:{$sevColor};line-height:1;">{$weakPct}%</p>
          <p class="t-fg-faint" style="margin:1px 0 0;font-size:8px;color:#6B7280;font-weight:600;">{$weakLbl}</p>
        </td>
      </tr>
    </table>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:10px;border-radius:99px;overflow:hidden;height:6px;">
      <tr>
        <td style="background:#E5484D;width:{$twPerc}%;height:6px;font-size:0;">&nbsp;</td>
        <td style="background:#FE7833;width:{$wkPerc}%;height:6px;font-size:0;">&nbsp;</td>
        <td style="background:#FFEF34;width:{$mdPerc}%;height:6px;font-size:0;">&nbsp;</td>
        <td style="background:#00B36A;width:{$stPerc}%;height:6px;font-size:0;">&nbsp;</td>
      </tr>
    </table>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-top:8px;">
      <tr>
        <td style="font-size:9px;color:#E5484D;font-weight:600;">{$lblVw} {$twPerc}%</td>
        <td style="font-size:9px;color:#FE7833;font-weight:600;">{$lblW} {$wkPerc}%</td>
        <td style="font-size:9px;color:#FFEF34;font-weight:600;">{$lblM} {$mdPerc}%</td>
        <td style="font-size:9px;color:#00B36A;font-weight:600;text-align:right;">{$lblS} {$stPerc}%</td>
      </tr>
    </table>
  </td></tr>
</table>
HTML;
        }

        $sectionTitle = htmlspecialchars($S['strength_title'], ENT_QUOTES, 'UTF-8');
        return <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
  <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:18px 22px 8px;background-color:#F8F9FA;border:1px solid rgba(255,239,52,.20);border-radius:12px;">
    <p class="t-yellow-text" style="margin:0 0 14px;font-size:9px;font-weight:700;color:#A88E00;text-transform:uppercase;letter-spacing:0.14em;">{$sectionTitle}</p>
    {$rows}
  </td></tr>
</table>
HTML;
    }

    public static function exposureReportEmail(
        string $domain,
        int $employees,
        int $thirdParties,
        int $customers,
        int $total,
        array $passStrength = [],
        int $searchedByCount = 0,
        string $signupUrl = '/register',
        ?array $apiResponse = null,
        string $lang = '',
        ?array $extras = null
    ): string {
        // T2.2 — auto-pick language by TLD if not given
        if ($lang === '' || !in_array($lang, ['es', 'en', 'pt'], true)) {
            $lang = self::reportLang($domain);
        }
        $S = self::reportStrings($lang);

        $eDomain = htmlspecialchars($domain, ENT_QUOTES, 'UTF-8');
        // Insert zero-width space after the dot to prevent Gmail auto-linking
        $eDomainSafe = str_replace('.', '.&#8203;', $eDomain);
        $fmtTotal = number_format($total);
        $fmtEmp   = number_format($employees);
        $fmtThird = number_format($thirdParties);
        $fmtCust  = number_format($customers);
        // T1.6 — UTM-tagged CTAs
        $ctaPrimaryUrl   = self::addUtm($signupUrl, 'cta_primary');
        $ctaSecondaryUrl = self::addUtm($signupUrl, 'cta_secondary_sales');
        $ctaPdfUrl       = self::addUtm($signupUrl, 'cta_pdf_download'); // PDF endpoint TBD in T3.3
        $eSignupP = htmlspecialchars($ctaPrimaryUrl,   ENT_QUOTES, 'UTF-8');
        $eSignupS = htmlspecialchars($ctaSecondaryUrl, ENT_QUOTES, 'UTF-8');
        $eSignupD = htmlspecialchars($ctaPdfUrl,       ENT_QUOTES, 'UTF-8');
        $date     = date('F j, Y');
        $year     = date('Y');

        // T1.8 — severity-driven copy + colors
        $sev      = self::severity($total, $S);
        $sevLabel = $sev['label'];
        $sevColor = $sev['color'];
        $sevIcon  = $sev['icon'];
        $tldr     = $sev['tldr'];

        // T1.1 — preheader (hidden inline text shown in inbox preview only)
        $preheaderText = $total === 0
            ? $S['preheader_clean']
            : sprintf($S['preheader_found'], $fmtTotal);
        $ePreheader = htmlspecialchars($preheaderText, ENT_QUOTES, 'UTF-8');

        // T1.5 — data-freshness chip (timestamp of report generation)
        $eFresh = htmlspecialchars($S['updated_chip'] . ': ' . date('H:i') . ' UTC', ENT_QUOTES, 'UTF-8');

        // Brand logo — referenced via CID; sender MUST attach the file.
        $brandLogo = self::brandLogoSrc();

        // ─── Tier-3 extras (all optional) ────────────────────────────────
        $pixelUrl    = (string) ($extras['pixel_url']       ?? '');
        $pdfUrl      = (string) ($extras['pdf_url']         ?? '');
        $sourceData  =          ($extras['source_breakdown'] ?? null);
        $samples     =          ($extras['sample_identities']?? null);
        $delta       =          ($extras['delta_since_last']?? null);

        // T3.7 — invisible 1×1 pixel at top of body
        $pixelHtml = $pixelUrl !== ''
            ? '<img src="' . htmlspecialchars($pixelUrl, ENT_QUOTES, 'UTF-8') . '" width="1" height="1" alt="" style="display:block;border:0;outline:0;width:1px;height:1px;opacity:0;" />'
            : '';

        // T3.3 — ghost CTA links to PDF if we have a URL
        if ($pdfUrl !== '') {
            $ctaPdfUrl = self::addUtm($pdfUrl, 'cta_pdf_email');
        } else {
            $ctaPdfUrl = self::addUtm($signupUrl, 'cta_pdf_fallback');
        }
        $eSignupD = htmlspecialchars($ctaPdfUrl, ENT_QUOTES, 'UTF-8');

        // T3.8 — delta chip (only if there's a previous snapshot)
        $deltaHtml = '';
        if (is_array($delta) && isset($delta['delta'])) {
            $diff = (int) $delta['delta'];
            $days = (int) ($delta['days_ago'] ?? 0);
            if ($diff !== 0 && $days > 0) {
                $arrow = $diff > 0 ? '↑' : '↓';
                $color = $diff > 0 ? '#E5484D' : '#00B36A';
                $abs   = number_format(abs($diff));
                $verb = $lang === 'pt' ? ($diff > 0 ? 'novas' : 'menos') :
                        ($lang === 'en' ? ($diff > 0 ? 'new' : 'fewer') :
                                         ($diff > 0 ? 'nuevas' : 'menos'));
                $sinceTpl = $lang === 'pt' ? 'desde %d dias atrás' :
                            ($lang === 'en' ? 'since %d days ago' : 'desde hace %d días');
                $deltaHtml = sprintf(
                    '<table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:8px auto 0;"><tr><td style="background:rgba(255,255,255,.04);border:1px solid %s;border-radius:999px;padding:4px 14px;"><p style="margin:0;font-size:10px;color:%s;font-weight:700;letter-spacing:.04em;">%s %s %s ' . sprintf($sinceTpl, $days) . '</p></td></tr></table>',
                    $color, $color, $arrow, $abs, $verb
                );
            }
        }

        // T3.1 — source breakdown card
        $sourcesHtml = '';
        if (is_array($sourceData) && !empty($sourceData['sample_size'])) {
            $b = $sourceData['buckets'];
            $tot = max(1, array_sum($b));
            $rowsSrc = '';
            $catLabels = [
                'es' => ['stealer_logs' => 'Stealer logs', 'databases' => 'Bases filtradas', 'combolists' => 'Combolists', 'other' => 'Otras fuentes'],
                'en' => ['stealer_logs' => 'Stealer logs', 'databases' => 'Leaked databases', 'combolists' => 'Combolists', 'other' => 'Other sources'],
                'pt' => ['stealer_logs' => 'Stealer logs', 'databases' => 'Bases vazadas',  'combolists' => 'Combolists', 'other' => 'Outras fontes'],
            ];
            $colors = ['stealer_logs' => '#E5484D', 'databases' => '#FE7833', 'combolists' => '#FFEF34', 'other' => '#5A5F70'];
            foreach ($b as $key => $cnt) {
                if ($cnt === 0) continue;
                $pct = round(($cnt / $tot) * 100, 1);
                $lbl = $catLabels[$lang][$key] ?? $key;
                $col = $colors[$key];
                $rowsSrc .= "<tr><td class=\"t-fg-mute\" style=\"padding:5px 0 5px 0;font-size:11px;color:#4B5563;\"><span style=\"display:inline-block;width:8px;height:8px;background:{$col};border-radius:50%;margin-right:8px;vertical-align:middle;\"></span>{$lbl}</td><td align=\"right\" class=\"t-fg\" style=\"font-size:11px;color:#1A1D27;font-weight:700;padding:5px 0;\">{$cnt} <span class=\"t-fg-faint\" style=\"color:#6B7280;font-weight:500;\">({$pct}%)</span></td></tr>";
            }
            $titleSrc = $lang === 'pt' ? 'FONTES (amostra recente)' : ($lang === 'en' ? 'SOURCES (recent sample)' : 'FUENTES (muestra reciente)');
            $sourcesHtml = <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
  <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:18px 22px;background-color:#F8F9FA;border-radius:12px;border:1px solid #E5E7EB;">
    <p style="margin:0 0 12px;font-size:9px;font-weight:700;color:#FE7833;text-transform:uppercase;letter-spacing:0.14em;">{$titleSrc}</p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">{$rowsSrc}</table>
  </td></tr>
</table>
HTML;
        }

        // T3.2 — sample masked identities
        $samplesHtml = '';
        if (is_array($samples) && !empty($samples)) {
            $titleSamp = $lang === 'pt' ? 'AMOSTRA DE CONTAS COMPROMETIDAS' : ($lang === 'en' ? 'SAMPLE COMPROMISED ACCOUNTS' : 'MUESTRA DE CUENTAS COMPROMETIDAS');
            $rowsSamp = '';
            foreach ($samples as $s) {
                $eS = htmlspecialchars($s, ENT_QUOTES, 'UTF-8');
                $rowsSamp .= "<tr><td class=\"t-card-bg\" bgcolor=\"#FFFFFF\" style=\"padding:6px 12px;background-color:#FFFFFF;border:1px solid #E5E7EB;border-radius:6px;font-family:'JetBrains Mono','Courier New',monospace;font-size:12px;color:#E5484D;font-weight:700;letter-spacing:.04em;\">{$eS}</td></tr>";
            }
            $samplesHtml = <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
  <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:18px 22px;background-color:#F8F9FA;border-radius:12px;border:1px solid rgba(229,72,77,.20);">
    <p style="margin:0 0 12px;font-size:9px;font-weight:700;color:#E5484D;text-transform:uppercase;letter-spacing:0.14em;">{$titleSamp}</p>
    <table role="presentation" cellpadding="6" cellspacing="0" border="0">{$rowsSamp}</table>
  </td></tr>
</table>
HTML;
        }

        // T1.4 — strength bars for ALL 3 buckets (LR returns blocks for each)
        // The legacy passStrength param is the employees block; if a full apiResponse
        // is provided, also render third + customer.
        $strengthBlocks = [
            'employees' => [
                'data'   => $passStrength,
                'label'  => $S['kpi_emp'],
                'sub'    => sprintf($S['kpi_emp_sub'], $eDomainSafe),
                'accent' => '#6D6090',
            ],
        ];
        if (is_array($apiResponse)) {
            if (!empty($apiResponse['third_parties_passwords'])) {
                $strengthBlocks['third'] = [
                    'data'   => $apiResponse['third_parties_passwords'],
                    'label'  => $S['kpi_third'],
                    'sub'    => $S['kpi_third_sub'],
                    'accent' => '#FE7833',
                ];
            }
            if (!empty($apiResponse['customer_passwords'])) {
                $strengthBlocks['customers'] = [
                    'data'   => $apiResponse['customer_passwords'],
                    'label'  => $S['kpi_cust'],
                    'sub'    => $S['kpi_cust_sub'],
                    'accent' => '#FFEF34',
                ];
            }
        }
        $passHtml = self::renderStrengthSection($strengthBlocks, $S, $sevColor);

        // Social proof
        $socialProof = '';
        if ($searchedByCount > 1) {
            $fmtSearched = number_format($searchedByCount);
            $sproofTxt = sprintf($S['social_proof'], $fmtSearched);
            $socialProof = <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:4px;">
  <tr><td align="center" class="t-soft-bg" bgcolor="#F8F9FA" style="padding:12px 16px;background-color:#F8F9FA;border:1px solid rgba(109,96,144,.25);border-radius:10px;">
    <p style="margin:0;font-size:11px;color:#6D6090;font-weight:600;">{$sproofTxt}</p>
  </td></tr>
</table>
HTML;
        }

        // Severity banner copy — stats-rich description (NOT the TL;DR action message).
        // Different per language; designed to set context, the TL;DR below provides
        // the next-step recommendation.
        if ($total === 0) {
            $sevDescTpl = $lang === 'pt'
                ? "Não detectamos credenciais expostas para <strong style=\"color:#E8EAF0;\">%s</strong> em nossa base de inteligência. Seu domínio aparenta estar limpo."
                : ($lang === 'en'
                    ? "We did not detect exposed credentials for <strong style=\"color:#E8EAF0;\">%s</strong> in our intelligence sources. Your domain appears clean."
                    : "No encontramos credenciales expuestas para <strong style=\"color:#E8EAF0;\">%s</strong> en nuestra base de inteligencia. Tu dominio aparenta estar limpio.");
            $sevDesc = sprintf($sevDescTpl, $eDomainSafe);
        } else {
            $sevDescTpl = $lang === 'pt'
                ? "Encontramos <strong style=\"color:%s;\">%s credenciais comprometidas</strong> vinculadas a <strong style=\"color:#E8EAF0;\">%s</strong> em bases de vazamentos, stealer logs e fontes da dark web."
                : ($lang === 'en'
                    ? "We found <strong style=\"color:%s;\">%s compromised credentials</strong> linked to <strong style=\"color:#E8EAF0;\">%s</strong> across leak databases, stealer logs and dark-web sources."
                    : "Encontramos <strong style=\"color:%s;\">%s credenciales comprometidas</strong> vinculadas a <strong style=\"color:#E8EAF0;\">%s</strong> en bases de filtraciones, stealer logs y fuentes de la dark web.");
            $sevDesc = sprintf($sevDescTpl, $sevColor, $fmtTotal, $eDomainSafe);
        }

        // T1.3 — TL;DR bar (1-sentence verdict directly below severity banner)
        $tldrHtml = '';
        if ($total > 0) {
            $tldrHtml = <<<HTML
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
  <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:14px 24px;background-color:#F8F9FA;border-radius:10px;border-left:3px solid {$sevColor};">
    <p class="t-fg" style="margin:0;font-size:13px;color:#1A1D27;line-height:1.5;font-weight:500;">{$tldr}</p>
  </td></tr>
</table>
HTML;
        }

        // T2.1 — "What to do next" actionable checklist
        $whatdoHtml = '';
        if ($total > 0) {
            $w1 = $S['whatdo_step1']; $w2 = $S['whatdo_step2'];
            $w3 = $S['whatdo_step3']; $w4 = $S['whatdo_step4'];
            $whatdoTitle = $S['whatdo_title'];
            $whatdoHtml = <<<HTML
<!-- WHAT TO DO NEXT -->
<table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
  <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:22px 24px;background-color:#F8F9FA;border-radius:12px;border:1px solid rgba(0,179,106,.18);">
    <p class="t-green-text" style="margin:0 0 14px;font-size:9px;font-weight:700;color:#00855A;text-transform:uppercase;letter-spacing:0.14em;">{$whatdoTitle}</p>
    <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
      <tr><td width="28" valign="top" style="padding:4px 0;"><span style="display:inline-block;width:20px;height:20px;background:#00B36A;color:#FFFFFF;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;">1</span></td>
          <td class="t-fg-mute" style="padding:4px 0 4px 10px;font-size:12px;color:#4B5563;line-height:1.55;">{$w1}</td></tr>
      <tr><td width="28" valign="top" style="padding:4px 0;"><span style="display:inline-block;width:20px;height:20px;background:#00B36A;color:#FFFFFF;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;">2</span></td>
          <td class="t-fg-mute" style="padding:4px 0 4px 10px;font-size:12px;color:#4B5563;line-height:1.55;">{$w2}</td></tr>
      <tr><td width="28" valign="top" style="padding:4px 0;"><span style="display:inline-block;width:20px;height:20px;background:#00B36A;color:#FFFFFF;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;">3</span></td>
          <td class="t-fg-mute" style="padding:4px 0 4px 10px;font-size:12px;color:#4B5563;line-height:1.55;">{$w3}</td></tr>
      <tr><td width="28" valign="top" style="padding:4px 0;"><span style="display:inline-block;width:20px;height:20px;background:#00B36A;color:#FFFFFF;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;">4</span></td>
          <td class="t-fg-mute" style="padding:4px 0 4px 10px;font-size:12px;color:#4B5563;line-height:1.55;">{$w4}</td></tr>
    </table>
  </td></tr>
</table>
HTML;
        }

        // T2.5 — i18n labels for the rendered shell
        $eBadge      = htmlspecialchars($S['badge'],          ENT_QUOTES, 'UTF-8');
        $eTitle      = htmlspecialchars($S['title'],          ENT_QUOTES, 'UTF-8');
        $eGenLabel   = htmlspecialchars($S['generated_on'],   ENT_QUOTES, 'UTF-8');
        $eHeroLabel  = htmlspecialchars($S['hero_label'],     ENT_QUOTES, 'UTF-8');
        $eKpiEmp     = htmlspecialchars($S['kpi_emp'],        ENT_QUOTES, 'UTF-8');
        $eKpiThird   = htmlspecialchars($S['kpi_third'],      ENT_QUOTES, 'UTF-8');
        $eKpiCust    = htmlspecialchars($S['kpi_cust'],       ENT_QUOTES, 'UTF-8');
        $eKpiEmpSub  = htmlspecialchars(sprintf($S['kpi_emp_sub'], $eDomainSafe), ENT_QUOTES, 'UTF-8');
        $eKpiThirdSub= htmlspecialchars($S['kpi_third_sub'],  ENT_QUOTES, 'UTF-8');
        $eKpiCustSub = htmlspecialchars($S['kpi_cust_sub'],   ENT_QUOTES, 'UTF-8');
        $eUnderstand = htmlspecialchars($S['understand'],     ENT_QUOTES, 'UTF-8');
        $eEduEmp     = sprintf($S['edu_emp'], $eDomainSafe);
        $eEduThird   = $S['edu_third'];
        $eEduCust    = $S['edu_cust'];
        $eCtaKicker  = htmlspecialchars($S['cta_kicker'],     ENT_QUOTES, 'UTF-8');
        $eCtaTitle   = htmlspecialchars($S['cta_title'],      ENT_QUOTES, 'UTF-8');
        $eCtaTitleHl = htmlspecialchars($S['cta_title_hl'],   ENT_QUOTES, 'UTF-8');
        $eCtaSub     = htmlspecialchars($S['cta_sub'],        ENT_QUOTES, 'UTF-8');
        $eCtaPrimary = htmlspecialchars($S['cta_primary'],    ENT_QUOTES, 'UTF-8');
        $eCtaSecondary = htmlspecialchars($S['cta_secondary'],ENT_QUOTES, 'UTF-8');
        $eCtaPdf     = htmlspecialchars($S['cta_pdf'],        ENT_QUOTES, 'UTF-8');
        $eTrust      = htmlspecialchars($S['trust_kicker'],   ENT_QUOTES, 'UTF-8');
        $eFootLegal  = htmlspecialchars($S['footer_legal'],   ENT_QUOTES, 'UTF-8');
        $eFootByline = htmlspecialchars($S['footer_byline'],  ENT_QUOTES, 'UTF-8');
        $eFootUnsub  = htmlspecialchars($S['footer_unsub'],   ENT_QUOTES, 'UTF-8');

        $fullHtml = <<<HTML
<!DOCTYPE html>
<html lang="{$lang}" xmlns="http://www.w3.org/1999/xhtml" xmlns:v="urn:schemas-microsoft-com:vml" xmlns:o="urn:schemas-microsoft-com:office:office">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta name="color-scheme" content="light dark">
<meta name="supported-color-schemes" content="light dark">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<title>{$eTitle}: {$eDomain}</title>
<!--[if mso]>
<noscript><xml><o:OfficeDocumentSettings><o:PixelsPerInch>96</o:PixelsPerInch></o:OfficeDocumentSettings></xml></noscript>
<style>table,td,th{font-family:Arial,'Helvetica Neue',Helvetica,sans-serif!important;color:#1A1D27!important}a{color:#0066CC!important}</style>
<![endif]-->
<style>
  :root { color-scheme: light dark; supported-color-schemes: light dark; }

  /* ─── Mobile responsive ─── */
  @media only screen and (max-width:620px) {
    .email-container { width:100% !important; }
    .content-pad { padding:24px 16px !important; }
    .header-pad { padding:32px 16px 24px !important; }
    .kpi-card { display:block !important; width:100% !important; margin-bottom:8px !important; }
    .hero-number { font-size:52px !important; }
    .module-cell { display:block !important; width:100% !important; padding:0 0 8px !important; }
  }
  body, table, td, p, a { -webkit-text-size-adjust:100%; -ms-text-size-adjust:100%; }
  body { margin:0 !important; padding:0 !important; width:100% !important; }

  /* ─── DARK THEME OVERRIDES ─── (applies when client supports prefers-color-scheme) */
  @media (prefers-color-scheme: dark) {
    .t-page-bg { background-color:#0F1117 !important; }
    .t-card-bg { background-color:#161822 !important; }
    .t-soft-bg { background-color:#1A1D27 !important; }
    .t-fg      { color:#E8EAF0 !important; }
    .t-fg-mute { color:#8B90A0 !important; }
    .t-fg-faint{ color:#5A5F70 !important; }
    .t-border  { border-color:rgba(255,255,255,0.06) !important; }
    .t-domain-chip { background-color:#1A1D27 !important; border-color:rgba(255,255,255,0.08) !important; }
    .t-edu-bg { background-color:#1A1D27 !important; }
    .t-strength-card { background-color:#0F1117 !important; }
    /* Yellow & green tones swap to brighter brand variants on dark */
    .t-yellow-text { color:#FFEF34 !important; }
    .t-green-text  { color:#00B36A !important; }
  }

  /* Outlook.com / Gmail mobile dark mode hooks (target via [data-ogsc] / etc) */
  [data-ogsc] .t-page-bg { background-color:#0F1117 !important; }
  [data-ogsc] .t-card-bg { background-color:#161822 !important; }
  [data-ogsc] .t-soft-bg { background-color:#1A1D27 !important; }
  [data-ogsc] .t-fg      { color:#E8EAF0 !important; }
  [data-ogsc] .t-fg-mute { color:#8B90A0 !important; }
  [data-ogsc] .t-fg-faint{ color:#5A5F70 !important; }
  [data-ogsc] .t-yellow-text { color:#FFEF34 !important; }
  [data-ogsc] .t-green-text  { color:#00B36A !important; }
</style>
</head>
<body class="body t-page-bg" bgcolor="#F5F5F2" style="margin:0;padding:0;background-color:#F5F5F2;font-family:'Space Grotesk',Arial,'Helvetica Neue',Helvetica,sans-serif;-webkit-font-smoothing:antialiased;">

<!-- T1.1 — PREHEADER (inbox preview only) -->
<div style="display:none !important; visibility:hidden; opacity:0; color:transparent; height:0; width:0; overflow:hidden; mso-hide:all; max-height:0; max-width:0; font-size:1px; line-height:1px;">{$ePreheader}&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;&zwnj;&nbsp;</div>

<!-- T3.7 — open-tracking pixel (1×1 transparent gif) -->
{$pixelHtml}

<!-- OUTER WRAPPER -->
<table role="presentation" class="t-page-bg" width="100%" cellpadding="0" cellspacing="0" border="0" bgcolor="#F5F5F2" style="background-color:#F5F5F2;">
<tr><td align="center" class="t-page-bg" bgcolor="#F5F5F2" style="padding:40px 16px;background-color:#F5F5F2;">

<!-- ═══ EMAIL CONTAINER ═══ -->
<table role="presentation" class="email-container t-card-bg" width="600" cellpadding="0" cellspacing="0" border="0" bgcolor="#FFFFFF" style="max-width:600px;width:100%;background-color:#FFFFFF;border-radius:16px;overflow:hidden;border:1px solid #E5E7EB;box-shadow:0 4px 24px rgba(0,0,0,0.06);">

  <!-- ═══ TOP ACCENT BAR ═══ -->
  <tr>
    <td style="height:3px;background:linear-gradient(90deg,#FFEF34 0%,#007878 50%,#5C1A8D 100%);font-size:0;line-height:0;">&nbsp;</td>
  </tr>

  <!-- ═══ HEADER ═══ -->
  <tr>
    <td class="header-pad t-card-bg" bgcolor="#FFFFFF" style="background-color:#FFFFFF;padding:40px 36px 32px;text-align:center;">
      <!-- Logo (inline base64 — renders in every client without 'show images') -->
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 24px;">
        <tr>
          <td>
            <img src="{$brandLogo}"
                 alt="Nx CyberSight"
                 width="240" height="29"
                 style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:240px;height:29px;max-width:240px;">
          </td>
        </tr>
      </table>
      <!-- Badge -->
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 20px;">
        <tr>
          <td style="background:rgba(255,239,52,.1);border:1px solid rgba(255,239,52,.2);border-radius:999px;padding:6px 18px;">
            <p style="margin:0;font-size:9px;font-weight:700;color:#FFEF34;letter-spacing:0.16em;text-transform:uppercase;">{$eBadge}</p>
          </td>
        </tr>
      </table>
      <!-- Title -->
      <h1 class="t-fg" style="margin:0 0 12px;font-size:28px;font-weight:700;color:#1A1D27;line-height:1.2;letter-spacing:-0.03em;">{$eTitle}</h1>
      <!-- Domain chip -->
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 8px;">
        <tr>
          <td class="t-domain-chip" style="background:#F8F9FA;border:1px solid #E5E7EB;border-radius:8px;padding:10px 24px;">
            <p class="t-fg" style="margin:0;font-size:16px;font-weight:700;color:#1A1D27;letter-spacing:0.01em;font-family:'JetBrains Mono','Courier New',monospace;">{$eDomainSafe}</p>
          </td>
        </tr>
      </table>
      <!-- T1.5 — freshness chip -->
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:10px auto 0;">
        <tr>
          <td style="background:rgba(0,179,106,.10);border:1px solid rgba(0,179,106,.3);border-radius:999px;padding:4px 14px;">
            <p class="t-green-text" style="margin:0;font-size:10px;font-weight:600;color:#00855A;letter-spacing:0.04em;">● {$eFresh}</p>
          </td>
        </tr>
      </table>
      <!-- T3.8 — delta-since-last-snapshot chip (only if previous data exists) -->
      {$deltaHtml}
      <p class="t-fg-faint" style="margin:8px 0 0;font-size:11px;color:#6B7280;font-weight:500;">{$eGenLabel} {$date}</p>
    </td>
  </tr>

  <!-- ═══ SEVERITY BANNER (T2.5: role=alert for screen readers) ═══ -->
  <tr>
    <td style="padding:20px 28px 0;" class="t-card-bg" bgcolor="#FFFFFF">
      <table role="alert" aria-live="polite" width="100%" cellpadding="0" cellspacing="0" border="0" class="t-soft-bg" bgcolor="#F8F9FA" style="background-color:#F8F9FA;border-radius:12px;border-left:4px solid {$sevColor};overflow:hidden;">
        <tr>
          <td style="padding:18px 24px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
              <tr>
                <td>
                  <p style="margin:0 0 4px;font-size:10px;font-weight:700;color:{$sevColor};letter-spacing:0.12em;text-transform:uppercase;"><span aria-hidden="true">{$sevIcon}</span> {$sevLabel}</p>
                  <p class="t-fg-mute" style="margin:0;font-size:13px;color:#4B5563;line-height:1.6;">{$sevDesc}</p>
                </td>
              </tr>
            </table>
          </td>
        </tr>
      </table>
    </td>
  </tr>

  <!-- ═══ TL;DR (T1.3) ═══ -->
  <tr>
    <td style="padding:14px 28px 0;">
      {$tldrHtml}
    </td>
  </tr>

  <!-- ═══ MAIN CONTENT ═══ -->
  <tr>
    <td class="content-pad" style="padding:28px 28px 8px;">

      <!-- ── BIG NUMBER (always dark for brand pop) ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
        <tr><td align="center" bgcolor="#0F1117" style="padding:28px 20px;background-color:#0F1117;border-radius:14px;border:1px solid rgba(255,239,52,.24);">
          <p class="hero-number" style="margin:0;font-size:60px;font-weight:800;color:#FFEF34;line-height:1;letter-spacing:-0.04em;font-family:'Space Grotesk',Arial,sans-serif;">{$fmtTotal}</p>
          <p style="margin:8px 0 0;font-size:10px;font-weight:700;color:#8B90A0;text-transform:uppercase;letter-spacing:0.14em;">{$eHeroLabel}</p>
        </td></tr>
      </table>

      <!-- ── KPI BREAKDOWN: 3 cards (theme-adaptive) ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
        <tr>
          <!-- Employees — Violet #6D6090 -->
          <td class="kpi-card" width="33%" align="center" style="padding:0 4px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="t-soft-bg" bgcolor="#F8F9FA" style="background-color:#F8F9FA;border-radius:12px;border:1px solid #E5E7EB;border-top:3px solid #6D6090;">
              <tr><td align="center" style="padding:20px 8px 16px;">
                <p class="t-fg-faint" style="margin:0;font-size:9px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">{$eKpiEmp}</p>
                <p style="margin:6px 0 0;font-size:32px;font-weight:800;color:#6D6090;line-height:1;letter-spacing:-0.02em;">{$fmtEmp}</p>
                <p class="t-fg-mute" style="margin:8px 0 0;font-size:10px;color:#4B5563;">{$eKpiEmpSub}</p>
              </td></tr>
            </table>
          </td>
          <!-- Third parties — Orange #FE7833 -->
          <td class="kpi-card" width="33%" align="center" style="padding:0 4px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="t-soft-bg" bgcolor="#F8F9FA" style="background-color:#F8F9FA;border-radius:12px;border:1px solid #E5E7EB;border-top:3px solid #FE7833;">
              <tr><td align="center" style="padding:20px 8px 16px;">
                <p class="t-fg-faint" style="margin:0;font-size:9px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">{$eKpiThird}</p>
                <p style="margin:6px 0 0;font-size:32px;font-weight:800;color:#FE7833;line-height:1;letter-spacing:-0.02em;">{$fmtThird}</p>
                <p class="t-fg-mute" style="margin:8px 0 0;font-size:10px;color:#4B5563;">{$eKpiThirdSub}</p>
              </td></tr>
            </table>
          </td>
          <!-- Customers — Yellow accent (with darker text on light) -->
          <td class="kpi-card" width="33%" align="center" style="padding:0 4px;">
            <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" class="t-soft-bg" bgcolor="#F8F9FA" style="background-color:#F8F9FA;border-radius:12px;border:1px solid #E5E7EB;border-top:3px solid #FFEF34;">
              <tr><td align="center" style="padding:20px 8px 16px;">
                <p class="t-fg-faint" style="margin:0;font-size:9px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">{$eKpiCust}</p>
                <p class="t-yellow-text" style="margin:6px 0 0;font-size:32px;font-weight:800;color:#A88E00;line-height:1;letter-spacing:-0.02em;">{$fmtCust}</p>
                <p class="t-fg-mute" style="margin:8px 0 0;font-size:10px;color:#4B5563;">{$eKpiCustSub}</p>
              </td></tr>
            </table>
          </td>
        </tr>
      </table>

      {$passHtml}

      {$samplesHtml}

      {$sourcesHtml}

      {$socialProof}

      {$whatdoHtml}

      <!-- ── WHAT YOU'RE MISSING ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;margin-top:20px;">
        <tr><td style="padding:24px 24px 20px;background:#1A1D27;border-radius:12px;border:1px solid rgba(255,255,255,.04);">
          <p style="margin:0 0 4px;font-size:9px;font-weight:700;color:#FFEF34;text-transform:uppercase;letter-spacing:0.14em;">LO QUE TU REPORTE GRATUITO NO MUESTRA</p>
          <p style="margin:0 0 18px;font-size:12px;color:#5A5F70;">Accede a la versi&oacute;n completa para ver todo el panorama</p>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
              <td class="module-cell" width="50%" valign="top" style="padding:0 6px 10px 0;">
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#0F1117;border-radius:10px;border:1px solid rgba(255,239,52,.08);">
                  <tr><td style="padding:16px 18px;">
                    <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
                      <td style="width:28px;height:28px;background:rgba(255,239,52,.12);border-radius:8px;text-align:center;line-height:28px;font-size:12px;color:#FFEF34;vertical-align:middle;">&#x1F511;</td>
                      <td style="padding-left:10px;font-size:11px;color:#FFEF34;font-weight:700;">Credenciales Reales</td>
                    </tr></table>
                    <p style="margin:8px 0 0;font-size:11px;color:#5A5F70;line-height:1.5;">Usuarios, contrase&ntilde;as y fuentes de cada filtraci&oacute;n</p>
                  </td></tr>
                </table>
              </td>
              <td class="module-cell" width="50%" valign="top" style="padding:0 0 10px 6px;">
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#0F1117;border-radius:10px;border:1px solid rgba(0,120,120,.12);">
                  <tr><td style="padding:16px 18px;">
                    <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
                      <td style="width:28px;height:28px;background:rgba(0,120,120,.15);border-radius:8px;text-align:center;line-height:28px;font-size:12px;color:#0D8A78;vertical-align:middle;">&#x2623;</td>
                      <td style="padding-left:10px;font-size:11px;color:#0D8A78;font-weight:700;">Acceso a Stealer Logs</td>
                    </tr></table>
                    <p style="margin:8px 0 0;font-size:11px;color:#5A5F70;line-height:1.5;">Tokens de sesi&oacute;n, cookies, contrase&ntilde;as guardadas y contexto del dispositivo</p>
                  </td></tr>
                </table>
              </td>
            </tr>
            <tr>
              <td class="module-cell" width="50%" valign="top" style="padding:0 6px 10px 0;">
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#0F1117;border-radius:10px;border:1px solid rgba(59,130,246,.1);">
                  <tr><td style="padding:16px 18px;">
                    <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
                      <td style="width:28px;height:28px;background:rgba(59,130,246,.12);border-radius:8px;text-align:center;line-height:28px;font-size:12px;color:#3B82F6;vertical-align:middle;">&#x1F4C8;</td>
                      <td style="padding-left:10px;font-size:11px;color:#3B82F6;font-weight:700;">Reportes Ejecutivos</td>
                    </tr></table>
                    <p style="margin:8px 0 0;font-size:11px;color:#5A5F70;line-height:1.5;">Reportes PDF con tendencias, scoring de riesgo y gu&iacute;a de remediaci&oacute;n</p>
                  </td></tr>
                </table>
              </td>
              <td class="module-cell" width="50%" valign="top" style="padding:0 0 10px 6px;">
                <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="background:#0F1117;border-radius:10px;border:1px solid rgba(254,120,51,.1);">
                  <tr><td style="padding:16px 18px;">
                    <table role="presentation" cellpadding="0" cellspacing="0" border="0"><tr>
                      <td style="width:28px;height:28px;background:rgba(254,120,51,.12);border-radius:8px;text-align:center;line-height:28px;font-size:12px;color:#FE7833;vertical-align:middle;">&#x1F4E1;</td>
                      <td style="padding-left:10px;font-size:11px;color:#FE7833;font-weight:700;">Monitoreo 24/7</td>
                    </tr></table>
                    <p style="margin:8px 0 0;font-size:11px;color:#5A5F70;line-height:1.5;">Alertas instant&aacute;neas cuando aparecen nuevos compromisos en tus dominios</p>
                  </td></tr>
                </table>
              </td>
            </tr>
          </table>
        </td></tr>
      </table>

      <!-- ── UNDERSTANDING YOUR RESULTS ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:24px;">
        <tr><td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:20px 24px;background-color:#F8F9FA;border-radius:12px;border:1px solid #E5E7EB;">
          <p style="margin:0 0 14px;font-size:9px;font-weight:700;color:#007878;text-transform:uppercase;letter-spacing:0.14em;">{$eUnderstand}</p>
          <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0">
            <tr>
              <td width="28" valign="top" style="padding:5px 0;"><span aria-hidden="true" style="display:inline-block;width:20px;height:20px;background:#6D6090;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;color:#fff;">E</span></td>
              <td class="t-fg-mute" style="padding:5px 0 5px 10px;font-size:12px;color:#4B5563;line-height:1.6;">{$eEduEmp}</td>
            </tr>
            <tr>
              <td width="28" valign="top" style="padding:5px 0;"><span aria-hidden="true" style="display:inline-block;width:20px;height:20px;background:#FE7833;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;color:#fff;">T</span></td>
              <td class="t-fg-mute" style="padding:5px 0 5px 10px;font-size:12px;color:#4B5563;line-height:1.6;">{$eEduThird}</td>
            </tr>
            <tr>
              <td width="28" valign="top" style="padding:5px 0;"><span aria-hidden="true" style="display:inline-block;width:20px;height:20px;background:#FFEF34;border-radius:50%;text-align:center;line-height:20px;font-size:10px;font-weight:800;color:#0F1117;">C</span></td>
              <td class="t-fg-mute" style="padding:5px 0 5px 10px;font-size:12px;color:#4B5563;line-height:1.6;">{$eEduCust}</td>
            </tr>
          </table>
        </td></tr>
      </table>

      <!-- ═══ CTA BLOCK (always dark for brand pop in both themes) ═══ -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:28px;">
        <tr><td bgcolor="#0F1117" style="background-color:#0F1117;border-radius:14px;padding:36px 32px 32px;text-align:center;border:1px solid rgba(255,239,52,.24);">
          <p style="margin:0 0 4px;font-size:9px;font-weight:700;color:#8B90A0;text-transform:uppercase;letter-spacing:0.14em;">{$eCtaKicker}</p>
          <p style="margin:0 0 8px;font-size:22px;font-weight:700;color:#E8EAF0;line-height:1.3;letter-spacing:-0.02em;">{$eCtaTitle} <span style="color:#FFEF34;">{$eCtaTitleHl}.</span></p>
          <p style="margin:0 0 24px;font-size:13px;color:#A0A4B0;line-height:1.7;max-width:420px;">{$eCtaSub}</p>
          <!-- Primary CTA -->
          <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 12px;">
            <tr>
              <td style="background:#FFEF34;border-radius:999px;text-align:center;">
                <!--[if mso]><v:roundrect xmlns:v="urn:schemas-microsoft-com:vml" href="{$eSignupP}" style="height:50px;v-text-anchor:middle;width:320px;" arcsize="50%" fillcolor="#FFEF34" stroke="f"><center style="color:#0F1117;font-family:Arial,sans-serif;font-size:15px;font-weight:bold;">{$eCtaPrimary}</center></v:roundrect><![endif]-->
                <a href="{$eSignupP}" target="_blank" style="display:inline-block;background:#FFEF34;color:#0F1117;font-family:'Space Grotesk',Arial,sans-serif;font-size:15px;font-weight:700;text-decoration:none;padding:15px 48px;border-radius:999px;line-height:1.4;letter-spacing:0.01em;mso-hide:all;">{$eCtaPrimary}</a>
              </td>
            </tr>
          </table>
          <!-- Secondary CTA (outline button) -->
          <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 8px;">
            <tr>
              <td style="border:1px solid rgba(255,239,52,.4);border-radius:999px;text-align:center;background:transparent;">
                <a href="{$eSignupS}" target="_blank" style="display:inline-block;color:#FFEF34;font-family:'Space Grotesk',Arial,sans-serif;font-size:13px;font-weight:600;text-decoration:none;padding:11px 32px;border-radius:999px;line-height:1.4;">{$eCtaSecondary}</a>
              </td>
            </tr>
          </table>
          <!-- Ghost link (PDF — wired in T3.3) -->
          <p style="margin:14px 0 0;font-size:11px;color:#5A5F70;"><a href="{$eSignupD}" target="_blank" style="color:#5A5F70;text-decoration:underline;">{$eCtaPdf}</a></p>
        </td></tr>
      </table>

      <!-- ── TRUST / STATS BAR ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:8px;">
        <tr>
          <td width="25%" align="center" style="padding:16px 4px;">
            <p class="t-yellow-text" style="margin:0;font-size:20px;font-weight:800;color:#A88E00;line-height:1;letter-spacing:-0.02em;font-family:'Space Grotesk',Arial,sans-serif;">34B+</p>
            <p class="t-fg-faint" style="margin:4px 0 0;font-size:8px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">Credenciales<br>Indexadas</p>
          </td>
          <td width="25%" align="center" style="padding:16px 4px;">
            <p style="margin:0;font-size:20px;font-weight:800;color:#007878;line-height:1;letter-spacing:-0.02em;font-family:'Space Grotesk',Arial,sans-serif;">4.5B+</p>
            <p class="t-fg-faint" style="margin:4px 0 0;font-size:8px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">Infecciones<br>Detectadas</p>
          </td>
          <td width="25%" align="center" style="padding:16px 4px;">
            <p class="t-fg" style="margin:0;font-size:20px;font-weight:800;color:#1A1D27;line-height:1;letter-spacing:-0.02em;font-family:'Space Grotesk',Arial,sans-serif;">21</p>
            <p class="t-fg-faint" style="margin:4px 0 0;font-size:8px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">Pa&iacute;ses<br>LATAM</p>
          </td>
          <td width="25%" align="center" style="padding:16px 4px;">
            <p style="margin:0;font-size:20px;font-weight:800;color:#6D6090;line-height:1;letter-spacing:-0.02em;font-family:'Space Grotesk',Arial,sans-serif;">24/7</p>
            <p class="t-fg-faint" style="margin:4px 0 0;font-size:8px;color:#6B7280;font-weight:700;text-transform:uppercase;letter-spacing:0.1em;">Monitoreo<br>Continuo</p>
          </td>
        </tr>
      </table>

      <!-- ── TRUSTED BY ── -->
      <table role="presentation" width="100%" cellpadding="0" cellspacing="0" border="0" style="margin-bottom:4px;">
        <tr><td align="center" style="padding:12px 0 4px;">
          <p class="t-fg-faint" style="margin:0;font-size:8px;font-weight:700;color:#6B7280;text-transform:uppercase;letter-spacing:0.16em;">{$eTrust}</p>
        </td></tr>
      </table>

    </td>
  </tr>

  <!-- ═══ FOOTER ═══ -->
  <tr>
    <td class="t-soft-bg" bgcolor="#F8F9FA" style="padding:24px 36px 28px;text-align:center;background-color:#F8F9FA;border-top:1px solid #E5E7EB;">
      <!-- Accent line -->
      <table role="presentation" width="60" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 16px;">
        <tr><td style="height:2px;background:linear-gradient(90deg,#FFEF34,#007878);border-radius:1px;font-size:0;">&nbsp;</td></tr>
      </table>
      <!-- Footer logo (smaller; same inline base64) -->
      <table role="presentation" cellpadding="0" cellspacing="0" border="0" style="margin:0 auto 6px;">
        <tr>
          <td>
            <img src="{$brandLogo}"
                 alt="Nx CyberSight"
                 width="180" height="22"
                 style="display:block;border:0;outline:none;text-decoration:none;-ms-interpolation-mode:bicubic;width:180px;height:22px;max-width:180px;">
          </td>
        </tr>
      </table>
      <p class="t-fg-faint" style="margin:0 0 4px;font-size:9px;font-weight:600;color:#6B7280;letter-spacing:0.1em;text-transform:uppercase;">{$eFootByline}</p>
      <p class="t-fg-mute" style="margin:12px 0 8px;font-size:10px;color:#4B5563;line-height:1.6;">{$eFootLegal}</p>
      <p class="t-fg-mute" style="margin:0 0 4px;font-size:10px;color:#4B5563;"><a href="https://wearenexa.com/privacy" target="_blank" class="t-fg-mute" style="color:#4B5563;text-decoration:underline;">{$eFootUnsub}</a></p>
      <p class="t-fg-faint" style="margin:0;font-size:10px;color:#9CA3AF;">&copy; {$year} Nexa &middot; wearenexa.com</p>
    </td>
  </tr>

</table>
<!-- End email container -->

</td></tr>
</table>
<!-- End outer wrapper -->

</body>
</html>
HTML;

        return $fullHtml;
    }

    /**
     * Free exposure report — plain text fallback.
     */
    public static function exposureReportEmailPlain(
        string $domain,
        int $employees,
        int $thirdParties,
        int $customers,
        int $total,
        string $signupUrl = '/register',
        ?array $apiResponse = null,
        string $lang = ''
    ): string {
        if ($lang === '' || !in_array($lang, ['es', 'en', 'pt'], true)) {
            $lang = self::reportLang($domain);
        }
        $S = self::reportStrings($lang);
        $sev = self::severity($total, $S);

        $titleLine = strtoupper($S['title']);
        $genLabel  = $S['generated_on'];

        $headerKey = ($total === 0) ? 'severity_clean' : 'severity_' . $sev['key'];
        $sevLabel  = $S[$headerKey] ?? $sev['label'];
        $tldr      = $sev['tldr'];

        $sep1 = str_repeat('=', 50);
        $sep2 = str_repeat('-', 50);

        $text  = "Nx CyberSight — {$titleLine}\n";
        $text .= "{$sep1}\n\n";
        $text .= "Domain:    {$domain}\n";
        $text .= "{$genLabel}: " . date('F j, Y') . "\n";
        $text .= "Lang:      " . strtoupper($lang) . "\n\n";

        // Severity banner
        $text .= ">> " . str_repeat('=', 46) . "\n";
        $text .= ">> {$sevLabel}\n";
        if ($total > 0) {
            $text .= ">> {$tldr}\n";
        }
        $text .= ">> " . str_repeat('=', 46) . "\n\n";

        if ($total === 0) {
            $text .= sprintf($S['preheader_clean']) . "\n\n";
        } else {
            $text .= sprintf($S['preheader_found'], number_format($total)) . "\n\n";

            // Breakdown
            $text .= "BREAKDOWN\n";
            $text .= "{$sep2}\n";
            $text .= sprintf("  %-14s %s\n", $S['kpi_emp']    . ':', number_format($employees));
            $text .= sprintf("  %-14s %s\n", $S['kpi_third']  . ':', number_format($thirdParties));
            $text .= sprintf("  %-14s %s\n", $S['kpi_cust']   . ':', number_format($customers));
            $text .= "{$sep2}\n";
            $text .= sprintf("  %-14s %s\n\n", 'TOTAL:', number_format($total));

            // Per-bucket strength (T1.4 + T1.9 parity with HTML)
            if (is_array($apiResponse)) {
                $bucketBlocks = [
                    $S['kpi_emp']   => $apiResponse['employee_passwords']      ?? null,
                    $S['kpi_third'] => $apiResponse['third_parties_passwords'] ?? null,
                    $S['kpi_cust']  => $apiResponse['customer_passwords']      ?? null,
                ];
                $hasAny = false;
                foreach ($bucketBlocks as $b) {
                    if (is_array($b) && (int)($b['total_pass'] ?? 0) > 0) { $hasAny = true; break; }
                }
                if ($hasAny) {
                    $text .= strtoupper($S['strength_title']) . "\n";
                    $text .= "{$sep2}\n";
                    foreach ($bucketBlocks as $bLabel => $b) {
                        if (!is_array($b) || (int)($b['total_pass'] ?? 0) === 0) continue;
                        $tw = (float)($b['too_weak']['perc'] ?? 0);
                        $wk = (float)($b['weak']['perc']     ?? 0);
                        $md = (float)($b['medium']['perc']   ?? 0);
                        $st = (float)($b['strong']['perc']   ?? 0);
                        $text .= sprintf("  %s (%d %s)\n", $bLabel, (int)$b['total_pass'], strtolower($S['kpi_emp_sub']));
                        $text .= sprintf("    %s: %s%%  |  %s: %s%%  |  %s: %s%%  |  %s: %s%%\n\n",
                            $S['strength_lbl_vw'], $tw,
                            $S['strength_lbl_w'],  $wk,
                            $S['strength_lbl_m'],  $md,
                            $S['strength_lbl_s'],  $st
                        );
                    }
                }
            }

            // What to do next (T2.1 in plain)
            $text .= strtoupper($S['whatdo_title']) . "\n";
            $text .= "{$sep2}\n";
            $text .= "  1. {$S['whatdo_step1']}\n";
            $text .= "  2. {$S['whatdo_step2']}\n";
            $text .= "  3. {$S['whatdo_step3']}\n";
            $text .= "  4. {$S['whatdo_step4']}\n\n";
        }

        // Dual CTA (T1.7 + T1.6 UTM-tagged)
        $text .= "{$sep2}\n";
        $text .= strtoupper($S['cta_title'] . ' ' . $S['cta_title_hl']) . "\n\n";
        $text .= "  → {$S['cta_primary']}: " . self::addUtm($signupUrl, 'cta_primary_text') . "\n";
        $text .= "  → {$S['cta_secondary']}: " . self::addUtm($signupUrl, 'cta_secondary_text') . "\n\n";

        $text .= "{$sep2}\n";
        $text .= "{$S['footer_legal']}\n\n";
        $text .= "Nx CyberSight — wearenexa.com\n";

        return $text;
    }
}
