import React, { useEffect, useState } from "react";
import DarkModeContext from "../Contexts/DarkModeContext";

function Default({ children }) {
  // dark mode setup
  const [theme, setTheme] = useState(null);

  // country mode setup
  const [countryMode, setCountryMode] = useState(localStorage.getItem('cnt') ? localStorage.getItem('cnt')?.toUpperCase() : '')


  const queryParams = new URLSearchParams(location?.search);
  const country = queryParams.get("cnt")?.toUpperCase();

  useEffect(() => {
    if (window.matchMedia("(prefers-color-scheme: dark)").matches) {
      setTheme("dark");
    } else {
      setTheme("light");
    }
  }, []);

  useEffect(() => {
    if (theme === "dark") {
      document.documentElement.classList.add("dark");
    } else {
      document.documentElement.classList.remove("dark");
    }
  }, [theme]);

  const handleThemeSwitch = () => {
    setTheme(theme === "dark" ? "light" : "dark");
  };

  useEffect(()=>{
    if(country){
      setCountryMode(country)
      localStorage.setItem('cnt', country)
    }
  },[countryMode])

  return (
    <>
      <DarkModeContext.Provider value={{ theme, handleThemeSwitch, countryMode }}>
        {children && children}
      </DarkModeContext.Provider>
    </>
  );
}

export default Default;
