import { useEffect, useState, useRef } from "react";
import { normalizeBackgroundUrl } from "@/lib/avatars";

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);
  const prevImageRef = useRef<string>(defaultImage);

  useEffect(() => {
    if (preferences) {
      const imageKey = `${page}Background` as keyof Preferences;
      const customImage = preferences[imageKey];
      const rawImage = customImage || defaultImage;
      // Normaliser l'URL pour utiliser l'API si nécessaire
      const targetImage = normalizeBackgroundUrl(rawImage) || defaultImage;

      // Ne changer que si l'image est vraiment différente
      if (targetImage !== prevImageRef.current) {
        prevImageRef.current = targetImage;
        // Précharger l'image avant de changer
        const img = new Image();
        img.onload = () => {
          setBackgroundImage(targetImage);
        };
        img.onerror = () => {
          // Si l'image échoue, utiliser l'image par défaut
          setBackgroundImage(defaultImage);
          prevImageRef.current = defaultImage;
        };
        img.src = targetImage;
      }
    }
  }, [preferences, page, defaultImage]);

  return backgroundImage;
}
