import { defineStore } from 'pinia';

interface Loader {
    name: string;
    active: number;
}

export const useUiStore = defineStore('ui', {
    state: () => ({
        loading: [] as Loader[],
        toggleSections: [] as string[]
    }),

    getters: {
        isLoading: (state) => (name: string): boolean => {
            const loader = state.loading.find(l => l.name === name);
            return loader ? loader.active > 0 : false;
        },
        isShowing: (state) => (name: string): boolean => {
            return state.toggleSections.includes(name);
        }
    },

    actions: {
        toggleLoading(name: string, status: boolean) {
            const loader = this.loading.find(l => l.name === name);
            if (status) {
                if (loader) {
                    loader.active++;
                } else {
                    this.loading.push({ name, active: 1 });
                }
            } else {
                if (loader && loader.active > 0) {
                    loader.active--;
                }
            }
        },

        toggleSection(name: string, status: boolean) {
            const index = this.toggleSections.indexOf(name);
            if (status) {
                if (index === -1) {
                    this.toggleSections.push(name);
                }
            } else {
                if (index !== -1) {
                    this.toggleSections.splice(index, 1);
                }
            }
        }
    }
});
