
import React, { createContext, useContext, useEffect, useState } from 'react';

type Theme = 'default' | 'dubai' | 'minimal' | 'nature';

interface ThemeContextType {
    theme: Theme;
    setTheme: (theme: Theme) => void;
}

const ThemeContext = createContext<ThemeContextType | undefined>(undefined);

export const ThemeProvider: React.FC<{ children: React.ReactNode }> = ({ children }) => {
    const [theme, setTheme] = useState<Theme>(() => {
        if (typeof window !== 'undefined') {
            const savedTheme = localStorage.getItem('app-theme');
            return (savedTheme as Theme) || 'default';
        }
        return 'default';
    });

    useEffect(() => {
        localStorage.setItem('app-theme', theme);
        const root = window.document.documentElement;

        // Remove old theme classes
        root.classList.remove('theme-default', 'theme-dubai', 'theme-minimal', 'theme-nature');

        // Add new theme class
        root.classList.add(`theme-${theme}`);

        // Check if we need to force dark mode for specific themes
        if (theme === 'dubai') {
            root.classList.add('dark');
        } else {
            root.classList.remove('dark');
        }

    }, [theme]);

    // Background Image Map
    const getBackgroundImage = () => {
        switch (theme) {
            case 'dubai': return "url('https://images.unsplash.com/photo-1512453979798-5ea9ba6a80f4?q=80&w=2000&auto=format&fit=crop')";
            case 'minimal': return "url('https://images.unsplash.com/photo-1550684848-fac1c5b4e853?q=80&w=2000&auto=format&fit=crop')";
            case 'nature': return "url('https://images.unsplash.com/photo-1470071459604-3b5ec3a7fe05?q=80&w=2000&auto=format&fit=crop')";
            default: return 'none'; // Gradient handles default
        }
    };

    return (
        <ThemeContext.Provider value={{ theme, setTheme }}>
            {/* Background Layer managed here for global coverage */}
            {theme !== 'default' && (
                <div
                    className="fixed inset-0 z-[-1] transition-all duration-700 ease-in-out bg-cover bg-center bg-no-repeat bg-fixed"
                    style={{ backgroundImage: getBackgroundImage() }}
                />
            )}
            {/* Overlay for contrast if needed */}
            {theme === 'dubai' && <div className="fixed inset-0 z-[-1] bg-black/40 pointer-events-none" />}

            {children}
        </ThemeContext.Provider>
    );
};

export const useTheme = () => {
    const context = useContext(ThemeContext);
    if (context === undefined) {
        throw new Error('useTheme must be used within a ThemeProvider');
    }
    return context;
};
