"use client";

import { useEffect, useState } from "react";

type Theme = "light" | "dark";

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

  useEffect(() => {
    setMounted(true);
    if (typeof window === "undefined") return;

    const stored = window.localStorage.getItem("camber-theme") as Theme | null;
    if (stored === "light" || stored === "dark") {
      applyTheme(stored);
      setTheme(stored);
      return;
    }

    const prefersDark = window.matchMedia?.(
      "(prefers-color-scheme: dark)",
    ).matches;
    const initial: Theme = prefersDark ? "dark" : "light";
    applyTheme(initial);
    setTheme(initial);
  }, []);

  const applyTheme = (value: Theme) => {
    if (typeof document === "undefined") return;
    const root = document.documentElement;
    root.classList.remove("dark");
    if (value === "dark") {
      root.classList.add("dark");
    }
    window.localStorage.setItem("camber-theme", value);
  };

  const handleToggle = () => {
    const next: Theme = theme === "light" ? "dark" : "light";
    setTheme(next);
    applyTheme(next);
  };

  if (!mounted) {
    return (
      <button
        aria-label="تغییر حالت تم"
        className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-border bg-background text-xs text-muted-foreground"
      >
        …
      </button>
    );
  }

  return (
    <button
      type="button"
      onClick={handleToggle}
      aria-label="تغییر حالت تم"
      className="inline-flex h-8 w-8 items-center justify-center rounded-full border border-border bg-background text-xs text-muted-foreground hover:border-foreground/60 hover:text-foreground"
    >
      {theme === "light" ? "☾" : "☼"}
    </button>
  );
}

