<?php
require_once __DIR__ . '/../../config/bootstrap.php';

use App\Services\ContractService;
use App\Services\SecurityService;

$contractService = new ContractService();
$security = new SecurityService();

$token = $_GET['token'] ?? '';

if (empty($token)) {
    header('HTTP/1.1 404 Not Found');
    die('Token no válido');
}

$canSign = $contractService->canBeSigned($token);

if (!$canSign['can_sign']) {
    $error = $canSign['message'];
    include __DIR__ . '/error.php';
    exit;
}

$contract = $canSign['contract'];
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <meta name="theme-color" content="#1d4ed8">
    <title>Firmar Contrato — <?= htmlspecialchars($contract['titulo']) ?></title>

    <script src="https://cdn.tailwindcss.com"></script>
    <script src="https://cdn.jsdelivr.net/npm/signature_pad@4.1.7/dist/signature_pad.umd.min.js"></script>

    <style>
        /* ── Sistema de fuente macOS / Apple ─────────────────────────────── */
        *,
        *::before,
        *::after {
            font-family: -apple-system, "SF Pro Display", "SF Pro Text",
                "Helvetica Neue", Helvetica, Arial, sans-serif;
            -webkit-font-smoothing: antialiased;
            -moz-osx-font-smoothing: grayscale;
            box-sizing: border-box;
        }

        /* ── Stepper ─────────────────────────────────────────────────────── */
        .stepper-wrap {
            display: flex;
            align-items: flex-start;
            width: 100%;
        }

        /* Ítem = columna centrada (dot + label) */
        .stepper-item {
            display: flex;
            flex-direction: column;
            align-items: center;
            flex: 1;
            min-width: 0;
            position: relative;
            z-index: 1;
        }

        /* Línea conectora entre ítems */
        .stepper-line {
            flex: 1;
            height: 2px;
            background: #e5e7eb;
            margin-top: 17px;
            /* alinea con el centro del dot */
            transition: background .45s ease;
        }

        .stepper-line.done {
            background: #16a34a;
        }

        /* Dot */
        .stepper-dot {
            width: 34px;
            height: 34px;
            border-radius: 50%;
            border: 2px solid #e5e7eb;
            background: #f9fafb;
            display: flex;
            align-items: center;
            justify-content: center;
            font-size: 12px;
            font-weight: 700;
            color: #9ca3af;
            transition: all .35s cubic-bezier(.4, 0, .2, 1);
            flex-shrink: 0;
        }

        .stepper-dot.active {
            background: #1d4ed8;
            border-color: #1d4ed8;
            color: #fff;
            box-shadow: 0 0 0 4px rgba(29, 78, 216, .15);
        }

        .stepper-dot.done {
            background: #16a34a;
            border-color: #16a34a;
            color: #fff;
        }

        /* Etiqueta debajo del dot — solo visible en ≥ sm */
        .stepper-label {
            margin-top: 6px;
            font-size: 10px;
            font-weight: 500;
            color: #9ca3af;
            text-align: center;
            white-space: nowrap;
            line-height: 1.2;
            display: none;
            /* oculto en móvil */
        }

        @media (min-width: 480px) {
            .stepper-label {
                display: block;
            }
        }

        .stepper-label.active {
            color: #1d4ed8;
            font-weight: 600;
        }

        .stepper-label.done {
            color: #16a34a;
        }

        /* ── Cámara / canvas ─────────────────────────────────────────────── */
        #signature-pad {
            touch-action: none;
            cursor: crosshair;
            border-radius: 12px;
            border: 2px dashed #d1d5db;
            background: #fff;
            width: 100%;
            height: 180px;
        }

        video,
        .photo-preview {
            width: 100%;
            border-radius: 12px;
            background: #000;
            object-fit: cover;
        }

        /* ── Input base ──────────────────────────────────────────────────── */
        .field {
            width: 100%;
            padding: 14px 16px;
            border: 1.5px solid #d1d5db;
            border-radius: 10px;
            font-size: 16px;
            /* evita zoom en iOS */
            color: #111827;
            background: #fff;
            transition: border-color .2s, box-shadow .2s;
            appearance: none;
        }

        .field:focus {
            outline: none;
            border-color: #1d4ed8;
            box-shadow: 0 0 0 3px rgba(29, 78, 216, .12);
        }

        .field::placeholder {
            color: #9ca3af;
        }

        /* ── Botones ─────────────────────────────────────────────────────── */
        .btn {
            display: inline-flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            padding: 14px 20px;
            border-radius: 12px;
            font-size: 15px;
            font-weight: 600;
            border: none;
            cursor: pointer;
            transition: transform .15s, box-shadow .15s, background .15s;
            -webkit-tap-highlight-color: transparent;
            width: 100%;
        }

        .btn:active {
            transform: scale(.97);
        }

        .btn-primary {
            background: #1d4ed8;
            color: #fff;
        }

        .btn-primary:hover:not(:disabled) {
            background: #1e40af;
            box-shadow: 0 4px 14px rgba(29, 78, 216, .35);
        }

        .btn-secondary {
            background: #f3f4f6;
            color: #374151;
        }

        .btn-secondary:hover {
            background: #e5e7eb;
        }

        .btn-green {
            background: #16a34a;
            color: #fff;
        }

        .btn-green:hover:not(:disabled) {
            background: #15803d;
            box-shadow: 0 4px 14px rgba(22, 163, 74, .35);
        }

        .btn-danger {
            background: #fff;
            color: #dc2626;
            border: 1.5px solid #fca5a5;
        }

        .btn-danger:hover {
            background: #fef2f2;
        }

        .btn:disabled {
            background: #e5e7eb;
            color: #9ca3af;
            cursor: not-allowed;
        }

        /* ── Tarjetas de recomendación ───────────────────────────────────── */
        .tip-card {
            display: flex;
            gap: 10px;
            align-items: flex-start;
            background: #eff6ff;
            border: 1px solid #bfdbfe;
            border-radius: 10px;
            padding: 12px 14px;
        }

        .tip-icon {
            flex-shrink: 0;
            width: 20px;
            height: 20px;
            color: #1d4ed8;
            margin-top: 1px;
        }

        /* ── Animación fade-in por paso ──────────────────────────────────── */
        .step-panel {
            animation: fadeUp .25s ease;
        }

        @keyframes fadeUp {
            from {
                opacity: 0;
                transform: translateY(10px);
            }

            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        /* ── Modal éxito ─────────────────────────────────────────────────── */
        #modal-success {
            display: none;
            position: fixed;
            inset: 0;
            z-index: 9999;
            background: rgba(0, 0, 0, .55);
            align-items: center;
            justify-content: center;
            padding: 16px;
        }

        #modal-success.open {
            display: flex;
        }

        #modal-success-box {
            background: #fff;
            border-radius: 20px;
            padding: 32px 24px;
            max-width: 420px;
            width: 100%;
            text-align: center;
            animation: popIn .3s cubic-bezier(.175, .885, .32, 1.275);
        }

        @keyframes popIn {
            from {
                opacity: 0;
                transform: scale(.85);
            }

            to {
                opacity: 1;
                transform: scale(1);
            }
        }
        /* ── Estilos para el contenido del contrato ────────────────────── */
        #contract-content h1 {
            font-size: 1.5rem;
            font-weight: 700;
            margin-top: 1.25rem;
            margin-bottom: 0.75rem;
            color: #111827;
            line-height: 1.2;
        }

        #contract-content h2 {
            font-size: 1.25rem;
            font-weight: 600;
            margin-top: 1rem;
            margin-bottom: 0.5rem;
            color: #1f2937;
            line-height: 1.3;
        }

        #contract-content h3 {
            font-size: 1.125rem;
            font-weight: 600;
            margin-top: 0.875rem;
            margin-bottom: 0.5rem;
            color: #374151;
            line-height: 1.4;
        }

        #contract-content p {
            margin-bottom: 0.75rem;
            line-height: 1.6;
        }

        #contract-content ul,
        #contract-content ol {
            margin-left: 1.25rem;
            margin-bottom: 0.75rem;
            line-height: 1.6;
        }

        #contract-content ul {
            list-style-type: disc;
        }

        #contract-content ol {
            list-style-type: decimal;
        }

        #contract-content li {
            margin-bottom: 0.375rem;
        }

        #contract-content strong {
            font-weight: 600;
            color: #111827;
        }

        #contract-content em {
            font-style: italic;
        }

        #contract-content u {
            text-decoration: underline;
        }

        #contract-content a {
            color: #1d4ed8;
            text-decoration: underline;
        }

        #contract-content a:hover {
            color: #1e40af;
        }

        #contract-content img {
            max-width: 100%;
            height: auto;
            margin: 0.75rem 0;
            border-radius: 0.375rem;
        }

        #contract-content table {
            width: 100%;
            border-collapse: collapse;
            margin: 0.75rem 0;
            font-size: 0.875rem;
        }

        #contract-content table th,
        #contract-content table td {
            border: 1px solid #e5e7eb;
            padding: 0.375rem;
            text-align: left;
        }

        #contract-content table th {
            background-color: #f9fafb;
            font-weight: 600;
        }

        #contract-content blockquote {
            border-left: 3px solid #e5e7eb;
            padding-left: 0.75rem;
            margin: 0.75rem 0;
            font-style: italic;
            color: #6b7280;
        }

        #contract-content pre {
            background-color: #f9fafb;
            border: 1px solid #e5e7eb;
            border-radius: 0.375rem;
            padding: 0.75rem;
            overflow-x: auto;
            margin: 0.75rem 0;
            font-size: 0.875rem;
        }

        #contract-content code {
            background-color: #f3f4f6;
            padding: 0.125rem 0.25rem;
            border-radius: 0.25rem;
            font-family: 'Courier New', monospace;
            font-size: 0.875rem;
        }
    </style>
