import { useEffect } from 'react';
import { GameConfig } from '../types';
import { hexToHslString } from '../utils/theme';

export function useGameTheme(gameConfig?: GameConfig | null) {
  useEffect(() => {
    if (!gameConfig?.colors?.primary) return;

    const root = document.documentElement;
    // Save original styles to revert them when unmounting
    const originalPrimary = root.style.getPropertyValue('--primary');
    const originalForeground = root.style.getPropertyValue('--primary-foreground');

    const hslColor = hexToHslString(gameConfig.colors.primary);

    // Apply game specific theme
    root.style.setProperty('--primary', hslColor);
    root.style.setProperty('--primary-foreground', '0 0% 100%'); // White text for primary buttons

    return () => {
      // Revert to global theme
      if (originalPrimary) root.style.setProperty('--primary', originalPrimary);
      else root.style.removeProperty('--primary');

      if (originalForeground) root.style.setProperty('--primary-foreground', originalForeground);
      else root.style.removeProperty('--primary-foreground');
    };
  }, [gameConfig]);
}
