import React, { createContext, useCallback } from 'react';

import { SafeAreaProvider as _SafeAreaProvider } from 'react-native-safe-area-context';

import type { ISafeAreaProvider, SafeAreaContextType, SafeAreaInsets } from '../type';

export const DEFAULT_INSETS: SafeAreaInsets = {};

export const SafeAreaContext = createContext<SafeAreaContextType>({ insets: DEFAULT_INSETS });

/**
 * Web build of SafeAreaProvider.
 *
 * The web target does not have a real safe-area primitive, so we lean
 * on React Native's `SafeAreaView` (which is rendered as a plain
 * `<View>` on web via react-native-web) purely to preserve the API
 * shape. The `SafeAreaContext.Provider` is the part that actually
 * matters: descendants rely on it for read/write access to the
 * in-memory inset object.
 */
export const SafeAreaProvider: React.FC<ISafeAreaProvider> = ({ children, initialMetrics = DEFAULT_INSETS }) => {
  const [insets, setInsets] = React.useState<SafeAreaInsets>(initialMetrics);

  const handleInsets = useCallback((newInsets: SafeAreaInsets) => {
    setInsets(newInsets);
  }, []);

  return (
    <_SafeAreaProvider>
      <SafeAreaContext.Provider value={{ insets, handleInsets }}>{children}</SafeAreaContext.Provider>
    </_SafeAreaProvider>
  );
};

export { useSafeArea, useGetSafeAreaInsets, useHandleSafeAreaInsets, useSetSafeAreaInsets } from './hooks';
