import { createContext, type ReactNode, useContext, useMemo } from 'react';

type GifPickerContextValue = {
  apiKey: string;
};

const GifPickerContext = createContext<GifPickerContextValue | null>(null);

/** Return type: apiKey is undefined when not inside GifPickerProvider. */
export type UseGifPickerReturn = { apiKey: string | undefined };

type GifPickerProviderProps = {
  /** Giphy API key (e.g. from import.meta.env.VITE_GIPHY_API_KEY). */
  apiKey: string;
  children: ReactNode;
};

export const GifPickerProvider = ({
  apiKey,
  children,
}: GifPickerProviderProps) => {
  const value = useMemo(() => ({ apiKey }), [apiKey]);

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

/** Returns the Giphy API key. apiKey is undefined when not inside GifPickerProvider. */
export const useGifPicker = (): UseGifPickerReturn => {
  const ctx = useContext(GifPickerContext);
  return ctx ? { apiKey: ctx.apiKey } : { apiKey: undefined };
};
