'use client';

import { useEffect } from 'react';

interface UseKeyboardNavigationOptions {
  enabled: boolean;
  onNext?: () => void;
  onPrevious?: () => void;
  onClose?: () => void;
}

/**
 * Hook for keyboard navigation in tours.
 * - ArrowRight/ArrowDown: Next step
 * - ArrowLeft/ArrowUp: Previous step
 * - Escape: Close tour
 */
export function useKeyboardNavigation({
  enabled,
  onNext,
  onPrevious,
  onClose,
}: UseKeyboardNavigationOptions): void {
  useEffect(() => {
    if (!enabled) return;

    const handleKeyDown = (event: KeyboardEvent) => {
      // Ignore if user is typing in an input
      const target = event.target as HTMLElement;
      if (
        target.tagName === 'INPUT' ||
        target.tagName === 'TEXTAREA' ||
        target.isContentEditable
      ) {
        return;
      }

      switch (event.key) {
        case 'ArrowRight':
        case 'ArrowDown':
          event.preventDefault();
          onNext?.();
          break;
        case 'ArrowLeft':
        case 'ArrowUp':
          event.preventDefault();
          onPrevious?.();
          break;
        case 'Escape':
          event.preventDefault();
          onClose?.();
          break;
      }
    };

    document.addEventListener('keydown', handleKeyDown);
    return () => document.removeEventListener('keydown', handleKeyDown);
  }, [enabled, onNext, onPrevious, onClose]);
}
