<template>
    <div class="chapter-selector">
        <label for="chapter-select" class="sr-only">Sélectionner un chapitre</label>
        <select
            id="chapter-select"
            v-model="selectedChapterId"
            @change="handleChapterChange"
            class="chapter-select"
            :disabled="isLoading"
        >
            <option
                v-for="chapter in availableChapters"
                :key="chapter.id"
                :value="chapter.id"
                :selected="chapter.id === currentChapterId"
            >
                Chapitre {{ chapter.number }} - {{ chapter.title }}
            </option>
        </select>
    </div>
</template>

<script setup>
import { computed, ref, watch } from 'vue';
import { useReaderStore } from '../../application/store/readerStore';

const props = defineProps({
    availableChapters: {
        type: Array,
        default: () => []
    }
});

const emit = defineEmits(['chapter-selected']);

const store = useReaderStore();

const selectedChapterId = ref(null);

const currentChapterId = computed(() => store.currentChapter?.id);
const isLoading = computed(() => store.isLoading);

// Synchroniser la sélection avec le chapitre actuel
watch(currentChapterId, (newId) => {
    selectedChapterId.value = newId;
}, { immediate: true });

// Gérer le changement de chapitre
const handleChapterChange = async () => {
    if (selectedChapterId.value && selectedChapterId.value !== currentChapterId.value) {
        await store.loadChapter(selectedChapterId.value);
        emit('chapter-selected', selectedChapterId.value);
    }
};
</script>

<style lang="postcss" scoped>
.chapter-selector {
    @apply relative;
}

.chapter-select {
    @apply w-full px-3 py-2 text-sm;
    @apply bg-gray-800 text-white border border-gray-600;
    @apply rounded-md shadow-sm;
    @apply focus:outline-none focus:ring-2 focus:ring-blue-500 focus:border-blue-500;
    @apply disabled:opacity-50 disabled:cursor-not-allowed;
    @apply transition-all duration-200;
}

.chapter-select:hover:not(:disabled) {
    @apply border-gray-500;
}

/* Style personnalisé pour la flèche du select */
.chapter-select {
    background-image: url("data:image/svg+xml,%3csvg xmlns='http://www.w3.org/2000/svg' fill='none' viewBox='0 0 20 20'%3e%3cpath stroke='%236b7280' stroke-linecap='round' stroke-linejoin='round' stroke-width='1.5' d='M6 8l4 4 4-4'/%3e%3c/svg%3e");
    background-position: right 0.5rem center;
    background-repeat: no-repeat;
    background-size: 1.5em 1.5em;
    padding-right: 2.5rem;
}
</style>
