import { defineStore } from 'pinia';

export const useHeaderStore = defineStore('header', {
    state: () => ({
        isHeaderVisible: true,
        isAutoHideEnabled: false,
        isReaderToolbarVisible: true,
        isReaderToolbarAutoHideEnabled: false,
        lastScrollY: 0,
        scrollDirection: 'up'
    }),

    getters: {
        shouldShowHeader: (state) => {
            if (!state.isAutoHideEnabled) return true;
            return state.isHeaderVisible;
        },
        shouldShowReaderToolbar: (state) => {
            if (!state.isReaderToolbarAutoHideEnabled) return true;
            return state.isReaderToolbarVisible;
        }
    },

    actions: {
        enableAutoHide() {
            this.isAutoHideEnabled = true;
        },

        disableAutoHide() {
            this.isAutoHideEnabled = false;
            this.isHeaderVisible = true;
        },

        enableReaderToolbarAutoHide() {
            this.isReaderToolbarAutoHideEnabled = true;
            this.isReaderToolbarVisible = true;
        },

        disableReaderToolbarAutoHide() {
            this.isReaderToolbarAutoHideEnabled = false;
            this.isReaderToolbarVisible = true;
        },

        toggleReaderToolbarAutoHide() {
            if (this.isReaderToolbarAutoHideEnabled) {
                this.disableReaderToolbarAutoHide();
                this.disableAutoHide();
            } else {
                this.enableReaderToolbarAutoHide();
                this.enableAutoHide();
            }
        },

        updateScrollDirection(scrollY) {
            const scrollDifference = Math.abs(scrollY - this.lastScrollY);

            if (scrollDifference < 5) {
                return;
            }

            if (scrollY > this.lastScrollY && scrollY > 100) {
                if (this.scrollDirection !== 'down') {
                    this.scrollDirection = 'down';
                    if (this.isAutoHideEnabled) this.isHeaderVisible = false;
                    if (this.isReaderToolbarAutoHideEnabled) this.isReaderToolbarVisible = false;
                }
            } else if (scrollY < this.lastScrollY) {
                if (this.scrollDirection !== 'up') {
                    this.scrollDirection = 'up';
                    if (this.isAutoHideEnabled) this.isHeaderVisible = true;
                    if (this.isReaderToolbarAutoHideEnabled) this.isReaderToolbarVisible = true;
                }
            }

            this.lastScrollY = scrollY;
        },

        showHeader() {
            this.isHeaderVisible = true;
        },

        hideHeader() {
            this.isHeaderVisible = false;
        }
    }
});
