'use client';

import { applyTheme, currentThemePreference } from '@/lib/theme/client';
import { themeStorageKey } from '@/lib/theme/config';
import { useEffect } from 'react';

export function ThemeController() {
  useEffect(() => {
    const media = window.matchMedia('(prefers-color-scheme: dark)');
    const handleSystemChange = () => {
      if (currentThemePreference() === 'system') applyTheme('system');
    };
    const handleStorage = (event: StorageEvent) => {
      if (event.key === themeStorageKey && event.newValue) {
        const preference = event.newValue;
        if (preference === 'light' || preference === 'dark' || preference === 'system') {
          applyTheme(preference);
        }
      }
    };

    media.addEventListener('change', handleSystemChange);
    window.addEventListener('storage', handleStorage);
    return () => {
      media.removeEventListener('change', handleSystemChange);
      window.removeEventListener('storage', handleStorage);
    };
  }, []);

  return null;
}
