import { useState, useEffect, createContext, useRef } from "react";
import { StyleSheet, Text, Animated } from "react-native";
import { Fonts, Palette, Style } from "../styles";
import { isWeb } from "../hooks/useLayoutType";

export const SplashAnimationContext = createContext();

const SplashAnimationProvider = ({ children }) => {
  const [isFullyLoaded, setIsFullyLoaded] = useState(false);
  const [showOverlay, setShowOverlay] = useState(true);

  const fadeAnim = useRef(new Animated.Value(1)).current;

  useEffect(() => {
    if (isFullyLoaded) {
      Animated.timing(fadeAnim, {
        toValue: 0,
        duration: 500,
        useNativeDriver: true,
      }).start(() => {
        setShowOverlay(false);
      });
    }
  }, [isFullyLoaded]);

  return (
    <SplashAnimationContext.Provider
      value={{ isFullyLoaded, setIsFullyLoaded }}
    >
      {children}

      {showOverlay && (
        <Animated.View
          style={{
            ...StyleSheet.absoluteFillObject,
            flex: 1,
            ...Style.containerCenter,
            backgroundColor: Palette.darkPurple,
            opacity: fadeAnim,
          }}
        >
          {isWeb && <Text style={Fonts({ type: "megaTitle" })}>m</Text>}
        </Animated.View>
      )}
    </SplashAnimationContext.Provider>
  );
};

export default SplashAnimationProvider;
