// ============================================================================
// VARIABLES GLOBALES
// ============================================================================
let currentStep = 1;
const TOTAL_STEPS = 8;

const STEP_LABELS = ['Inicio', 'Contrato', 'Doc. Frontal', 'Doc. Trasero', 'Datos', 'Selfie', 'Firma', 'Confirmar'];

const signatureData = {
    firma_imagen:       null,
    selfie:             null,
    documento_frontal:  null,
    documento_trasero:  null,
    tipo_documento:     '',
    numero_documento:   '',
    nombre_completo:    '',
    fecha_nacimiento:   '',
    fecha_expedicion:   '',
    telefono:           '',
    lat:                null,
    lng:                null,
    precision:          null,
    screen_width:       window.screen.width,
    screen_height:      window.screen.height,
    timezone:           Intl.DateTimeFormat().resolvedOptions().timeZone,
    language:           navigator.language
};

const cameraStreams = {};
let signaturePad   = null;

// ============================================================================
// STEPPER — construcción y actualización
// ============================================================================
const TICK_SVG = `<svg width="14" height="14" viewBox="0 0 24 24" fill="none"
    stroke="currentColor" stroke-width="3" stroke-linecap="round" stroke-linejoin="round">
    <polyline points="20 6 9 17 4 12"/>
</svg>`;

function buildStepper() {
    const wrap = document.getElementById('stepper');
    if (!wrap) return;
    wrap.innerHTML = '';

    for (let i = 1; i <= TOTAL_STEPS; i++) {
        // Columna: dot + label
        const col = document.createElement('div');
        col.className = 'stepper-item';

        const dot = document.createElement('div');
        dot.className = 'stepper-dot';
        dot.id = `s-dot-${i}`;
        dot.textContent = i;

        const lbl = document.createElement('div');
        lbl.className = 'stepper-label';
        lbl.id = `s-lbl-${i}`;
        lbl.textContent = STEP_LABELS[i - 1];

        col.appendChild(dot);
        col.appendChild(lbl);
        wrap.appendChild(col);

        // Línea entre ítems (no después del último)
        if (i < TOTAL_STEPS) {
            const line = document.createElement('div');
            line.className = 'stepper-line';
            line.id = `s-line-${i}`;
            wrap.appendChild(line);
        }
    }
}

function updateStepper(allDone) {
    for (let i = 1; i <= TOTAL_STEPS; i++) {
        const dot = document.getElementById(`s-dot-${i}`);
        const lbl = document.getElementById(`s-lbl-${i}`);
        if (!dot) continue;

        dot.classList.remove('active', 'done');
        if (lbl) lbl.classList.remove('active', 'done');

        const isDone   = allDone || i < currentStep;
        const isActive = !allDone && i === currentStep;

        if (isDone) {
            dot.classList.add('done');
            dot.innerHTML = TICK_SVG;
            if (lbl) lbl.classList.add('done');
        } else if (isActive) {
            dot.classList.add('active');
            dot.textContent = i;
            if (lbl) lbl.classList.add('active');
        } else {
            dot.textContent = i;
        }

        // Línea que va HACIA este ítem (la de la izquierda, índice i-1)
        if (i > 1) {
            const line = document.getElementById(`s-line-${i - 1}`);
            if (line) {
                if (allDone || i <= currentStep) line.classList.add('done');
                else                              line.classList.remove('done');
            }
        }
    }
}

// ============================================================================
// NAVEGACIÓN
// ============================================================================
function goToStep(step) {
    document.querySelectorAll('.step-panel').forEach(el => el.classList.add('hidden'));

    const target = document.getElementById(`step-${step}`);
    if (target) {
        target.classList.remove('hidden');
        target.classList.add('step-panel'); // asegura animación
        // Forzar re-animación
        target.style.animation = 'none';
        target.offsetHeight; // reflow
        target.style.animation = '';
    }

    currentStep = step;
    updateStepper(false);

    // Scroll suave al inicio del contenido
    window.scrollTo({ top: 0, behavior: 'smooth' });

    // Acciones especiales por paso
    if (step === 2) setupContractScrolling();
    if (step === 7) initializeSignaturePad();
    if (step === 8) { showSummary(); requestGeolocation(); }
}

