"use client";

import { Laptop, Moon, Sun } from "lucide-react";
import { useEffect, useMemo, useState } from "react";

type ThemeVal = "light" | "dark" | "system";
const themes: ThemeVal[] = ["light", "dark", "system"];

export function ThemeToggle() {
  const initialTheme = useMemo<ThemeVal>(() => {
    if (typeof window === "undefined") return "system";
    const stored = window.localStorage.getItem("theme") as ThemeVal | null;
    return stored && themes.includes(stored) ? stored : "system";
  }, []);

  const [theme, setTheme] = useState<ThemeVal>(initialTheme);

  // Persist to localStorage
  useEffect(() => {
    window.localStorage.setItem("theme", theme);
  }, [theme]);

  // Apply theme to DOM
  useEffect(() => {
    const root = document.documentElement;
    root.classList.remove("light", "dark");
    if (theme === "system") {
      root.classList.add(
        window.matchMedia("(prefers-color-scheme: dark)").matches
          ? "dark"
          : "light",
      );
    } else {
      root.classList.add(theme);
    }
  }, [theme]);

  const handleToggle = () => {
    const currentIndex = themes.indexOf(theme);
    const nextIndex = (currentIndex + 1) % themes.length;
    setTheme(themes[nextIndex]);
  };

  const Icon = theme === "light" ? Sun : theme === "dark" ? Moon : Laptop;

  return (
    <button
      onClick={handleToggle}
      className="inline-flex items-center gap-2 text-sm text-[var(--color-text-muted)] hover:text-[var(--color-heading)] transition-colors"
      aria-label={`Current theme: ${theme}`}
      type="button"
    >
      <Icon className="h-4 w-4" />
      <span className="hidden sm:inline uppercase tracking-[1px] text-xs">
        {theme}
      </span>
    </button>
  );
}
