import React, { useMemo } from 'react';
import { ThemeProvider } from 'styled-components';
import { useMaterialUIController } from '../../ui-kit/context';
import palettes from '../../ui-kit/assets/theme/base/palettes';

type GlobalThemeWrapperProps = {
    children: React.ReactNode;
};

const GlobalThemeWrapper = ({ children }: GlobalThemeWrapperProps): JSX.Element => {
    const [controller] = useMaterialUIController();
    const { themeColor, darkMode } = controller;

    // Stable theme ref — ParticleBackground restarts its canvas whenever theme identity changes.
    const theme = useMemo(() => {
        const selectedPalette = palettes[themeColor as keyof typeof palettes] || palettes.blue;
        return {
            main: selectedPalette.main,
            focus: selectedPalette.focus,
            darkMode: darkMode,
            colors: {
                background: darkMode ? '#1a2035' : '#f0f2f5',
                text: darkMode ? '#ffffff' : '#344767',
                cardBackground: darkMode ? 'rgba(0, 0, 0, 0.4)' : 'rgba(255, 255, 255, 0.8)',
                cardBorder: darkMode ? 'rgba(255, 255, 255, 0.1)' : 'rgba(0, 0, 0, 0.05)',
            }
        };
    }, [themeColor, darkMode]);

    return (
        <ThemeProvider theme={theme}>
            {children}
        </ThemeProvider>
    );
};

export default GlobalThemeWrapper;
