import { writable, derived } from 'svelte/store';

export interface ShortcutDef {
    key: string; // e.g., 'Ctrl+S'
    description: string;
    action: () => void;
    group?: string;
    /**
     * When true, KeyboardManager will not run the default post-action focus
     * (focusMainContentPrimary) for Alt+ shortcuts. Use when the action sets focus explicitly.
     */
    skipDefaultFocusAfter?: boolean;
}

interface ShortcutState {
    contexts: Record<string, ShortcutDef[]>;
}

function createShortcutStore() {
    const { subscribe, set, update } = writable<ShortcutState>({
        contexts: {}
    });

    return {
        subscribe,
        /**
         * Register local shortcuts for the current view.
         * Call this on mount (or $effect).
         */
        register: (context: string, shortcuts: ShortcutDef[]) => {
            update(state => ({
                ...state,
                contexts: {
                    ...state.contexts,
                    [context]: shortcuts
                }
            }));
        },
        /**
         * Clear shortcuts (on unmount)
         */
        clear: (contextToClear: string) => {
            update(state => {
                const newContexts = { ...state.contexts };
                delete newContexts[contextToClear];
                return { ...state, contexts: newContexts };
            });
        }
    };
}

export const shortcutStore = createShortcutStore();

/**
 * Flattened list of all active shortcuts across ALL contexts.
 * Last registered context takes priority in case of key conflicts (or we can decide otherwise).
 */
export const activeShortcutsList = derived(shortcutStore, ($store) => {
    const list: (ShortcutDef & { context: string })[] = [];
    for (const [context, shortcuts] of Object.entries($store.contexts)) {
        (shortcuts as ShortcutDef[]).forEach((s: ShortcutDef) => list.push({ ...s, context }));
    }
    return list;
});

// For backward compatibility
export const activeShortcuts = derived(shortcutStore, ($state) => {
    const list: (ShortcutDef & { context: string })[] = [];
    for (const [context, shortcuts] of Object.entries($state.contexts)) {
        (shortcuts as ShortcutDef[]).forEach((s: ShortcutDef) => list.push({ ...s, context }));
    }
    return {
        context: Object.keys($state.contexts).join(', ') || 'None',
        shortcuts: list
    };
});
