/**
 * Online Board flight details route.
 *
 * Parses flight ID from URL, renders detailed flight info with SEO.
 * SEO head is rendered at route level with static info from URL params.
 * JSON-LD is rendered inside the details component once flight data loads.
 * URL: /{lang}/onlineboard/{carrier}{flightNumber}-{yyyyMMdd}
 */

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

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

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

  if (!parsed) return <ErrorPage code="404" />;

  const redirect = boardDateRedirect(locale, parsed.date);
  if (redirect) return <Navigate to={redirect} replace />;

  const canonicalOrigin = getEnv().PROD_ORIGIN;
  // Render SeoHead OUTSIDE the lazy Suspense boundary so SSR gets the
  // <title> and <meta> into the first response. The inner component's
  // own SeoHead still runs once hydrated; React/Modern.js de-dupes
  // head tags, so the final document ends up with one correct copy.
  const seoProps = buildFlightDetailsSeoFromId(t, parsed, locale, canonicalOrigin);

  return (
    <>
      <SeoHead {...seoProps} />
      <Suspense fallback={<FlightListSkeleton count={1} />}>
        <OnlineBoardDetailsPage
          flightId={parsed}
          locale={locale}
          canonicalOrigin={canonicalOrigin}
        />
      </Suspense>
    </>
  );
}
