import { createContext, useContext, useEffect, useState } from "react";

type Season = "spring" | "summer" | "autumn" | "winter";

interface SeasonContextProps {
  season: Season;
  setSeason: (season: Season) => void;
}

const defaultSeason: Season = "spring";

const SeasonContext = createContext<SeasonContextProps>({
  season: defaultSeason,
  setSeason: () => {},
});

export function SeasonProvider({ children }: { children: React.ReactNode }) {
  const [season, setSeason] = useState<Season>(() => {
    // Try to get the saved season from localStorage
    if (typeof window !== 'undefined') {
      const savedSeason = localStorage.getItem("season") as Season;
      return savedSeason || defaultSeason;
    }
    return defaultSeason;
  });

  useEffect(() => {
    // Apply the season class to the document element
    const html = document.documentElement;
    html.classList.remove("spring", "summer", "autumn", "winter");
    html.classList.add(season);
    
    // Save the current season to localStorage
    localStorage.setItem("season", season);
  }, [season]);

  return (
    <SeasonContext.Provider value={{ season, setSeason }}>
      {children}
    </SeasonContext.Provider>
  );
}

export const useSeason = () => useContext(SeasonContext);
