<?php
/**
 * FLEXIA / Antara — Login page (server-rendered).
 *
 * - Bootstraps the encrypted store, session and auth_config.
 * - If the user is already logged in, redirects to the main app.
 * - Renders the existing visual template with conditional blocks driven by
 *   auth_config (allow_password_login, allow_user_registration, allow_webauthn).
 * - Embeds a public config JSON + CSRF token for the JS layer to consume.
 */

require_once __DIR__ . '/../includes/install_public.php';
antara_install_redirect_if_active();

require __DIR__ . '/../core/auth/bootstrap_auth.php';

try {
    $cfg = AntaraStore::configRead();
} catch (\RuntimeException $e) {
    require_once __DIR__ . '/../core/auth/vault_config_recovery.php';
    antara_vault_config_recovery_respond_and_exit($e);
}

$reasonEarly = isset($_GET['reason']) && is_string($_GET['reason']) ? $_GET['reason'] : '';
if ($reasonEarly === 'logout' && empty($cfg['login_required']) && !AntaraSession::isLoggedIn()) {
    $script = $_SERVER['SCRIPT_NAME'] ?? '/login/index.php';
    $base = rtrim(str_replace('\\', '/', dirname(dirname($script))), '/');
    $home = ($base === '' ? '' : $base) . '/index.php';
    header('Location: ' . $home, true, 302);
    exit;
}

if (AntaraSession::isLoggedIn()) {
    $next = isset($_GET['next']) && is_string($_GET['next']) ? $_GET['next'] : null;
    if (!$next || !preg_match('#^/[^/\\\\]#', $next)) {
        $script = $_SERVER['SCRIPT_NAME'] ?? '/login/index.php';
        $base = rtrim(str_replace('\\', '/', dirname(dirname($script))), '/');
        $next = ($base === '' ? '' : $base) . '/index.php';
    }
    header('Location: ' . $next, true, 302);
    exit;
}

$publicCfg = [
    'login_required'          => (bool)$cfg['login_required'],
    'allow_user_registration' => (bool)$cfg['allow_user_registration'],
    'allow_webauthn'          => (bool)$cfg['allow_webauthn'],
    'allow_password_login'    => (bool)$cfg['allow_password_login'],
    'rp_id'                   => AntaraWebAuthn::rpId($cfg),
    'rp_name'                 => AntaraWebAuthn::rpName($cfg),
];
$csrfToken = AntaraCsrf::token();

$loginScript = $_SERVER['SCRIPT_NAME'] ?? '/login/index.php';
$projectBase = rtrim(str_replace('\\', '/', dirname(dirname($loginScript))), '/');

function antara_asset_url(string $rel, string $base): string {
    $relClean = ltrim($rel, '/');
    $full = dirname(dirname(__DIR__)) . DIRECTORY_SEPARATOR . str_replace('/', DIRECTORY_SEPARATOR, $relClean);
    $v = @filemtime($full) ?: time();
    return ($base === '' ? '' : $base) . '/' . $relClean . '?v=' . rawurlencode((string)$v);
}

$reasonMessages = [
    'login_required'  => 'Debes iniciar sesión para continuar.',
    'expired'         => 'Tu sesión ha expirado.',
    'blocked'         => 'Tu cuenta ha sido bloqueada o desactivada.',
    'account_removed' => 'La cuenta asociada ya no existe.',
    'logout'          => 'Has cerrado sesión.',
];
$reason = isset($_GET['reason']) && is_string($_GET['reason']) ? $_GET['reason'] : '';
$reasonText = $reasonMessages[$reason] ?? '';

