---
import Button from '@components/base/Button.astro';
import PocketBase, { ClientResponseError } from 'pocketbase';

// Локальные переменные состояния
let isSuccess = false;
let formError = '';
let emailForDisplay = ''; // Переменная для отображения email после успешной регистрации

// === ЛОГИКА СЕРВЕРА ===
if (Astro.request.method === "POST") {
    try {
        const formData = await Astro.request.formData();
        const name = formData.get("name") as string;
        const email = formData.get("email") as string;
        const password = formData.get("password") as string;
        const confirmPassword = formData.get("confirmPassword") as string;

        // 1. Проверка паролей на сервере
        if (password !== confirmPassword) {
            throw new Error("Passwörter stimmen nicht überein.");
        }

        // 2. Подключение к PocketBase
        // Используем переменную окружения или дефолтный адрес
        const pb = new PocketBase(import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090');

        // 3. Создание пользователя
        await pb.collection('users').create({
            username: undefined, // Генерируется автоматически, если не задан
            email: email,
            emailVisibility: true,
            password: password,
            passwordConfirm: confirmPassword,
            name: name,
        });

        // 4. Отправка письма подтверждения
        await pb.collection('users').requestVerification(email);

        // 5. Успех
        isSuccess = true;
        emailForDisplay = email; // Сохраняем email для отображения на странице успеха

    } catch (e: unknown) {
        console.error("Registration error:", e);

        if (e instanceof ClientResponseError) {
            const data = e.data.data;
            if (data) {
                // Преобразуем ошибки API PocketBase в читаемый вид
                const errors = Object.entries(data).map(([key, val]) => {
                    const errorObj = val as { code: string; message: string };

                    if (key === 'email' && errorObj.code === 'validation_not_unique') {
                        return "Diese E-Mail-Adresse ist bereits vergeben. Bitte melden Sie sich an.";
                    }
                    if (key === 'password' && errorObj.code === 'validation_length_short') {
                        return "Das Passwort ist zu kurz (mindestens 8 Zeichen).";
                    }
                    return `${key}: ${errorObj.message}`;
                }).join(' ');

                formError = errors;
            } else {
                formError = e.message;
            }
        } else if (e instanceof Error) {
            formError = e.message;
        } else {
            formError = "Ein unbekannter Fehler ist aufgetreten.";
        }
    }
}
---

<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="Интерьер комфортабельного минивэна"
                    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">

            {isSuccess ? (
                // === БЛОК УСПЕХА ===
                <div class="text-center animate-fade-in">
                        <div class="mx-auto flex items-center justify-center h-20 w-20 rounded-full bg-green-100 mb-6">
                            <svg class="h-10 w-10 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path>
                            </svg>
                        </div>

                        <h2 class="text-2xl font-bold text-gray-900 mb-4">Bitte überprüfen Sie Ihre E-Mails</h2>

                        <p class="text-gray-600 mb-8 text-lg leading-relaxed">
                            Wir haben einen Bestätigungslink an <strong>{emailForDisplay}</strong> gesendet.<br/>
                            Bitte klicken Sie auf den Link, um Ihr Konto zu aktivieren.
                        </p>

                        <div class="p-4 bg-blue-50 text-blue-800 rounded-lg text-sm mb-6">
                            Keine E-Mail erhalten? Bitte überprüfen Sie Ihren Spam-Ordner.
                        </div>

                        <div>
                            <a href="/" class="text-gray-500 hover:text-gray-800 font-medium text-sm transition-colors">Zurück zur Startseite</a>
                        </div>
                    </div>
            ) : (
                // === БЛОК ФОРМЫ ===
                <>
                        <div class="mb-8">
                            <h2 class="font-bold text-gray-900 text-3xl">Erstellen Sie Ihr Konto</h2>
                            <p class="text-gray-500 mt-2">
                                Füllen Sie das Formular aus, um zu beginnen.
                            </p>
                        </div>

                    {formError && (
                            <div class="bg-red-50 border-l-4 border-red-500 text-red-700 p-4 mb-6 rounded-r" role="alert">
                                <p class="font-bold">Fehler bei der Registrierung</p>
                                <p>{formError}</p>
                            </div>
                    )}

                        <form method="POST" class="space-y-5" id="registerForm" novalidate>

                            {/* NAME */}
                            <div class="group">
                                <label for="name" class="block text-sm font-medium text-gray-700 mb-1">Name</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 7a4 4 0 11-8 0 4 4 0 018 0zM12 14a7 7 0 00-7 7h14a7 7 0 00-7-7z"></path></svg>
                                    </div>
                                    <input
                                            id="name"
                                            name="name"
                                            type="text"
                                            autocomplete="name"
                                            required
                                            minlength="2"
                                            maxlength="50"
                                            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="Ihr Name"
                                            aria-describedby="nameError"
                                    />
                                </div>
                                <div id="nameError" class="text-xs mt-1 text-red-600 hidden h-4"></div>
                            </div>

                            {/* EMAIL */}
                            <div class="group">
                                <label for="email" class="block text-sm font-medium text-gray-700 mb-1">E-Mail-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
                                            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>

                            {/* 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="new-password"
                                            required
                                            minlength="8"
                                            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 focus:outline-none cursor-pointer 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 class="mt-2 h-1 w-full bg-gray-200 rounded-full overflow-hidden">
                                    <div id="passwordStrengthBar" class="h-full w-0 bg-red-500 transition-all duration-300 ease-out"></div>
                                </div>
                                <div class="flex justify-between items-start mt-1">
                                    <div id="passwordError" class="text-xs text-red-600 hidden"></div>
                                    <div id="passwordStrengthText" class="text-xs text-gray-400 ml-auto whitespace-nowrap"></div>
                                </div>
                            </div>

                            {/* CONFIRM PASSWORD */}
                            <div class="group">
                                <label for="confirmPassword" class="block text-sm font-medium text-gray-700 mb-1">Passwort bestätigen</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="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                    </div>
                                    <input
                                            id="confirmPassword"
                                            name="confirmPassword"
                                            type="password"
                                            autocomplete="new-password"
                                            required
                                            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="Passwort wiederholen"
                                    />
                                    <button type="button" id="toggleConfirmPassword" class="absolute inset-y-0 right-0 pr-3 flex items-center text-gray-400 hover:text-gray-600 focus:outline-none cursor-pointer transition-colors" aria-label="Passwort anzeigen">
                                        <svg id="confirmEyeIcon" 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="passwordMatchMessage" class="text-xs mt-1 h-4 hidden"></div>
                            </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"
                                >
                                    Konto erstellen
                                </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" 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 hover:cursor-pointer transition-colors focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500">
                                    <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">
                                Haben Sie bereits ein Konto?{' '}
                                <a href="/auth/login" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
                                    Anmelden
                                </a>
                            </p>
                        </div>
                    </>
            )}
        </div>
    </div>
</div>

<script>
    document.addEventListener('DOMContentLoaded', () => {
        // === ПОЛУЧЕНИЕ ЭЛЕМЕНТОВ DOM ===
        const form = document.querySelector('#registerForm') as HTMLFormElement | null;
        if (!form) return;

        const submitButton = document.getElementById('submitButton') as HTMLButtonElement;

        const nameInput = document.getElementById('name') as HTMLInputElement;
        const emailInput = document.getElementById('email') as HTMLInputElement;
        const passwordInput = document.getElementById('password') as HTMLInputElement;
        const confirmInput = document.getElementById('confirmPassword') as HTMLInputElement;

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

        const passwordMatchMessage = document.getElementById('passwordMatchMessage') as HTMLDivElement;
        const passwordStrengthBar = document.getElementById('passwordStrengthBar') as HTMLDivElement;
        const passwordStrengthText = document.getElementById('passwordStrengthText') as HTMLDivElement;

        // Переключатели видимости пароля
        const togglePassBtn = document.getElementById('togglePassword');
        const toggleConfirmBtn = document.getElementById('toggleConfirmPassword');
        const eyeIcon = document.getElementById('eyeIcon');
        const confirmEyeIcon = document.getElementById('confirmEyeIcon');

        // === ВСПОМОГАТЕЛЬНЫЕ ФУНКЦИИ ===

        /** Показать ошибку */
        const showError = (el: HTMLElement, message: string) => {
            el.textContent = message;
            el.classList.remove('hidden');
        };

        /** Скрыть ошибку */
        const hideError = (el: HTMLElement) => {
            el.textContent = '';
            el.classList.add('hidden');
        };

        /** Переключение иконки глаза */
        const updateEyeIcon = (icon: HTMLElement | null, isVisible: boolean) => {
            if (!icon) return;
            if (isVisible) {
                // Иконка "скрыть" (глаз перечеркнут)
                icon.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 {
                // Иконка "показать" (глаз обычный)
                icon.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><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>`;
            }
        };

        // === 1. ВАЛИДАЦИЯ ИМЕНИ (СТРОГАЯ) ===
        // Разрешаем: Латиница, Кириллица, пробел, дефис, апостроф.
        const nameRegex = /^[a-zA-Zа-яА-ЯёЁ\s\-']+$/u;

        // Блокировка ввода клавиш
        nameInput.addEventListener('keydown', (e) => {
            const allowedKeys = ['Backspace', 'Delete', 'Tab', 'Escape', 'Enter', 'ArrowLeft', 'ArrowRight', 'Home', 'End'];
            if (allowedKeys.includes(e.key) || e.ctrlKey || e.metaKey || e.altKey) return;

            // Если символ не соответствует регулярке - предотвращаем ввод
            if (!nameRegex.test(e.key)) {
                e.preventDefault();
            }
        });

        // Санитизация ввода (против вставки и автозаполнения)
        nameInput.addEventListener('input', (e) => {
            const target = e.target as HTMLInputElement;
            // Удаляем всё, что не соответствует разрешенным символам
            // Note: инвертируем диапазон для replace
            const sanitized = target.value.replace(/[^a-zA-Zа-яА-ЯёЁ\s\-']/gu, '');
            if (sanitized !== target.value) {
                target.value = sanitized;
            }
            validateGlobal();
        });

        nameInput.addEventListener('blur', () => {
            if (!nameInput.value.trim()) {
                showError(nameError, 'Name ist erforderlich');
                nameInput.classList.add('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
            } else if (nameInput.value.trim().length < 2) {
                showError(nameError, 'Name muss mindestens 2 Zeichen lang sein');
                nameInput.classList.add('border-red-500');
            } else {
                hideError(nameError);
                nameInput.classList.remove('border-red-500', 'focus:ring-red-500', 'focus:border-red-500');
                nameInput.classList.add('border-green-500');
            }
            validateGlobal();
        });

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

        const validateEmail = () => {
            const val = emailInput.value.trim();
            if (!val) return false;
            return emailRegex.test(val);
        };

        emailInput.addEventListener('blur', () => {
            if (!emailInput.value.trim()) {
                showError(emailError, 'E-Mail ist erforderlich');
                emailInput.classList.add('border-red-500');
            } else if (!validateEmail()) {
                showError(emailError, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
                emailInput.classList.add('border-red-500');
            } else {
                hideError(emailError);
                emailInput.classList.remove('border-red-500');
                emailInput.classList.add('border-green-500');
            }
            validateGlobal();
        });

        emailInput.addEventListener('input', validateGlobal);


        // === 3. ВАЛИДАЦИЯ И СИЛА ПАРОЛЯ ===
        const checkPasswordStrength = (pass: string) => {
            let score = 0;
            if (!pass) return 0;
            if (pass.length >= 8) score += 1;
            if (pass.length >= 12) score += 1;
            if (/[A-Z]/.test(pass)) score += 1;
            if (/[0-9]/.test(pass)) score += 1;
            if (/[^A-Za-z0-9]/.test(pass)) score += 1;
            return score; // Max 5
        };

        const updateStrengthMeter = (pass: string) => {
            const score = checkPasswordStrength(pass);
            const width = (score / 5) * 100;

            passwordStrengthBar.style.width = `${width}%`;

            // Цвета и текст
            if (score <= 1) {
                passwordStrengthBar.className = 'h-full bg-red-500 transition-all duration-300';
                passwordStrengthText.textContent = 'Sehr schwach';
                passwordStrengthText.className = 'text-xs text-red-500 ml-auto whitespace-nowrap font-medium';
            } else if (score === 2) {
                passwordStrengthBar.className = 'h-full bg-orange-500 transition-all duration-300';
                passwordStrengthText.textContent = 'Schwach';
                passwordStrengthText.className = 'text-xs text-orange-500 ml-auto whitespace-nowrap font-medium';
            } else if (score === 3) {
                passwordStrengthBar.className = 'h-full bg-yellow-500 transition-all duration-300';
                passwordStrengthText.textContent = 'Mittel';
                passwordStrengthText.className = 'text-xs text-yellow-600 ml-auto whitespace-nowrap font-medium';
            } else if (score >= 4) {
                passwordStrengthBar.className = 'h-full bg-green-500 transition-all duration-300';
                passwordStrengthText.textContent = 'Stark';
                passwordStrengthText.className = 'text-xs text-green-600 ml-auto whitespace-nowrap font-medium';
            }

            return score;
        };

        passwordInput.addEventListener('input', () => {
            const val = passwordInput.value;
            const score = updateStrengthMeter(val);

            if (val.length > 0 && val.length < 8) {
                showError(passwordError, 'Mindestens 8 Zeichen erforderlich');
            } else {
                hideError(passwordError);
            }

            validateGlobal();
        });

        // === 4. ПРОВЕРКА СОВПАДЕНИЯ ===
        const checkMatch = () => {
            const pass = passwordInput.value;
            const conf = confirmInput.value;

            if (!conf) {
                hideError(passwordMatchMessage);
                confirmInput.classList.remove('border-red-500', 'border-green-500');
                return false;
            }

            if (pass !== conf) {
                passwordMatchMessage.textContent = 'Passwörter stimmen nicht überein';
                passwordMatchMessage.className = 'text-xs mt-1 text-red-600 block';
                confirmInput.classList.add('border-red-500');
                confirmInput.classList.remove('border-green-500');
                return false;
            } else {
                passwordMatchMessage.textContent = 'Passwörter stimmen überein';
                passwordMatchMessage.className = 'text-xs mt-1 text-green-600 block';
                confirmInput.classList.remove('border-red-500');
                confirmInput.classList.add('border-green-500');
                return true;
            }
        };

        confirmInput.addEventListener('input', () => {
            checkMatch();
            validateGlobal();
        });

        // Повторная проверка совпадения, если меняется основной пароль
        passwordInput.addEventListener('input', () => {
            if (confirmInput.value) checkMatch();
        });


        // === ГЛОБАЛЬНАЯ ВАЛИДАЦИЯ КНОПКИ ===
        function validateGlobal() {
            const isNameValid = nameInput.value.trim().length >= 2;
            const isEmailValid = validateEmail();
            const isPassValid = passwordInput.value.length >= 8 && checkPasswordStrength(passwordInput.value) >= 2; // Требуем хотя бы слабой сложности
            const isMatch = passwordInput.value === confirmInput.value && confirmInput.value.length > 0;

            if (isNameValid && isEmailValid && isPassValid && isMatch) {
                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');
            }
        }

        // === ЛОГИКА ГЛАЗКОВ ===
        if (togglePassBtn) {
            togglePassBtn.addEventListener('click', () => {
                const type = passwordInput.type === 'password' ? 'text' : 'password';
                passwordInput.type = type;
                updateEyeIcon(eyeIcon as HTMLElement, type === 'text');
            });
        }

        if (toggleConfirmBtn) {
            toggleConfirmBtn.addEventListener('click', () => {
                const type = confirmInput.type === 'password' ? 'text' : 'password';
                confirmInput.type = type;
                updateEyeIcon(confirmEyeIcon as HTMLElement, type === 'text');
            });
        }
    });
</script>