/**
 * Schedule flight-details catch-all route.
 *
 * This module backs the framework-mandated `src/routes/[lang]/schedule/$.tsx`
 * splat file. The `$.tsx` filename is how Modern.js (via react-router) marks
 * a route that captures every trailing segment, so we keep it as a thin
 * re-export and put the real code under a readable path.
 *
 * Captures variable-length paths for multi-flight chains, e.g.
 *   /{lang}/schedule/{flight1-date}[/{flight2-date}]...
 * Also handles the airport-code detail variant:
 *   /{lang}/schedule/{depCode}/{flight-date}/{arrCode}/...
 */

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 { ErrorPage } from "@/ui/errors/ErrorPage.js";
import { getEnv } from "@/env/index.js";
import type { IScheduleFlightId } from "./types.js";

const ScheduleDetailsPage = lazy(() =>
  import("./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 ScheduleDetailsCatchAllRoute(): JSX.Element {
  const routeParams = useParams<{ "*": string; lang: string }>();
  const locale = routeParams.lang ?? "ru-ru";
  const canonicalOrigin = getEnv().PROD_ORIGIN;

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

  if (flights.length === 0) return <ErrorPage code="404" />;

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