"use client";

import { useCallback, useEffect } from "react";
import { useLocalStorage } from "./useLocalStorage.js";

export type ThemeMode = "light" | "dark";
export type AccentColor = "sky" | "indigo" | "violet" | "emerald" | "rose" | "amber";

export interface ThemePreferences {
  mode: ThemeMode;
  accent: AccentColor;
}

const STORAGE_KEY = "nexus_theme";
const DEFAULT: ThemePreferences = { mode: "light", accent: "sky" };

function applyTheme(prefs: ThemePreferences) {
  const html = document.documentElement;
  if (prefs.mode === "dark") html.classList.add("dark");
  else html.classList.remove("dark");
  html.setAttribute("data-accent", prefs.accent);
}

export function useTheme() {
  const [prefs, setPrefs] = useLocalStorage<ThemePreferences>(STORAGE_KEY, DEFAULT);

  // Apply theme to DOM whenever prefs change
  useEffect(() => {
    applyTheme(prefs);
  }, [prefs]);

  const setMode = useCallback(
    (mode: ThemeMode) => {
      setPrefs((prev) => ({ ...prev, mode }));
    },
    [setPrefs],
  );

  const setAccent = useCallback(
    (accent: AccentColor) => {
      setPrefs((prev) => ({ ...prev, accent }));
    },
    [setPrefs],
  );

  return { prefs, setMode, setAccent };
}
