import React from 'react';

type KeyboardNavigationContextValue = {
  isKeyboardNavigationActive: boolean;
  activateKeyboardNavigation: () => void;
  deactivateKeyboardNavigation: () => void;
  showGlobalShortcuts: boolean;
  setShowGlobalShortcuts: (show: boolean) => void;
};

const KeyboardNavigationContext = React.createContext<KeyboardNavigationContextValue | undefined>(undefined);

export const KeyboardNavigationProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
  const [activeCount, setActiveCount] = React.useState(0);
  const [showGlobalShortcuts, setShowGlobalShortcuts] = React.useState(false);

  const activateKeyboardNavigation = React.useCallback(() => {
    setActiveCount((count) => count + 1);
  }, []);

  const deactivateKeyboardNavigation = React.useCallback(() => {
    setActiveCount((count) => Math.max(0, count - 1));
  }, []);

  const value = React.useMemo(() => ({
    isKeyboardNavigationActive: activeCount > 0,
    activateKeyboardNavigation,
    deactivateKeyboardNavigation,
    showGlobalShortcuts,
    setShowGlobalShortcuts,
  }), [activeCount, activateKeyboardNavigation, deactivateKeyboardNavigation, showGlobalShortcuts]);

  return (
    <KeyboardNavigationContext.Provider value={value}>
      {children}
    </KeyboardNavigationContext.Provider>
  );
};

export const useKeyboardNavigationActivity = (): KeyboardNavigationContextValue => {
  const context = React.useContext(KeyboardNavigationContext);

  if (!context) {
    throw new Error('useKeyboardNavigationActivity must be used within a KeyboardNavigationProvider');
  }

  return context;
};
