"use client";

import { fetchOnce } from "@/lib/fetch-once";

import { useEffect } from "react";
import { useAuth } from "@/lib/auth-context";

/**
 * Applies the person's chosen theme by setting CSS custom properties on the
 * document. Themes are data, so a new one needs no code — just tokens.
 */
export function ThemeApplier() {
  const { user } = useAuth();

  useEffect(() => {
    if (!user) return;

    fetchOnce<{ active: boolean; tokens: Record<string, string> }[]>("/api/themes")
      .then((d) => d)
      .then((themes: { active: boolean; tokens: Record<string, string> }[]) => {
        const chosen = themes.find((t) => t.active);
        const root = document.documentElement;

        // Clear whatever the last theme set before applying the new one.
        for (const prop of Array.from(root.style)) {
          if (prop.startsWith("--theme-")) root.style.removeProperty(prop);
        }
        if (!chosen) return;
        for (const [key, value] of Object.entries(chosen.tokens)) {
          root.style.setProperty(key, value);
        }
      })
      .catch(() => {});
  }, [user]);

  return null;
}
