<template>
  <div class="weatherinfo" :class="{ hidden: isPresidentAddressOpen }">
    <div class="time">{{ formattedTime }}</div>
    <div class="date">{{ formattedDate }}, {{ dayOfWeek }}</div>

    <div class="weather-forecast">
      <div class="current-weather">
        <img
          :src="weatherIcon(currentWeather.description, true)"
          alt="Weather Icon"
        />
        <div class="temperature-celsius">
          {{ currentWeather.temperatureCelsius }}°
        </div>
        <div>
          {{ currentWeather.description }}
        </div>
      </div>

      <div class="forecast">
        <div v-for="day in forecastDays" :key="day.date" class="forecast-day">
          <img :src="weatherIcon(day.description)" alt="Forecast Icon" />
          <div>{{ day.dayShort }}</div>
          <div class="forecast-temperature">{{ day.temperatureCelsius }}°</div>
        </div>
        <div class="additional-forecast">
          <div class="humidity">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="13"
              height="18"
              fill="none"
              viewBox="0 0 12 16"
            >
              <path
                fill="#fff"
                d="M6 15.92a5.708 5.708 0 0 1-5.702-5.702c0-3.155 3.36-7.75 4.804-9.578C5.32.363 5.647.205 6 .205s.68.158.897.435c1.445 1.83 4.806 6.425 4.806 9.578A5.71 5.71 0 0 1 6 15.92ZM6 1.203a.143.143 0 0 0-.112.055c-1.078 1.362-4.59 6.037-4.59 8.957A4.708 4.708 0 0 0 6 14.918a4.708 4.708 0 0 0 4.703-4.703c0-2.92-3.513-7.595-4.588-8.957A.15.15 0 0 0 6 1.203Z"
              />
            </svg>

            <span>{{ currentWeather.humidity }}%</span>
          </div>
          <div class="wind">
            <svg
              xmlns="http://www.w3.org/2000/svg"
              width="18"
              height="18"
              fill="none"
              viewBox="0 0 16 16"
            >
              <g class="det_wind">
                <path
                  fill="#fff"
                  d="M5.507 5.83H1.15a.501.501 0 0 1-.5-.5c0-.275.225-.5.5-.5h4.355c.995 0 1.805-.81 1.805-1.805 0-.995-.81-1.805-1.805-1.805-.995 0-1.805.81-1.805 1.805 0 .275-.225.5-.5.5a.501.501 0 0 1-.5-.5A2.809 2.809 0 0 1 5.505.22 2.81 2.81 0 0 1 8.31 3.025 2.808 2.808 0 0 1 5.507 5.83Z"
                  class="Vector"
                />
                <path
                  fill="#fff"
                  d="M12.543 8.575H3.537a.501.501 0 0 1-.5-.5c0-.275.225-.5.5-.5h9.006c.995 0 1.805-.81 1.805-1.805 0-.995-.81-1.805-1.806-1.805-.995 0-1.804.81-1.804 1.805 0 .275-.226.5-.5.5a.501.501 0 0 1-.5-.5 2.809 2.809 0 0 1 2.805-2.805 2.809 2.809 0 0 1 2.805 2.805 2.809 2.809 0 0 1-2.806 2.805Zm-2.385 7.207a2.809 2.809 0 0 1-2.806-2.805c0-.275.225-.5.5-.5s.5.225.5.5c0 .995.81 1.805 1.806 1.805.995 0 1.805-.81 1.805-1.805 0-.995-.81-1.805-1.805-1.805H1.15a.501.501 0 0 1-.5-.5c0-.275.225-.5.5-.5h9.005a2.809 2.809 0 0 1 2.805 2.805 2.807 2.807 0 0 1-2.803 2.805Z"
                  class="Vector"
                />
              </g>
            </svg>

            <span>{{ currentWeather.windSpeed }} м/с</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import "../assets/style/main.css";
import { API_URL, WEATHER_URL } from "../config";

import axios from "axios";
import clearIcon from "@/icons/clear-day.svg";
import cloudsIcon from "@/icons/cloudy.svg";
import rainIcon from "@/icons/rainy.svg";
import snowIcon from "@/icons/snowy.svg";
import defaultIcon from "@/icons/default.svg";
import thunderIcon from "@/icons/thunderstorms.svg";
import fogIcon from "@/icons/fog.svg";

