'use client';

import React, { createContext, useContext, useState, ReactNode, useMemo } from 'react';
import { BackgroundMode, BACKGROUND_MODE_PALETTES, ColorPalette, PALETTES, ThemeId } from '../types/theme';

interface BackgroundContextType {
    currentTheme: ThemeId;
    palette: ColorPalette;
    setTheme: (theme: ThemeId) => void;
    darkMode: boolean;
    backgroundMode: BackgroundMode;
    backgroundPalette: ColorPalette;
}

const BackgroundContext = createContext<BackgroundContextType | undefined>(undefined);

export const BackgroundProvider: React.FC<{ children: ReactNode; darkMode: boolean; backgroundMode?: BackgroundMode }> = ({
    children,
    darkMode,
    backgroundMode = 'classic',
}) => {
    const [currentTheme, setCurrentTheme] = useState<ThemeId>('default');

    const setTheme = (theme: ThemeId) => {
        if (PALETTES[theme]) {
            setCurrentTheme(theme);
        } else {
            console.warn(`Theme '${theme}' not found, falling back to default.`);
            setCurrentTheme('default');
        }
    };

    const palette = useMemo(() => {
        const themeConfig = PALETTES[currentTheme];
        return darkMode ? themeConfig.dark : themeConfig.light;
    }, [currentTheme, darkMode]);

    const backgroundPalette = useMemo(() => {
        const themeConfig = BACKGROUND_MODE_PALETTES[backgroundMode] ?? BACKGROUND_MODE_PALETTES.classic;
        return darkMode ? themeConfig.dark : themeConfig.light;
    }, [backgroundMode, darkMode]);

    const value = {
        currentTheme,
        palette,
        setTheme,
        darkMode,
        backgroundMode,
        backgroundPalette,
    };

    return (
        <BackgroundContext.Provider value={value}>
            {children}
        </BackgroundContext.Provider>
    );
};

export const useBackground = () => {
    const context = useContext(BackgroundContext);
    if (context === undefined) {
        throw new Error('useBackground must be used within a BackgroundProvider');
    }
    return context;
};
