<template>
    <div class="intro">
        <h1 style="color:white;margin-left: 20px;">F1 Teams</h1>
        <p style="color:white;margin-left: 20px;">Find the Formula 1 teams for the 2025 season</p>
    </div>
    <el-skeleton v-if="loading" :rows="3" animated />
    <el-empty v-else-if="error || !teams.length" description="暂无数据" />
    <div v-else class="showcase">
        <template v-for="team in teams" :key="team.id">
            <div class="card-wrapper" @click="goTeam(team.id)">
                <TeamCard :name="team.name" :nation="team.nation" :image="getCarImage(team.name)" :color="getColor(team.name)" :driver1="getDriverList(team.name)[0].name" :driver2="getDriverList(team.name)[1].name" :logo="getLogo(team.name)" />
            </div>
        </template>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import TeamCard from '@/components/TeamCard.vue'
import { getColor, getCarImage, getLogo } from '@/assets/source'
import { useDriversStore } from '@/store/SeasonDrivers'
// import { teams } from '@/assets/source'

const router = useRouter()
const loading = ref(true)
const error = ref('')
const teams = ref<any[]>([])
const driversStore = useDriversStore()

onMounted(async () => {
    try {
        const res = await fetch('/api/teams')
        const json = await res.json()
        const list = Array.isArray(json) ? json : (json?.data ?? [])
        teams.value = list.map((t: any) => ({
            id: t.id ?? t.teamId,
            name: t.name,
            nation: t.nation,
            image: t.image ?? t.imageUrl,
            color: t.color ?? getColor(t.name),
            driver1: Array.isArray(t.drivers) ? t.drivers[0] : t.driver1 ?? '',
            driver2: Array.isArray(t.drivers) ? t.drivers[1] : t.driver2 ?? '',
            logo: t.logo ?? t.logoUrl
        }))
        driversStore.ensureDriversLoaded()
    } catch (e) {
        error.value = '加载失败'
    } finally {
        loading.value = false
    }
})

const getDriverList = (name: string) => {
    return driversStore.driversList.filter((d: any) => d.team === name)
}

const goTeam = (id: number) => {
    router.push(`/teams/${id}`)
}

</script>

<style lang="scss" scoped>
.intro h1 {
    font-size: 40px;
    font-weight: bolder;
}

.intro p {
    font-size: 20px;
    margin-bottom: 20px;
}

.showcase {
    display: grid;
    grid-template-columns: 1fr;
    row-gap: 20px;
}

.card-wrapper:hover {
    cursor: pointer;
}
</style>