export default {
  name: "WeatherInfo",
  props: {
    isPresidentAddressOpen: {
      type: Boolean,
      default: false,
    },
  },
  data() {
    return {
      isModalOpen: false,
      autoCloseTimer: null,
      imageUrl: "",
      sightId: null,
      stopName: "",
      articles: [],
      selectedArticleId: null,
      selectedArticleBody: "",
      currentWeather: { description: "", temperatureCelsius: "" },
      forecastDays: [],
      formattedTime: "",
      formattedDate: "",
      dayOfWeek: "",
      timerInterval: null,
      weatherDescriptionMap: {
        thunderstorm: "гроза",
        drizzle: "слабый дождь",
        rain: "дождь",
        snow: "снег",
        atmosphere: "туман",
        clear: "ясно",
        clouds: "облачно",
      },
    };
  },
  methods: {
    async fetchSightInfo() {
      // Do nothing if sightId is null, zero, or empty
      if (!this.sightId) return;

      const response = await axios.get(`${API_URL}/sight/${this.sightId}`);
      this.stopName = response.data.name;
    },
    async fetchArticles() {
      // Do nothing if sightId is null, zero, or empty
      if (!this.sightId) return;

      const response = await axios.get(
        `${API_URL}/sight/${this.sightId}/article`
      );
      this.articles = response.data;
      if (this.articles.length > 0) {
        this.selectArticle(this.articles[0].id);
      }
    },
    selectArticle(id) {
      this.selectedArticleId = id;
      const selected = this.articles.find((article) => article.id === id);
      this.selectedArticleBody = selected ? selected.body : "";
    },
    getCurrentTime() {
      const now = new Date();
      const separator = now.getSeconds() % 2 === 0 ? ":" : " ";
      this.formattedTime = now
        .toLocaleTimeString("ru-RU", {
          hour: "2-digit",
          minute: "2-digit",
          hour12: false,
        })
        .replace(":", separator);
      this.formattedDate = now.toLocaleDateString("ru-RU", {
        day: "2-digit",
        month: "2-digit",
      });
      this.dayOfWeek = now.toLocaleDateString("ru-RU", { weekday: "long" });
    },
    weatherIcon(description) {
      if (!description) return clearIcon;

      switch (this.reverseTranslateDescription(description).toLowerCase()) {
        case "clear":
          return clearIcon;
        case "clouds":
          return cloudsIcon;
        case "rain":
        case "drizzle":
          return rainIcon;
        case "snow":
          return snowIcon;
        case "thunderstorm":
          return thunderIcon;
        case "atmosphere":
          return fogIcon;
        default:
          return defaultIcon;
      }
    },
    reverseTranslateDescription(translated) {
      const entry = Object.entries(this.weatherDescriptionMap).find(
        ([, value]) => value === translated
      );
      return entry ? entry[0] : translated;
    },
    async fetchWeatherData() {
      console.log("Fetching weather data...");
      const now = new Date();
      const response = await axios.post(`${WEATHER_URL}/v1/weather`, {
        coordinates: { latitude: 59.938784, longitude: 30.314997 },
      });
      this.currentWeather = {
        ...response.data.currentWeather,
        temperatureCelsius: Math.round(
          response.data.currentWeather.temperatureCelsius
        ),
      };
      const descriptionKey =
        response.data.currentWeather.description.toLowerCase();
      this.currentWeather.description =
        this.weatherDescriptionMap[descriptionKey] ||
        response.data.currentWeather.description;

      const nextThreeDays = response.data.forecast
        .filter((item) => {
          const itemDate = new Date(item.date);
          return itemDate > now;
        })
        .sort((a, b) => new Date(a.date) - new Date(b.date))
        .reduce((acc, item) => {
          const day = item.date.split(" ")[0];
          if (!acc[day]) {
            acc[day] = {
              date: item.date,
              description: item.description,
              temps: [item.minTemperatureCelsius, item.maxTemperatureCelsius],
            };
          } else {
            acc[day].temps.push(
              item.minTemperatureCelsius,
              item.maxTemperatureCelsius
            );
          }
          return acc;
        }, {});

      this.forecastDays = Object.entries(nextThreeDays)
        .slice(1, 4)
        .map(([, info]) => {
          const avgTemp =
            info.temps.reduce((a, b) => a + b, 0) / info.temps.length;
          const descriptionKey = info.description.toLowerCase();
          const translatedDescription =
            this.weatherDescriptionMap[descriptionKey] || info.description;
          return {
            date: info.date,
            description: translatedDescription,
            temperatureCelsius: Math.round(avgTemp),
            dayShort: new Date(info.date)
              .toLocaleDateString("ru-RU", { weekday: "short" })
              .replace(/^\p{L}/u, (char) => char.toUpperCase()),
          };
        });
    },
  },
  mounted() {
    this.fetchSightInfo();
    this.fetchArticles();
    this.fetchWeatherData();
    this.getCurrentTime();
    this.timerInterval = setInterval(this.getCurrentTime, 1000);
  },
  unmounted() {
    if (this.timerInterval) {
      clearInterval(this.timerInterval);
    }
    if (this.autoCloseTimer) {
      clearTimeout(this.autoCloseTimer);
    }
  },
};
</script>
