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

export default function ThemeToggle() {
  const [isDark, setIsDark] = useState(false);
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    // unikamy SSR, działamy dopiero po stronie klienta
    if (typeof window === "undefined") return;

    const saved = localStorage.getItem("theme");
    const systemPrefersDark = window.matchMedia("(prefers-color-scheme: dark)").matches;

    const dark = saved === "dark" || (!saved && systemPrefersDark);

    setIsDark(dark);
    document.documentElement.classList.toggle("dark", dark);

    setMounted(true);
  }, []);

  const toggleTheme = () => {
    const newDark = !isDark;
    setIsDark(newDark);

    document.documentElement.classList.toggle("dark", newDark);
    localStorage.setItem("theme", newDark ? "dark" : "light");
  };

  if (!mounted) return null;

  return (
    <button
      type="button"
      onClick={toggleTheme}
      class="theme-toggle-btn"
      aria-label="Zmień motyw"
    >
      {isDark ? "🌙" : "🌞"}
    </button>
  );
}
