"use client";

import { useEffect, useState } from "react";

import { applyUiTheme, normalizeUiTheme, readStoredUiTheme, storeUiTheme, type UiTheme, UI_THEME_STORAGE_KEY } from "@/lib/theme";

export function ThemeToggle() {
  const [theme, setTheme] = useState<UiTheme>("dark");

  useEffect(() => {
    const initialTheme = readStoredUiTheme();
    setTheme(initialTheme);
    applyUiTheme(initialTheme);

    function handleStorage(event: StorageEvent) {
      if (event.key !== UI_THEME_STORAGE_KEY) {
        return;
      }
      const nextTheme = normalizeUiTheme(event.newValue);
      setTheme(nextTheme);
      applyUiTheme(nextTheme);
    }

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

  function handleToggle() {
    const nextTheme: UiTheme = theme === "dark" ? "light" : "dark";
    setTheme(nextTheme);
    storeUiTheme(nextTheme);
  }

  return (
    <button type="button" className="theme-toggle-floating" onClick={handleToggle} aria-label="Cambia tema">
      <span className="theme-toggle-floating-label">Tema</span>
      <strong>{theme === "dark" ? "Chiaro" : "Scuro"}</strong>
    </button>
  );
}
