import type { FC, MouseEvent } from "react";
import { useCityName } from "@/shared/hooks/useDictionaries.js";
import { airportUrl } from "@/shared/airportUrls.js";
import "./StationDisplay.scss";

export interface StationDisplayProps {
  /** IATA airport code, e.g. "SVO" */
  airportCode: string;
  /** Airport name (optional, displayed if provided) */
  airportName?: string;
  /** City name override (falls back to useCityName hook) */
  cityName?: string;
  /** Terminal code (e.g. "B") rendered as a gray sub-line below the city */
  terminal?: string;
  /** When true, shows the city+terminal as the primary line and hides the IATA code */
  cityFirst?: boolean;
}

/**
 * Renders an airport IATA code with city name.
 *
 * Two layouts:
 *  - default (SEO-friendly): IATA code + airport name + city below.
 *  - `cityFirst`: city (bold) on top, airport + terminal below — matches
 *    Angular's <station> layout in board-flight-header rows.
 */
export const StationDisplay: FC<StationDisplayProps> = ({
  airportCode,
  airportName,
  cityName,
  terminal,
  cityFirst,
}) => {
  const resolvedCity = cityName ?? useCityName(airportCode);
  const terminalLine = [airportName, terminal].filter(Boolean).join(" — ");
  const url = airportUrl(airportCode);

  // Clicking the airport link should NOT toggle the parent flight row.
  const stopBubble = (e: MouseEvent): void => {
    e.stopPropagation();
  };

  // Airport tooltip mirrors Angular's `terminal-link` pTooltip — the
  // full "Airport name — Terminal N" (e.g. "Шереметьево — B"). The
  // city tooltip just shows the city name itself, matching station's
  // `[tooltip]="city"` ellipsis helper.
  const airportTooltip = terminalLine || airportName || undefined;
  const cityTooltip = resolvedCity;

  const terminalEl = terminalLine ? (
    url ? (
      <a
        className="station__terminal station__terminal--link"
        href={url}
        target="_blank"
        rel="noopener noreferrer"
        onClick={stopBubble}
        title={airportTooltip}
      >
        {terminalLine}
      </a>
    ) : (
      <span className="station__terminal" title={airportTooltip}>
        {terminalLine}
      </span>
    )
  ) : null;

  if (cityFirst) {
    return (
      <div className="station station--city-first">
        <span
          className="station__city station__city--bold"
          title={cityTooltip}
        >
          {resolvedCity}
        </span>
        {terminalEl}
      </div>
    );
  }

  return (
    <div className="station">
      <span className="station__code">{airportCode}</span>
      {airportName ? (
        <span className="station__name">{airportName}</span>
      ) : null}
      <span className="station__city" title={cityTooltip}>
        {resolvedCity}
      </span>
    </div>
  );
};
