"use client";

import { useEffect, useState } from "react";

type ThemeMode = "light" | "dark";

function getInitialTheme(): ThemeMode {
  if (typeof window === "undefined") return "dark";
  const saved = window.localStorage.getItem("mtg_theme");
  if (saved === "light" || saved === "dark") return saved;
  const prefersDark = window.matchMedia && window.matchMedia("(prefers-color-scheme: dark)").matches;
  return prefersDark ? "dark" : "light";
}

function applyTheme(t: ThemeMode) {
  if (typeof document === "undefined") return;
  document.documentElement.dataset.theme = t;
}

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

  useEffect(() => {
    const t = getInitialTheme();
    setTheme(t);
    applyTheme(t);
  }, []);

  function toggle() {
    const next: ThemeMode = theme === "dark" ? "light" : "dark";
    setTheme(next);
    applyTheme(next);
    try {
      window.localStorage.setItem("mtg_theme", next);
    } catch {
      // ignore
    }
  }

  const label = theme === "dark" ? "Switch to light" : "Switch to dark";

  return (
    <button
      type="button"
      aria-label={label}
      onClick={toggle}
      className="fixed right-4 top-4 z-50 rounded-full border px-3 py-2 text-sm backdrop-blur"
      style={{ borderColor: "var(--border)", background: "var(--card)", color: "var(--foreground)" }}
    >
      {theme === "dark" ? (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <path
            d="M21 12.6A8.5 8.5 0 0 1 11.4 3a6.7 6.7 0 1 0 9.6 9.6Z"
            stroke="currentColor"
            strokeWidth="1.8"
            strokeLinecap="round"
            strokeLinejoin="round"
          />
        </svg>
      ) : (
        <svg width="18" height="18" viewBox="0 0 24 24" fill="none" xmlns="http://www.w3.org/2000/svg">
          <circle cx="12" cy="12" r="4" stroke="currentColor" strokeWidth="1.8" />
          <path d="M12 2v2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M12 20v2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M2 12h2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M20 12h2" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M4.9 4.9l1.4 1.4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M17.7 17.7l1.4 1.4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M19.1 4.9l-1.4 1.4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
          <path d="M6.3 17.7l-1.4 1.4" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" />
        </svg>
      )}
    </button>
  );
}
