'use client';

import { useEffect, useState } from 'react';
import { SettingsData } from '@/types';
import { DEFAULT_SETTINGS, loadSettings } from '@/utils/storage/settingsStorage';
import { useAuth } from '@/contexts/AuthContext';

export default function useSettings() {
  const [settings, setSettings] = useState<SettingsData>(DEFAULT_SETTINGS);
  const [isSettingsLoaded, setIsLoaded] = useState(false);
  const { token: authToken } = useAuth();

  useEffect(() => {
    let isMounted = true;

    loadSettings()
      .then(data => {
        if (isMounted) {
          setSettings(data);
          setIsLoaded(true);
        }
      })
      .catch(error => {
        console.error('Error fetching settings:', error);
        if (isMounted) {
          setIsLoaded(true);
        }
      });

    return () => {
      isMounted = false;
    };
  }, []);

  useEffect(() => {
    if (!isSettingsLoaded) {
      return;
    }
    setSettings(prev => {
      const nextToken = authToken || '';
      if (prev.HF_TOKEN === nextToken) {
        return prev;
      }
      return { ...prev, HF_TOKEN: nextToken };
    });
  }, [authToken, isSettingsLoaded]);

  return { settings, setSettings, isSettingsLoaded };
}
