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

// Create the ThemeContext
const ThemeContext = createContext();

// Custom hook for consuming ThemeContext
export const useTheme = () => {
  return useContext(ThemeContext);
};

const ThemeProvider = ({ children }) => {
  const [colormode, setColormode] = useState(() => {
    return localStorage.getItem("colormode") || "dark"; // Default to dark mode
  });

  useEffect(() => {
    localStorage.setItem("colormode", colormode);
    document.documentElement.setAttribute("data-theme", colormode); // For global CSS styling
  }, [colormode]);

  const toggleColorMode = () => {
    setColormode((prevMode) => (prevMode === "dark" ? "light" : "dark"));
  };

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

export default ThemeProvider;
