"use client";

import { useEffect, useState } from "react";

const STORAGE_KEY = "mawidi-theme";

type Theme = "light" | "dark";

const icons = {
  light: "☀️",
  dark: "🌙",
};

export default function ThemeToggle() {
  const [theme, setTheme] = useState<Theme>("light");
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    const prefersDark = window.matchMedia(
      "(prefers-color-scheme: dark)",
    ).matches;
    const stored =
      (window.localStorage.getItem(STORAGE_KEY) as Theme | null) ??
      (prefersDark ? "dark" : "light");
    document.documentElement.classList.toggle("dark", stored === "dark");
    setTheme(stored);
    setMounted(true);
  }, []);

  useEffect(() => {
    if (!mounted) return;
    document.documentElement.classList.toggle("dark", theme === "dark");
    window.localStorage.setItem(STORAGE_KEY, theme);
  }, [theme, mounted]);

  return (
    <button
      type="button"
      onClick={() => setTheme(theme === "dark" ? "light" : "dark")}
      aria-label={
        theme === "dark" ? "Switch to light mode" : "Switch to dark mode"
      }
      className="rounded-full border border-slate-200 bg-white px-3 py-2 text-base shadow-sm transition-colors hover:border-brand-green hover:text-brand-green dark:border-slate-700 dark:bg-slate-900 dark:text-slate-200 md:px-4 md:py-3"
    >
      {icons[theme]}
    </button>
  );
}
