/**
 * Online Board arrival search route.
 *
 * Parses station params from URL, renders shared search page with SEO.
 * URL: /{lang}/onlineboard/arrival/{station}-{yyyyMMdd}[-{timeRange}]
 */

import { lazy, Suspense } from "react";
import { useParams, Navigate } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { parseStationUrlParams } from "@/features/online-board/url.js";
import { buildArrivalSearchSeo } from "@/features/online-board/seo.js";
import { SeoHead } from "@/ui/seo/SeoHead.js";
import { FlightListSkeleton } from "@/ui/flights/FlightListSkeleton.js";
import { ErrorPage } from "@/ui/errors/ErrorPage.js";
import { getEnv } from "@/env/index.js";
import { useCityName } from "@/shared/hooks/useDictionaries.js";
import { boardSearchRedirect } from "../../_guards.js";

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

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

  // Resolve IATA → city name for `<title>`. Hooks must run unconditionally.
  const stationName = useCityName(parsed?.station ?? "");

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

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

  const canonicalOrigin = getEnv().PROD_ORIGIN;
  const searchParams = {
    type: "arrival" as const,
    station: parsed.station,
    date: parsed.date,
    ...(parsed.timeFrom !== undefined && parsed.timeTo !== undefined
      ? { timeFrom: parsed.timeFrom, timeTo: parsed.timeTo }
      : {}),
  };

  const seoProps = buildArrivalSearchSeo(t, searchParams, locale, canonicalOrigin, {
    arrival: stationName,
  });

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