<?php

declare(strict_types=1);

require_once __DIR__ . '/includes/auth.php';

if (isAuthenticated()) {
    header('Location: ' . appUrl('index'));
    exit;
}

$error = null;
if (($_GET['error'] ?? '') === 'inactive') {
    $error = 'Tu cuenta ha sido desactivada por el administrador.';
}

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (!verifyCsrfToken($_POST['csrf_token'] ?? '')) {
        $error = 'La sesión del formulario expiró. Intenta nuevamente.';
    } else {
        $username = trim($_POST['username'] ?? '');
        $password = $_POST['password'] ?? '';

        if ($username === '' || $password === '') {
            $error = 'Por favor, completa tu usuario y contraseña.';
        } else {
            $result = attemptLogin($username, $password);
            if ($result['success']) {
                header('Location: ' . appUrl('index'));
                exit;
            } else {
                $error = $result['message'];
            }
        }
    }
}

$csrfToken = getCsrfToken();
?>
<!DOCTYPE html>
<html lang="es">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Iniciar Sesión — Portal de Sistemas</title>
    <link rel="stylesheet" href="assets/css/app.css">
    <script src="assets/js/lucide.min.js"></script>
    <style>
        body.login-screen {
            background-color: #F7F7F5;
            color: #121211;
            position: relative;
            overflow: hidden;
            display: flex;
            align-items: center;
            justify-content: center;
            min-height: 100vh;
            padding: 20px;
        }

        .bg-grid {
            position: fixed;
            inset: 0;
            background-image:
                linear-gradient(to right, rgba(18, 18, 17, 0.035) 1px, transparent 1px),
                linear-gradient(to bottom, rgba(18, 18, 17, 0.035) 1px, transparent 1px);
            background-size: 38px 38px;
            mask-image: radial-gradient(circle at center, black 40%, transparent 90%);
            -webkit-mask-image: radial-gradient(circle at center, black 40%, transparent 90%);
            pointer-events: none;
            z-index: 0;
        }

        .ambient-orb {
            position: fixed;
            border-radius: 50%;
            filter: blur(75px);
            pointer-events: none;
            z-index: 0;
            opacity: 0.65;
            animation: floatOrb 18s infinite alternate ease-in-out;
        }

        .orb-1 {
            width: 440px;
            height: 440px;
            background: radial-gradient(circle, rgba(16, 185, 129, 0.16), rgba(59, 130, 246, 0.06), transparent 70%);
            top: -120px;
            left: -100px;
        }

        .orb-2 {
            width: 500px;
            height: 500px;
            background: radial-gradient(circle, rgba(245, 158, 11, 0.13), rgba(18, 18, 17, 0.05), transparent 70%);
            bottom: -160px;
            right: -120px;
            animation-delay: -9s;
        }

        @keyframes floatOrb {
            0% {
                transform: translate(0, 0) scale(1);
            }

            50% {
                transform: translate(35px, 25px) scale(1.07);
            }

            100% {
                transform: translate(-25px, 40px) scale(0.95);
            }
        }

        .login-card {
            position: relative;
            z-index: 10;
            width: 100%;
            max-width: 400px;
            background: rgba(255, 255, 255, 0.88);
            backdrop-filter: blur(16px);
            -webkit-backdrop-filter: blur(16px);
            border: 1px solid #E4E4E0;
            border-radius: 20px;
            padding: 34px 30px;
            box-shadow: 0 24px 48px -12px rgba(0, 0, 0, 0.06), 0 4px 12px -2px rgba(0, 0, 0, 0.03);
            animation: cardEnter 0.35s cubic-bezier(0.16, 1, 0.3, 1);
        }

        @keyframes cardEnter {
            from {
                opacity: 0;
                transform: translateY(12px) scale(0.99);
            }

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

        .login-logo {
            width: 46px;
            height: 46px;
            border-radius: 13px;
            background: #121211;
            color: #FFFFFF;
            display: flex;
            align-items: center;
            justify-content: center;
            margin-bottom: 18px;
            box-shadow: 0 8px 18px -4px rgba(18, 18, 17, 0.25);
        }

        .input-wrap {
            position: relative;
            display: flex;
            align-items: center;
        }

        .input-icon {
            position: absolute;
            left: 13px;
            color: #9A9A93;
            pointer-events: none;
            width: 16px;
            height: 16px;
        }

        .login-input {
            width: 100%;
            padding: 10.5px 38px 10.5px 38px;
            border-radius: 11px;
            border: 1px solid #DFDFDA;
            background: #FFFFFF;
            color: #121211;
            font-size: 13.5px;
            outline: none;
            transition: border-color 0.18s ease, box-shadow 0.18s ease;
        }

        .login-input:focus {
            border-color: #121211;
            box-shadow: 0 0 0 3px rgba(18, 18, 17, 0.06);
        }

        .pass-toggle {
            position: absolute;
            right: 10px;
            background: none;
            border: none;
            color: #6E6E68;
            cursor: pointer;
            padding: 4px;
            display: flex;
            align-items: center;
            border-radius: 6px;
        }

        .pass-toggle:hover {
            color: #121211;
            background: #F2F2EE;
        }

        .login-submit {
            width: 100%;
            margin-top: 10px;
            padding: 11.5px;
            border-radius: 11px;
            background: #121211;
            color: #FFFFFF;
            font-weight: 600;
            font-size: 13.5px;
            border: none;
            cursor: pointer;
            display: flex;
            align-items: center;
            justify-content: center;
            gap: 8px;
            transition: transform 0.15s ease, opacity 0.15s ease, box-shadow 0.15s ease;
        }

        .login-submit:hover {
            opacity: 0.94;
            transform: translateY(-1px);
            box-shadow: 0 10px 20px -8px rgba(18, 18, 17, 0.35);
        }

        .login-submit:active {
            transform: translateY(0);
        }
    </style>
</head>

<body class="login-screen">

    <div class="bg-grid"></div>
    <div class="ambient-orb orb-1"></div>
    <div class="ambient-orb orb-2"></div>

    <div class="login-card">
        <div style="display:flex; align-items:center; justify-content: center;">
            <div class="login-logo">
                <i data-lucide="layers" style="width:22px;height:22px;"></i>
            </div>
        </div>

        <h1 style="font-size: 19px; font-weight: 700; letter-spacing: -0.02em; margin-bottom: 4px; text-align: center;">
            Portal de Sistemas
        </h1>
        <p style="font-size: 12.5px; color: #6E6E68; margin-bottom: 22px; text-align: center;">
            Ingrese sus credenciales para acceder
        </p>

        <?php if ($error): ?>
            <div class="alert alert-error" style="margin-bottom: 18px; font-size: 12.5px; padding: 10px 12px;">
                <div class="flex-center" style="gap: 8px;">
                    <i data-lucide="alert-circle" style="width:16px;height:16px;flex-shrink:0;"></i>
                    <span><?= e($error) ?></span>
                </div>
            </div>
        <?php endif; ?>

        <form method="POST" autocomplete="on">
            <input type="hidden" name="csrf_token" value="<?= e($csrfToken) ?>">

            <div class="form-group" style="margin-bottom: 14px;">
                <label class="form-label" for="username" style="color:#121211;">Usuario</label>
                <div class="input-wrap">
                    <i data-lucide="user" class="input-icon"></i>
                    <input
                        type="text"
                        id="username"
                        name="username"
                        class="login-input mono"
                        placeholder="usuario"
                        value="<?= e($_POST['username'] ?? '') ?>"
                        required
                        autofocus>
                </div>
            </div>

            <div class="form-group" style="margin-bottom: 18px;">
                <label class="form-label" for="password" style="color:#121211;">Contraseña</label>
                <div class="input-wrap">
                    <i data-lucide="lock" class="input-icon"></i>
                    <input
                        type="password"
                        id="password"
                        name="password"
                        class="login-input"
                        placeholder="••••••••"
                        required>
                    <button type="button" class="pass-toggle" onclick="togglePass()" title="Mostrar / ocultar contraseña">
                        <i data-lucide="eye" id="eye-icon" style="width:16px;height:16px;"></i>
                    </button>
                </div>
            </div>

            <button type="submit" class="login-submit">
                <span>Ingresar al Portal</span>
                <i data-lucide="arrow-right" style="width:16px;height:16px;"></i>
            </button>
        </form>

        <div style="margin-top: 24px; padding-top: 16px; border-top: 1px solid #EDEDEA; display:flex; justify-content:center; align-items:center; font-size:11px; color:#9A9A93;">
            <span>Directorio Centralizado</span>
        </div>
    </div>

    <script>
        lucide.createIcons();

        function togglePass() {
            const input = document.getElementById('password');
            const icon = document.getElementById('eye-icon');
            if (input.type === 'password') {
                input.type = 'text';
                icon.setAttribute('data-lucide', 'eye-off');
            } else {
                input.type = 'password';
                icon.setAttribute('data-lucide', 'eye');
            }
            lucide.createIcons();
        }
    </script>
</body>

</html>