import { useEffect, useState } from "react";
import type { LegacyVesselDataset } from "../model/types";

export function useLegacyVessels(url = "/data/legacy/chinese-permitted.v1.json") {
  const [data, setData] = useState<LegacyVesselDataset | 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 legacy vessels: ${res.status} ${res.statusText}`);
        const json = (await res.json()) as LegacyVesselDataset;
        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 };
}

