import React, { createContext, useContext, useMemo } from 'react';
import type { ShadeBridge } from '../integration/shade-bridge.js';
import type { FilesNamespace } from '../integration/files-namespace.js';

export interface ShadeFilesContextValue {
  shade: ShadeBridge;
  files: FilesNamespace;
}

const ShadeFilesContext = createContext<ShadeFilesContextValue | null>(null);

export interface ShadeFilesProviderProps {
  /** Initialized `Shade` instance (or any `ShadeBridge`-shaped object). */
  shade: ShadeBridge;
  /**
   * The `FilesNamespace` to expose to children. Pass `shade.files` from
   * `@shade/sdk`, or a `createFilesNamespace(...)` result for tests /
   * custom bridges.
   */
  files: FilesNamespace;
  children: React.ReactNode;
}

/**
 * Provider for `@shade/files` React hooks. Distinct from
 * `<ShadeRuntimeProvider>` in `@shade/widgets` so file-RPC consumers
 * don't pull in the widget tree.
 */
export function ShadeFilesProvider({ shade, files, children }: ShadeFilesProviderProps): React.ReactElement {
  const value = useMemo<ShadeFilesContextValue>(() => ({ shade, files }), [shade, files]);
  return React.createElement(ShadeFilesContext.Provider, { value }, children);
}

/** Throws if no `<ShadeFilesProvider>` is mounted above. */
export function useShadeFilesContext(): ShadeFilesContextValue {
  const ctx = useContext(ShadeFilesContext);
  if (ctx === null) {
    throw new Error('useShadeFilesContext: missing <ShadeFilesProvider>');
  }
  return ctx;
}
