import React, { createContext, useState, useContext, useEffect } from 'react';
import { applyStoredTheme } from '../utils/themeUtils';

const ThemeContext = createContext();

export const useTheme = () => {
  const context = useContext(ThemeContext);
  if (!context) {
    throw new Error('useTheme must be used within a ThemeProvider');
  }
  return context;
};

export const ThemeProvider = ({ children }) => {
  const [theme, setTheme] = useState(() => {
    const savedTheme = localStorage.getItem('sat-theme');
    return savedTheme || 'light';
  });

  useEffect(() => {
    document.body.classList.remove('light-mode', 'night-mode');
    document.body.classList.add(theme === 'light' ? 'light-mode' : 'night-mode');
    localStorage.setItem('sat-theme', theme);
    applyStoredTheme();
  }, [theme]);

  const toggleTheme = () => {
    setTheme(prev => prev === 'light' ? 'night' : 'light');
  };

  return (
    <ThemeContext.Provider value={{ theme, toggleTheme }}>
      {children}
    </ThemeContext.Provider>
  );
};
