/**
 * Buy-ticket URL for the arrival popup (Angular parity: `getLink`).
 *
 * Base path + fixed params are hardcoded to the Russian-locale Aeroflot
 * search page. The routes triple `{dep}.{date}.{arr}` is the only variable
 * part of the URL.
 *
 * TZ §4.1.24.6: When `Дата рейса` is not known, the transition to SB must be
 * performed without a date ("переход в SB должен выполнятся без даты").
 * In that case, pass `undefined` for `date` and the date segment is omitted:
 *   routes=MOW..LED  → omitted: routes=MOW.LED
 */

import { buildAeroflotSbSearchUrl } from "@/shared/booking/aeroflot.js";

const MAP_UTM_PARAMS = {
  utm_source: "aflwebbot",
  utm_medium: "referral",
  utm_campaign: "ref_3015_general_rf_button.index__all_flight.map",
} as const;

/**
 * Build the SB search URL for a single one-way leg.
 *
 * @param departure 3-letter city code (e.g. "MOW").
 * @param arrival 3-letter city code (e.g. "LED").
 * @param date YYYYMMDD — pass `undefined` when no date is selected; the date
 *   segment is then omitted from the routes triple per TZ §4.1.24.6 Table 70.
 */
export function buildBuyTicketUrl(
  departure: string,
  arrival: string,
  date: string | undefined,
): string {
  return buildAeroflotSbSearchUrl({
    departure,
    arrival,
    date,
    extraParams: MAP_UTM_PARAMS,
  });
}

/**
 * Minimal HTML escape for popup content — prevents injection via
 * city names containing `& < > "`.
 */
export function escapeHtml(s: string): string {
  return s
    .replace(/&/g, "&amp;")
    .replace(/</g, "&lt;")
    .replace(/>/g, "&gt;")
    .replace(/"/g, "&quot;");
}
