"use client";

import { useEffect, useState } from "react";
import { Tooltip } from "@/components/ui/tooltip";

type Theme = "light" | "dark" | "system";

const KEY = "sag.theme";

function applyTheme(theme: Theme) {
  if (typeof document === "undefined") return;
  const root = document.documentElement;
  const resolved = theme === "system"
    ? (window.matchMedia("(prefers-color-scheme: dark)").matches ? "dark" : "light")
    : theme;
  if (resolved === "dark") root.classList.add("dark");
  else root.classList.remove("dark");
}

export function ThemeToggle() {
  const [theme, setTheme] = useState<Theme>("system");

  useEffect(() => {
    const t = setTimeout(() => {
      const saved = (typeof window !== "undefined" && window.localStorage.getItem(KEY)) as Theme | null;
      const initial = saved && ["light", "dark", "system"].includes(saved) ? saved : "system";
      setTheme(initial);
      applyTheme(initial);
    }, 0);
    return () => clearTimeout(t);
  }, []);

  useEffect(() => {
    // Watch system preference changes
    if (theme !== "system") return;
    const mq = window.matchMedia("(prefers-color-scheme: dark)");
    const onChange = () => applyTheme("system");
    mq.addEventListener("change", onChange);
    return () => mq.removeEventListener("change", onChange);
  }, [theme]);

  function pick(next: Theme) {
    setTheme(next);
    window.localStorage.setItem(KEY, next);
    applyTheme(next);
  }

  return (
    <div className="flex items-center gap-1 rounded-md border bg-background p-0.5">
      <ThemeBtn label="☀" active={theme === "light"} onClick={() => pick("light")} title="Light" />
      <ThemeBtn label="◐" active={theme === "system"} onClick={() => pick("system")} title="System" />
      <ThemeBtn label="☾" active={theme === "dark"} onClick={() => pick("dark")} title="Dark" />
    </div>
  );
}

function ThemeBtn({ label, active, onClick, title }: { label: string; active: boolean; onClick: () => void; title: string }) {
  return (
    <Tooltip content={title}>
      <button
        onClick={onClick}
        aria-label={title}
        className={`text-xs px-2 py-1 rounded transition-colors ${
          active ? "bg-foreground text-background" : "text-muted-foreground hover:bg-accent"
        }`}
      >
        {label}
      </button>
    </Tooltip>
  );
}
