import { useCallback } from "react";
import { useNavigate } from "@modern-js/runtime/router";
import type { HostContract } from "@/host-contract";
import { PopularRequestsPanel } from "@/features/popular-requests/components/PopularRequestsPanel.js";
import type { PopularRequest } from "@/features/popular-requests/types.js";
import { useLocale } from "@/i18n/useLocale.js";
import { languageToLocale, isLanguage } from "@/i18n/resolver.js";

/**
 * MF expose wrapper for the Popular Requests feature.
 *
 * Renders the PopularRequestsPanel and handles navigation on click
 * by routing to the appropriate onlineboard/schedule page within the
 * host application.
 */
export interface PopularRequestsRemoteProps {
  hostContract: HostContract;
}

export default function PopularRequestsRemote({
  hostContract,
}: PopularRequestsRemoteProps): JSX.Element {
  const navigate = useNavigate();
  const { locale: urlLocale } = useLocale();
  // Host contracts pass the short language code; promote to BCP-47 for
  // outgoing URLs. URL locale wins when both are present.
  const locale =
    urlLocale ??
    (isLanguage(hostContract.locale) ? languageToLocale(hostContract.locale) : "ru-ru");

  const handleRequestClick = useCallback(
    (request: PopularRequest) => {
      const nav = hostContract.navigate ?? ((path: string) => void navigate(path));

      switch (request.mode) {
        case "FlightNumber":
          nav(`/${locale}/onlineboard`);
          return;
        case "Arrival":
          nav(`/${locale}/onlineboard`);
          return;
        case "Departure":
          nav(`/${locale}/onlineboard`);
          return;
        case "Route":
          if (request.type === "Onlineboard") {
            nav(`/${locale}/onlineboard`);
          } else {
            nav(`/${locale}/schedule`);
          }
          return;
        case "RouteWithBack":
          nav(`/${locale}/schedule`);
          return;
      }
    },
    [hostContract.navigate, navigate, locale],
  );

  return (
    <div data-mf-expose="PopularRequests">
      <PopularRequestsPanel onRequestClick={handleRequestClick} />
    </div>
  );
}
