---
import Layout from '@/layouts/Layout.astro';
import Button from '@components/base/Button.astro';
import { authService } from '@/lib/authService';

// Получаем глобальные настройки сайта из PocketBase
const pb = authService.createClientFromRequest(Astro.request);
const siteSettings = await pb.collection('site_settings').getFirstListItem('');
const siteUrl = siteSettings.site_url;

// Получаем данные страницы из PocketBase
const pageData = await pb.collection('pages').getFirstListItem('slug = "reset-password"');
const title = `${pageData.title} | ${siteSettings.site_name}`;
const description = pageData.meta_description;
const canonicalLink = pageData.canonical_url ? pageData.canonical_url : `${siteUrl}/${pageData.slug}`;

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

let successMessage = null;
let errorMessage = null;

if (Astro.request.method === "POST" && token) {
    const formData = await Astro.request.formData();
    const password = formData.get("password") as string;
    const passwordConfirm = formData.get("passwordConfirm") as string;

    if (password !== passwordConfirm) {
        errorMessage = "Passwörter stimmen nicht überein.";
    } else if (password.length < 8) {
        errorMessage = "Das Passwort muss mindestens 8 Zeichen lang sein.";
    } else {
        try {
            const PocketBase = (await import('pocketbase')).default;
            const pb = new PocketBase(import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090');

            // Подтверждаем сброс пароля с токеном
            await pb.collection('users').confirmPasswordReset(token, password, passwordConfirm);

            successMessage = "Ihr Passwort wurde erfolgreich geändert. Sie können sich nun anmelden.";
        } catch (e: any) {
            console.error(e);
            if (e.message?.includes('expired')) {
                errorMessage = "Der Passwort-Reset-Link ist abgelaufen. Bitte fordern Sie einen neuen an.";
            } else if (e.message?.includes('invalid')) {
                errorMessage = "Der Passwort-Reset-Link ist ungültig. Bitte fordern Sie einen neuen an.";
            } else {
                errorMessage = "Es ist ein Fehler beim Zurücksetzen des Passworts aufgetreten. Bitte versuchen Sie es erneut.";
            }
        }
    }
}
---

<Layout {title} {description} {canonicalLink}>
    <div class="min-h-screen flex items-center justify-center bg-gray-100 p-4">
        <div class="w-full max-w-md bg-white rounded-2xl shadow-2xl overflow-hidden p-8 md:p-12">
            <div class="mb-8 text-center">
                <div class="mx-auto flex items-center justify-center h-16 w-16 rounded-full bg-blue-100 mb-4">
                    <svg class="h-8 w-8 text-blue-600" 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>
                <h2 class="font-bold text-gray-900 text-3xl mb-2">Passwort zurücksetzen</h2>
                <p class="text-gray-600">Erstellen Sie ein neues Passwort für Ihr Konto</p>
            </div>

            {!token ? (
                    <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">Ungültiger Reset-Link</p>
                        <p>Der Passwort-Reset-Link ist ungültig oder abgelaufen. Bitte fordern Sie einen neuen an.</p>
                    </div>
            ) : (
                    <>
                        {successMessage ? (
                                <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">Passwort erfolgreich geändert</h2>

                                    <p class="text-gray-600 mb-8 text-lg leading-relaxed">
                                        Ihr Passwort wurde erfolgreich aktualisiert.<br/>
                                        Sie können sich nun mit Ihrem neuen Passwort anmelden.
                                    </p>

                                    <div class="pt-2">
                                        <a href="/auth/login" class="block">
                                            <Button
                                                    variant="blue"
                                                    size="md"
                                                    fullWidth={true}
                                            >
                                                Zum Login
                                            </Button>
                                        </a>
                                    </div>
                                </div>
                        ) : (
                                <form method="POST" class="space-y-6" id="resetPasswordForm" novalidate>
                                    {errorMessage && (
                                            <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</p>
                                                <p>{errorMessage}</p>
                                            </div>
                                    )}

                                    <div class="group">
                                        <label for="password" class="block text-sm font-medium text-gray-700 mb-1">Neues 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
                                                    type="password"
                                                    id="password"
                                                    name="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>

                                    <div class="group">
                                        <label for="passwordConfirm" 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
                                                    type="password"
                                                    id="passwordConfirm"
                                                    name="passwordConfirm"
                                                    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="Passwort wiederholen"
                                            />
                                            <button type="button" id="togglePasswordConfirm" 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"
                                        >
                                            Passwort ändern
                                        </Button>
                                    </div>
                                </form>
                        )}
                    </>
            )}

            {!successMessage && (
                    <div class="mt-8 text-center">
                        <p class="text-sm text-gray-600">
                            Zurück zum{' '}
                            <a href="/auth/login" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
                                Login
                            </a>
                        </p>
                    </div>
            )}
        </div>
    </div>
</Layout>

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

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

        const passwordInput = document.getElementById('password') as HTMLInputElement;
        const confirmInput = document.getElementById('passwordConfirm') as HTMLInputElement;

        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('togglePasswordConfirm');
        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>`;
            }
        };

        // === ВАЛИДАЦИЯ И СИЛА ПАРОЛЯ ===
        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');
                passwordInput.classList.add('border-red-500');
                passwordInput.classList.remove('border-green-500');
            } else if (score >= 2) {
                hideError(passwordError);
                passwordInput.classList.remove('border-red-500');
                passwordInput.classList.add('border-green-500');
            } else {
                hideError(passwordError);
                passwordInput.classList.remove('border-red-500', 'border-green-500');
            }

            validateGlobal();
        });

        // === ПРОВЕРКА СОВПАДЕНИЯ ===
        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 isPassValid = passwordInput.value.length >= 8 && checkPasswordStrength(passwordInput.value) >= 2;
            const isMatch = passwordInput.value === confirmInput.value && confirmInput.value.length > 0;

            if (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');
            });
        }

        // Инициализация валидации
        validateGlobal();
    });
</script>