"use client";

import { useEffect, useRef } from "react";

import {
  applyUiPrefsToStore,
  fetchUiPrefs,
  useUiPrefsStoreSetters,
} from "@/app/dashboard/_lib/ui-prefs-client";

/**
 * Loads admin Appearance prefs once and applies them for the signed-in backend user.
 */
export function DashboardUiPrefsHydrator({ userId }: { userId?: number | null }) {
  const appliedKey = useRef<string | null>(null);
  const setters = useUiPrefsStoreSetters();

  useEffect(() => {
    if (!userId) return;
    let cancelled = false;

    async function load() {
      try {
        const prefs = await fetchUiPrefs();
        if (cancelled) return;

        const key = `${userId}:${JSON.stringify(prefs)}`;
        if (appliedKey.current === key) return;
        appliedKey.current = key;

        applyUiPrefsToStore(prefs, setters);
      } catch {
        // Keep cookie/boot defaults if the prefs endpoint is unavailable.
      }
    }

    void load();
    return () => {
      cancelled = true;
    };
  }, [userId, setters]);

  return null;
}
