import { useEffect } from 'react';
import { useEditorStore } from '@/core/store';

// Accent color mappings
const accentColorMap: Record<string, { hsl: string; hex: string }> = {
  blue: { hsl: '217 91% 60%', hex: '#3b82f6' },
  green: { hsl: '142 71% 45%', hex: '#10b981' },
  purple: { hsl: '262 83% 58%', hex: '#8b5cf6' },
  orange: { hsl: '25 95% 53%', hex: '#f97316' },
  pink: { hsl: '330 81% 60%', hex: '#ec4899' },
  red: { hsl: '0 84% 60%', hex: '#ef4444' },
  cyan: { hsl: '187 80% 42%', hex: '#06b6d4' },
  periwinkle: { hsl: '230 70% 65%', hex: '#818cf8' },
  teal: { hsl: '173 80% 40%', hex: '#14b8a6' },
  yellow: { hsl: '45 93% 47%', hex: '#eab308' },
  lime: { hsl: '75 85% 50%', hex: '#84cc16' },
  forest: { hsl: '142 76% 36%', hex: '#059669' },
  lavender: { hsl: '270 60% 75%', hex: '#c4b5fd' },
  coral: { hsl: '15 90% 55%', hex: '#fb7185' },
  sky: { hsl: '199 89% 70%', hex: '#38bdf8' },
  royal: { hsl: '258 90% 66%', hex: '#a855f7' },
};

/**
 * Component that syncs settings to CSS variables and document attributes
 * This ensures theme, accent color, and other settings are applied globally
 */
export const SettingsSync: React.FC = () => {
  const { settings } = useEditorStore();

  useEffect(() => {
    const root = document.documentElement;

    // Apply theme
    const applyTheme = () => {
      if (settings.theme) {
        if (settings.theme === 'system') {
          const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
          if (prefersDark) {
            root.classList.add('dark');
          } else {
            root.classList.remove('dark');
          }
        } else if (settings.theme === 'dark') {
          root.classList.add('dark');
        } else {
          root.classList.remove('dark');
        }
      } else {
        // Default to dark if no theme set
        root.classList.add('dark');
      }
    };

    applyTheme();

    // Apply accent color
    if (settings.accentColor) {
      const accentColor = accentColorMap[settings.accentColor] || accentColorMap.cyan;
      root.style.setProperty('--primary', accentColor.hsl);
      root.style.setProperty('--accent', accentColor.hsl);
      root.style.setProperty('--ring', accentColor.hsl);
      root.style.setProperty('--sidebar-primary', accentColor.hsl);
      root.style.setProperty('--sidebar-ring', accentColor.hsl);
    }

    // Apply font family globally
    if (settings.fontFamily) {
      root.style.setProperty('--font-mono', settings.fontFamily);
    }

    // Listen for system theme changes if using system theme
    if (settings.theme === 'system') {
      const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
      const handleChange = () => applyTheme();
      mediaQuery.addEventListener('change', handleChange);
      return () => mediaQuery.removeEventListener('change', handleChange);
    }
  }, [settings.theme, settings.accentColor, settings.fontFamily]);

  return null;
};

export default SettingsSync;
