---
import { authService } from '@/lib/authService';

// 1. Получаем URL PocketBase для формирования ссылок на картинки
const PB_URL = import.meta.env.PUBLIC_POCKETBASE_URL || 'http://127.0.0.1:8090';

let reviews = [];

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

    // Получаем 3 последних отзыва
    const result = await pb.collection('reviews').getList(1, 3, {
        sort: '-created',
        expand: 'author'
    });

    // Форматируем данные
    reviews = result.items.map((r) => {
        const authorData = r.expand?.author;
        const authorName = authorData?.name || authorData?.email?.split('@')[0] || 'Anonym';

        // Логика формирования URL аватара
        // Путь: /api/files/COLLECTION_ID/RECORD_ID/FILENAME
        const avatarFilename = authorData?.avatar;
        const authorCollectionId = authorData?.collectionId;
        const authorId = authorData?.id;

        const avatarUrl = (avatarFilename && authorCollectionId && authorId)
            ? `${PB_URL}/api/files/${authorCollectionId}/${authorId}/${avatarFilename}`
            : null;

        return {
            id: r.id,
            author: authorName,
            initials: authorName.substring(0, 2).toUpperCase(),
            rating: r.rating,
            title: r.title,
            content: r.content,
            avatarUrl: avatarUrl,
            created: new Date(r.created).toLocaleDateString("de-DE", {
                day: "numeric",
                month: "long",
                year: "numeric",
            })
        };
    });
} catch (e) {
    console.error("Error fetching latest reviews:", e);
    reviews = [];
}

const stars = [1, 2, 3, 4, 5];
---

<section class="py-16 bg-gray-50">
    <div class="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8">

        {/* Заголовок секции */}
        <div class="text-center mb-12 animate-fade-in-up">
            <h2 class="text-3xl font-bold text-gray-900 sm:text-4xl">
                Letzte Bewertungen
            </h2>
            <p class="mt-4 text-lg text-gray-600 max-w-2xl mx-auto">
                Lesen Sie, was andere über unseren Service sagen
            </p>
        </div>

        {/* Сетка отзывов */}
        <div class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-8">
            {reviews.length > 0 ? (
                reviews.map((review) => (
                        <div class="bg-white rounded-2xl shadow-lg p-6 hover:shadow-xl transition-shadow duration-300 flex flex-col h-full">

                            {/* Шапка отзыва: Аватар и Имя */}
                            <div class="flex items-center mb-4">

                                {/* АВАТАР ИЛИ ИНИЦИАЛЫ */}
                                <div class="flex-shrink-0">
                                    {review.avatarUrl ? (
                                            <img
                                                    src={review.avatarUrl}
                                                    alt={review.author}
                                                    width="48"
                                                    height="48"
                                                    class="w-12 h-12 rounded-full object-cover border border-gray-100 shadow-sm"
                                                    loading="lazy"
                                            />
                                    ) : (
                                            <div class="bg-gradient-to-br from-blue-100 to-indigo-200 text-indigo-800 font-bold rounded-full w-12 h-12 flex items-center justify-center text-lg shadow-sm">
                                                {review.initials}
                                            </div>
                                    )}
                                </div>

                                <div class="ml-4">
                                    <h3 class="text-lg font-bold text-gray-900">
                                        {review.author}
                                    </h3>
                                    <time class="text-xs text-gray-500">
                                        {review.created}
                                    </time>
                                </div>
                            </div>

                            {/* Звезды */}
                            <div class="flex mb-3 space-x-1">
                                {stars.map((star) => (
                                        <svg
                                                xmlns="http://www.w3.org/2000/svg"
                                                viewBox="0 0 512 512"
                                                class={`h-5 w-5 ${star <= review.rating ? 'text-[#FE9901]' : 'text-gray-300'}`}
                                                fill="currentColor"
                                        >
                                            <path d="M394 480a16 16 0 01-9.39-3L256 383.76 127.39 477a16 16 0 01-24.55-17.82l49.1-151.05-128.77-93.55a16 16 0 019.38-28.84l159.05-.29L240.79 31.81a16 16 0 0130.42 0l49.18 153.64 159.05.29a16 16 0 019.38 28.84l-128.77 93.55 49.1 151.05A16 16 0 01394 480z"/>
                                        </svg>
                                ))}
                            </div>

                            {/* Заголовок отзыва */}
                            {review.title && (
                                    <h4 class="text-lg font-bold text-gray-900 mb-2 leading-tight">
                                        {review.title}
                                    </h4>
                            )}

                            {/* Текст отзыва */}
                            <p class="text-gray-700 text-sm leading-relaxed italic flex-grow">
                                „{review.content}“
                            </p>
                        </div>
                ))
            ) : (
                    <div class="col-span-full text-center py-12 text-gray-500 bg-white rounded-xl shadow-sm">
                        Noch keine Bewertungen verfügbar.
                    </div>
            )}
        </div>

        {/* Кнопка "Все отзывы" */}
        <div class="text-center mt-12">
            <a
                    href="/bewertungen"
                    class="inline-flex items-center justify-center px-8 py-3 border border-transparent text-base font-medium rounded-md text-white bg-blue-600 hover:bg-blue-700 transition-colors shadow-md hover:shadow-lg"
            >
                Alle Bewertungen ansehen
                <svg class="ml-2 -mr-1 w-5 h-5" fill="currentColor" viewBox="0 0 20 20">
                    <path fill-rule="evenodd" d="M7.293 14.707a1 1 0 010-1.414L10.586 10 7.293 6.707a1 1 0 011.414-1.414l4 4a1 1 0 010 1.414l-4 4a1 1 0 01-1.414 0z" clip-rule="evenodd" />
                </svg>
            </a>
        </div>
    </div>
</section>