<!DOCTYPE html>
<html lang="es" class="h-full bg-slate-950">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title><?php echo isset($title) ? $title : 'Nueva Contraseña - ASISMA CRM'; ?></title>
    <link rel="icon" type="image/png" href="<?php echo APP_URL; ?>/public/assets/img/favicon.png">
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Plus+Jakarta+Sans:wght@300;400;500;600;700;800&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/sweetalert2@11"></script>
    <script src="https://unpkg.com/lucide@latest"></script>
    <style>
        body { font-family: 'Plus Jakarta Sans', sans-serif; }
        .animated-bg {
            background: linear-gradient(-45deg, #0f172a, #1e3a8a, #020617, #172554);
            background-size: 400% 400%;
            animation: gradientBG 15s ease infinite;
        }
        @keyframes gradientBG {
            0% { background-position: 0% 50%; }
            50% { background-position: 100% 50%; }
            100% { background-position: 0% 50%; }
        }
    </style>
</head>
<body class="h-full animated-bg flex items-center justify-center px-6 py-12 text-slate-100">

    <div class="absolute inset-0 bg-[radial-gradient(circle_at_top_right,rgba(37,99,235,0.15),transparent_45%)]"></div>

    <div class="w-full max-w-md relative z-10">
        <div class="flex items-center justify-center gap-2 mb-8">
            <div class="w-11 h-11 rounded-xl bg-gradient-to-tr from-blue-600 to-indigo-500 flex items-center justify-center shadow-lg shadow-blue-500/30">
                <i data-lucide="layers" class="w-6 h-6 text-white"></i>
            </div>
            <span class="text-2xl font-extrabold text-white">ASISMA<span class="text-blue-500">CRM</span></span>
        </div>

        <div class="bg-slate-900/70 border border-slate-800/80 rounded-2xl p-8 shadow-2xl backdrop-blur-md">

            <?php if (!$valido): ?>
            <!-- Enlace invalido o vencido -->
            <div class="text-center">
                <div class="w-14 h-14 mx-auto mb-4 rounded-2xl bg-red-500/10 border border-red-500/20 flex items-center justify-center">
                    <i data-lucide="link-2-off" class="w-7 h-7 text-red-400"></i>
                </div>
                <h2 class="text-2xl font-bold tracking-tight text-white">Enlace no válido</h2>
                <p class="text-slate-400 mt-2 text-sm">Este enlace de recuperación no es válido, ya se usó o venció (dura 1 hora). Solicita uno nuevo.</p>
                <a href="<?php echo APP_URL; ?>/password/olvide"
                   class="mt-6 w-full inline-flex items-center justify-center gap-2 py-3.5 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-semibold rounded-xl transition-all shadow-lg shadow-blue-500/20">
                    <i data-lucide="rotate-cw" class="w-5 h-5"></i> Solicitar un nuevo enlace
                </a>
                <a href="<?php echo APP_URL; ?>/login" class="inline-flex items-center gap-1.5 mt-4 text-sm text-slate-400 hover:text-slate-200 transition-colors">
                    <i data-lucide="arrow-left" class="w-4 h-4"></i> Volver al inicio de sesión
                </a>
            </div>

            <?php else: ?>
            <!-- Formulario de nueva contrasena -->
            <div class="text-center mb-6">
                <div class="w-14 h-14 mx-auto mb-4 rounded-2xl bg-blue-500/10 border border-blue-500/20 flex items-center justify-center">
                    <i data-lucide="lock-keyhole" class="w-7 h-7 text-blue-400"></i>
                </div>
                <h2 class="text-2xl font-bold tracking-tight text-white">Crea tu nueva contraseña</h2>
                <p class="text-slate-400 mt-2 text-sm"><?php echo ClaveHelper::DESCRIPCION; ?></p>
            </div>

            <form id="resetForm" class="space-y-5">
                <input type="hidden" name="token" value="<?php echo htmlspecialchars($token); ?>">

                <div>
                    <label for="password" class="block text-sm font-semibold text-slate-300 mb-1">Nueva Contraseña</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center text-slate-500">
                            <i data-lucide="lock" class="w-5 h-5"></i>
                        </span>
                        <input type="password" id="password" name="password" required minlength="8"
                               pattern="<?php echo ClaveHelper::patronHtml(); ?>" title="<?php echo ClaveHelper::DESCRIPCION; ?>"
                               class="block w-full pl-11 pr-11 py-3 bg-slate-950 border border-slate-800 rounded-xl text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                               placeholder="••••••••">
                        <button type="button" id="togglePassword" class="absolute inset-y-0 right-0 pr-3.5 flex items-center text-slate-500 hover:text-slate-300 transition-colors">
                            <i data-lucide="eye" class="w-5 h-5" id="eyeIcon"></i>
                        </button>
                    </div>
                    <div id="medidorClave"></div>
                </div>

                <div>
                    <label for="password_confirmacion" class="block text-sm font-semibold text-slate-300 mb-1">Repetir Contraseña</label>
                    <div class="relative">
                        <span class="absolute inset-y-0 left-0 pl-3.5 flex items-center text-slate-500">
                            <i data-lucide="lock" class="w-5 h-5"></i>
                        </span>
                        <input type="password" id="password_confirmacion" name="password_confirmacion" required minlength="8"
                               class="block w-full pl-11 pr-4 py-3 bg-slate-950 border border-slate-800 rounded-xl text-slate-100 placeholder-slate-500 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-transparent transition-all"
                               placeholder="••••••••">
                    </div>
                </div>

                <button type="submit" id="submitBtn"
                        class="w-full py-3.5 bg-gradient-to-r from-blue-600 to-indigo-600 hover:from-blue-500 hover:to-indigo-500 text-white font-semibold rounded-xl transition-all duration-300 shadow-lg shadow-blue-500/20 hover:shadow-blue-500/40 focus:outline-none focus:ring-2 focus:ring-blue-500 flex items-center justify-center gap-2">
                    <span id="btnText">Guardar nueva contraseña</span>
                    <svg class="hidden animate-spin h-5 w-5 text-white" id="btnSpinner" fill="none" viewBox="0 0 24 24">
                        <circle class="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" stroke-width="4"></circle>
                        <path class="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                    </svg>
                </button>
            </form>
            <?php endif; ?>
        </div>
    </div>

    <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
    <script src="<?php echo APP_URL; ?>/public/assets/js/medidor_clave.js"></script>
    <script>
        $(document).ready(function() {
            lucide.createIcons();
            iniciarMedidorClave('password', 'medidorClave');

            $('#togglePassword').on('click', function() {
                var f = $('#password');
                var isPass = f.attr('type') === 'password';
                f.attr('type', isPass ? 'text' : 'password');
                $('#eyeIcon').attr('data-lucide', isPass ? 'eye-off' : 'eye');
                lucide.createIcons();
            });

            $('#resetForm').on('submit', function(e) {
                e.preventDefault();

                // Espejo de la política del servidor (ClaveHelper::validar)
                var clave = $('#password').val();
                if (!/^(?=.*[A-Z])(?=.*[0-9])(?=.*[^a-zA-Z0-9]).{8,}$/.test(clave)) {
                    Swal.fire({ icon: 'warning', title: 'Contraseña débil', text: '<?php echo ClaveHelper::DESCRIPCION; ?>', background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#f59e0b' });
                    return;
                }

                if ($('#password').val() !== $('#password_confirmacion').val()) {
                    Swal.fire({ icon: 'warning', title: 'No coinciden', text: 'Las dos contraseñas deben ser iguales.', background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#f59e0b' });
                    return;
                }

                $('#submitBtn').attr('disabled', true).addClass('opacity-80');
                $('#btnText').addClass('hidden');
                $('#btnSpinner').removeClass('hidden');

                $.ajax({
                    url: '<?php echo APP_URL; ?>/password/guardar',
                    type: 'POST',
                    data: $(this).serialize(),
                    dataType: 'json',
                    success: function(response) {
                        if (response.success) {
                            Swal.fire({
                                icon: 'success',
                                title: '¡Contraseña actualizada!',
                                text: response.message,
                                background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#3b82f6',
                                showConfirmButton: false, timer: 1800
                            }).then(function() {
                                window.location.href = response.redirect;
                            });
                        } else {
                            Swal.fire({ icon: 'error', title: 'No se pudo guardar', text: response.message, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#ef4444' });
                            resetBtn();
                        }
                    },
                    error: function(xhr) {
                        var msg = (xhr.responseJSON && xhr.responseJSON.message) ? xhr.responseJSON.message : 'Ocurrió un error al procesar la solicitud.';
                        Swal.fire({ icon: 'error', title: 'Error', text: msg, background: '#1e293b', color: '#f8fafc', confirmButtonColor: '#ef4444' });
                        resetBtn();
                    }
                });
            });

            function resetBtn() {
                $('#submitBtn').attr('disabled', false).removeClass('opacity-80');
                $('#btnText').removeClass('hidden');
                $('#btnSpinner').addClass('hidden');
            }
        });
    </script>
</body>
</html>