$apiUrl = ($projectBase === '' ? '' : $projectBase) . '/core/auth/api.php';
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8" />
  <meta name="viewport" content="width=device-width, initial-scale=1, viewport-fit=cover" />
  <meta name="color-scheme" content="dark" />
  <title><?php echo htmlspecialchars($publicCfg['rp_name']); ?> — Acceso seguro</title>
  <meta name="referrer" content="same-origin" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(antara_asset_url('assets/auth/login.css', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" />
  <link rel="stylesheet" href="<?php echo htmlspecialchars(antara_asset_url('assets/css/tooltips.css', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" />
</head>
<body>
  <div class="bg" aria-hidden="true">
    <div class="bg__grid"></div>
    <div class="bg__silhouettes"></div>
    <div id="particles"></div>
  </div>

  <main class="stage">
    <div class="scene scene--entrance" id="scene">
      <section class="panel panel--animating-entrance" id="panel" aria-labelledby="brand-name">
        <header class="panel__meta">
          <div>
            <div class="sys-tag">SYS-7</div>
            <div class="sys-bar" aria-hidden="true"><div class="sys-bar__fill"></div></div>
          </div>
          <div class="clock-block">
            <div class="clock-time" id="clock-time">00:00</div>
            <div class="clock-date" id="clock-date">—</div>
            <div class="globe-icon" aria-hidden="true">
              <svg viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.2">
                <circle cx="12" cy="12" r="10" stroke="#00f2ff" opacity="0.6" />
                <path d="M2 12h20M12 2a15 15 0 0 1 0 20M12 2a15 15 0 0 0 0 20" opacity="0.5" />
              </svg>
            </div>
          </div>
        </header>

        <div class="brand">
          <div class="brand__logo" aria-hidden="true"></div>
          <h1 class="brand__name" id="brand-name"><?php echo htmlspecialchars($publicCfg['rp_name']); ?></h1>
          <p class="brand__welcome">Welcome back</p>
        </div>

        <form class="login-form" id="login-form" action="#" method="post" novalidate
              onsubmit="return false;"<?php echo $publicCfg['allow_password_login'] ? '' : ' hidden'; ?>>
          <div class="field">
            <label class="field__label" for="username" id="username-label">Teléfono</label>
            <div class="input-shell">
              <button type="button" class="toggle-identity" id="toggle-identity"
                      aria-label="Iniciar sesión con correo electrónico" title="Usar correo">
                <span class="toggle-identity__icon is-visible" data-mode-icon="to-email" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" stroke-width="1.5">
                    <path d="M4 6h16v12H4z" opacity="0.85" />
                    <path d="M4 8l8 6 8-6" />
                  </svg>
                </span>
                <span class="toggle-identity__icon" data-mode-icon="to-phone" aria-hidden="true">
                  <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" stroke-width="1.5" stroke-linecap="round" stroke-linejoin="round">
                    <rect x="8" y="2" width="8" height="20" rx="2" />
                    <path d="M11 5.5h2" opacity="0.65" />
                    <path d="M12 18.25h.01" />
                  </svg>
                </span>
              </button>
              <input id="username" name="username" type="tel" inputmode="tel"
                     autocomplete="tel" placeholder="Tu número celular o correo" required />
            </div>
          </div>

          <div class="field">
            <label class="field__label" for="password">Contraseña</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <rect x="5" y="11" width="14" height="10" rx="2" stroke-width="1.5" />
                <path stroke-width="1.5" d="M8 11V8a4 4 0 0 1 8 0v3" opacity="0.85" />
              </svg>
              <input id="password" name="password" type="password" autocomplete="current-password"
                     placeholder="Ingresa tu contraseña" required />
              <button type="button" class="toggle-pass" id="toggle-password"
                      aria-label="Mostrar contraseña" aria-pressed="false">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
                  <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z" />
                  <circle cx="12" cy="12" r="3" />
                </svg>
              </button>
            </div>
          </div>

          <a class="link-muted" href="#" id="link-forgot">¿Olvidaste tu contraseña?</a>

          <button type="submit" class="btn-primary" id="btn-submit-login">
            Sign in
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" aria-hidden="true">
              <path d="M9 6l6 6-6 6" />
            </svg>
          </button>
          <p id="form-feedback" class="form-feedback" role="status" aria-live="polite"><?php echo htmlspecialchars($reasonText); ?></p>

          <div id="biometric-section" class="biometric-section" aria-hidden="true">
            <div class="or-row" role="presentation"><span>OR</span></div>
            <button type="button" class="btn-bio" id="btn-biometric" tabindex="-1">
              <span class="btn-bio__icon" aria-hidden="true">
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" stroke-width="1.3">
                  <path d="M12 10a2 2 0 1 0 2 2" opacity="0.9" />
                  <path d="M15 8a5 5 0 0 0-6 6" />
                  <path d="M17 6a8 8 0 0 0-10 10" opacity="0.85" />
                  <path d="M19 4c-4-2-10-1-14 6" opacity="0.7" />
                </svg>
              </span>
              <span>
                <span class="btn-bio__title">Login with biometrics</span>
                <span class="btn-bio__sub">Usa tu huella para acceder</span>
              </span>
            </button>
            <p id="bio-feedback" class="bio-feedback" role="status" aria-live="polite"></p>
          </div>

          <p class="signup" id="signup-row"<?php echo $publicCfg['allow_user_registration'] ? '' : ' hidden'; ?>>
            ¿Nuevo usuario?
            <a href="#" id="link-signup-wizard">Crear cuenta</a>
          </p>
          <p class="privacy-login-wrap">
            <button type="button" class="btn-text-wizard" data-open-privacy-modal>
              Aviso de privacidad
            </button>
          </p>
        </form>

        <?php if (!$publicCfg['allow_password_login']): ?>
        <div class="form-feedback is-ok" style="margin-top:1rem;">
          El acceso por contraseña está deshabilitado por el administrador.
          <?php if ($publicCfg['allow_webauthn']): ?>
            Usa tu huella o passkey para entrar.
          <?php endif; ?>
        </div>
        <div id="biometric-section-fallback" class="biometric-section" aria-hidden="true" style="margin-top:1rem;">
          <button type="button" class="btn-bio" id="btn-biometric-only" tabindex="0">
            <span class="btn-bio__icon" aria-hidden="true">
              <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" stroke-width="1.3">
                <path d="M12 10a2 2 0 1 0 2 2" opacity="0.9" />
                <path d="M15 8a5 5 0 0 0-6 6" />
                <path d="M17 6a8 8 0 0 0-10 10" opacity="0.85" />
                <path d="M19 4c-4-2-10-1-14 6" opacity="0.7" />
              </svg>
            </span>
            <span>
              <span class="btn-bio__title">Acceder con huella</span>
              <span class="btn-bio__sub">WebAuthn / Passkey</span>
            </span>
          </button>
        </div>
        <?php endif; ?>

        <footer class="panel__secure">
          <div class="secure-left">
            <span class="secure-dot" aria-hidden="true"></span>
            <span>Secure protocol active</span>
          </div>
          <div class="secure-right">
            <svg width="28" height="14" viewBox="0 0 28 14" aria-hidden="true">
              <path d="M0 10 Q7 2 14 10 T28 10" stroke="#00f2ff" stroke-width="1" fill="none" opacity="0.7" />
            </svg>
            <span>256-bit encryption</span>
          </div>
        </footer>
      </section>
    </div>
  </main>

  <div id="signup-wizard" class="signup-wizard" aria-hidden="true" hidden>
    <div class="signup-wizard__backdrop" aria-hidden="true"></div>
    <div class="signup-wizard__panel" role="dialog" aria-modal="true" aria-labelledby="signup-wizard-title">
      <div class="signup-wizard__scroll">
        <div class="signup-wizard__head">
          <div class="signup-wizard__head-main">
            <div class="wizard-head-avatar" id="wizard-head-avatar" aria-hidden="true">
              <img src="" alt="" id="wizard-head-avatar-img" />
            </div>
            <div class="signup-wizard__head-copy">
              <h2 class="signup-wizard__title" id="signup-wizard-title">Crear cuenta</h2>
              <p class="signup-wizard__subtitle" id="signup-wizard-step-label">Paso 1 · Bienvenida</p>
            </div>
          </div>
          <button type="button" class="btn-wizard-back" id="wizard-close-login">Volver al login</button>
        </div>

        <div class="wizard-progress" id="wizard-progress" aria-hidden="true"></div>

        <div class="wizard-step is-active" data-wizard-step="intro" id="wizard-step-intro">
          <p class="wizard-step__lead">
            Configura tu perfil <?php echo htmlspecialchars($publicCfg['rp_name']); ?> en unos pasos. La foto es opcional;
            si la añades podrás encuadrarla antes de guardarla.
          </p>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-from-intro-next">Siguiente</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="photo" id="wizard-step-photo">
          <p class="wizard-step__lead">¿Quieres foto de perfil? Elige si prefieres la galería o la cámara.</p>
          <div class="wizard-photo-preview-wrap" id="wizard-photo-preview-wrap" aria-hidden="true">
            <div class="wizard-photo-preview" id="wizard-photo-preview">
              <img src="" alt="" id="wizard-photo-preview-img" width="96" height="96" hidden decoding="async" />
            </div>
          </div>
          <input type="file" id="wizard-file-gallery" accept="image/*" hidden />
          <input type="file" id="wizard-file-camera" accept="image/*" capture="environment" hidden />
          <div class="wizard-actions wizard-actions--row">
            <button type="button" class="btn-secondary-wizard" id="wizard-pick-gallery">Galería</button>
            <button type="button" class="btn-secondary-wizard" id="wizard-pick-camera">Cámara</button>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
          </div>
          <div class="wizard-actions">
            <button type="button" class="btn-text-wizard" id="wizard-skip-photo">Omitir foto</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="crop" id="wizard-step-crop">
          <p class="wizard-step__lead">Arrastra para centrar y usa el zoom para encuadrar.</p>
          <div class="wizard-crop-wrap">
            <div class="wizard-crop-viewport" id="wizard-crop-viewport">
              <img src="" alt="" id="wizard-crop-img" />
              <div class="wizard-crop-frame" aria-hidden="true"></div>
            </div>
            <div class="wizard-crop-zoom">
              <span>Zoom</span>
              <input type="range" id="wizard-crop-zoom-range" min="100" max="280" value="100" />
            </div>
            <p class="wizard-crop-hint">Arrastra con el dedo o el ratón sobre la imagen.</p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav wizard-actions--nav-triple">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-secondary-wizard" id="wizard-crop-change">Cambiar imagen</button>
            <button type="button" class="btn-primary" id="wizard-crop-apply">Aplicar recorte</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="name" id="wizard-step-name">
          <div class="field">
            <label class="field__label" for="wizard-fullname">Nombre completo</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <path stroke-width="1.5" d="M12 12a4 4 0 1 0-4-4 4 4 0 0 0 4 4Z" />
                <path stroke-width="1.5" d="M4 21a8 8 0 0 1 16 0" opacity="0.7" />
              </svg>
              <input id="wizard-fullname" type="text" autocomplete="name"
                     placeholder="Nombre y apellidos" required aria-required="true" />
            </div>
            <p class="wizard-field-hint" id="wizard-name-step-msg"></p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-from-name-next">Siguiente</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="email" id="wizard-step-email">
          <div class="field">
            <label class="field__label" for="wizard-email">Correo electrónico</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <path stroke-width="1.5" d="M4 6h16v12H4z" opacity="0.85" />
                <path stroke-width="1.5" d="M4 8l8 6 8-6" />
              </svg>
              <input id="wizard-email" type="email" inputmode="email" autocomplete="email"
                     placeholder="correo@ejemplo.com" required aria-required="true" />
            </div>
            <p class="wizard-field-hint" id="wizard-email-step-msg"></p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-from-email-next">Siguiente</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="phone" id="wizard-step-phone">
          <div class="field">
            <label class="field__label" for="wizard-phone">Número de celular</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <path stroke-width="1.5" d="M6 3h4l2 5-2 1a12 12 0 0 0 5 5l1-2 5 2v4a2 2 0 0 1-2 2C10.5 21 3 13.5 3 5a2 2 0 0 1 2-2Z" opacity="0.9" />
              </svg>
              <input id="wizard-phone" type="tel" inputmode="tel" autocomplete="tel"
                     placeholder="Ejemplo 4424575952" required aria-required="true"
                     aria-describedby="wizard-phone-region" />
            </div>
            <p class="wizard-phone-region" id="wizard-phone-region" aria-live="polite"></p>
            <p class="wizard-field-hint" id="wizard-phone-step-msg"></p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-from-phone-next">Siguiente</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="password" id="wizard-step-password">
          <div class="field">
            <label class="field__label" for="wizard-password">Contraseña</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <rect x="5" y="11" width="14" height="10" rx="2" stroke-width="1.5" />
                <path stroke-width="1.5" d="M8 11V8a4 4 0 0 1 8 0v3" opacity="0.85" />
              </svg>
              <input id="wizard-password" type="password" autocomplete="new-password"
                     placeholder="Nueva contraseña (mín. 8)" required aria-required="true" />
              <button type="button" class="toggle-pass" id="wizard-toggle-pass-a"
                      aria-label="Mostrar contraseña" aria-pressed="false">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
                  <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z" />
                  <circle cx="12" cy="12" r="3" />
                </svg>
              </button>
            </div>
            <div class="password-meter" aria-hidden="true">
              <div class="password-meter__fill level-0" id="wizard-password-meter"></div>
            </div>
            <p class="password-strength-label" id="wizard-password-strength-text">Fortaleza: —</p>
          </div>
          <div class="field">
            <label class="field__label" for="wizard-password2">Confirmar contraseña</label>
            <div class="input-shell">
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#00f2ff" aria-hidden="true">
                <rect x="5" y="11" width="14" height="10" rx="2" stroke-width="1.5" />
                <path stroke-width="1.5" d="M8 11V8a4 4 0 0 1 8 0v3" opacity="0.85" />
              </svg>
              <input id="wizard-password2" type="password" autocomplete="new-password"
                     placeholder="Repite la contraseña" required aria-required="true" />
              <button type="button" class="toggle-pass" id="wizard-toggle-pass-b"
                      aria-label="Mostrar confirmación" aria-pressed="false">
                <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5" aria-hidden="true">
                  <path d="M2 12s4-7 10-7 10 7 10 7-4 7-10 7S2 12 2 12Z" />
                  <circle cx="12" cy="12" r="3" />
                </svg>
              </button>
            </div>
            <p class="wizard-field-hint" id="wizard-password-match-hint"></p>
            <p class="wizard-field-hint" id="wizard-password-step-msg"></p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-from-password-next">Siguiente</button>
          </div>
        </div>

        <div class="wizard-step" data-wizard-step="done" id="wizard-step-done">
          <div class="wizard-avatar-preview" id="wizard-avatar-preview">
            <img src="" alt="" id="wizard-avatar-img" />
          </div>
          <p class="wizard-privacy-link-wrap">
            <button type="button" class="btn-text-wizard" data-open-privacy-modal>Aviso de privacidad</button>
          </p>
          <div class="wizard-actions">
            <button type="button" class="btn-secondary-wizard" id="wizard-btn-fingerprint">
              Registrar huella dactilar
            </button>
            <p class="wizard-bio-feedback" id="wizard-bio-feedback" role="status" aria-live="polite"></p>
          </div>
          <div class="wizard-actions wizard-actions--row wizard-actions--nav">
            <button type="button" class="btn-secondary-wizard" data-wizard-regresar>Regresar</button>
            <button type="button" class="btn-primary" id="wizard-btn-create-mock">Crear cuenta</button>
          </div>
          <p class="wizard-field-hint" id="wizard-mock-msg" style="text-align: center; margin: 0"></p>
        </div>
      </div>
    </div>
  </div>

  <div id="privacy-modal" class="privacy-modal" aria-hidden="true" hidden>
    <div class="privacy-modal__backdrop" data-close-privacy-modal tabindex="-1"></div>
    <div class="privacy-modal__dialog" role="dialog" aria-modal="true" aria-labelledby="privacy-modal-title">
      <div class="privacy-modal__head">
        <h2 class="privacy-modal__title" id="privacy-modal-title">Aviso de privacidad</h2>
        <button type="button" class="privacy-modal__close" data-close-privacy-modal aria-label="Cerrar">×</button>
      </div>
      <div class="privacy-modal__body">
        <p>En este sitio <strong>no realizamos lecturas propias de cookies externas</strong> con fines de
          seguimiento o publicidad por nuestra parte.</p>
        <p>Cualquier <strong>lectura o señal</strong> que pueda existir en tu navegador puede
          <strong>derivar de servicios de terceros</strong> (por ejemplo Google, YouTube u otros
          contenidos o scripts incrustados), según su configuración y sus políticas.</p>
        <p><strong>Huella dactilar y datos biométricos.</strong> El uso de tu huella u otro factor
          biométrico (rostro, etc.) para acceder o registrar credenciales está
          <strong>directamente ligado a servicios de terceros</strong>: el sistema operativo de tu
          dispositivo, el navegador y, cuando corresponda, el estándar
          <strong>Web Authentication (WebAuthn)</strong> y el autenticador integrado en la plataforma
          (sensor + almacén seguro). Esos terceros son quienes, en la práctica, gestionan el hardware
          del sensor, las plantillas o referencias biométricas y las políticas locales de uso.</p>
        <p>En los flujos habituales actuales, <strong>este sitio no recibe ni guarda una imagen escaneada de
          tu huella</strong>. La información biométrica sensible queda bajo control del
          <strong>dispositivo y del sistema operativo</strong>; la aplicación web solo obtiene
          resultados criptográficos (una prueba firmada) para comprobar que quien usa el navegador puede
          usar ese autenticador.</p>
        <p><strong>No utilizaremos tus datos personales para contactarte</strong> con fines comerciales,
          promocionales o no solicitados, salvo que exista una base legal y un consentimiento claro.</p>
        <p>Aplicamos criterios de <strong>minimización de datos</strong>, <strong>finalidad limitada</strong>
          y <strong>transparencia</strong>.</p>
      </div>
      <div class="privacy-modal__foot">
        <button type="button" class="btn-primary" data-close-privacy-modal>Entendido</button>
      </div>
    </div>
  </div>

  <script>
    window.AUTH_CFG = <?php echo json_encode($publicCfg, JSON_UNESCAPED_SLASHES | JSON_HEX_TAG | JSON_HEX_AMP | JSON_HEX_APOS | JSON_HEX_QUOT); ?>;
    window.AUTH_CSRF = <?php echo json_encode($csrfToken, JSON_UNESCAPED_SLASHES); ?>;
    window.AUTH_API_URL = <?php echo json_encode($apiUrl, JSON_UNESCAPED_SLASHES); ?>;
    window.AUTH_NEXT_URL = <?php echo json_encode(($projectBase === '' ? '' : $projectBase) . '/index.php', JSON_UNESCAPED_SLASHES); ?>;
    window.ANTARA_AUTH_TAB_SYNC_CFG = {
      listenLogin: true,
      listenLogout: false,
      nextUrl: <?php echo json_encode(($projectBase === '' ? '' : $projectBase) . '/index.php', JSON_UNESCAPED_SLASHES); ?>
    };
    window.FLEXIA_INSTANCE_GUARD = {
      apiUrl: <?php echo json_encode(($projectBase === '' ? '' : $projectBase) . '/index.php?action=flexiaInstance', JSON_UNESCAPED_SLASHES); ?>,
      poll: false
    };
  </script>
  <?php
  require_once __DIR__ . '/../includes/flexia_instance.php';
  antara_flexia_emit_instance_script();
  ?>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/js/flexia_instance_guard.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>"></script>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/js/tooltips.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" defer></script>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/auth/auth_tab_sync.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" defer></script>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/js/clock-format.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" defer></script>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/auth/avatar_square_crop.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" defer></script>
  <script src="<?php echo htmlspecialchars(antara_asset_url('assets/auth/login.js', $projectBase), ENT_QUOTES, 'UTF-8'); ?>" defer></script>
</body>
</html>
