/**
 * @file Root provider for impact-ui keyboard shortcuts.
 *
 * By default (no provider), all shortcuts that come from impact-ui components
 * are bypassed — they never register with ShortcutManager, so they can't fire.
 *
 * A consuming app opts in by rendering this provider anywhere above its
 * component tree (typically at the root, alongside other providers):
 *
 *   // Enable ALL impact-ui shortcuts
 *   <ShortcutsProvider enabled>
 *     <App />
 *   </ShortcutsProvider>
 *
 *   // Enable only specific component namespaces
 *   <ShortcutsProvider enabled={['sidebar', 'filterPanel']}>
 *     <App />
 *   </ShortcutsProvider>
 *
 *   // Disable everything (default — same as not using the provider at all)
 *   <ShortcutsProvider enabled={false}>
 *     <App />
 *   </ShortcutsProvider>
 *
 * Note: shortcuts registered by consumer code via useShortcut WITHOUT a
 * namespace are NEVER gated — this provider only controls impact-ui library
 * shortcuts that carry a namespace.
 */

import React, { useMemo } from 'react';
import PropTypes from 'prop-types';
import { ShortcutsConfigContext } from './ShortcutsConfigContext';

/**
 * @param {Object} props
 * @param {boolean | string[]} [props.enabled=false]
 *   - false         → bypass all impact-ui shortcuts (default)
 *   - true          → enable all impact-ui shortcuts
 *   - string[]      → enable only the listed namespaces (e.g. ['sidebar', 'filterPanel'])
 * @param {React.ReactNode} props.children
 */
export function ShortcutsProvider({ enabled = false, children }) {
  const value = useMemo(() => {
    if (!enabled) {
      return { enabled: false, namespaces: null };
    }
    if (Array.isArray(enabled)) {
      return { enabled: true, namespaces: enabled };
    }
    return { enabled: true, namespaces: null };
  }, [Array.isArray(enabled) ? enabled.join(',') : enabled]); // stable dep for array form

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

ShortcutsProvider.propTypes = {
  enabled: PropTypes.oneOfType([PropTypes.bool, PropTypes.arrayOf(PropTypes.string)]),
  children: PropTypes.node.isRequired,
};
