import { onMount, onDestroy } from 'svelte';
import { shortcutStore, type ShortcutDef } from '$lib/stores/shortcut-store';
import { page } from '$app/stores';
import { get } from 'svelte/store';
import { browser } from '$app/environment';
import { hasAccessTokenInDocument } from '$lib/access-token-cookie-browser';

/**
 * Hook to register shortcuts for a component lifecycle.
 * Only works when user is authenticated (inside /dashboard routes).
 * @param context Name of the context (e.g., 'Goods List')
 * @param shortcuts Array of shortcut definitions
 */
export function useShortcuts(context: string, shortcuts: ShortcutDef[]) {
    onMount(() => {
        // Solo registrar atajos si estamos en una ruta autenticada
        if (!browser) return;
        
        const currentPath = get(page)?.url?.pathname || '';
        const isAuthenticatedRoute = currentPath.startsWith('/dashboard');
        
        // Verificar también que haya un token de acceso
        const hasAccessToken = hasAccessTokenInDocument() ||
                               localStorage.getItem('access_token');
        
        if (isAuthenticatedRoute && hasAccessToken) {
            shortcutStore.register(context, shortcuts);
        }
    });

    onDestroy(() => {
        shortcutStore.clear(context);
    });
}
