/**
 * Online Board flight number search route.
 *
 * Parses flight params from URL, renders shared search page with SEO.
 * URL: /{lang}/onlineboard/flight/{carrier}{flightNumber}-{yyyyMMdd}
 */

import { lazy, Suspense } from "react";
import { useParams } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { parseFlightUrlParams } from "@/features/online-board/url.js";
import { buildFlightSearchSeo } from "@/features/online-board/seo.js";
import { SeoHead } from "@/ui/seo/SeoHead.js";
import { FlightListSkeleton } from "@/ui/flights/FlightListSkeleton.js";
import { getEnv } from "@/env/index.js";

const OnlineBoardSearchPage = lazy(() =>
  import("@/features/online-board/components/OnlineBoardSearchPage.js").then(
    (m) => ({ default: m.OnlineBoardSearchPage }),
  ),
);

export default function FlightSearchPage(): JSX.Element {
  const { t } = useTranslation();
  const routeParams = useParams<{ params: string; lang: string }>();
  const raw = routeParams.params ?? "";
  const locale = routeParams.lang ?? "ru";
  const parsed = parseFlightUrlParams(raw);

  if (!parsed) {
    return (
      <div data-testid="invalid-params">
        <p>Invalid flight parameters.</p>
      </div>
    );
  }

  const canonicalOrigin = getEnv().PROD_ORIGIN;
  const searchParams = parsed.suffix
    ? {
        type: "flight" as const,
        carrier: parsed.carrier,
        flightNumber: parsed.flightNumber,
        suffix: parsed.suffix,
        date: parsed.date,
      }
    : {
        type: "flight" as const,
        carrier: parsed.carrier,
        flightNumber: parsed.flightNumber,
        date: parsed.date,
      };

  const seoProps = buildFlightSearchSeo(t, searchParams, locale, canonicalOrigin);

  return (
    <>
      <SeoHead {...seoProps} />
      <Suspense fallback={<FlightListSkeleton />}>
        <OnlineBoardSearchPage params={searchParams} />
      </Suspense>
    </>
  );
}
