/**
 * React hook for flights map calendar day availability.
 *
 * Calls `getFlightsMapCalendar` on param change, manages loading/days state.
 *
 * @module
 */

import { useState, useEffect, useRef } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { getFlightsMapCalendar } from "../api.js";
import type { FlightsMapCalendarParams } from "../types.js";

export interface UseFlightsMapCalendarResult {
  availableDays: string[];
  loading: boolean;
}

/**
 * Hook for the calendar strip. Fetches available flights-map days for the
 * given route context.
 */
export function useFlightsMapCalendar(
  params: FlightsMapCalendarParams | null,
): UseFlightsMapCalendarResult {
  const client = useApiClient();
  const [availableDays, setAvailableDays] = useState<string[]>([]);
  const [loading, setLoading] = useState(false);

  const paramsRef = useRef(params);
  paramsRef.current = params;

  useEffect(() => {
    if (!paramsRef.current) {
      setAvailableDays([]);
      setLoading(false);
      return;
    }

    let cancelled = false;
    setLoading(true);

    getFlightsMapCalendar(client, paramsRef.current)
      .then((result) => {
        if (!cancelled) {
          setAvailableDays(result);
          setLoading(false);
        }
      })
      .catch(() => {
        if (!cancelled) {
          setAvailableDays([]);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [
    client,
    params?.date,
    params?.departure,
    params?.arrival,
    params?.connections,
  ]);

  return { availableDays, loading };
}
