<template>
    <div v-if="loading" class="flex justify-center items-center h-64">
        <div class="animate-spin rounded-full h-12 w-12 border-b-2 border-primary"></div>
    </div>

    <div v-else-if="error" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
        {{ error }}
    </div>

    <div v-else-if="currentManga" class="relative">
        <MangaHeader :manga="currentManga" />
        <MangaVolumeList :volumes="volumes" :manga-slug="currentManga.slug" />
    </div>
</template>

<script setup>
    import { computed, onMounted, onUnmounted, watch } from 'vue';
    import { useRoute } from 'vue-router';
    import { useMangaStore } from '../../application/store/mangaStore';
    import { storeToRefs } from 'pinia';
    import MangaHeader from '../components/MangaHeader.vue';
    import MangaVolumeList from '../components/MangaVolumeList.vue';

    const route = useRoute();
    const store = useMangaStore();
    const { currentManga, chapters, loading, error } = storeToRefs(store);

    const volumes = computed(() => {
        if (!chapters.value) return [];

        const chaptersArray = Array.isArray(chapters.value)
            ? chapters.value
            : chapters.value.items
            ? chapters.value.items
            : [];

        const volumeMap = new Map();

        chaptersArray.forEach(chapter => {
            const volumeNumber = chapter.volume || 'Unknown';
            if (!volumeMap.has(volumeNumber)) {
                volumeMap.set(volumeNumber, {
                    number: volumeNumber,
                    downloadedChapter: 0,
                    totalChapter: 0,
                    chapters: []
                });
            }
            volumeMap.get(volumeNumber).chapters.push({
                ...chapter,
                isDownloaded: Boolean(chapter.cbzPath)
            });
        });

        for (const volume of volumeMap.values()) {
            volume.downloadedChapter = volume.chapters.filter(c => c.isDownloaded).length;
            volume.totalChapter = volume.chapters.length;
        }

        return Array.from(volumeMap.values()).sort((a, b) => b.number - a.number);
    });

    const loadData = async () => {
        const mangaId = route.params.id;
        await Promise.all([store.fetchMangaDetails(mangaId), store.fetchMangaChapters(mangaId)]);
    };

    // Ajouter le watcher sur l'ID de la route
    watch(
        () => route.params.id,
        (newId, oldId) => {
            if (newId !== oldId) {
                loadData();
            }
        }
    );

    onMounted(() => {
        loadData();
    });

    onUnmounted(() => {
        store.clearCurrentManga();
    });
</script>
