// src/hooks/useMapData.ts
import { useState, useEffect, useCallback, useRef } from "react";
function transformGeoJSONFeatures(geoJSON) {
  return geoJSON.features.map((feature) => ({
    id: feature.properties?.GEOCODIGO || feature.properties?.NOME || "",
    name: feature.properties?.NRE ? `NRE ${feature.properties.NRE}` : feature.properties?.NOME || "",
    value: feature.properties?.value ?? 0,
    accessCount: feature.properties?.totalAccess ?? 0,
    geoJson: feature
  }));
}
function transformRegionData(region) {
  if (!region.geoJson) {
    return null;
  }
  return {
    id: region.schoolGroupId,
    name: region.schoolGroupName,
    code: region.schoolGroupCode,
    value: region.value,
    accessCount: region.totalAccess,
    geoJson: region.geoJson
  };
}
var createUseMapData = (fetchMapDataApi) => {
  return (filters) => {
    const filtersRef = useRef(filters);
    filtersRef.current = filters;
    const filtersKey = JSON.stringify(filters);
    const fetchIdRef = useRef(0);
    const [data, setData] = useState([]);
    const [bounds, setBounds] = useState(null);
    const [geoJSON, setGeoJSON] = useState(null);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState(null);
    const fetchData = useCallback(async () => {
      const fetchId = ++fetchIdRef.current;
      setLoading(true);
      setError(null);
      try {
        const mapData = await fetchMapDataApi(filtersRef.current);
        if (fetchIdRef.current !== fetchId) return;
        const transformedRegions = mapData.data.geoJSON ? transformGeoJSONFeatures(mapData.data.geoJSON) : mapData.data.regions.map(transformRegionData).filter((r) => r !== null);
        setData(transformedRegions);
        setBounds(mapData.data.bounds);
        setGeoJSON(mapData.data.geoJSON ?? null);
      } catch (err) {
        if (fetchIdRef.current !== fetchId) return;
        const errorMessage = err instanceof Error ? err.message : "Erro ao carregar dados do mapa";
        setError(errorMessage);
        setData([]);
        setBounds(null);
        setGeoJSON(null);
      } finally {
        if (fetchIdRef.current === fetchId) {
          setLoading(false);
        }
      }
    }, [filtersKey]);
    useEffect(() => {
      fetchData();
    }, [fetchData]);
    return {
      data,
      bounds,
      geoJSON,
      loading,
      error,
      refetch: fetchData
    };
  };
};
export {
  createUseMapData
};
//# sourceMappingURL=index.mjs.map