"use client";

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

/**
 * Global light/dark switch. Reads and writes the shared "profile-theme"
 * localStorage key, which the inline script in app/layout.tsx applies to
 * <html data-theme> on every page load — so one toggle controls the whole site.
 *
 * variant="floating" — fixed circular button (profile pages).
 * variant="inline"   — in-flow button styled for the dashboard top bar.
 */
export default function ThemeToggle({ variant = "floating" }: { variant?: "floating" | "inline" }) {
  const [theme, setTheme] = useState<"dark" | "light">("dark");
  const [mounted, setMounted] = useState(false);

  useEffect(() => {
    setMounted(true);
    const saved = window.localStorage.getItem("profile-theme");
    if (saved === "light" || saved === "dark") {
      setTheme(saved);
      document.documentElement.dataset.theme = saved;
    }
  }, []);

  function toggle() {
    const next = theme === "dark" ? "light" : "dark";
    setTheme(next);
    document.documentElement.dataset.theme = next;
    try { window.localStorage.setItem("profile-theme", next); } catch {}
  }

  const inline = variant === "inline";

  return (
    <button
      type="button"
      onClick={toggle}
      aria-label={theme === "dark" ? "Switch to light mode" : "Switch to dark mode"}
      title={theme === "dark" ? "Light mode" : "Dark mode"}
      className={
        inline
          ? "w-[38px] h-[38px] rounded-xl flex-none border border-[#2d2020] bg-[#0d1215] text-[#c20707] grid place-items-center cursor-pointer p-0 hover:opacity-80 transition-opacity"
          : "fixed top-[18px] right-[18px] z-[90] w-10 h-10 rounded-full border border-white/20 bg-[#111820]/85 text-[#ae0606] grid place-items-center cursor-pointer hover:opacity-80 transition-opacity"
      }
      suppressHydrationWarning
    >
      <span suppressHydrationWarning className="grid place-items-center pointer-events-none">
        {mounted && theme === "light" ? <Moon size={18} /> : <Sun size={18} />}
      </span>
    </button>
  );
}
