/**
 * Online Board route search page.
 *
 * Parses departure + arrival + date from URL, renders shared search page with SEO.
 * URL: /{lang}/onlineboard/route/{dep}-{arr}-{yyyyMMdd}[-{timeRange}]
 */

import { lazy, Suspense } from "react";
import { useParams, Navigate } from "@modern-js/runtime/router";
import { useTranslation } from "@/i18n/provider.js";
import { parseRouteUrlParams } from "@/features/online-board/url.js";
import { buildRouteSearchSeo } 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 RouteSearchPage(): JSX.Element {
  const { t } = useTranslation();
  const routeParams = useParams<{ params: string; lang: string }>();
  const raw = routeParams.params ?? "";
  const locale = routeParams.lang ?? "ru-ru";
  const parsed = parseRouteUrlParams(raw);

  // Resolve IATA → city names for `<title>`. Hooks must run unconditionally.
  const depName = useCityName(parsed?.departure ?? "");
  const arrName = useCityName(parsed?.arrival ?? "");

  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: "route" as const,
    departure: parsed.departure,
    arrival: parsed.arrival,
    date: parsed.date,
    ...(parsed.timeFrom !== undefined && parsed.timeTo !== undefined
      ? { timeFrom: parsed.timeFrom, timeTo: parsed.timeTo }
      : {}),
  };

  const seoProps = buildRouteSearchSeo(t, searchParams, locale, canonicalOrigin, {
    departure: depName,
    arrival: arrName,
  });

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