'use client';

import { useMemo } from 'react';
import { useRouter } from 'next/navigation';
import { CommandPalette, useCommandPalette, useRegisterCommands } from '@bytelyst/command-palette';
import { useTheme } from '@/lib/theme-context';
import { useAuth } from '@/lib/auth-context';
import { useProduct } from '@/lib/product-context';
import { buildCommands } from '@/lib/command-registry';

/**
 * ⌘K / Ctrl-K command palette shell (UX-5). Mounted once inside the providers
 * tree (within CommandRegistryProvider) and loaded via next/dynamic so the
 * palette code stays out of the initial bundle.
 */
export default function CommandMenu() {
  const router = useRouter();
  const { theme, setTheme } = useTheme();
  const { logout } = useAuth();
  const { products, setProductId } = useProduct();
  const cmdk = useCommandPalette();

  const commands = useMemo(
    () =>
      buildCommands({
        navigate: href => router.push(href),
        newItem: () => router.push('/dashboard/items?new=1'),
        toggleTheme: () => setTheme(theme === 'dark' ? 'light' : 'dark'),
        signOut: () => {
          logout();
          router.push('/login');
        },
        setProduct: setProductId,
        products,
      }),
    [router, theme, setTheme, logout, setProductId, products]
  );

  useRegisterCommands(commands);

  return (
    <CommandPalette open={cmdk.open} onClose={cmdk.hide} onNavigate={href => router.push(href)} />
  );
}
