'use client';

import usePreference from '@/hooks/helpers/usePreference';
import React, { useEffect, useState } from 'react';
import { useParams } from 'next/navigation';
import { useGetAbout } from '@/app/[name]/(Main)/about/hooks/useAboutData';
import SplashScreen from '@/components/overlays/SplashScreen';
import { hexToOklch, calculateBrightness } from '@/lib/helpers/colorUtils';
import {
    applyCachedThemeToDom,
    buildThemeCacheFromRestaurant,
    clearRestaurantBackgroundOverrides,
    getCachedMenuColor,
    getThemeCache,
    setThemeCache,
} from '@/lib/helpers/themeCache';

type Props = {
    children: React.ReactNode
}

function applyPrimaryColor(colorHex: string) {
    const root = document.documentElement;
    const oklchColor = hexToOklch(colorHex);

    if (oklchColor) {
        root.style.setProperty('--primary', oklchColor);

        const brightness = calculateBrightness(colorHex);
        const foregroundOklch = brightness > 0.5 ? 'oklch(0 0 0)' : 'oklch(1 0 0)';
        root.style.setProperty('--primary-foreground', foregroundOklch);
    }
}

function PreferenceWrapper({ children }: Props) {
    const params = useParams();
    const restaurantSlug = typeof params.name === 'string' ? params.name : '';

    const { state: nightMode } = usePreference('night-mode', false);
    const { data: aboutData } = useGetAbout();

    const [showSplash, setShowSplash] = useState(() => {
        if (typeof window === 'undefined') return true;
        const navigationEntries = performance.getEntriesByType('navigation') as PerformanceNavigationTiming[];
        const isReload = navigationEntries.length > 0 && navigationEntries[0].type === 'reload';
        return !sessionStorage.getItem('app-loaded') || isReload;
    });

    const [cachedLogo, setCachedLogo] = useState<string | null>(null);
    const [cachedName, setCachedName] = useState<string | null>(null);

    useEffect(() => {
        const savedColor = getCachedMenuColor(restaurantSlug);
        const cachedTheme = restaurantSlug ? getThemeCache(restaurantSlug) : null;
        if (cachedTheme) {
            applyCachedThemeToDom(cachedTheme);
        } else if (savedColor) {
            applyPrimaryColor(savedColor);
        }

        const savedLogo = localStorage.getItem('shop-logo');
        const savedName = localStorage.getItem('shop-name');
        if (savedLogo) setCachedLogo(savedLogo);
        if (savedName) setCachedName(savedName);

        sessionStorage.setItem('app-loaded', 'true');
    }, [restaurantSlug]);

    useEffect(() => {
        const menuColor = aboutData?.data?.menuColor;
        if (!menuColor || !restaurantSlug) return;

        const restaurant = aboutData.data;
        const cached = getThemeCache(restaurantSlug);
        const themeBase = buildThemeCacheFromRestaurant(restaurant);

        setThemeCache(restaurantSlug, {
            menuColor,
            bgType: themeBase.bgType,
            bgUrl: restaurant.bgUrl,
            bgBlur: themeBase.bgBlur,
            bgOpacity: themeBase.bgOpacity,
            bgOverlay: themeBase.bgOverlay,
            isPattern: themeBase.isPattern,
            patternDataUrl: cached?.patternDataUrl ?? null,
        });

        const updatedTheme = getThemeCache(restaurantSlug);
        if (updatedTheme) {
            applyCachedThemeToDom(updatedTheme);
        }

        localStorage.setItem('theme-primary-color', menuColor);

        if (restaurant.logo) {
            localStorage.setItem('shop-logo', restaurant.logo);
        }
        if (restaurant.name) {
            localStorage.setItem('shop-name', restaurant.name);
        }

        applyPrimaryColor(menuColor);
    }, [aboutData?.data, restaurantSlug]);

    useEffect(() => {
        document.documentElement.setAttribute('data-theme', nightMode ? 'dark' : 'light');

        if (nightMode) {
            clearRestaurantBackgroundOverrides();
            return;
        }

        if (!restaurantSlug) return;

        const cached = getThemeCache(restaurantSlug);
        if (cached) {
            applyCachedThemeToDom(cached);
        }
    }, [nightMode, restaurantSlug]);

    useEffect(() => {
        if (showSplash) {
            const timer = setTimeout(() => {
                setShowSplash(false);
            }, 2500);

            return () => clearTimeout(timer);
        }
    }, [showSplash]);

    const splashLogo = aboutData?.data?.logo || cachedLogo || undefined;
    const splashName = aboutData?.data?.name || cachedName || undefined;

    return (
        <>
            {showSplash && (
                <SplashScreen
                    logo={splashLogo}
                    shopName={splashName}
                    duration={2500}
                />
            )}
            {!showSplash && children}
        </>
    )
}

export default PreferenceWrapper