function nextStep() {
    if (currentStep < TOTAL_STEPS) {
        goToStep(currentStep + 1);
    }
}

// ============================================================================
// PASO 2: SCROLL DEL CONTRATO
// ============================================================================
function setupContractScrolling() {
    const content  = document.getElementById('contract-content');
    const checkbox = document.getElementById('accept-terms');
    const button   = document.getElementById('continue-after-read');
    const message  = document.getElementById('scroll-message');
    let reached    = false;

    function enable() {
        if (reached) return;
        reached = true;
        checkbox.disabled = false;
        if (message) message.classList.add('hidden');
    }

    // Si el contenido no necesita scroll, habilitar de inmediato
    setTimeout(() => {
        if (content.scrollHeight <= content.clientHeight + 5) enable();
    }, 400);

    content.addEventListener('scroll', () => {
        if (content.scrollHeight - content.scrollTop <= content.clientHeight + 12) enable();
    });

    // Fallback a los 6 segundos
    setTimeout(() => {
        if (!reached && message) {
            message.innerHTML = '<p class="text-sm text-gray-700">¿No puedes desplazarte? <button onclick="forceEnableContract()" class="underline font-semibold text-blue-700">Pulsa aquí</button></p>';
        }
    }, 6000);

    checkbox.addEventListener('change', () => {
        button.disabled = !checkbox.checked;
    });
}

window.forceEnableContract = function () {
    const checkbox = document.getElementById('accept-terms');
    const message  = document.getElementById('scroll-message');
    if (message) message.classList.add('hidden');
    checkbox.disabled = false;
    checkbox.checked  = true;
    checkbox.dispatchEvent(new Event('change'));
};

// ============================================================================
// CAPTURA DE FOTOS (pasos 3, 4 y 6)
// ============================================================================
async function startCamera(type) {
    try {
        const facingMode = type === 'selfie' ? 'user' : 'environment';
        const stream = await navigator.mediaDevices.getUserMedia({
            video: { facingMode, width: { ideal: 1920 }, height: { ideal: 1080 } }
        });

        const video = document.getElementById(`camera-${type}`);
        video.srcObject = stream;
        video.classList.remove('hidden');
        cameraStreams[type] = stream;

        document.getElementById(`start-camera-${type}`).classList.add('hidden');
        document.getElementById(`controls-${type}`).classList.remove('hidden');
    } catch (err) {
        console.error('Camera error:', err);
        showToast('No se pudo acceder a la cámara. Verifica los permisos del navegador.', 'error');
    }
}

function capturePhoto(type) {
    const video   = document.getElementById(`camera-${type}`);
    const canvas  = document.getElementById(`canvas-${type}`);
    const preview = document.getElementById(`preview-${type}`);

    canvas.width  = video.videoWidth;
    canvas.height = video.videoHeight;

    const ctx = canvas.getContext('2d');

    // Para selfie, voltear horizontalmente (espejo → natural)
    if (type === 'selfie') {
        ctx.translate(canvas.width, 0);
        ctx.scale(-1, 1);
    }

    ctx.drawImage(video, 0, 0, canvas.width, canvas.height);

    const imageData = canvas.toDataURL('image/jpeg', 0.88);

    preview.src = imageData;
    preview.classList.remove('hidden');
    video.classList.add('hidden');
    stopCamera(type);

    const fieldMap = { 'doc-frontal': 'documento_frontal', 'doc-trasero': 'documento_trasero', 'selfie': 'selfie' };
    signatureData[fieldMap[type] || type] = imageData;

    // Mostrar acciones (repetir / continuar)
    const controls     = document.getElementById(`controls-${type}`);
    const photoActions = document.getElementById(`photo-actions-${type}`);
    controls.querySelectorAll('button')[0].classList.add('hidden');
    if (photoActions) photoActions.classList.remove('hidden');
}

