// Rôle : charge le contenu éditorial et les données publiques nécessaires à l'application.
import { useEffect, useState } from "react";
import { INITIAL_DIABLO4_STATE, INITIAL_MHWILDS_STATE, loadDiablo4Data, loadMhwildsData } from "../features/games/loaders.js";

export function useAppData(route) {
  const [siteContent, setSiteContent] = useState(null);
  const [siteContentError, setSiteContentError] = useState("");
  const [games, setGames] = useState([]);
  const [gamesError, setGamesError] = useState("");
  const [mhwilds, setMhwilds] = useState(INITIAL_MHWILDS_STATE);
  const [diablo4, setDiablo4] = useState(INITIAL_DIABLO4_STATE);

  useEffect(() => {
    Promise.all([
      fetch("/data/site.json").then((response) => {
        if (!response.ok) throw new Error("Impossible de charger le contenu du site.");
        return response.json();
      }).catch((error) => {
        setSiteContentError(error.message);
        return null;
      }),
      fetch("/data/games.json").then((response) => response.ok ? response.json() : { games: [] }).catch((error) => {
        setGamesError(error.message);
        return { games: [] };
      })
    ]).then(([content, gamesPayload]) => {
      if (content) setSiteContent(content);
      setGames(Array.isArray(gamesPayload.games) ? gamesPayload.games : []);
    });
  }, []);

  useEffect(() => {
    if (!route.startsWith("/games/mhwilds") || mhwilds.loaded || mhwilds.loading) return;
    setMhwilds((state) => ({ ...state, loading: true, error: "" }));
    loadMhwildsData()
      .then(setMhwilds)
      .catch((error) => setMhwilds({ ...INITIAL_MHWILDS_STATE, loaded: true, error: error.message }));
  }, [route, mhwilds.loaded, mhwilds.loading]);

  useEffect(() => {
    if (!route.startsWith("/games/diablo4") || diablo4.loaded || diablo4.loading) return;
    setDiablo4((state) => ({ ...state, loading: true, error: "" }));
    loadDiablo4Data()
      .then(setDiablo4)
      .catch((error) => setDiablo4({ ...INITIAL_DIABLO4_STATE, loaded: true, error: error.message }));
  }, [route, diablo4.loaded, diablo4.loading]);

  return {
    siteContent,
    siteContentError,
    games,
    gamesError,
    mhwilds,
    diablo4
  };
}
