'use client';

import { useMemo } from 'react';
import dynamic from 'next/dynamic';
import { useRouter } from 'next/navigation';
import { useCommandPalette, useRegisterCommands } from '@bytelyst/command-palette';
import { useAuth } from '@/lib/auth-context';
import { useTheme } from '@/lib/theme-context';
import { buildAdminCommands } from '@/lib/admin-commands';

// Lazy-load the dialog itself (own chunk, client only) — see
// command-palette-dialog.tsx for why the dynamic target is a local re-export.
const CommandPalette = dynamic(
  () => import('./command-palette-dialog').then(m => ({ default: m.CommandPalette })),
  { ssr: false }
);

/**
 * Mounts the ⌘K command palette for the dashboard (UX-3). Registers
 * navigate-mode commands for the major surfaces plus theme-toggle / sign-out
 * actions, and binds the global ⌘K / Ctrl-K hotkey via `useCommandPalette`.
 *
 * Must render inside a `<CommandRegistryProvider>` (mounted in the dashboard
 * layout) so `useRegisterCommands` and the dialog share one registry.
 */
export function CommandMenu() {
  const router = useRouter();
  const { logout } = useAuth();
  const { resolved, setTheme } = useTheme();
  const cmdk = useCommandPalette();

  const commands = useMemo(
    () =>
      buildAdminCommands({
        resolvedTheme: resolved,
        toggleTheme: () => setTheme(resolved === 'dark' ? 'light' : 'dark'),
        signOut: () => {
          logout();
          router.replace('/login');
        },
      }),
    [resolved, setTheme, logout, router]
  );

  useRegisterCommands(commands);

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