import { defineNuxtPlugin } from "#app";

/** Muat tema & bahasa dari localStorage, lalu sinkron dari API jika sudah login. */
export default defineNuxtPlugin({
  name: "workpulse-preferences-init",
  setup() {
    const { initTheme } = useTheme();
    const { initLocale } = useWorkpulseLocale();
    const { isAuthenticated } = useAuth();
    const { loadAndApplyPreferences } = useWorkpulsePreferences();

    initTheme();
    initLocale();

    if (!import.meta.client) return;

    const syncFromApi = () => {
      if (!isAuthenticated.value) return;
      void loadAndApplyPreferences();
    };

    syncFromApi();

    watch(isAuthenticated, (on) => {
      if (on) syncFromApi();
    });
  }
});
