/**
 * =============================================================================
 * QWHPI — Quebec Weekly Housing Price Index
 * Author  : Simon-Pierre Boucher
 * Contact : contact@spboucher.ai
 * File    : web/components/ThemeToggle.tsx
 * Purpose : Light/dark theme toggle (data-theme attribute wins over OS).
 * =============================================================================
 */
"use client";

import { useEffect, useState } from "react";

export default function ThemeToggle() {
  const [theme, setTheme] = useState<string | null>(null);

  useEffect(() => {
    const saved = localStorage.getItem("qwhpi-theme");
    if (saved) {
      setTheme(saved);
      document.documentElement.dataset.theme = saved;
    }
  }, []);

  const toggle = () => {
    const current =
      theme ??
      (window.matchMedia("(prefers-color-scheme: dark)").matches
        ? "dark"
        : "light");
    const next = current === "dark" ? "light" : "dark";
    setTheme(next);
    document.documentElement.dataset.theme = next;
    localStorage.setItem("qwhpi-theme", next);
  };

  return (
    <button className="ctrl" onClick={toggle} aria-label="Toggle color theme">
      {theme === "dark" ? "Light" : "Dark"} mode
    </button>
  );
}
