/**
 * Schedule flight details catch-all route.
 *
 * Captures variable-length paths for multi-flight chains.
 * URL: /{lang}/schedule/{flight1-date}[/{flight2-date}]...
 * Also handles: /{lang}/schedule/{depCode}/{flight-date}/{arrCode}/...
 *
 * Modern.js catch-all route: [...flights] captures all remaining segments.
 */

import { lazy, Suspense } from "react";
import { useParams } from "@modern-js/runtime/router";
import { parseFlightUrlParams } from "@/features/online-board/url.js";
import { FlightListSkeleton } from "@/ui/flights/FlightListSkeleton.js";
import { getEnv } from "@/env/index.js";
import type { IScheduleFlightId } from "@/features/schedule/types.js";

const ScheduleDetailsPage = lazy(() =>
  import("@/features/schedule/components/ScheduleDetailsPage.js").then(
    (m) => ({ default: m.ScheduleDetailsPage }),
  ),
);

/**
 * Parse the catch-all segments into flight IDs.
 * Segments that are 3 chars or less are treated as airport codes and skipped.
 */
function parseFlightSegments(segments: string[]): IScheduleFlightId[] {
  const flights: IScheduleFlightId[] = [];

  for (const segment of segments) {
    if (segment.length <= 3) continue;

    const parsed = parseFlightUrlParams(segment);
    if (parsed) {
      const flight: IScheduleFlightId = {
        carrier: parsed.carrier,
        flightNumber: parsed.flightNumber,
        date: parsed.date,
      };
      if (parsed.suffix !== undefined) {
        flight.suffix = parsed.suffix;
      }
      flights.push(flight);
    }
  }

  return flights;
}

export default function ScheduleDetailsRoute(): JSX.Element {
  const routeParams = useParams<{ "*": string; lang: string }>();
  const locale = routeParams.lang ?? "ru";
  const canonicalOrigin = getEnv().PROD_ORIGIN;

  // Modern.js $.tsx splat route provides the remaining path via "*" param.
  const rawFlights = routeParams["*"] ?? "";
  const segments = rawFlights.split("/").filter(Boolean);
  const flights = parseFlightSegments(segments);

  if (flights.length === 0) {
    return (
      <div data-testid="invalid-params">
        <p>Invalid schedule flight parameters.</p>
      </div>
    );
  }

  return (
    <Suspense fallback={<FlightListSkeleton count={flights.length} />}>
      <ScheduleDetailsPage
        flights={flights}
        locale={locale}
        canonicalOrigin={canonicalOrigin}
      />
    </Suspense>
  );
}
