---
import Button from '@components/base/Button.astro';

// Получаем ошибку из параметров URL
const url = new URL(Astro.request.url);
const initialError = url.searchParams.get('error');
---

<div class="min-h-screen flex items-center justify-center bg-gray-100 p-4">
    <div class="flex flex-col md:flex-row w-full max-w-4xl bg-white rounded-2xl shadow-2xl overflow-hidden">

        {/* ЛЕВАЯ КОЛОНКА (Изображение) */}
        <div class="w-full md:w-1/2 relative min-h-[300px] md:min-h-0">
            <img
                    src="/images/auth/sign-in.avif"
                    alt="Interior"
                    class="object-cover w-full h-full"
            />
            <div class="absolute inset-0 bg-black/40 flex flex-col justify-end p-8">
                <h2 class="text-white font-bold text-3xl">Minivan Berlin</h2>
                <p class="text-white text-lg mt-2 font-light">
                    Ihr zuverlässiger Partner für komfortable Fahrten.
                </p>
            </div>
        </div>

        {/* ПРАВАЯ КОЛОНКА (Форма) */}
        <div class="w-full md:w-1/2 p-8 md:p-12 flex flex-col justify-center">
            <div class="mb-8">
                <h2 class="font-bold text-gray-900 text-3xl">Willkommen zurück</h2>
                <p class="text-gray-500 mt-2">
                    Melden Sie sich an, um fortzufahren.
                </p>
            </div>

            {/* Глобальный блок ошибок (от сервера или API) */}
            <div id="global-error-container" class={`mb-6 ${initialError ? '' : 'hidden'}`}>
                <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 rounded-r" role="alert">
                    <p class="font-bold">Anmeldung fehlgeschlagen</p>
                    <p id="global-error-message">{initialError}</p>
                </div>
            </div>

            {/* ФОРМА */}
            <form id="login-form" class="space-y-5" novalidate>

                {/* EMAIL */}
                <div class="group">
                    <label for="email" class="block text-sm font-medium text-gray-700 mb-1">Email-Adresse</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M16 12a4 4 0 10-8 0 4 4 0 008 0zm0 0v1.5a2.5 2.5 0 005 0V12a9 9 0 10-9 9m4.5-1.206a8.959 8.959 0 01-4.5 1.207"></path></svg>
                        </div>
                        <input
                                id="email"
                                name="email"
                                type="email"
                                autocomplete="email"
                                required
                                minlength="5"
                                maxlength="100"
                                class="form-input block w-full pl-10 pr-3 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
                                placeholder="beispiel@email.de"
                                aria-describedby="emailError"
                        />
                    </div>
                    <div id="emailError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
                    <div class="text-xs text-gray-500 mt-1">5-100 Zeichen</div>
                </div>

                {/* PASSWORD */}
                <div class="group">
                    <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Passwort</label>
                    <div class="relative">
                        <div class="absolute inset-y-0 left-0 pl-3 flex items-center pointer-events-none">
                            <svg class="h-5 w-5 text-gray-400 group-focus-within:text-blue-500 transition-colors" 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"></path></svg>
                        </div>
                        <input
                                id="password"
                                name="password"
                                type="password"
                                autocomplete="current-password"
                                required
                                minlength="8"
                                maxlength="128"
                                class="form-input block w-full pl-10 pr-10 py-2.5 border border-gray-300 rounded-lg shadow-sm placeholder-gray-400 focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500 sm:text-sm transition-all"
                                placeholder="Mindestens 8 Zeichen"
                                aria-describedby="passwordError"
                        />
                        <button type="button" id="togglePassword" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 cursor-pointer focus:outline-none transition-colors" aria-label="Passwort anzeigen">
                            <svg id="eyeIcon" 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="M15 12a3 3 0 11-6 0 3 3 0 016 0z"></path>
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z"></path>
                            </svg>
                        </button>
                    </div>
                    <div id="passwordError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
                    <div class="text-xs text-gray-500 mt-1">Mindestens 8 Zeichen</div>
                </div>

                <div class="flex items-center justify-end text-sm">
                    <a href="/auth/forgot-password" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
                        Passwort vergessen?
                    </a>
                </div>

                <div class="pt-2">
                    <Button
                            id="submitButton"
                            type="submit"
                            variant="blue"
                            size="md"
                            fullWidth={true}
                            disabled={true}
                            className="opacity-50 cursor-not-allowed transition-all duration-300"
                    >
                        Anmelden
                    </Button>
                </div>
            </form>

            <div class="mt-8">
                <div class="relative">
                    <div class="absolute inset-0 flex items-center">
                        <div class="w-full border-t border-gray-200" />
                    </div>
                    <div class="relative flex justify-center text-sm">
                        <span class="px-3 bg-white text-gray-500">Oder weiter mit</span>
                    </div>
                </div>

                <div class="mt-6">
                    <a
                            href={`/api/auth/google${Astro.url.searchParams.get('callbackUrl') ? `?callbackUrl=${encodeURIComponent(Astro.url.searchParams.get('callbackUrl'))}` : ''}`}
                            class="w-full flex justify-center items-center px-4 py-3 border border-gray-300 rounded-lg shadow-sm bg-white font-medium text-gray-700 hover:bg-gray-50 transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500 cursor-pointer"
                    >
                        <svg class="w-5 h-5 mr-2" viewBox="0 0 24 24" width="24" height="24">
                            <path d="M22.56 12.25c0-.78-.07-1.53-.2-2.25H12v4.26h5.92c-.26 1.37-1.04 2.53-2.21 3.31v2.77h3.57c2.08-1.92 3.28-4.74 3.28-8.09z" fill="#4285F4"/>
                            <path d="M12 23c2.97 0 5.46-.98 7.28-2.66l-3.57-2.77c-.98.66-2.23 1.06-3.71 1.06-2.86 0-5.29-1.93-6.16-4.53H2.18v2.84C3.99 20.53 7.7 23 12 23z" fill="#34A853"/>
                            <path d="M5.84 14.09c-.22-.66-.35-1.36-.35-2.09s.13-1.43.35-2.09V7.07H2.18C1.43 8.55 1 10.22 1 12s.43 3.45 1.18 4.93l2.85-2.22.81-.62z" fill="#FBBC05"/>
                            <path d="M12 5.38c1.62 0 3.06.56 4.21 1.64l3.15-3.15C17.45 2.09 14.97 1 12 1 7.7 1 3.99 3.47 2.18 7.07l3.66 2.84c.87-2.6 3.3-4.53 6.16-4.53z" fill="#EA4335"/>
                        </svg>
                        Mit Google anmelden
                    </a>
                </div>
            </div>

            <div class="mt-8 text-center">
                <p class="text-sm text-gray-600">
                    Noch kein Konto?{' '}
                    <a href="/auth/register" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
                        Registrieren
                    </a>
                </p>
            </div>
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // === ЭЛЕМЕНТЫ DOM ===
        const form = document.getElementById('login-form') as HTMLFormElement;
        const submitButton = document.getElementById('submitButton') as HTMLButtonElement;

        const emailInput = document.getElementById('email') as HTMLInputElement;
        const passwordInput = document.getElementById('password') as HTMLInputElement;

        const emailError = document.getElementById('emailError') as HTMLDivElement;
        const passwordError = document.getElementById('passwordError') as HTMLDivElement;

        const globalErrorContainer = document.getElementById('global-error-container');
        const globalErrorMessage = document.getElementById('global-error-message');

        const togglePassword = document.getElementById('togglePassword');
        const eyeIcon = document.getElementById('eyeIcon');

        // === ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ===
        const showError = (el: HTMLElement, message: string) => {
            el.textContent = message;
            el.classList.remove('hidden');
        };

        const hideError = (el: HTMLElement) => {
            el.textContent = '';
            el.classList.add('hidden');
        };

        const setValidState = (input: HTMLInputElement, isValid: boolean) => {
            if (isValid) {
                input.classList.remove('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
                input.classList.add('border-green-500');
            } else {
                input.classList.remove('border-green-500');
                input.classList.add('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
            }
        };

        const resetState = (input: HTMLInputElement) => {
            input.classList.remove('border-red-500', 'border-green-500');
        };

        // === 1. УПРАВЛЕНИЕ ПАРОЛЕМ (ГЛАЗОК) ===
        if (togglePassword && passwordInput && eyeIcon) {
            togglePassword.addEventListener('click', () => {
                const type = passwordInput.getAttribute('type') === 'password' ? 'text' : 'password';
                passwordInput.setAttribute('type', type);

                if (type === 'text') {
                    // Глаз перечеркнут (скрыть)
                    eyeIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13.875 18.825A10.05 10.05 0 0112 19c-4.478 0-8.268-2.943-9.543-7a9.97 9.97 0 011.563-3.029m5.858.908a3 3 0 114.243 4.243M9.878 9.878l4.242 4.242M9.88 9.88l-3.29-3.29m7.532 7.532l3.29 3.29M3 3l3.59 3.59m0 0A9.953 9.953 0 0112 5c4.478 0 8.268 2.943 9.543 7a10.025 10.025 0 01-4.132 5.411m0 0L21 21" />';
                } else {
                    // Глаз открыт (показать)
                    eyeIcon.innerHTML = '<path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M15 12a3 3 0 11-6 0 3 3 0 016 0z" /><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M2.458 12C3.732 7.943 7.523 5 12 5c4.478 0 8.268 2.943 9.542 7-1.274 4.057-5.064 7-9.542 7-4.477 0-8.268-2.943-9.542-7z" />';
                }
            });
        }

        // === 2. ВАЛИДАЦИЯ EMAIL ===
        const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;

        // Запрет пробелов в Email
        if (emailInput) {
            emailInput.addEventListener('keydown', (e) => {
                if (e.key === ' ') e.preventDefault();
            });

            // Санитизация при вставке
            emailInput.addEventListener('input', (e) => {
                const target = e.target as HTMLInputElement;
                if (target.value.includes(' ')) {
                    target.value = target.value.replace(/\s/g, '');
                }

                // Проверка длины
                if (target.value.length > 100) {
                    target.value = target.value.substring(0, 100);
                }

                validateGlobal();
            });

            emailInput.addEventListener('blur', () => {
                const val = emailInput.value.trim();
                if (!val) {
                    showError(emailError, 'E-Mail ist erforderlich');
                    setValidState(emailInput, false);
                } else if (val.length < 5) {
                    showError(emailError, 'E-Mail muss mindestens 5 Zeichen enthalten');
                    setValidState(emailInput, false);
                } else if (val.length > 100) {
                    showError(emailError, 'E-Mail darf maximal 100 Zeichen enthalten');
                    setValidState(emailInput, false);
                } else if (!emailRegex.test(val)) {
                    showError(emailError, 'Ungültiges E-Mail-Format');
                    setValidState(emailInput, false);
                } else {
                    hideError(emailError);
                    setValidState(emailInput, true);
                }
                validateGlobal();
            });
        }

        // === 3. ВАЛИДАЦИЯ ПАРОЛЯ ===
        if (passwordInput) {
            // Запрет пробелов в начале и конце пароля
            passwordInput.addEventListener('input', (e) => {
                const target = e.target as HTMLInputElement;

                // Проверка длины
                if (target.value.length > 128) {
                    target.value = target.value.substring(0, 128);
                }

                validateGlobal();
            });

            passwordInput.addEventListener('blur', () => {
                const val = passwordInput.value;
                if (!val) {
                    showError(passwordError, 'Passwort ist erforderlich');
                    setValidState(passwordInput, false);
                } else if (val.length < 8) {
                    showError(passwordError, 'Passwort muss mindestens 8 Zeichen enthalten');
                    setValidState(passwordInput, false);
                } else if (val.length > 128) {
                    showError(passwordError, 'Passwort darf maximal 128 Zeichen enthalten');
                    setValidState(passwordInput, false);
                } else {
                    hideError(passwordError);
                    resetState(passwordInput); // Пароль не красим в зеленый для безопасности, просто убираем красный
                }
                validateGlobal();
            });

            passwordInput.addEventListener('input', validateGlobal);
        }

        // === 4. ГЛОБАЛЬНАЯ ВАЛИДАЦИЯ КНОПКИ ===
        function validateGlobal() {
            if (!emailInput || !passwordInput || !submitButton) return;

            const isEmailFilled = emailInput.value.trim().length > 0;
            const isEmailLengthValid = emailInput.value.trim().length >= 5 && emailInput.value.trim().length <= 100;
            const isEmailFormatValid = emailRegex.test(emailInput.value.trim());
            const isPasswordFilled = passwordInput.value.length > 0;
            const isPasswordLengthValid = passwordInput.value.length >= 8 && passwordInput.value.length <= 128;

            if (isEmailFilled && isEmailLengthValid && isEmailFormatValid && isPasswordFilled && isPasswordLengthValid) {
                submitButton.disabled = false;
                submitButton.classList.remove('opacity-50', 'cursor-not-allowed');
                submitButton.classList.add('hover:shadow-lg', 'cursor-pointer');
            } else {
                submitButton.disabled = true;
                submitButton.classList.add('opacity-50', 'cursor-not-allowed');
                submitButton.classList.remove('hover:shadow-lg', 'cursor-pointer');
            }
        }

        // Инициализация
        validateGlobal();


        // === 5. ОТПРАВКА ФОРМЫ (AJAX) ===
        if (form) {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();

                // Извлекаем callbackUrl из URL параметров
                const urlParams = new URLSearchParams(window.location.search);
                const callbackUrl = urlParams.get('callbackUrl') || '/bewertungen'; // По умолчанию остаемся на странице отзывов

                // UI Loading State
                const originalContent = submitButton.innerHTML;
                const originalWidth = submitButton.offsetWidth; // Фиксируем ширину, чтобы кнопка не дергалась
                submitButton.style.width = `${originalWidth}px`;

                submitButton.innerHTML = `
                    <div class="flex items-center justify-center">
                        <svg class="animate-spin -ml-1 mr-3 h-5 w-5 text-white" xmlns="http://www.w3.org/2000/svg" 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>
                        Wird geladen...
                    </div>
                `;
                submitButton.disabled = true;

                // Скрываем старые ошибки
                if (globalErrorContainer) globalErrorContainer.classList.add('hidden');

                const formData = new FormData(form);
                const data = Object.fromEntries(formData);

                try {
                    const response = await fetch('/api/auth/login', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify(data)
                    });

                    const result = await response.json();

                    if (result.success) {
                        // Успех - редирект на callbackUrl с параметром для отображения уведомления
                        const successUrl = callbackUrl.includes('?')
                            ? `${callbackUrl}&loginSuccess=true`
                            : `${callbackUrl}?loginSuccess=true`;
                        window.location.href = successUrl;
                    } else {
                        // Ошибка API
                        if (globalErrorMessage && globalErrorContainer) {
                            globalErrorMessage.textContent = result.message || 'E-Mail oder Passwort falsch.';
                            globalErrorContainer.classList.remove('hidden');
                        }
                        // Возвращаем кнопку
                        submitButton.innerHTML = originalContent;
                        submitButton.style.width = 'auto';
                        submitButton.disabled = false;
                    }
                } catch (error) {
                    console.error(error);
                    if (globalErrorMessage && globalErrorContainer) {
                        globalErrorMessage.textContent = 'Verbindungsfehler. Bitte versuchen Sie es später erneut.';
                        globalErrorContainer.classList.remove('hidden');
                    }
                    submitButton.innerHTML = originalContent;
                    submitButton.style.width = 'auto';
                    submitButton.disabled = false;
                }
            });
        }
    });
</script>