"use client";

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

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

const getMyTheme = (): ThemeVal => {
  try {
    if (typeof window === "undefined") return "system";
    const stored = window.localStorage.getItem("theme") as ThemeVal | null;
    return stored && themes.includes(stored) ? stored : "system";
  } catch (e) {
    return "system";
  }
};

const setMyTheme = (theme: ThemeVal) => {
  try {
    if (typeof window === "undefined") return;
    window.localStorage.setItem("theme", theme);
  } catch (e) {
    // ignore
  }
};

export function ThemeToggle() {
  const [theme, setTheme] = useState<ThemeVal>("system");
  const [mounted, setMounted] = useState(false);

  // Load from localStorage after mount to ensure server and initial client render match (hydration safety)
  useEffect(() => {
    const stored = getMyTheme();
    setTheme(stored);
    setMounted(true);

    // Apply the effective theme immediately (avoid a flash of the default "system" resolution)
    const root = document.documentElement;
    root.classList.remove("light", "dark");
    if (stored === "system") {
      root.classList.add(
        window.matchMedia("(prefers-color-scheme: dark)").matches
          ? "dark"
          : "light",
      );
    } else {
      root.classList.add(stored);
    }
  }, []);

  // Apply theme to DOM on subsequent changes (after hydration)
  useEffect(() => {
    if (!mounted) return;
    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, mounted]);

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

  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" aria-hidden="true" />
      <span className="hidden sm:inline uppercase tracking-[1px] text-xs">
        {theme}
      </span>
    </button>
  );
}
