<script setup>
import { ref, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import { dataService } from '../services/dataService'
import Skeleton from 'primevue/skeleton'

const router = useRouter()
const characters = ref([])
const loading = ref(true)
const API_URL = import.meta.env.VITE_API_URL

onMounted(async () => {
    loading.value = true
    try {
        characters.value = await dataService.getCharacters()
    } catch (e) {
        console.error('Failed to load characters', e)
    } finally {
        loading.value = false
    }
})

const goToDetail = (id) => {
    router.push({ name: 'character-detail', params: { id } })
}


</script>

<template>
    <div class="flex flex-col h-full p-8 overflow-y-auto text-slate-100">
        <!-- Top Bar -->
        <header class="flex justify-between items-end mb-8">
            <div>
                <h1 class="text-4xl font-bold m-0">Characters</h1>
                <p class="mt-2 mb-0 text-slate-400">Manage your AI personas</p>
            </div>
        </header>

        <!-- Loading State -->
        <div v-if="loading" class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="i in 6" :key="i" class="glass-panel rounded-2xl p-6 flex items-center gap-6">
                <Skeleton shape="circle" size="5rem" />
                <div class="flex-1">
                    <Skeleton class="mb-2" height="1.5rem" />
                    <Skeleton height="1rem" />
                </div>
            </div>
        </div>

        <!-- Characters Grid -->
        <div v-else class="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
            <div v-for="char in characters" :key="char.id"
                class="glass-panel rounded-2xl p-6 flex items-center gap-6 transition-all duration-300 cursor-pointer border border-white/5 hover:-translate-y-1 hover:bg-white/5 hover:border-white/10"
                @click="goToDetail(char.id)">
                <div class="w-20 h-20 rounded-full overflow-hidden flex-shrink-0 border-3 border-white/10">
                    <img :src="API_URL + char.avatar_image || 'https://via.placeholder.com/150'" :alt="char.name"
                        class="w-full h-full object-cover" />
                </div>
                <div class="flex-1 overflow-hidden">
                    <h3 class="m-0 mb-2 text-xl font-semibold">{{ char.name }}</h3>
                    <p class="m-0 text-sm text-slate-400 line-clamp-2">
                        {{ char.character_bio }}
                    </p>
                </div>
            </div>
        </div>
    </div>
</template>

<style scoped>
/* Line clamp utility for older browsers */
.line-clamp-2 {
    display: -webkit-box;
    -webkit-line-clamp: 2;
    line-clamp: 2;
    -webkit-box-orient: vertical;
    overflow: hidden;
}
</style>
