<template>
    <div v-if="errorDetails" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
        {{ errorDetails.message || 'Une erreur est survenue lors du chargement des détails.' }}
    </div>

    <div v-else-if="currentManga" class="relative">
        <div v-if="isRefreshingDetails" class="absolute top-2 right-2 text-gray-500">
            <ArrowPathIcon class="h-5 w-5 animate-spin" />
        </div>
        <MangaHeader :manga="currentManga" />

        <!-- Section Volumes -->
        <div class="mt-8">
            <div v-if="isLoadingVolumes" class="flex justify-center items-center h-32">
                <div class="animate-spin rounded-full h-8 w-8 border-b-2 border-primary"></div>
            </div>
            <div v-else-if="errorVolumes" class="bg-red-100 border border-red-400 text-red-700 px-4 py-3 rounded">
                {{ errorVolumes.message || 'Une erreur est survenue lors du chargement des volumes.' }}
            </div>
            <MangaVolumeList v-else :volumes="volumes" :manga-slug="currentManga.slug" />
        </div>
    </div>

    <div v-else-if="isLoadingDetails" 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 class="text-center text-gray-500 py-10"> Aucun manga sélectionné ou trouvé. </div>
</template>

<script setup>
    import { computed, onUnmounted, watch } from 'vue';
    import { useRoute } from 'vue-router';
    import { ArrowPathIcon } from '@heroicons/vue/24/outline';

    import { useMangaDetails } from '../composables/useMangaDetails';
    import { useMangaVolumes } from '../composables/useMangaVolumes';

    import MangaHeader from '../components/MangaHeader.vue';
    import MangaVolumeList from '../components/MangaVolumeList.vue';

    import { useMangaStore } from '../../application/store/mangaStore';

    const route = useRoute();
    const mangaStore = useMangaStore();

    const mangaId = computed(() => route.params.id || null);

    const {
        data: currentManga,
        isLoading: isLoadingDetails,
        isFetching: isRefreshingDetails,
        error: errorDetails
    } = useMangaDetails(mangaId);

    const {
        volumes,
        isLoading: isLoadingVolumes,
        isFetching: isRefreshingVolumes,
        error: errorVolumes
    } = useMangaVolumes(mangaId);

    const loading = computed(() => isLoadingDetails.value || isLoadingVolumes.value);
    const isRefreshing = computed(() => isRefreshingDetails.value || isRefreshingVolumes.value);
    const error = computed(() => errorDetails.value || errorVolumes.value);

    watch(
        mangaId,
        newId => {
            if (newId) {
                mangaStore.setCurrentMangaId(newId);
            }
        },
        { immediate: true }
    );

    onUnmounted(() => {
        mangaStore.clearCurrentMangaFocus();
    });
</script>
