'use client';

import { useState, useEffect } from 'react';
import { getRuntimeConfig } from '@/services/config';

/**
 * Hook to ensure runtime config is loaded before components render
 * This prevents race conditions where API calls are made before config is ready
 */
export const useRuntimeConfig = () => {
  const [isConfigReady, setIsConfigReady] = useState(false);
  const [error, setError] = useState<string | null>(null);

  useEffect(() => {
    const initConfig = async () => {
      try {
        await getRuntimeConfig();
        setIsConfigReady(true);
      } catch (err) {
        console.error('Failed to load runtime config:', err);
        setError('Failed to load configuration');
        // Still mark as ready to allow fallback behavior
        setIsConfigReady(true);
      }
    };

    initConfig();
  }, []);

  return { isConfigReady, error };
};
