import { useState, useEffect } from 'react';
import { logNonAbortError } from '../lib/api';
import { TRANSPORT_MODES, type TransportMode } from './useTravelTime';

/**
 * Server may report transit variants (transit-no-bus, transit-no-change, …)
 * alongside the four base modes. The UI mode picker only exposes the base modes;
 * the transit variants are surfaced via toggles on a transit entry. This typing
 * keeps the data model honest: the server speaks strings, we narrow at the edge.
 */
interface TravelModeInfo {
  mode: string;
  destinations: number;
}

function isBaseMode(mode: string): mode is TransportMode {
  return (TRANSPORT_MODES as readonly string[]).includes(mode);
}

/** Fetches which transport modes have precomputed travel time data. */
export function useTravelModes() {
  const [availableModes, setAvailableModes] = useState<Set<TransportMode> | null>(null);

  useEffect(() => {
    const controller = new AbortController();

    fetch('/api/travel-modes', { signal: controller.signal })
      .then((res) => {
        if (!res.ok) throw new Error(`HTTP ${res.status}`);
        return res.json();
      })
      .then((data: { modes: TravelModeInfo[] }) => {
        const modes = new Set<TransportMode>();
        let anyTransitVariantHasData = false;
        for (const m of data.modes) {
          if (m.destinations <= 0) continue;
          if (isBaseMode(m.mode)) {
            modes.add(m.mode);
          } else if (m.mode.startsWith('transit-')) {
            // Variant directories ensure the transit mode is reachable even if
            // someone deletes the base `transit/` parquet folder by mistake.
            anyTransitVariantHasData = true;
          }
        }
        if (anyTransitVariantHasData) modes.add('transit');
        setAvailableModes(modes);
      })
      .catch((err) => logNonAbortError('travel modes', err));

    return () => controller.abort();
  }, []);

  return availableModes;
}