function retakePhoto(type) {
    const preview = document.getElementById(`preview-${type}`);
    preview.classList.add('hidden');
    preview.src = '';

    const fieldMap = { 'doc-frontal': 'documento_frontal', 'doc-trasero': 'documento_trasero', 'selfie': 'selfie' };
    signatureData[fieldMap[type] || type] = null;

    const controls     = document.getElementById(`controls-${type}`);
    const photoActions = document.getElementById(`photo-actions-${type}`);
    controls.querySelectorAll('button')[0].classList.remove('hidden');
    if (photoActions) photoActions.classList.add('hidden');

    startCamera(type);
}

function stopCamera(type) {
    if (cameraStreams[type]) {
        cameraStreams[type].getTracks().forEach(t => t.stop());
        delete cameraStreams[type];
    }
}

// ============================================================================
// PASO 5: VALIDAR DATOS
// ============================================================================
function updatePhonePlaceholder() {
    const sel = document.getElementById('phone-indicativo');
    const inp = document.getElementById('telefono-numero');
    if (!sel || !inp) return;
    const opt = sel.options[sel.selectedIndex];
    inp.placeholder = opt.dataset.mask || 'Número';
}

function validateDocumentData() {
    const nombre    = document.getElementById('nombre-completo').value.trim();
    const fechaNac  = document.getElementById('fecha-nacimiento').value;
    const tipo      = document.getElementById('tipo-documento').value;
    const numero    = document.getElementById('numero-documento').value.trim();
    const fechaExp  = document.getElementById('fecha-expedicion').value;

    // Teléfono: indicativo + número separados
    const indicativoSel = document.getElementById('phone-indicativo');
    const telefonoNum   = document.getElementById('telefono-numero');
    const indicativo    = indicativoSel ? indicativoSel.value.replace(/\D/g, '') : '57';
    const numLimpio     = telefonoNum   ? telefonoNum.value.replace(/\D/g, '')   : '';
    const telefonoFull  = indicativo + numLimpio;

    if (!nombre) {
        showToast('Por favor ingresa tu nombre completo.', 'error');
        document.getElementById('nombre-completo').focus();
        return;
    }
    if (!fechaNac) {
        showToast('Por favor ingresa tu fecha de nacimiento.', 'error');
        return;
    }
    if (!tipo) {
        showToast('Por favor selecciona el tipo de documento.', 'error');
        return;
    }
    if (!numero || numero.length < 4) {
        showToast('Por favor ingresa un número de documento válido.', 'error');
        document.getElementById('numero-documento').focus();
        return;
    }
    if (!fechaExp) {
        showToast('Por favor ingresa la fecha de expedición de tu documento.', 'error');
        return;
    }
    if (numLimpio.length < 7) {
        showToast('Por favor ingresa un número de teléfono válido.', 'error');
        if (telefonoNum) telefonoNum.focus();
        return;
    }

    // Actualizar campo oculto #telefono con número completo
    const telefonoHidden = document.getElementById('telefono');
    if (telefonoHidden) telefonoHidden.value = telefonoFull;

    signatureData.nombre_completo   = nombre;
    signatureData.fecha_nacimiento  = fechaNac;
    signatureData.tipo_documento    = tipo;
    signatureData.numero_documento  = numero;
    signatureData.fecha_expedicion  = fechaExp;
    signatureData.telefono          = telefonoFull;

    nextStep();
}

