/**
 * React hook for fetching popular requests.
 *
 * Calls `getPopularRequests` on mount, manages loading/error/data state.
 *
 * @module
 */

import { useState, useEffect } from "react";
import { useApiClient } from "@/shared/api/provider.js";
import { getPopularRequests } from "../api.js";
import type { PopularRequest } from "../types.js";
import type { ApiError } from "@/shared/api/errors.js";

/**
 * Fallback popular requests shown when the API is unavailable.
 * Matches the Angular mock data so the start page renders identically.
 */
const FALLBACK_REQUESTS: PopularRequest[] = [
  {
    mode: "FlightNumber",
    carrier: "SU",
    flightNumber: "9027",
    type: "Onlineboard",
  },
  {
    mode: "FlightNumber",
    carrier: "SU",
    flightNumber: "9006",
    type: "Onlineboard",
  },
  {
    mode: "Route",
    departure: "KUF",
    arrival: "ABA",
    type: "Onlineboard",
  },
  {
    mode: "Route",
    departure: "RTW",
    arrival: "ABA",
    type: "Onlineboard",
  },
];

export interface UsePopularRequestsResult {
  requests: PopularRequest[];
  loading: boolean;
  error: ApiError | null;
}

/**
 * Hook that fetches popular requests on mount. Returns loading/error/data.
 * Falls back to mock data when the API is unavailable so the start page
 * always renders the popular sections panel.
 */
export function usePopularRequests(): UsePopularRequestsResult {
  const client = useApiClient();
  const [requests, setRequests] = useState<PopularRequest[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<ApiError | null>(null);

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

    getPopularRequests(client)
      .then((data) => {
        if (!cancelled) {
          setRequests(data.length > 0 ? data : FALLBACK_REQUESTS);
          setLoading(false);
        }
      })
      .catch((err: ApiError) => {
        if (!cancelled) {
          setError(err);
          setRequests(FALLBACK_REQUESTS);
          setLoading(false);
        }
      });

    return () => {
      cancelled = true;
    };
  }, [client]);

  return { requests, loading, error };
}
