import { useEffect, useState } from "preact/hooks";

export default function ThemeToggle() {
  const [dark, setDark] = useState(false);

  useEffect(() => {
    setDark(document.documentElement.classList.contains("dark"));
  }, []);

  const toggle = () => {
    const isDark = !dark;
    setDark(isDark);
    document.documentElement.classList.toggle("dark", isDark);
    localStorage.setItem("theme", isDark ? "dark" : "light");
    document.dispatchEvent(new CustomEvent("ThemeChange", { detail: isDark }));
  };

  return (
    <i
      className={`bi ${
        dark ? "bi-sun" : "bi-moon-stars"
      } text-base cursor-pointer hover:text-blue-600 dark:hover:text-blue-400`}
      onClick={toggle}
      title={dark ? "Switch to light mode" : "Switch to dark mode"}
    />
  );
}
