/** @jsxImportSource react */

import { createContext, useContext, useMemo } from 'react';
import { createApiClient, ApiClient } from './create-api-client';
import type { ApiClientConfig } from './types';

const ApiClientContext = createContext<ApiClient | null>(null);

interface ApiClientProviderProps extends ApiClientConfig {
  children: React.ReactNode;
}

export function ApiClientProvider({ children, ...config }: ApiClientProviderProps) {
  const client = useMemo(() => createApiClient(config), [config.baseURL]);

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

export function useApiClient(): ApiClient {
  const client = useContext(ApiClientContext);
  if (!client) {
    throw new Error('useApiClient must be used within ApiClientProvider');
  }
  return client;
}
