/**
 * Loads the four dictionary endpoints and returns the transformed, ready-to-use
 * IDictionaries object. Mounts once per session (the map is client-only and
 * only mounts once). Not intended for multiple concurrent consumers.
 */

import { useEffect, useState } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { fetchDictionaries } from "./api.js";
import { transformDictionaries } from "./transform.js";
import type { IDictionariesState } from "./types.js";

export function useDictionaries(lang: string): IDictionariesState {
  const client = useApiClient();
  const [state, setState] = useState<IDictionariesState>({
    dictionaries: null,
    loading: true,
    error: null,
  });

  useEffect(() => {
    let cancelled = false;

    fetchDictionaries(client)
      .then((raw) => {
        if (cancelled) return;
        const dictionaries = transformDictionaries(raw, lang);
        setState({ dictionaries, loading: false, error: null });
      })
      .catch((err: Error) => {
        if (cancelled) return;
        setState({ dictionaries: null, loading: false, error: err });
      });

    return () => {
      cancelled = true;
    };
  }, [client, lang]);

  return state;
}
