---
import AverageRating from './AverageRating.astro';
import ReviewForm from './ReviewForm.astro';
import ReviewsList from './ReviewsList.astro';
import NotificationToast from '@components/base/NotificationToast.astro';
import { authService } from '@/lib/authService';

// --- SERVER SIDE LOGIC ---
const user = Astro.locals.user;
const url = Astro.url;
const pageParam = url.searchParams.get('page');
const successParam = url.searchParams.get('success');

const currentPage = pageParam ? parseInt(pageParam) : 1;
const REVIEWS_PER_PAGE = 6;

let reviews = [];
let error = null;

try {
    const pb = authService.createClientFromRequest(Astro.request);

    // Получаем список отзывов
    const records = await pb.collection('reviews').getFullList({
        sort: '-created',
        expand: 'author'
    });

    // Преобразуем данные
    reviews = records.map((r) => ({
        id: r.id,
        author: r.expand?.author?.name || r.expand?.author?.email?.split('@')[0] || 'Anonym',
        authorId: r.author,

        // !!! ДОБАВЛЕНЫ ПОЛЯ ДЛЯ АВАТАРА !!!
        authorAvatar: r.expand?.author?.avatar,           // Имя файла (напр. "image.jpg")
        authorCollectionId: r.expand?.author?.collectionId, // ID коллекции (нужен для URL)

        rating: r.rating,
        title: r.title,
        content: r.content,
        createdAt: r.created
    }));

} catch (e) {
    console.error("Fehler beim Laden der Bewertungen:", e);
    reviews = [];
    error = "Keine Verbindung zur Datenbank";
}

// Статистика
const totalReviews = reviews.length;
const averageRating = totalReviews > 0
    ? reviews.reduce((acc, r) => acc + r.rating, 0) / totalReviews
    : 0;

// Пагинация
const totalPages = Math.ceil(totalReviews / REVIEWS_PER_PAGE);
const startIndex = (currentPage - 1) * REVIEWS_PER_PAGE;
const paginatedReviews = reviews.slice(startIndex, startIndex + REVIEWS_PER_PAGE);
---

<div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 py-12">

    {successParam === 'true' && (
            <NotificationToast message="Vielen Dank für Ihre Bewertung!" type="success" />
    )}

    <div class="text-center mb-12">
        <h1 class="text-4xl font-bold text-gray-900 mb-4">Erfahren Sie von unseren Kunden</h1>
        <p class="text-lg text-gray-600">Ehrliches Feedback von unseren geschätzten Kunden.</p>
    </div>

    <div class="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-12">

        {/* ЛЕВАЯ КОЛОНКА */}
        <div class="lg:col-span-4 space-y-8 order-1">
            <AverageRating averageRating={averageRating} totalReviews={totalReviews} />
            <ReviewForm isAuthenticated={!!user} />
        </div>

        {/* ПРАВАЯ КОЛОНКА */}
        <div class="lg:col-span-8 order-2">
            <div class="flex items-center justify-between mb-6">
                <h2 class="text-2xl font-bold text-gray-900">Alle Bewertungen</h2>
                <span class="text-sm text-gray-500 bg-gray-100 px-3 py-1 rounded-full">{totalReviews} Gesamt</span>
            </div>

            {paginatedReviews.length > 0 ? (
                    <ReviewsList
                            reviews={paginatedReviews}
                            currentUserId={user?.id}
                            isAdmin={user?.role === 'admin'}
                    />
            ) : (
                    <div class="text-center py-12 bg-gray-50 rounded-2xl border border-dashed border-gray-300">
                        <p class="text-gray-500">Noch keine Bewertungen vorhanden.</p>
                    </div>
            )}

            {/* Пагинация */}
            {totalPages > 1 && (
                    <div class="flex justify-center items-center gap-2 mt-10">
                        <a
                                href={`?page=${currentPage - 1}`}
                                class={`px-4 py-2 rounded-lg border border-gray-300 transition ${currentPage === 1 ? 'pointer-events-none opacity-50 bg-gray-50' : 'hover:bg-gray-100'}`}
                        >
                            ←
                        </a>

                        {Array.from({ length: totalPages }, (_, i) => i + 1).map((p) => (
                                <a
                                        href={`?page=${p}`}
                                        class={`w-10 h-10 flex items-center justify-center rounded-lg transition ${
                                            p === currentPage
                                                ? 'bg-blue-600 text-white shadow-md'
                                                : 'text-gray-600 hover:bg-gray-100'
                                        }`}
                                >
                                    {p}
                                </a>
                        ))}

                        <a
                                href={`?page=${currentPage + 1}`}
                                class={`px-4 py-2 rounded-lg border border-gray-300 transition ${currentPage === totalPages ? 'pointer-events-none opacity-50 bg-gray-50' : 'hover:bg-gray-100'}`}
                        >
                            →
                        </a>
                    </div>
            )}
        </div>
    </div>
</div>