"use client";

import { useEffect, useState } from "react";

const storageKey = "hadlock_theme";

const prefersLight = () =>
  window.matchMedia("(prefers-color-scheme: light)").matches;

export function ThemeToggle() {
  const [isLight, setIsLight] = useState(false);

  useEffect(() => {
    const saved = window.localStorage.getItem(storageKey);
    if (saved === "light" || saved === "dark") {
      setIsLight(saved === "light");
      return;
    }
    setIsLight(prefersLight());
  }, []);

  function toggle() {
    const saved = window.localStorage.getItem(storageKey);
    const next = !(saved === "light" || saved === "dark"
      ? saved === "light"
      : prefersLight());
    setIsLight(next);
    document.documentElement.classList.remove("light", "dark");
    document.documentElement.classList.add(next ? "light" : "dark");
    try {
      window.localStorage.setItem(storageKey, next ? "light" : "dark");
    } catch {}
  }

  return (
    <button
      type="button"
      onClick={toggle}
      aria-label={isLight ? "Switch to dark mode" : "Switch to light mode"}
      className="border-border bg-surface/50 text-text-secondary hover:text-text flex h-9 w-9 items-center justify-center border backdrop-blur-md transition"
    >
      {isLight ? (
        <SunIcon className="h-4 w-4" />
      ) : (
        <MoonIcon className="h-4 w-4" />
      )}
    </button>
  );
}

function SunIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      className={className}
      aria-hidden="true"
    >
      <circle cx="12" cy="12" r="4" />
      <path d="M12 2v2M12 20v2M4.93 4.93l1.41 1.41M17.66 17.66l1.41 1.41M2 12h2M20 12h2M6.34 17.66l-1.41 1.41M19.07 4.93l-1.41 1.41" />
    </svg>
  );
}

function MoonIcon({ className }: { className?: string }) {
  return (
    <svg
      viewBox="0 0 24 24"
      fill="none"
      stroke="currentColor"
      strokeWidth="2"
      strokeLinecap="round"
      strokeLinejoin="round"
      className={className}
      aria-hidden="true"
    >
      <path d="M21 12.79A9 9 0 1 1 11.21 3 7 7 0 0 0 21 12.79z" />
    </svg>
  );
}
