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

interface VehicleItem {
    id: string;
    title: string;
    capacity?: string | null;
    models?: string | null;
    image?: string | null;
    alt_text?: string | null;
    order?: number;
    is_active?: boolean;
    collectionId: string;
}

interface Props {
    title?: string;
    collectionName?: string;
    limit?: number;
}

const {
    title = 'Unsere Flotte',
    collectionName = 'about_fleet',
    limit = 100
} = Astro.props;

// Получаем данные из PocketBase
const pb = authService.createClientFromRequest(Astro.request);

let vehicles: VehicleItem[] = [];

try {
    const response = await pb.collection(collectionName).getList(1, limit, {
        filter: 'is_active = true',
        sort: 'order'
    });

    vehicles = response.items.map(item => ({
        id: item.id,
        title: item.title,
        capacity: item.capacity,
        models: item.models,
        image: item.image,
        alt_text: item.alt_text,
        order: item.order,
        is_active: item.is_active,
        collectionId: item.collectionId
    }));
} catch (error) {
    console.error(`Ошибка при загрузке данных из коллекции ${collectionName}:`, error);
    // В случае ошибки используем пустой массив
    vehicles = [];
}

// Функция для генерации URL изображения
const getImageUrl = (collectionId: string, id: string, imageName: string) => {
    return `${import.meta.env.POCKETBASE_URL || import.meta.env.PUBLIC_POCKETBASE_URL}/api/files/${collectionId}/${id}/${imageName}`;
};
---

<div class="mb-20 animate-staggerFadeIn">
    <h2 class="text-2xl sm:text-3xl font-semibold mb-12 text-center text-gray-800 animate-fadeInUp">
        {title}
    </h2>

    <div class="grid grid-cols-1 md:grid-cols-3 gap-8">
        {vehicles && vehicles.length > 0 ? (
            vehicles.map((vehicle, index) => (
                    <div
                            class="fleet-card bg-white rounded-2xl overflow-hidden shadow-xl transition-all duration-300 transform animate-cardEntry"
                            style={`animation-delay: ${index * 0.1}s; animation-fill-mode: both;`}
                    >
                        {vehicle.image && (
                                <div class="relative h-48 overflow-hidden">
                                    <img
                                            src={getImageUrl(vehicle.collectionId, vehicle.id, vehicle.image)}
                                            alt={vehicle.alt_text || vehicle.title}
                                            class="w-full h-full object-cover transition-transform duration-500 hover:scale-110"
                                            loading="lazy"
                                    />
                                    <div class="absolute inset-0 bg-linear-to-b from-transparent to-black/20"></div>
                                </div>
                        )}
                        <div class="p-6">
                            <h3 class="text-xl font-bold text-gray-900 mb-2">
                                {vehicle.title}
                            </h3>
                            {vehicle.capacity && (
                                    <p class="text-blue-600 font-medium mb-2">
                                        {vehicle.capacity}
                                    </p>
                            )}
                            {vehicle.models && (
                                    <p class="text-sm text-gray-500">{vehicle.models}</p>
                            )}
                        </div>
                    </div>
            ))
        ) : (
                <div class="col-span-3 text-center text-gray-400 py-10">
                    Keine Fahrzeuge gefunden.
                </div>
        )}
    </div>
</div>

<style>
    /* Локальные анимации */
    @keyframes fadeInUp {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }
    @keyframes staggerFadeIn {
        from { opacity: 0; }
        to { opacity: 1; }
    }
    @keyframes cardEntry {
        from { opacity: 0; transform: translateY(20px); }
        to { opacity: 1; transform: translateY(0); }
    }

    .animate-fadeInUp { animation: fadeInUp 0.8s ease-out forwards; }
    .animate-staggerFadeIn { animation: staggerFadeIn 0.8s ease-out forwards; }
    .animate-cardEntry { animation: cardEntry 0.6s ease-out forwards; }

    .fleet-card:hover {
        transform: translateY(-12px);
        box-shadow: 0 25px 50px -12px rgba(0, 0, 0, 0.25);
    }
</style>