/**
 * React hook for calendar day availability.
 *
 * Calls `getCalendarDays` on param change, manages loading/days state.
 * Thin wrapper — integration-tested by 2E/2H, not unit-tested here.
 *
 * @module
 */

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

export interface UseCalendarDaysResult {
  days: string[];
  loading: boolean;
}

/**
 * Hook for the calendar strip. Fetches available flight days for the
 * given search context.
 */
export function useCalendarDays(params: CalendarParams): UseCalendarDaysResult {
  const client = useApiClient();
  const [days, setDays] = useState<string[]>([]);
  const [loading, setLoading] = useState(true);

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

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

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

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

  return { days, loading };
}
