import { defineStore } from 'pinia';
import { useUserPreferencesStore } from '../../../setting/application/store/userPreferencesStore';
import { Chapter } from '../../domain/entities/Chapter';
import { ApiChapterRepository } from '../../infrastructure/repository/ApiChapterRepository';

export const useReaderStore = defineStore('reader', {
    state: () => ({
        currentChapter: null,
        currentPage: 0,
        readingMode: 'single', // 'single' ou 'infinite'
        readingDirection: 'ltr', // 'ltr' ou 'rtl'
        zoom: 1,
        isLoading: false,
        error: null,
        pages: [],
        totalPages: 0,

        // Paramètres pour les doubles pages
        doublePageSettings: {
            autoDetect: true,
            mobileMode: 'rotate', // 'rotate', 'scroll', 'normal'
            detectionThreshold: 1.2 // Ratio largeur/hauteur pour détecter une double page
        }
    }),

    getters: {
        isFirstPage: state => state.currentPage === 0,
        isLastPage: state => state.currentPage === state.totalPages - 1,
        currentPageData: state => state.pages[state.currentPage],
        hasPreviousChapter: state => Boolean(state.currentChapter?.navigation?.previousChapter),
        hasNextChapter: state => Boolean(state.currentChapter?.navigation?.nextChapter),

        // Getters pour les doubles pages
        effectiveDoublePageMode: (state) => {
            if (!state.doublePageSettings.autoDetect) {
                return 'normal';
            }
            return state.doublePageSettings.mobileMode;
        },

        // Préférences sauvegardées dans localStorage
        savedPreferences: (state) => ({
            readingMode: state.readingMode,
            readingDirection: state.readingDirection,
            zoom: state.zoom,
            doublePageSettings: state.doublePageSettings
        })
    },

    actions: {
        async loadChapter(chapterId) {
            this.isLoading = true;
            this.error = null;
            try {
                const repository = new ApiChapterRepository();

                const [chapterData, pagesData] = await Promise.all([
                    repository.getChapter(chapterId),
                    repository.getChapterPages(chapterId, 1, 9999),
                ]);

                this.currentChapter = Chapter.create(chapterData);
                this.pages = pagesData.pages.map(p => ({
                    id: p.id,
                    pageNumber: p.pageNumber,
                    url: p.url,
                    dimensions: p.dimensions,
                }));
                this.totalPages = pagesData.totalItems;
                this.currentPage = 0;
            } catch (error) {
                this.error = error.message;
            } finally {
                this.isLoading = false;
            }
        },

        handlePageVisible(pageIndex) {
            if (pageIndex !== this.currentPage) {
                this.currentPage = pageIndex;
            }
        },

        nextPage() {
            if (!this.isLastPage) {
                this.currentPage++;
            }
        },

        previousPage() {
            if (!this.isFirstPage) {
                this.currentPage--;
            }
        },

        async setReadingMode(mode) {
            if (mode === this.readingMode) return;
            this.readingMode = mode;
            this.savePreferences();
        },

        setReadingDirection(direction) {
            this.readingDirection = direction;
            this.savePreferences();
        },

        setZoom(zoom) {
            this.zoom = Math.max(0.5, Math.min(2, zoom));
            this.savePreferences();
        },

        setDoublePageMode(mode) {
            if (['rotate', 'scroll', 'normal'].includes(mode)) {
                this.doublePageSettings.mobileMode = mode;
                this.savePreferences();
            }
        },

        setDoublePageAutoDetect(enabled) {
            this.doublePageSettings.autoDetect = enabled;
            this.savePreferences();
        },

        setDoublePageDetectionThreshold(threshold) {
            this.doublePageSettings.detectionThreshold = Math.max(1.0, Math.min(3.0, threshold));
            this.savePreferences();
        },

        updateDoublePageSettings(settings) {
            this.doublePageSettings = {
                ...this.doublePageSettings,
                ...settings
            };
            this.savePreferences();
        },

        async goToNextChapter() {
            if (this.currentChapter?.navigation?.nextChapter) {
                await this.loadChapter(this.currentChapter.navigation.nextChapter);
            }
        },

        async goToPreviousChapter() {
            if (this.currentChapter?.navigation?.previousChapter) {
                await this.loadChapter(this.currentChapter.navigation.previousChapter);
                this.currentPage = Math.max(0, this.totalPages - 1);
            }
        },

        savePreferences() {
            try {
                const preferences = {
                    readingMode: this.readingMode,
                    readingDirection: this.readingDirection,
                    zoom: this.zoom,
                    doublePageSettings: this.doublePageSettings
                };
                localStorage.setItem('mangarr-reader-preferences', JSON.stringify(preferences));
            } catch (error) {
                console.error('Erreur lors de la sauvegarde des préférences:', error);
            }
        },

        loadPreferences() {
            try {
                const stored = localStorage.getItem('mangarr-reader-preferences');
                if (!stored) {
                    const userPrefs = useUserPreferencesStore();
                    this.readingDirection = userPrefs.readingDirection;
                    const modeMap = { scroll: 'infinite', single: 'single', double: 'single' };
                    this.readingMode = modeMap[userPrefs.readingMode] ?? 'single';
                    if (userPrefs.readingMode === 'double') {
                        this.doublePageSettings.autoDetect = true;
                    }
                    return;
                }
                if (stored) {
                    const preferences = JSON.parse(stored);

                    if (preferences.readingMode) this.readingMode = preferences.readingMode;
                    if (preferences.readingDirection) this.readingDirection = preferences.readingDirection;
                    if (typeof preferences.zoom === 'number') this.zoom = preferences.zoom;

                    // Migration: si l'ancien doublePageMode existe, le migrer vers mobileMode
                    if (preferences.doublePageMode && ['rotate', 'scroll', 'normal'].includes(preferences.doublePageMode)) {
                        this.doublePageSettings.mobileMode = preferences.doublePageMode;
                    }

                    if (preferences.doublePageSettings) {
                        this.doublePageSettings = {
                            ...this.doublePageSettings,
                            ...preferences.doublePageSettings
                        };
                    }
                }
            } catch (error) {
                console.error('Erreur lors du chargement des préférences:', error);
            }
        },

        resetPreferences() {
            this.readingMode = 'single';
            this.readingDirection = 'ltr';
            this.zoom = 1;
            this.doublePageSettings = {
                autoDetect: true,
                mobileMode: 'rotate',
                detectionThreshold: 1.2
            };
            this.savePreferences();
        }
    }
});
