import { defineStore } from "pinia";
import { computed, reactive, ref } from "vue";
import { useSpaceStore } from "@/stores/spaceStore";

export interface ToolbarButton {
    id?: string;
    text?: string;
    icon?: string;
    to?: string;
    onClickId?: string;
    disabled?: boolean;
    class?: string;
    title?: string;
}

export type ToolbarConfig =
    | ToolbarButton[]
    | ((ctx: { spaceStore: ReturnType<typeof useSpaceStore> }) => ToolbarButton[]);

export const useToolbarStore = defineStore("toolbar", () => {
    const spaceStore = useSpaceStore();

    // обработчики
    const handlers: Record<string, () => void> = reactive({});
    const registerHandler = (key: string, fn: () => void) => (handlers[key] = fn);
    const unregisterHandler = (key: string) => delete handlers[key];
    const invoke = (key?: string) => {
        if (!key) return;
        const fn = handlers[key];
        if (typeof fn === "function") fn();
    };

    // текущие кнопки (сделал ref — теперь реактивно)
    const _current = ref<ToolbarButton[]>([]);
    const set = (items: ToolbarButton[]) => void (_current.value = items);
    const clear = () => void (_current.value = []);

    const setByConfig = (config?: ToolbarConfig) => {
        if (!config) return clear();
        _current.value =
            typeof config === "function" ? config({ spaceStore }) : config;
    };

    const defaults = computed<ToolbarButton[]>(() => [
        {
            id: 'space',
            text: spaceStore.selectedSpaceName ?? 'Select Space',
            icon: '',
            onClickId: 'openSpacePicker',
        },

    ]);

    const current = computed<ToolbarButton[]>(() => {
        const map = new Map<string, ToolbarButton>();
        for (const b of defaults.value) map.set(b.id ?? crypto.randomUUID(), b);
        for (const b of _current.value) map.set(b.id ?? crypto.randomUUID(), b);
        return Array.from(map.values());
    });

    return {
        current,
        registerHandler,
        unregisterHandler,
        invoke,
        set,
        clear,
        setByConfig,
    };
});