import { useCallback, useEffect, useState } from 'react';

const PREFERENCES_ENDPOINT = '/api/user/preferences';
const useUserPreferences = ({ authorizedFetch, sessionToken }) => {
  const [preferences, setPreferences] = useState(null);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState('');

  const loadPreferences = useCallback(async () => {
    if (!sessionToken || !authorizedFetch) {
      setPreferences(null);
      return;
    }
    setLoading(true);
    setError('');
    try {
      const response = await authorizedFetch(PREFERENCES_ENDPOINT);
      if (!response.ok) {
        throw new Error(`HTTP ${response.status}`);
      }
      const data = await response.json();
      setPreferences(data);
    } catch (err) {
      setError(`Einstellungen konnten nicht geladen werden: ${err.message}`);
    } finally {
      setLoading(false);
    }
  }, [authorizedFetch, sessionToken]);

  useEffect(() => {
    if (sessionToken) {
      loadPreferences();
    } else {
      setPreferences(null);
    }
  }, [sessionToken, loadPreferences]);

  return {
    preferences,
    loading,
    error,
    loadPreferences
  };
};

export default useUserPreferences;
