import styles from "./RouteWidget.module.css";
import { useMapData } from "../MapDataContext";
import { languageStore } from "@shared";
import { observer } from "mobx-react-lite";

const shouldAnimate = (text: string | undefined, maxLength: number) =>
  (text?.length ?? 0) > maxLength;

const getNumberSizeClass = (text: string | undefined) => {
  const length = text?.length ?? 0;
  if (length <= 2) return "";
  if (length === 3) return styles["route-widget-number--3"];
  if (length === 4) return styles["route-widget-number--4"];
  return styles["route-widget-number--5"];
};

const getLabelSizeClass = (text: string | undefined) => {
  const length = text?.length ?? 0;
  if (length <= 40) return "";
  if (length <= 60) return styles["route-widget-label--medium"];
  if (length <= 80) return styles["route-widget-label--small"];
  return styles["route-widget-label--xsmall"];
};

export const RouteWidget = observer(() => {
  const { routeData, stationData } = useMapData();
  const { language } = languageStore;

  const stations = stationData?.[language] ?? stationData?.["ru"] ?? [];
  const stationsRu = stationData?.["ru"] ?? [];

  const startStation = stations[0];
  const endStation = stations[stations.length - 1];

  const startStationRu = stationsRu[0];
  const endStationRu = stationsRu[stationsRu.length - 1];

  const enSubtitle = `${startStationRu?.name ?? ""} - ${endStationRu?.name ?? ""}`;
  const zhSubtitle = `${startStation?.name ?? ""} - ${endStation?.name ?? ""}`;
  const subtitle = language === "zh" ? zhSubtitle : enSubtitle;

  return (
    <div className={styles["route-widget"]} style={{ position: "relative" }}>
      <div className={[styles["route-widget-number"], getNumberSizeClass(routeData?.route_sys_number)].join(" ")}>
        {routeData?.route_sys_number || ""}
      </div>
      <div className={styles["route-widget-content"]}>
        <div
          className={[
            styles["route-widget-label"],
            shouldAnimate(startStation?.name, 18) ? styles["marquee"] : "",
            getLabelSizeClass(startStation?.name),
          ].join(" ")}
          title={startStation?.name}
        >
          {startStation?.name}
        </div>
        <div
          className={[
            styles["route-widget-label"],
            shouldAnimate(endStation?.name, 18) ? styles["marquee"] : "",
            getLabelSizeClass(endStation?.name),
          ].join(" ")}
          title={endStation?.name}
        >
          {endStation?.name}
        </div>
        <div
          className={[
            styles["route-widget-subtitle"],
            shouldAnimate(subtitle, 50) ? styles["marquee"] : "",
          ].join(" ")}
          title={subtitle}
        >
          {subtitle}
        </div>
      </div>
    </div>
  );
});
