/**
 * @ai-summary Hook to sync dark mode preference with backend
 * Load from backend on auth, sync changes to backend on toggle
 */

import { useEffect, useRef } from 'react';
import { useAuth0 } from '@auth0/auth0-react';
import { usePreferences, useUpdatePreferences } from '../../features/settings/hooks/usePreferences';
import { useTheme } from './ThemeContext';

/**
 * Syncs theme preference with backend.
 * Place this hook in an authenticated component (e.g., Layout or App authenticated section).
 *
 * Behavior:
 * - On auth: loads darkMode from backend and updates ThemeContext
 * - On toggle: syncs new darkMode value to backend
 */
export const useThemeSync = () => {
  const { isAuthenticated } = useAuth0();
  const { data: preferences, isLoading } = usePreferences();
  const updatePreferences = useUpdatePreferences();
  const { setDarkMode, registerBackendSync, isDarkMode } = useTheme();
  const hasLoadedFromBackend = useRef(false);

  // Register backend sync function
  useEffect(() => {
    const syncToBackend = (darkMode: boolean) => {
      if (isAuthenticated) {
        updatePreferences.mutate({ darkMode });
      }
    };

    registerBackendSync(syncToBackend);
  }, [isAuthenticated, updatePreferences, registerBackendSync]);

  // Load from backend on initial auth (only once)
  useEffect(() => {
    if (
      isAuthenticated &&
      !isLoading &&
      preferences &&
      !hasLoadedFromBackend.current
    ) {
      hasLoadedFromBackend.current = true;

      // Only update if backend has an explicit preference
      if (preferences.darkMode !== null && preferences.darkMode !== undefined) {
        // Update local state without syncing back to backend
        setDarkMode(preferences.darkMode, false);
      }
    }
  }, [isAuthenticated, isLoading, preferences, setDarkMode]);

  // Reset flag when user logs out
  useEffect(() => {
    if (!isAuthenticated) {
      hasLoadedFromBackend.current = false;
    }
  }, [isAuthenticated]);

  return {
    isDarkMode,
    isLoading: isLoading && isAuthenticated,
  };
};
