import { isDevMode } from "@/lib/utils/env";
import { RootProviders } from "@/providers";
import { useCurrentPalette } from "@/providers/ThemeProvider";
import {
    Lexend_100Thin,
    Lexend_200ExtraLight,
    Lexend_300Light,
    Lexend_400Regular,
    Lexend_500Medium,
    Lexend_600SemiBold,
    Lexend_700Bold,
    Lexend_800ExtraBold,
    Lexend_900Black,
    useFonts,
} from "@expo-google-fonts/lexend";
import { Slot, SplashScreen } from "expo-router";
import { useEffect } from "react";
import { Platform, View } from "react-native";
import { GestureHandlerRootView } from "react-native-gesture-handler";

const RootLayoutInner = () => {
    const [loaded, error] = useFonts({
        Lexend_100Thin,
        Lexend_200ExtraLight,
        Lexend_300Light,
        Lexend_400Regular,
        Lexend_500Medium,
        Lexend_600SemiBold,
        Lexend_700Bold,
        Lexend_800ExtraBold,
        Lexend_900Black,
    });

    const { semantic } = useCurrentPalette();

    useEffect(() => {
        if (!isDevMode) return;
        if (Platform.OS === "web" && typeof window !== "undefined") {
            const hostname = window.location.hostname;
            if (hostname === "127.0.0.1") return;
            if (hostname === "localhost") {
                const newUrl = window.location.href.replace(
                    "localhost",
                    "127.0.0.1",
                );
                window.location.replace(newUrl);
                return;
            }

            throw new Error(
                "don't use localhost, use 127.0.0.1. this shouldn't error unless you've done something very wrong.",
            );
        }
    });

    useEffect(() => {
        if (loaded || error) {
            void SplashScreen.hideAsync();
        }
    }, [loaded, error]);

    if (!loaded && !error) {
        return null;
    }

    return (
        <View style={{ backgroundColor: semantic.background, flex: 1 }}>
            <Slot />
        </View>
    );
};

const RootLayout = () => {
    return (
        <GestureHandlerRootView>
            <RootProviders>
                <RootLayoutInner />
            </RootProviders>
        </GestureHandlerRootView>
    );
};

export default RootLayout;
