/**
 * useSpeedLimits — fetch the posted-limit track for a route once (per encoded
 * shape) and hold it. Returns null while loading, on failure, or for routes
 * with no encoded shape (synthetic/mock). The caller reads it with
 * speedLimitKphAtFraction at the puck's position.
 */
import { useEffect, useState } from "react";
import type { Route } from "../../../modules/mapmap-react-native/src/MapmapNav.types";
import { fetchSpeedLimits, type SpeedLimitTrack } from "./speedLimits";

export function useSpeedLimits(
  route: Route | undefined,
  apiKey: string
): SpeedLimitTrack | null {
  const [track, setTrack] = useState<SpeedLimitTrack | null>(null);
  const shape = route?.encodedShape;

  useEffect(() => {
    if (!shape) {
      setTrack(null);
      return;
    }
    let cancelled = false;
    setTrack(null); // clear the previous route's limits while the new fetch runs
    void fetchSpeedLimits(apiKey, shape).then((t) => {
      if (!cancelled) setTrack(t);
    });
    return () => {
      cancelled = true;
    };
  }, [shape, apiKey]);

  return track;
}
