import React, { useState, useEffect } from 'react'; import { Card } from '../Card/Card'; import { Input } from '../Input/Input'; import { Stack } from '../Stack/Stack'; import { SegmentedControl } from '../SegmentedControl/SegmentedControl'; import { Text } from '../Text/Text'; import { Theme } from '../../core'; import { useTheme, defaultTheme } from '../../core/theme/ThemeProvider'; import { useDebounce } from '../../core/hooks/useInteractions'; export const ThemeSwitcher: React.FC = () => { const { theme, mode, switchTheme, setCustomTheme } = useTheme(); // Local state for custom color inputs, initialized from the current theme const [primary, setPrimary] = useState(theme.colors.primary); const [background, setBackground] = useState(theme.colors.background); const [text, setText] = useState(theme.colors.text); // Debounce the local state to avoid excessive re-renders while typing const debouncedPrimary = useDebounce(primary, 300); const debouncedBackground = useDebounce(background, 300); const debouncedText = useDebounce(text, 300); // Effect to update the global custom theme when debounced values change useEffect(() => { if (mode === 'custom') { // Use defaultTheme as the base to prevent re-render loops from theme dependency. const newCustomTheme: Theme = { ...defaultTheme, // Base all properties on the stable default theme colors: { ...defaultTheme.colors, // Inherit all default colors primary: debouncedPrimary, background: debouncedBackground, text: debouncedText, } }; setCustomTheme(newCustomTheme); } }, [debouncedPrimary, debouncedBackground, debouncedText, mode, setCustomTheme]); // Removed `theme` dependency // Effect to sync local input state when the global theme/mode changes externally useEffect(() => { setPrimary(theme.colors.primary); setBackground(theme.colors.background); setText(theme.colors.text); }, [theme.colors.primary, theme.colors.background, theme.colors.text]); return ( Theme Settings switchTheme(newMode as any)} /> {mode === 'custom' && ( setPrimary(e.target.value)} /> setBackground(e.target.value)} /> setText(e.target.value)} /> )} ); };