/**
 * Schedule round-trip route search page.
 *
 * Parses outbound + return route direction params from URL.
 * URL: /{lang}/schedule/route/{outboundParams}/{returnParams}
 */

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

const ScheduleSearchPage = lazy(() =>
  import("@/features/schedule/components/ScheduleSearchPage.js").then(
    (m) => ({ default: m.ScheduleSearchPage }),
  ),
);

export default function ScheduleRoundTripSearchPage(): JSX.Element {
  const { t } = useTranslation();
  const routeParams = useParams<{ params: string; returnParams: string; lang: string }>();
  const outboundRaw = routeParams.params ?? "";
  const inboundRaw = routeParams.returnParams ?? "";
  const locale = routeParams.lang ?? "ru";

  const outbound = parseScheduleRouteParams(outboundRaw);
  const inbound = parseScheduleRouteParams(inboundRaw);

  if (!outbound || !inbound) {
    return (
      <div data-testid="invalid-params">
        <p>Invalid round-trip schedule parameters.</p>
      </div>
    );
  }

  const canonicalOrigin = getEnv().PROD_ORIGIN;
  const scheduleParams = { type: "roundtrip" as const, outbound, inbound };
  const seoProps = buildScheduleSearchSeo(t, scheduleParams, locale, canonicalOrigin);

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