</head>

<body class="bg-gray-50 min-h-screen">

    <!-- ══════════════════════════════════════════════════════════
         NAVBAR
    ══════════════════════════════════════════════════════════════ -->
    <header class="bg-white border-b border-gray-200 sticky top-0 z-40">
        <div class="max-w-2xl mx-auto px-4 h-14 flex items-center justify-between">
            <!-- Logo / Empresa -->
            <div class="flex items-center gap-2.5">
                <div class="w-8 h-8 bg-blue-700 rounded-lg flex items-center justify-center flex-shrink-0">
                    <svg class="w-4 h-4 text-white" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                            d="M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z" />
                    </svg>
                </div>
                <div class="leading-none">
                    <p class="text-sm font-700 text-gray-900 font-bold tracking-tight"><?= htmlspecialchars(COMPANY_NAME) ?></p>
                    <p class="text-[10px] text-gray-400 hidden sm:block"><?= htmlspecialchars(COMPANY_TAGLINE) ?></p>
                </div>
            </div>
            <!-- Seguridad badge -->
            <div class="flex items-center gap-1.5 bg-green-50 border border-green-200 rounded-full px-3 py-1">
                <svg class="w-3.5 h-3.5 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5"
                        d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                </svg>
                <span class="text-[11px] font-600 text-green-700 font-semibold">Cifrado SSL</span>
            </div>
        </div>
    </header>

    <!-- ══════════════════════════════════════════════════════════
         STEPPER
    ══════════════════════════════════════════════════════════════ -->
    <div class="bg-white border-b border-gray-100 shadow-sm">
        <div class="max-w-2xl mx-auto px-4 py-4">
            <div id="stepper" class="stepper-wrap">
                <!-- generado por JS -->
            </div>
        </div>
    </div>

    <!-- ══════════════════════════════════════════════════════════
         CONTENIDO PRINCIPAL
    ══════════════════════════════════════════════════════════════ -->
    <main class="max-w-2xl mx-auto px-4 py-6 pb-24">

        <!-- ───── PASO 1: BIENVENIDA ───────────────────────────────────── -->
        <div id="step-1" class="step-panel">
            <h1 class="text-2xl font-bold text-gray-900 mb-1 tracking-tight">
                Hola, <?= htmlspecialchars($contract['cliente_nombre']) ?> 👋
            </h1>
            <p class="text-gray-500 text-sm mb-6">Vas a firmar digitalmente el contrato <strong class="text-gray-800"><?= htmlspecialchars($contract['titulo']) ?></strong>. El proceso toma aproximadamente 5 minutos.</p>

            <div class="space-y-3 mb-8">
                <?php
                $steps_info = [
                    ['icon' => 'M9 12h6m-6 4h6m2 5H7a2 2 0 01-2-2V5a2 2 0 012-2h5.586a1 1 0 01.707.293l5.414 5.414a1 1 0 01.293.707V19a2 2 0 01-2 2z', 'title' => 'Lectura del contrato', 'desc' => 'Revisa el documento completo'],
                    ['icon' => 'M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z M15 13a3 3 0 11-6 0 3 3 0 016 0z', 'title' => 'Fotografías del documento', 'desc' => 'Frontal y trasero del ID'],
                    ['icon' => 'M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z', 'title' => 'Selfie de verificación', 'desc' => 'Una foto de tu rostro'],
                    ['icon' => 'M15.232 5.232l3.536 3.536m-2.036-5.036a2.5 2.5 0 113.536 3.536L6.5 21.036H3v-3.572L16.732 3.732z', 'title' => 'Firma digital', 'desc' => 'Tu firma manuscrita digital'],
                ];
                foreach ($steps_info as $i => $s): ?>
                    <div class="flex items-center gap-4 bg-white rounded-2xl border border-gray-100 shadow-sm p-4">
                        <div class="w-10 h-10 rounded-xl bg-blue-50 flex items-center justify-center flex-shrink-0">
                            <svg class="w-5 h-5 text-blue-700" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.75" d="<?= $s['icon'] ?>" />
                            </svg>
                        </div>
                        <div class="min-w-0">
                            <p class="text-sm font-semibold text-gray-900"><?= $s['title'] ?></p>
                            <p class="text-xs text-gray-400"><?= $s['desc'] ?></p>
                        </div>
                        <div class="ml-auto w-6 h-6 rounded-full bg-gray-100 flex items-center justify-center flex-shrink-0">
                            <span class="text-xs font-bold text-gray-400"><?= $i + 1 ?></span>
                        </div>
                    </div>
                <?php endforeach; ?>
            </div>

            <!-- Necesitarás -->
            <div class="bg-amber-50 border border-amber-200 rounded-2xl p-4 mb-8">
                <p class="text-xs font-semibold text-amber-800 uppercase tracking-wide mb-2">Antes de empezar necesitas</p>
                <ul class="space-y-1.5">
                    <?php foreach (['Tu documento de identidad físico', 'Buena iluminación en la habitación', 'Cámara activa en este dispositivo'] as $need): ?>
                        <li class="flex items-center gap-2 text-sm text-amber-900">
                            <svg class="w-4 h-4 text-amber-600 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                            </svg>
                            <?= $need ?>
                        </li>
                    <?php endforeach; ?>
                </ul>
            </div>

            <button onclick="nextStep()" class="btn btn-primary">
                <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M13 7l5 5m0 0l-5 5m5-5H6" />
                </svg>
                Comenzar proceso
            </button>
        </div>

        <!-- ───── PASO 2: LECTURA DEL CONTRATO ────────────────────────── -->
        <div id="step-2" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Lee el contrato</h2>
            <p class="text-gray-500 text-sm mb-4">Desplázate hasta el final para habilitar la aceptación.</p>

            <div id="scroll-message" class="flex items-center gap-2 bg-blue-50 border border-blue-200 rounded-xl p-3 mb-4 text-sm text-blue-800">
                <svg class="w-4 h-4 flex-shrink-0 text-blue-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7" />
                </svg>
                Desplázate hasta el final del documento
            </div>

            <div id="contract-content"
                class="bg-white border border-gray-200 rounded-2xl p-5 mb-5 overflow-y-auto text-sm text-gray-700 leading-relaxed"
                style="max-height: 340px;">
                <?= $contract['contenido'] ?>
                <div class="mt-8 pt-5 border-t border-gray-200 text-center">
                    <span class="inline-flex items-center gap-2 text-xs font-semibold text-gray-500 bg-gray-100 rounded-full px-4 py-2">
                        <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7" />
                        </svg>
                        Fin del documento
                    </span>
                </div>
            </div>

            <label class="flex items-start gap-3 cursor-pointer mb-5 bg-white border border-gray-200 rounded-2xl p-4">
                <input type="checkbox" id="accept-terms" disabled
                    class="w-5 h-5 rounded border-gray-300 text-blue-700 mt-0.5 flex-shrink-0 cursor-pointer">
                <div>
                    <p class="text-sm font-semibold text-gray-900">He leído y acepto los términos del contrato</p>
                    <p class="text-xs text-gray-400 mt-0.5">Al marcar confirmo que leí el documento completo.</p>
                </div>
            </label>

            <button id="continue-after-read" onclick="nextStep()" disabled class="btn btn-primary">
                Continuar
            </button>
        </div>

        <!-- ───── PASO 3: DOCUMENTO FRONTAL ───────────────────────────── -->
        <div id="step-3" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Documento — cara frontal</h2>
            <p class="text-gray-500 text-sm mb-4">Fotografía la parte <strong>delantera</strong> de tu cédula / documento.</p>

            <!-- Recomendaciones -->
            <div class="space-y-2 mb-5">
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364-6.364l-.707.707M6.343 6.343l-.707-.707m12.728 12.728l-.707-.707M6.343 17.657l-.707.707" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Buena iluminación:</strong> evita sombras o reflejos sobre el documento.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Encuadre completo:</strong> el documento debe ocupar el 80 % de la imagen.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z M2.458 12C3.732 7.943 7.523 5 12 5c4.477 0 8.268 2.943 9.542 7-1.274 4.057-5.065 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Texto legible:</strong> asegúrate que el número y nombre sean claramente visibles.</p>
                </div>
            </div>

            <div class="max-w-lg mx-auto">
                <div class="mb-4 flex justify-center">
                    <video id="camera-doc-frontal" class="hidden" autoplay playsinline></video>
                    <canvas id="canvas-doc-frontal" class="hidden"></canvas>
                    <img id="preview-doc-frontal" class="photo-preview hidden" alt="Doc frontal">
                </div>
                <button id="start-camera-doc-frontal" onclick="startCamera('doc-frontal')" class="btn btn-primary mb-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    Activar Cámara
                </button>
                <div id="controls-doc-frontal" class="hidden space-y-3">
                    <button onclick="capturePhoto('doc-frontal')" class="btn btn-green">
                        Capturar Foto
                    </button>
                    <div class="grid grid-cols-2 gap-3 hidden" id="photo-actions-doc-frontal">
                        <button onclick="retakePhoto('doc-frontal')" class="btn btn-secondary">Repetir</button>
                        <button onclick="nextStep()" class="btn btn-primary">Continuar</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ───── PASO 4: DOCUMENTO TRASERO ───────────────────────────── -->
        <div id="step-4" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Documento — cara trasera</h2>
            <p class="text-gray-500 text-sm mb-4">Voltea tu documento y fotografía la parte <strong>trasera</strong>.</p>

            <div class="space-y-2 mb-5">
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 21a4 4 0 01-4-4V5a2 2 0 012-2h4a2 2 0 012 2v12a4 4 0 01-4 4zm0 0h12a2 2 0 002-2v-4a2 2 0 00-2-2h-2.343M11 7.343l1.657-1.657a2 2 0 012.828 0l2.829 2.829a2 2 0 010 2.828l-8.486 8.485M7 17h.01" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Cara opuesta:</strong> voltea el documento, no repitas la misma cara.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M4 8V4m0 0h4M4 4l5 5m11-1V4m0 0h-4m4 0l-5 5M4 16v4m0 0h4m-4 0l5-5m11 5l-5-5m5 5v-4m0 4h-4" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Encuadre completo:</strong> incluye los cuatro bordes del documento.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Sin dobleces ni reflejos</strong> que oculten información del reverso.</p>
                </div>
            </div>

            <div class="max-w-lg mx-auto">
                <div class="mb-4 flex justify-center">
                    <video id="camera-doc-trasero" class="hidden" autoplay playsinline></video>
                    <canvas id="canvas-doc-trasero" class="hidden"></canvas>
                    <img id="preview-doc-trasero" class="photo-preview hidden" alt="Doc trasero">
                </div>
                <button id="start-camera-doc-trasero" onclick="startCamera('doc-trasero')" class="btn btn-primary mb-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    Activar Cámara
                </button>
                <div id="controls-doc-trasero" class="hidden space-y-3">
                    <button onclick="capturePhoto('doc-trasero')" class="btn btn-green">
                        Capturar Foto
                    </button>
                    <div class="grid grid-cols-2 gap-3 hidden" id="photo-actions-doc-trasero">
                        <button onclick="retakePhoto('doc-trasero')" class="btn btn-secondary">Repetir</button>
                        <button onclick="nextStep()" class="btn btn-primary">Continuar</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ───── PASO 5: DATOS DEL DOCUMENTO ─────────────────────────── -->
        <div id="step-5" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Datos personales</h2>
            <p class="text-gray-500 text-sm mb-6">Completa la información de tu documento de identidad.</p>

            <div class="space-y-4 max-w-lg mx-auto">
                <!-- Nombre completo -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Nombre completo <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="nombre-completo" placeholder="Como aparece en tu documento"
                        class="field" autocomplete="name" inputmode="text">
                </div>

                <!-- Fecha de nacimiento -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Fecha de nacimiento <span class="text-red-500">*</span>
                    </label>
                    <input type="date" id="fecha-nacimiento" class="field" max="<?= date('Y-m-d', strtotime('-14 years')) ?>">
                </div>

                <!-- Tipo de documento -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Tipo de documento <span class="text-red-500">*</span>
                    </label>
                    <select id="tipo-documento" class="field">
                        <option value="">Seleccionar...</option>
                        <option value="CC">Cédula de Ciudadanía (CC)</option>
                        <option value="TI">Tarjeta de Identidad (TI)</option>
                        <option value="CE">Cédula de Extranjería (CE)</option>
                        <option value="PP">Pasaporte</option>
                        <option value="DNI">DNI</option>
                        <option value="RUT">RUT</option>
                    </select>
                </div>

                <!-- Número de documento -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Número de documento <span class="text-red-500">*</span>
                    </label>
                    <input type="text" id="numero-documento" placeholder="Ej: 1234567890"
                        class="field" inputmode="numeric" pattern="[0-9A-Za-z\-]+">
                </div>

                <!-- Fecha de expedición -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Fecha de expedición del documento <span class="text-red-500">*</span>
                    </label>
                    <input type="date" id="fecha-expedicion" class="field" max="<?= date('Y-m-d') ?>">
                </div>

                <!-- Teléfono -->
                <div>
                    <label class="block text-sm font-semibold text-gray-700 mb-1.5">
                        Número de teléfono <span class="text-red-500">*</span>
                    </label>
                    <div class="flex gap-2">
                        <select id="phone-indicativo"
                            class="px-2 py-2.5 border border-gray-300 rounded-xl focus:ring-2 focus:ring-indigo-500 bg-white text-sm font-medium min-w-[90px]"
                            onchange="updatePhonePlaceholder()">
                            <option value="57"  data-mask="300 123 4567" selected>🇨🇴 +57</option>
                            <option value="1"   data-mask="(310) 555-0100">🇺🇸 +1</option>
                            <option value="52"  data-mask="55 1234 5678">🇲🇽 +52</option>
                            <option value="34"  data-mask="612 345 678">🇪🇸 +34</option>
                            <option value="54"  data-mask="011 1234-5678">🇦🇷 +54</option>
                            <option value="56"  data-mask="9 1234 5678">🇨🇱 +56</option>
                            <option value="51"  data-mask="987 654 321">🇵🇪 +51</option>
                            <option value="58"  data-mask="412-345-6789">🇻🇪 +58</option>
                            <option value="593" data-mask="98 765 4321">🇪🇨 +593</option>
                            <option value="55"  data-mask="(11) 91234-5678">🇧🇷 +55</option>
                            <option value="44"  data-mask="7700 900123">🇬🇧 +44</option>
                            <option value="49"  data-mask="151 23456789">🇩🇪 +49</option>
                            <option value="33"  data-mask="6 12 34 56 78">🇫🇷 +33</option>
                            <option value="39"  data-mask="312 345 6789">🇮🇹 +39</option>
                            <option value="591" data-mask="7 123 4567">🇧🇴 +591</option>
                            <option value="595" data-mask="98 123 456">🇵🇾 +595</option>
                            <option value="598" data-mask="9123 4567">🇺🇾 +598</option>
                            <option value="507" data-mask="6123-4567">🇵🇦 +507</option>
                            <option value="503" data-mask="7123-4567">🇸🇻 +503</option>
                            <option value="502" data-mask="5123-4567">🇬🇹 +502</option>
                        </select>
                        <input type="tel" id="telefono-numero"
                            class="field flex-1" inputmode="numeric"
                            placeholder="300 123 4567" autocomplete="tel-national">
                    </div>
                    <p class="mt-1 text-xs text-gray-400">Indica el país e ingresa el número sin el indicativo.</p>
                    <!-- Campo oculto con el número completo que usará el JS -->
                    <input type="hidden" id="telefono">
                </div>

                <button onclick="validateDocumentData()" class="btn btn-primary mt-2">
                    Continuar
                </button>
            </div>
        </div>

        <!-- ───── PASO 6: SELFIE ───────────────────────────────────────── -->
        <div id="step-6" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Verificación facial</h2>
            <p class="text-gray-500 text-sm mb-4">Toma una foto clara de tu rostro para confirmar tu identidad.</p>

            <!-- Recomendaciones selfie -->
            <div class="space-y-2 mb-5">
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Mira directo a la cámara</strong> y mantén la cara centrada en el encuadre.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 3v1m0 16v1m9-9h-1M4 12H3m15.364-6.364l-.707.707M6.343 6.343l-.707-.707" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Buena iluminación frontal,</strong> sin sombras en el rostro ni contraluz.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Sin objetos sobre el rostro:</strong> retira gafas oscuras, mascarilla o gorra.</p>
                </div>
                <div class="tip-card">
                    <svg class="tip-icon" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    <p class="text-xs text-blue-900"><strong>Expresión neutral,</strong> boca cerrada y ojos abiertos.</p>
                </div>
            </div>

            <div class="max-w-lg mx-auto">
                <div class="mb-4 flex justify-center">
                    <video id="camera-selfie" class="hidden" autoplay playsinline style="transform: scaleX(-1);"></video>
                    <canvas id="canvas-selfie" class="hidden"></canvas>
                    <img id="preview-selfie" class="photo-preview hidden" alt="Selfie">
                </div>
                <button id="start-camera-selfie" onclick="startCamera('selfie')" class="btn btn-primary mb-3">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M3 9a2 2 0 012-2h.93a2 2 0 001.664-.89l.812-1.22A2 2 0 0110.07 4h3.86a2 2 0 011.664.89l.812 1.22A2 2 0 0018.07 7H19a2 2 0 012 2v9a2 2 0 01-2 2H5a2 2 0 01-2-2V9z M15 13a3 3 0 11-6 0 3 3 0 016 0z" />
                    </svg>
                    Activar Cámara Frontal
                </button>
                <div id="controls-selfie" class="hidden space-y-3">
                    <button onclick="capturePhoto('selfie')" class="btn btn-green">
                        Capturar Selfie
                    </button>
                    <div class="grid grid-cols-2 gap-3 hidden" id="photo-actions-selfie">
                        <button onclick="retakePhoto('selfie')" class="btn btn-secondary">Repetir</button>
                        <button onclick="nextStep()" class="btn btn-primary">Continuar</button>
                    </div>
                </div>
            </div>
        </div>

        <!-- ───── PASO 7: FIRMA DIGITAL ───────────────────────────────── -->
        <div id="step-7" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Firma digital</h2>
            <p class="text-gray-500 text-sm mb-5">Dibuja tu firma con el dedo o el cursor. Debe ser similar a tu firma habitual.</p>

            <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4 mb-4">
                <canvas id="signature-pad"></canvas>
                <p class="text-center text-xs text-gray-400 mt-3">Firma aquí arriba</p>
            </div>

            <div class="grid grid-cols-2 gap-3">
                <button onclick="clearSignature()" class="btn btn-danger">
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M6 18L18 6M6 6l12 12" />
                    </svg>
                    Limpiar
                </button>
                <button onclick="validateSignature()" class="btn btn-primary">
                    Confirmar
                    <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M13 7l5 5m0 0l-5 5m5-5H6" />
                    </svg>
                </button>
            </div>
        </div>

        <!-- ───── PASO 8: CONFIRMACIÓN ────────────────────────────────── -->
        <div id="step-8" class="step-panel hidden">
            <h2 class="text-xl font-bold text-gray-900 mb-1">Confirmar y firmar</h2>
            <p class="text-gray-500 text-sm mb-5">Revisa que todo esté correcto antes de enviar.</p>

            <!-- Resumen datos -->
            <div id="summary" class="space-y-4 mb-5"></div>

            <div class="bg-amber-50 border border-amber-200 rounded-2xl p-4 mb-6">
                <p class="text-xs text-amber-900 leading-relaxed">
                    <strong>Declaración de voluntad:</strong> al pulsar "Firmar contrato" confirmas que has leído el documento completo, que eres la persona identificada y que aceptas todos los términos establecidos con plena validez legal.
                </p>
            </div>

            <div class="space-y-3">
                <button onclick="submitSignature()" id="submit-btn" class="btn btn-green">
                    <svg class="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
                    </svg>
                    Firmar contrato
                </button>
                <button onclick="goToStep(1)" class="btn btn-secondary text-sm">
                    Volver al inicio
                </button>
            </div>
        </div>

    </main>

    <!-- ══════════════════════════════════════════════════════════
         FOOTER
    ══════════════════════════════════════════════════════════════ -->
    <footer class="bg-white border-t border-gray-200 mt-8">
        <div class="max-w-2xl mx-auto px-4 py-6 text-center">
            <p class="text-xs text-gray-400 leading-relaxed">
                Este proceso de firma digital es legalmente vinculante conforme a la ley de firma electrónica.<br>
                Tus datos están protegidos con cifrado de extremo a extremo.
            </p>
            <div class="flex items-center justify-center gap-4 mt-4">
                <span class="flex items-center gap-1 text-xs text-gray-400">
                    <svg class="w-3.5 h-3.5 text-green-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
                    </svg>
                    Proceso seguro
                </span>
                <span class="text-gray-200">|</span>
                <span class="flex items-center gap-1 text-xs text-gray-400">
                    <svg class="w-3.5 h-3.5 text-blue-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 15v2m-6 4h12a2 2 0 002-2v-6a2 2 0 00-2-2H6a2 2 0 00-2 2v6a2 2 0 002 2zm10-10V7a4 4 0 00-8 0v4h8z" />
                    </svg>
                    Datos encriptados
                </span>
                <span class="text-gray-200">|</span>
                <span class="text-xs text-gray-400">© <?= date('Y') ?> <?= htmlspecialchars(COMPANY_NAME) ?></span>
            </div>
        </div>
    </footer>

    <!-- ══════════════════════════════════════════════════════════
         MODAL DE ÉXITO
    ══════════════════════════════════════════════════════════════ -->
    <div id="modal-success">
        <div id="modal-success-box">
            <!-- Icono animado -->
            <div class="w-20 h-20 bg-green-100 rounded-full mx-auto mb-5 flex items-center justify-center">
                <svg class="w-11 h-11 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                </svg>
            </div>

            <h2 class="text-2xl font-bold text-gray-900 mb-2 tracking-tight">¡Contrato firmado!</h2>
            <p class="text-gray-500 text-sm mb-6 leading-relaxed">
                Tu firma ha sido registrada correctamente y el contrato ha quedado formalizado con validez legal.
            </p>

            <!-- Datos de confirmación -->
            <div class="bg-gray-50 rounded-2xl p-4 mb-6 text-left space-y-2">
                <div class="flex items-center gap-2 text-sm text-gray-700">
                    <svg class="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                    </svg>
                    Firma digital registrada
                </div>
                <div class="flex items-center gap-2 text-sm text-gray-700">
                    <svg class="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                    </svg>
                    Evidencias fotográficas guardadas
                </div>
                <div class="flex items-center gap-2 text-sm text-gray-700">
                    <svg class="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                    </svg>
                    PDF con constancia generado
                </div>
                <div class="flex items-center gap-2 text-sm text-gray-700">
                    <svg class="w-4 h-4 text-green-500 flex-shrink-0" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2.5" d="M5 13l4 4L19 7" />
                    </svg>
                    Copia enviada a tu correo
                </div>
            </div>

            <p class="text-xs text-gray-400 mb-2">Ya puedes cerrar esta ventana.</p>
        </div>
    </div>

    <script>
        const contractToken = '<?= htmlspecialchars($token) ?>';
        const apiUrl        = '/firma/api';
    </script>
    <script>
        <?= file_get_contents(__DIR__ . '/../assets/js/firma-proceso.js') ?>
    </script>
</body>

</html>