/**
 * Widget context provider for React.
 *
 * ⚠️ AUTO-GENERATED BY PRISM - DO NOT EDIT
 */

import React, { createContext, useContext, useMemo, type ReactNode } from 'react';
import type { Widget, WidgetKey, FieldType } from './types';
import { WidgetRegistry, widgetRegistry } from './registry';

const WidgetContext = createContext<WidgetRegistry>(widgetRegistry);

export interface WidgetProviderProps {
  children: ReactNode;
  /** Additional widgets to register in this scope */
  widgets?: Record<WidgetKey, Widget>;
  /** Replace the entire registry (not recommended) */
  registry?: WidgetRegistry;
}

/**
 * Provider component for widget registry.
 *
 * Use this to override widgets at any level of your component tree.
 *
 * @example
 * <WidgetProvider widgets={{ '{{' }} "Customer.email": CustomEmailWidget {{ '}}' }}>
 *   <CustomerForm />
 * </WidgetProvider>
 */
export function WidgetProvider({
  children,
  widgets,
  registry,
}: WidgetProviderProps): JSX.Element {
  const parentRegistry = useContext(WidgetContext);

  const scopedRegistry = useMemo(() => {
    const base = registry ?? parentRegistry.scoped();
    if (widgets) {
      base.registerAll(widgets);
    }
    return base;
  }, [registry, widgets, parentRegistry]);

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

/**
 * Hook to access the widget registry.
 */
export function useWidgetRegistry(): WidgetRegistry {
  return useContext(WidgetContext);
}

/**
 * Hook to resolve a widget for a specific field.
 */
export function useWidget(
  modelName: string,
  fieldName: string,
  fieldType: FieldType,
  uiWidget?: string
): Widget {
  const registry = useWidgetRegistry();
  return registry.resolve(modelName, fieldName, fieldType, uiWidget);
}
