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

let successMessage = null;
let errorMessage = null;
let isLoading = false;

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

// Нам нужен ТОЛЬКО токен. Email в ссылке не обязателен для этого метода.
if (token) {
    isLoading = true;
    try {
        const PocketBase = (await import('pocketbase')).default;
        const pb = new PocketBase(import.meta.env.POCKETBASE_URL || 'http://127.0.0.1:8090');

        // ПРАВИЛЬНЫЙ МЕТОД SDK: confirmVerification(token)
        await pb.collection("users").confirmVerification(token);

        successMessage = "Ihre E-Mail-Adresse wurde erfolgreich bestätigt! Sie können sich jetzt anmelden.";
    } catch (e: unknown) {
        console.error("Fehler bei der E-Mail-Bestätigung:", e);
        errorMessage = "Der Link ist ungültig oder die Gültigkeit ist abgelaufen.";
    }
    isLoading = false;
} else {
    errorMessage = "Ungültiger Link. Bestätigungstoken fehlt.";
}

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

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

<Layout {title} {description} {canonicalLink}>
    <main 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" role="main">
            <div class="w-full md:w-1/2 relative min-h-[300px] md:min-h-0" aria-hidden="true">
                <img
                    src="/images/auth/sign-in.avif"
                    alt="Bestätigung der E-Mail-Adresse für Minivan Berlin"
                    class="object-cover w-full h-full"
                />
                <div class="absolute inset-0 bg-black/30 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">
                        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">
                <h2 class="font-bold text-gray-900 text-3xl mb-4" id="verify-email-heading">E-Mail-Adresse bestätigen</h2>
                <p class="text-gray-600 mb-8">
                    Bestätigen Sie Ihre E-Mail-Adresse, um Ihr Konto zu aktivieren.
                </p>

                {isLoading && (
                    <div class="flex justify-center mb-4" role="status" aria-live="polite">
                        <div class="animate-spin rounded-full h-10 w-10 border-b-2 border-blue-600" aria-label="Wird geladen..."></div>
                    </div>
                )}

                {successMessage && (
                    <div
                        class="bg-green-100 border border-green-400 text-green-700 px-4 py-3 rounded relative mb-4"
                        role="alert"
                        aria-labelledby="success-message"
                    >
                        <span id="success-message" class="block sm:inline">✅ {successMessage}</span>
                    </div>
                )}

                {errorMessage && (
                    <div
                        class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded relative mb-4"
                        role="alert"
                        aria-labelledby="error-message"
                    >
                        <span id="error-message" class="block sm:inline">❌ {errorMessage}</span>
                    </div>
                )}

                <div class="pt-4">
                    <a
                        href="/auth/login?emailVerified=true"
                        class="w-full inline-flex justify-center items-center px-4 py-2 border border-transparent text-sm font-medium rounded-md shadow-sm text-white bg-blue-600 hover:bg-blue-700 focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-blue-500"
                        aria-label="Zur Anmeldeseite navigieren"
                    >
                        Zur Anmeldung
                    </a>
                </div>
            </div>
        </div>
    </main>

    <script>
    </script>
</Layout>