import { useEffect, useState } from "react";

export type ZonesGeoJson = GeoJSON.FeatureCollection<
  GeoJSON.MultiPolygon,
  GeoJSON.GeoJsonProperties
>;

export function useZones(url = "/data/zones/zones.wgs84.geojson") {
  const [data, setData] = useState<ZonesGeoJson | null>(null);
  const [error, setError] = useState<string | null>(null);

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

    async function run() {
      try {
        setError(null);
        const res = await fetch(url);
        if (!res.ok) throw new Error(`Failed to load zones: ${res.status} ${res.statusText}`);
        const json = (await res.json()) as ZonesGeoJson;
        if (cancelled) return;
        setData(json);
      } catch (e) {
        if (cancelled) return;
        setError(e instanceof Error ? e.message : String(e));
      }
    }

    void run();
    return () => {
      cancelled = true;
    };
  }, [url]);

  return { data, error };
}

