/**
 * Container component for the Popular Requests panel.
 *
 * Angular equivalent: `PopularRequestsComponent` (popular-requests.component.ts)
 * — fetches popular requests on mount, renders up to 4 items in a 2-column
 * grid, and handles click navigation.
 *
 * This component is embedded in start pages (OnlineBoard, Schedule),
 * not rendered as a standalone route.
 */

import { useTranslation } from "@/i18n/provider.js";
import { usePopularRequests } from "../hooks/usePopularRequests.js";
import { PopularRequestItem } from "./PopularRequestItem.js";
import "./PopularRequestsPanel.scss";
import type { PopularRequest } from "../types.js";

/** Build a stable React key from a popular request's discriminated fields. */
function getRequestKey(request: PopularRequest): string {
  switch (request.mode) {
    case "FlightNumber":
      return `fn-${request.carrier}-${request.flightNumber}`;
    case "Arrival":
      return `arr-${request.arrival}`;
    case "Departure":
      return `dep-${request.departure}`;
    case "Route":
    case "RouteWithBack":
      return `${request.mode}-${request.departure}-${request.arrival}`;
  }
}

export interface PopularRequestsPanelProps {
  /** Callback invoked when a user clicks a popular request. The host page
   *  handles navigation based on the request mode and type. */
  onRequestClick: (request: PopularRequest) => void;
}

/**
 * Renders the "Popular sections" panel with up to 4 popular request items.
 * Shows nothing while loading, nothing on error (graceful degradation).
 */
export function PopularRequestsPanel({
  onRequestClick,
}: PopularRequestsPanelProps): JSX.Element | null {
  const { t } = useTranslation();
  const { requests, loading } = usePopularRequests();

  // Don't render while loading or when there are no requests
  if (loading || requests.length === 0) {
    return null;
  }

  // Angular renders exactly 4 items (requests[0]..requests[3])
  const visibleRequests = requests.slice(0, 4);

  return (
    <div className="popular-requests">
      <h3 className="popular-requests__title">
        {t("BOARD.POPULAR-CHAPTERS")}
      </h3>
      {visibleRequests.map((request) => (
        <div key={getRequestKey(request)} className="popular-requests__item">
          <PopularRequestItem
            request={request}
            onClick={onRequestClick}
          />
        </div>
      ))}
    </div>
  );
}
