import { useEffect, useState } from "react";

interface Preferences {
  homeBackground: string | null;
  eventsBackground: string | null;
  leaderboardBackground: string | null;
}

export function usePreferences() {
  const [preferences, setPreferences] = useState<Preferences | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    // Les préférences sont maintenant globales, pas besoin d'authentification
    fetch("/api/preferences")
      .then((res) => res.json())
      .then((data) => {
        setPreferences(
          data || {
            homeBackground: null,
            eventsBackground: null,
            leaderboardBackground: null,
          }
        );
        setLoading(false);
      })
      .catch(() => {
        setPreferences({
          homeBackground: null,
          eventsBackground: null,
          leaderboardBackground: null,
        });
        setLoading(false);
      });
  }, []);

  return { preferences, loading };
}

export function useBackgroundImage(
  page: "home" | "events" | "leaderboard",
  defaultImage: string
) {
  const { preferences } = usePreferences();
  const [backgroundImage, setBackgroundImage] = useState(defaultImage);

  useEffect(() => {
    if (preferences) {
      const imageKey = `${page}Background` as keyof Preferences;
      const customImage = preferences[imageKey];
      // Utiliser requestAnimationFrame pour éviter les cascades de rendu
      requestAnimationFrame(() => {
        setBackgroundImage(customImage || defaultImage);
      });
    }
  }, [preferences, page, defaultImage]);

  return backgroundImage;
}
