"use client";

import { createContext, useContext, useEffect, useMemo, useState } from "react";

type Theme = "light" | "dark";

const ThemeContext = createContext<{ theme: Theme; toggle: () => void }>({ theme: "light", toggle: () => undefined });

export function ThemeProvider({ children }: { children: React.ReactNode }) {
  const [theme, setTheme] = useState<Theme>("light");

  useEffect(() => {
    const saved = window.localStorage.getItem("sellfin:theme");
    // Sellfin is an operations workspace; default to the light data-dense view
    // used by the connected marketplace tools. A manual theme choice still wins.
    const next = saved === "dark" || saved === "light" ? saved : "light";
    document.documentElement.classList.toggle("dark", next === "dark");
    const frame = window.requestAnimationFrame(() => setTheme(next));
    return () => window.cancelAnimationFrame(frame);
  }, []);

  const value = useMemo(() => ({
    theme,
    toggle: () => setTheme((current) => {
      const next = current === "dark" ? "light" : "dark";
      window.localStorage.setItem("sellfin:theme", next);
      document.documentElement.classList.toggle("dark", next === "dark");
      return next;
    }),
  }), [theme]);

  return <ThemeContext.Provider value={value}>{children}</ThemeContext.Provider>;
}

export function useTheme() {
  return useContext(ThemeContext);
}
