---
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 = "forgot-password"');
const title = `${pageData.title} | ${siteSettings.site_name}`;
const description = pageData.meta_description;
const canonicalLink = pageData.canonical_url ? pageData.canonical_url : `${siteUrl}/${pageData.slug}`;

let successMessage = null;
let errorMessage = null;

if (Astro.request.method === "POST") {
    const formData = await Astro.request.formData();
    const email = formData.get("email") as string | null;

    try {
        const PocketBase = (await import('pocketbase')).default;
        const pb = new PocketBase(import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090');

        // Проверяем, что email не null
        if (!email) {
            errorMessage = "E-Mail-Adresse ist erforderlich.";
            return;
        }

        // Отправляем запрос на сброс пароля с указанием правильного URL
        const frontendUrl = import.meta.env.FRONTEND_URL || 'http://localhost:3000';
        await pb.collection('users').requestPasswordReset(email, {
            redirectUrl: `${frontendUrl}/auth/reset-password`
        });

        // По правилам безопасности мы всегда говорим "Если такой email есть, мы отправили письмо"
        successMessage = "Wenn ein Konto mit dieser E-Mail-Adresse existiert, haben wir Anweisungen zum Zurücksetzen des Passworts gesendet.";
    } catch (e: any) {
        console.error(e);
        if (e.message?.includes('failed')) {
            errorMessage = "Die Anfrage konnte nicht verarbeitet werden. Bitte versuchen Sie es später erneut.";
        } else if (e.message?.includes('rate limit')) {
            errorMessage = "Zu viele Anfragen. Bitte warten Sie einige Minuten, bevor Sie es erneut versuchen.";
        } else {
            errorMessage = "Es ist ein Fehler beim Senden der Anfrage aufgetreten. Bitte überprüfen Sie Ihre E-Mail-Adresse.";
        }
    }
}
---

<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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                    </svg>
                </div>
                <h2 class="font-bold text-gray-900 text-3xl mb-2">Passwort vergessen?</h2>
                <p class="text-gray-600">Geben Sie Ihre E-Mail-Adresse ein, um Anweisungen zum Zurücksetzen Ihres Passworts zu erhalten.</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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                            </svg>
                        </div>

                        <h2 class="text-2xl font-bold text-gray-900 mb-4">E-Mail gesendet</h2>

                        <p class="text-gray-600 mb-6 text-lg leading-relaxed">
                            Wenn ein Konto mit dieser E-Mail-Adresse existiert, haben wir Ihnen Anweisungen zum Zurücksetzen des Passworts gesendet.
                        </p>

                        <div class="p-4 bg-blue-50 text-blue-800 rounded-lg text-sm mb-6">
                            <p class="font-medium">✓ E-Mail gesendet</p>
                            <p class="mt-1">Bitte überprüfen Sie Ihren Posteingang und Spam-Ordner.</p>
                        </div>

                        <div class="space-y-3">
                            <a href="/auth/login" class="block">
                                <Button
                                        variant="blue"
                                        size="md"
                                        fullWidth={true}
                                >
                                    Zurück zum Login
                                </Button>
                            </a>
                            <p class="text-sm text-gray-500">
                                Keine E-Mail erhalten?{' '}
                                <button onclick="location.reload()" class="font-medium text-blue-600 hover:text-blue-500 transition-colors">
                                    Erneut versuchen
                                </button>
                            </p>
                        </div>
                    </div>
            ) : (
                // === БЛОК ФОРМЫ ===
                <>
                    {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>
                    )}

                        <form method="POST" class="space-y-6" id="forgotPasswordForm" novalidate>
                            <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="M3 8l7.89 5.26a2 2 0 002.22 0L21 8M5 19h14a2 2 0 002-2V7a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z"></path>
                                        </svg>
                                    </div>
                                    <input
                                            type="email"
                                            id="email"
                                            name="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"
                                            autocomplete="email"
                                            aria-describedby="emailError"
                                    />
                                </div>
                                <div id="emailError" class="text-xs mt-1 text-red-600 hidden h-4"></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 zurücksetzen
                                </Button>
                            </div>
                        </form>

                        <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('#forgotPasswordForm') as HTMLFormElement | null;
        if (!form) return;

        const submitButton = document.getElementById('submitButton') as HTMLButtonElement | null;
        const emailInput = document.getElementById('email') as HTMLInputElement | null;
        const emailError = document.getElementById('emailError') as HTMLDivElement | null;

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

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

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

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

        const validateEmail = () => {
            if (!emailInput) return false;

            const val = emailInput.value.trim();
            if (!val) {
                showError(emailError, 'E-Mail ist erforderlich');
                emailInput.classList.add('border-red-500');
                emailInput.classList.remove('border-green-500');
                return false;
            }

            if (!emailRegex.test(val)) {
                showError(emailError, 'Bitte geben Sie eine gültige E-Mail-Adresse ein');
                emailInput.classList.add('border-red-500');
                emailInput.classList.remove('border-green-500');
                return false;
            }

            hideError(emailError);
            emailInput.classList.remove('border-red-500');
            emailInput.classList.add('border-green-500');
            return true;
        };

        // === ГЛОБАЛЬНАЯ ВАЛИДАЦИЯ КНОПКИ ===
        function validateGlobal() {
            const isEmailValid = validateEmail();

            if (submitButton) {
                if (isEmailValid) {
                    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 (emailInput) {
            emailInput.addEventListener('input', () => {
                validateEmail();
                validateGlobal();
            });

            emailInput.addEventListener('blur', () => {
                validateEmail();
                validateGlobal();
            });
        }

        // === ИНИЦИАЛИЗАЦИЯ ===
        if (emailInput) {
            validateGlobal();
        }

        // === ОБРАБОТКА ОТПРАВКИ ФОРМЫ ===
        form.addEventListener('submit', (e) => {
            if (submitButton?.disabled) {
                e.preventDefault();
                return;
            }

            // Показываем индикатор загрузки
            const originalText = submitButton?.innerHTML || '';
            if (submitButton) {
                submitButton.disabled = true;
                submitButton.innerHTML = `
                    <svg class="animate-spin h-5 w-5 mr-2 inline" 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 gesendet...
                `;
            }

            // Восстанавливаем кнопку через 5 секунд (на случай, если отправка застрянет)
            setTimeout(() => {
                if (submitButton) {
                    submitButton.disabled = false;
                    submitButton.innerHTML = originalText;
                }
            }, 5000);
        });

        // === УСКОРИТЬ ВВОД С КЛАВИАТУРЫ ===
        if (emailInput) {
            emailInput.addEventListener('keydown', (e) => {
                if (e.key === 'Enter' && !submitButton?.disabled) {
                    form.requestSubmit();
                }
            });
        }
    });
</script>