<template>
  <div class="routeinfo">
    <div class="route-number">{{ routeNumber }}</div>
    <div class="route-names">
      <!-- Russian names -->
      <div class="route-name ru">
        <div class="scroll-wrapper">
          <div :class="isStartScrolling ? 'scroll-inner scrolling' : ''">
            <div class="scroll-content">
              <div class="name-block">
                <span class="name" ref="startStopRuText">
                  <template v-if="isStartScrolling">
                    {{ startStopName }} &nbsp;&nbsp;&nbsp;
                    {{ startStopName }} &nbsp;&nbsp;&nbsp; {{ startStopName }}
                  </template>
                  <template v-else>
                    {{ startStopName }}
                  </template>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <div class="route-name ru">
        <div class="scroll-wrapper">
          <div :class="isEndScrolling ? 'scroll-inner scrolling' : ''">
            <div class="scroll-content">
              <div class="name-block">
                <span class="name" ref="endStopRuText">
                  <template v-if="isEndScrolling">
                    {{ endStopName }} &nbsp;&nbsp;&nbsp;
                    {{ endStopName }} &nbsp;&nbsp;&nbsp; {{ endStopName }}
                  </template>
                  <template v-else>
                    {{ endStopName }}
                  </template>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>

      <!-- English names -->
      <div class="route-name en">
        <div class="scroll-wrapper">
          <div :class="isEnScrolling ? 'scroll-inner scrolling' : ''">
            <div class="scroll-content">
              <div class="name-block">
                <span class="translate" ref="enText">
                  <template v-if="isEnScrolling">
                    {{ startStopNameEn }} —
                    {{ endStopNameEn }} &nbsp;&nbsp;&nbsp;
                    {{ startStopNameEn }} —
                    {{ endStopNameEn }} &nbsp;&nbsp;&nbsp;
                    {{ startStopNameEn }} — {{ endStopNameEn }}
                  </template>
                  <template v-else>
                    {{ startStopNameEn }} — {{ endStopNameEn }}
                  </template>
                </span>
              </div>
            </div>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import { API_URL, GEO_URL } from "../config";

export default {
  name: "RouteInfo",
  data() {
    return {
      routeNumber: "",
      startStopName: "",
      endStopName: "",
      startStopNameEn: "",
      endStopNameEn: "",
      isStartScrolling: false,
      isEndScrolling: false,
      isEnScrolling: false,
      pollId: null,
      hasLoadedStops: false,
    };
  },
  watch: {
    startStopName() {
      this.$nextTick(this.checkScroll);
    },
    endStopName() {
      this.$nextTick(this.checkScroll);
    },
    startStopNameEn() {
      this.$nextTick(this.checkScroll);
    },
    endStopNameEn() {
      this.$nextTick(this.checkScroll);
    },
  },
  mounted() {
    this.startPollingContext();
  },
  methods: {
    startPollingContext() {
      // first request immediately, then every 3 s
      this.fetchContext();
      this.pollId = setInterval(this.fetchContext, 3000);
    },

    async fetchContext() {
      try {
        const res = await fetch(`${GEO_URL}/v1/geolocation/context`);
        const data = await res.json();

        if (data.routeNumber) {
          this.routeNumber = data.routeNumber;
        }

        const { startStopId, endStopId } = data;

        // when both IDs are available for the first time, load names and stop polling
        if (startStopId && endStopId && !this.hasLoadedStops) {
          await this.loadStopNames(startStopId, endStopId);
          this.hasLoadedStops = true;
          if (this.pollId) {
            clearInterval(this.pollId);
            this.pollId = null;
          }
        }
      } catch (err) {
        console.error("Failed to fetch geolocation context", err);
      }
    },

    async loadStopNames(startStopId, endStopId) {
      try {
        const [startRuRes, endRuRes] = await Promise.all([
          fetch(`${API_URL}/station/${startStopId}`),
          fetch(`${API_URL}/station/${endStopId}`),
        ]);
        const startRu = await startRuRes.json();
        const endRu = await endRuRes.json();

        this.startStopName = startRu.name;
        this.endStopName = endRu.name;

        const [startEnRes, endEnRes] = await Promise.all([
          fetch(`${API_URL}/station/${startStopId}?lang=en`),
          fetch(`${API_URL}/station/${endStopId}?lang=en`),
        ]);
        const startEn = await startEnRes.json();
        const endEn = await endEnRes.json();

        this.startStopNameEn = startEn.name;
        this.endStopNameEn = endEn.name;

        this.$nextTick(this.checkScroll);
      } catch (err) {
        console.error("Failed to load station names", err);
      }
    },

    checkScroll() {
      const threshold = 280;
      if (this.$refs.startStopRuText) {
        this.isStartScrolling =
          this.$refs.startStopRuText.offsetWidth > threshold;
      }
      if (this.$refs.endStopRuText) {
        this.isEndScrolling = this.$refs.endStopRuText.offsetWidth > threshold;
      }
      if (this.$refs.enText) {
        this.isEnScrolling = this.$refs.enText.offsetWidth > threshold;
      }
    },
  },
};
</script>
<style scoped>
.route-name {
  overflow: hidden;
  width: 280px;
  white-space: nowrap;
}

.scroll-inner.scrolling {
  animation: marquee 12s linear infinite;
}

@keyframes marquee {
  0% {
    transform: translateX(0);
  }
  100% {
    transform: translateX(-50%);
  }
}
</style>