// ============================================================================
// PASO 7: FIRMA DIGITAL
// ============================================================================
function initializeSignaturePad() {
    if (signaturePad) {
        signaturePad.clear();
        return;
    }

    const canvas = document.getElementById('signature-pad');

    function resizeCanvas() {
        const ratio  = Math.max(window.devicePixelRatio || 1, 1);
        canvas.width  = canvas.offsetWidth  * ratio;
        canvas.height = canvas.offsetHeight * ratio;
        canvas.getContext('2d').scale(ratio, ratio);
        if (signaturePad) signaturePad.clear();
    }

    window.addEventListener('resize', resizeCanvas);
    resizeCanvas();

    signaturePad = new SignaturePad(canvas, {
        backgroundColor: 'rgb(255,255,255)',
        penColor:        'rgb(15,15,15)',
        minWidth:        1,
        maxWidth:        3.5,
        throttle:        8
    });
}

function clearSignature() {
    if (signaturePad) signaturePad.clear();
}

function validateSignature() {
    if (!signaturePad || signaturePad.isEmpty()) {
        showToast('Por favor, dibuja tu firma antes de continuar.', 'error');
        return;
    }
    signatureData.firma_imagen = signaturePad.toDataURL('image/png');
    nextStep();
}

// ============================================================================
// PASO 8: RESUMEN
// ============================================================================
function formatDate(val) {
    if (!val) return '—';
    const [y, m, d] = val.split('-');
    return `${d}/${m}/${y}`;
}

function showSummary() {
    const summary = document.getElementById('summary');
    if (!summary) return;

    const tipoMap = { CC: 'Cédula de Ciudadanía', TI: 'Tarjeta de Identidad', CE: 'Cédula de Extranjería', PP: 'Pasaporte', DNI: 'DNI', RUT: 'RUT' };

    summary.innerHTML = `
        <!-- Datos personales -->
        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
            <p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Datos del firmante</p>
            <div class="grid grid-cols-2 gap-3">
                <div class="col-span-2">
                    <p class="text-xs text-gray-500 mb-0.5">Nombre completo</p>
                    <p class="text-sm font-semibold text-gray-900">${escHtml(signatureData.nombre_completo)}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-0.5">Fecha de nacimiento</p>
                    <p class="text-sm font-semibold text-gray-900">${formatDate(signatureData.fecha_nacimiento)}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-0.5">Teléfono</p>
                    <p class="text-sm font-semibold text-gray-900">+${escHtml(signatureData.telefono)}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-0.5">Tipo de documento</p>
                    <p class="text-sm font-semibold text-gray-900">${tipoMap[signatureData.tipo_documento] || signatureData.tipo_documento}</p>
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-0.5">Número</p>
                    <p class="text-sm font-semibold text-gray-900">${escHtml(signatureData.numero_documento)}</p>
                </div>
                <div class="col-span-2">
                    <p class="text-xs text-gray-500 mb-0.5">Fecha de expedición</p>
                    <p class="text-sm font-semibold text-gray-900">${formatDate(signatureData.fecha_expedicion)}</p>
                </div>
            </div>
        </div>

        <!-- Evidencias -->
        <div class="bg-white rounded-2xl border border-gray-200 shadow-sm p-4">
            <p class="text-xs font-semibold text-gray-400 uppercase tracking-wide mb-3">Evidencias capturadas</p>
            <div class="grid grid-cols-2 gap-3">
                <div>
                    <p class="text-xs text-gray-500 mb-1.5">Doc. Frontal</p>
                    <img src="${signatureData.documento_frontal}" alt="Doc frontal"
                         class="w-full rounded-xl border border-gray-200 object-cover aspect-video">
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-1.5">Doc. Trasero</p>
                    <img src="${signatureData.documento_trasero}" alt="Doc trasero"
                         class="w-full rounded-xl border border-gray-200 object-cover aspect-video">
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-1.5">Selfie</p>
                    <img src="${signatureData.selfie}" alt="Selfie"
                         class="w-full rounded-xl border border-gray-200 object-cover aspect-square">
                </div>
                <div>
                    <p class="text-xs text-gray-500 mb-1.5">Firma digital</p>
                    <img src="${signatureData.firma_imagen}" alt="Firma"
                         class="w-full rounded-xl border border-gray-200 bg-white object-contain aspect-square">
                </div>
            </div>
        </div>
    `;
}

