/**
 * 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 } 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;
  loaded: boolean;
}

/**
 * Hook for the calendar strip. Fetches available flight days for the
 * given search context. Pass `null` while user input is incomplete to
 * skip the fetch entirely (the hook returns an empty `days` array so
 * the filter's disabled-dates derivation is a no-op until the user has
 * typed enough to resolve a search segment).
 */
export function useCalendarDays(
  params: CalendarParams | null,
): UseCalendarDaysResult {
  const client = useApiClient();
  const [days, setDays] = useState<string[]>([]);
  const [loading, setLoading] = useState(Boolean(params));
  const [loaded, setLoaded] = useState(false);

  useEffect(() => {
    if (!params) {
      setDays([]);
      setLoading(false);
      setLoaded(false);
      return;
    }

    let cancelled = false;
    setLoading(true);
    setLoaded(false);

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

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

  return { days, loading, loaded };
}
