import { useEffect, useState } from "react";

export const useDarkMode = () => {
  const [isDark, setIsDark] = useState(() => {
    return (
      localStorage.theme === "dark" ||
      (!("theme" in localStorage) &&
        window.matchMedia("(prefers-color-scheme: dark)").matches)
    );
  });

  useEffect(() => {
    const updateState = () => {
      const newValue =
        localStorage.theme === "dark" ||
        (!("theme" in localStorage) &&
          window.matchMedia("(prefers-color-scheme: dark)").matches);
      setIsDark(newValue);
    };

    const handleStorage = (e: StorageEvent) => {
      if (e.key === "theme") updateState();
    };

    const handleLocalChange = () => updateState();

    window.addEventListener("storage", handleStorage);
    window.addEventListener("themeChange", handleLocalChange);

    return () => {
      window.removeEventListener("storage", handleStorage);
      window.removeEventListener("themeChange", handleLocalChange);
    };
  }, []);

  useEffect(() => {
    const root = window.document.documentElement;
    if (isDark) {
      root.classList.add("dark");
      localStorage.theme = "dark";
    } else {
      root.classList.remove("dark");
      localStorage.theme = "light";
    }
    window.dispatchEvent(new Event("themeChange"));
  }, [isDark]);

  return [isDark, setIsDark] as const;
};