function escHtml(str) {
    return String(str || '')
        .replace(/&/g, '&amp;')
        .replace(/</g, '&lt;')
        .replace(/>/g, '&gt;')
        .replace(/"/g, '&quot;');
}

// ============================================================================
// GEOLOCALIZACIÓN
// ============================================================================
function requestGeolocation() {
    if (!navigator.geolocation) return;
    navigator.geolocation.getCurrentPosition(
        ({ coords }) => {
            signatureData.lat       = coords.latitude;
            signatureData.lng       = coords.longitude;
            signatureData.precision = Math.round(coords.accuracy);
        },
        (err) => console.warn('Geolocation not available:', err.message),
        { timeout: 8000 }
    );
}

// ============================================================================
// ENVÍO DE LA FIRMA
// ============================================================================
async function submitSignature() {
    const btn = document.getElementById('submit-btn');
    btn.disabled    = true;
    btn.textContent = 'Procesando…';

    try {
        const res    = await fetch(apiUrl, {
            method:  'POST',
            headers: { 'Content-Type': 'application/json' },
            body:    JSON.stringify({ token: contractToken, ...signatureData })
        });
        const result = await res.json();

        if (result.success) {
            showSuccessModal(result.signature_id);
        } else {
            showToast(result.message || 'No se pudo procesar la firma. Intenta de nuevo.', 'error');
            btn.disabled    = false;
            btn.textContent = 'Firmar contrato';
        }
    } catch (err) {
        console.error('Submit error:', err);
        showToast('Error de conexión. Verifica tu internet e intenta de nuevo.', 'error');
        btn.disabled    = false;
        btn.textContent = 'Firmar contrato';
    }
}

// ============================================================================
// MODAL DE ÉXITO
// ============================================================================
function showSuccessModal(signatureId) {
    // Poner todos los pasos del stepper en verde
    updateStepper(true);

    // Ocultar todo el contenido de pasos
    document.querySelectorAll('.step-panel').forEach(el => el.classList.add('hidden'));

    // Mostrar ID de firma si existe
    const sigIdEl = document.getElementById('success-signature-id');
    if (sigIdEl && signatureId) {
        sigIdEl.textContent = `ID de firma: ${signatureId}`;
    }

    // Abrir modal
    const modal = document.getElementById('modal-success');
    if (modal) {
        modal.classList.add('open');
        document.body.style.overflow = 'hidden';
    }
}

// ============================================================================
// TOAST DE NOTIFICACIONES
// ============================================================================
function showToast(message, type = 'info') {
    // Eliminar toast anterior si existe
    const prev = document.getElementById('toast-msg');
    if (prev) prev.remove();

    const colors = {
        info:    'bg-gray-900 text-white',
        error:   'bg-red-600 text-white',
        success: 'bg-green-600 text-white'
    };

    const toast = document.createElement('div');
    toast.id        = 'toast-msg';
    toast.className = `fixed bottom-6 left-1/2 -translate-x-1/2 z-50 px-5 py-3 rounded-2xl text-sm font-medium shadow-xl max-w-xs text-center ${colors[type] || colors.info}`;
    toast.style.cssText = 'animation: fadeUp .25s ease; white-space: pre-line;';
    toast.textContent   = message;

    document.body.appendChild(toast);

    setTimeout(() => {
        toast.style.opacity = '0';
        toast.style.transition = 'opacity .3s';
        setTimeout(() => toast.remove(), 300);
    }, 3800);
}

// ============================================================================
// INICIALIZACIÓN
// ============================================================================
document.addEventListener('DOMContentLoaded', () => {
    buildStepper();
    updateStepper(false);

    // Paso 1 siempre visible al cargar
    const step1 = document.getElementById('step-1');
    if (step1) step1.classList.remove('hidden');

    // Inicializar placeholder teléfono
    updatePhonePlaceholder();
});

// Limpiar cámaras al salir
window.addEventListener('beforeunload', () => {
    Object.keys(cameraStreams).forEach(stopCamera);
});
