<script setup lang="ts">
import axios from 'axios'
import { onMounted, onUnmounted, ref } from 'vue'
import { ChangeTitle } from '@/utils/change-title'

const backendUrl = import.meta.env.VITE_BACKEND_DOMAIN

// api
const lastfmapi = import.meta.env.VITE_LASTFM_API
const lastfmusername = 'snsxd'

const header = ref('silence...')
const artist = ref('today...')
const track = ref("we're silnce...")
const labelurl = ref('/default-cover.png')

// colors
const border_color = ref('#656565')
const background_color = ref('#353535')
const primary_color = ref('#656565') // #FFFFFF

async function checkNowPlaying(api: string, username: string) {
  try {
    const response = await axios.get(
      `https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${username}&api_key=${api}&format=json&limit=1`,
    )
    return response.data.recenttracks.track
  } catch (error) {
    console.error('Error fetching data:', error)
  }
}

function changeCover(artist: string, album: string, mbid: string): string {
  // Убираем слеш на конце домена, если он там случайно остался
  const baseUrl = backendUrl.replace(/\/$/, '')

  // Кодируем спецсимволы и задаём 'unknown' для пустых значений
  const safeArtist = encodeURIComponent(artist || 'unknown')
  const safeAlbum = encodeURIComponent(album || 'unknown')
  const safeMbid = mbid || '0'

  return `${baseUrl}/cover/${safeArtist}/${safeAlbum}/${safeMbid}`
}

let timerId: ReturnType<typeof setTimeout>

onMounted(() => {
  const updateSong = async () => {
    const trackData = await checkNowPlaying(lastfmapi, lastfmusername)
    console.log(trackData)
    if (trackData) {
      if (trackData.length > 1) {
        if (header.value !== 'now playing') {
          await ChangeTitle(header, header.value, 'now playing')
          primary_color.value = '#FFFFFF'
        }
        if (artist.value != trackData[0].artist['#text'])
          ChangeTitle(artist, artist.value, trackData[0].artist['#text'])
        if (track.value != trackData[0].name) {
          labelurl.value = changeCover(
            trackData[0].artist['#text'],
            trackData[0].album['#text'],
            trackData[0].album.mbid,
          )
          console.log(labelurl.value)
          ChangeTitle(track, track.value, trackData[0].name)
        }
      } else {
        if (header.value !== 'silence...') ChangeTitle(header, header.value, 'silence...')
        primary_color.value = '#656565'
        labelurl.value = '/default-cover.png'
        ChangeTitle(artist, artist.value, 'today...')
        ChangeTitle(track, track.value, "we're silnce...")
      }
    }
    timerId = setTimeout(updateSong, 10000)
  }

  updateSong()
})

onUnmounted(() => {
  if (timerId) clearTimeout(timerId)
})
</script>

<style scoped>
.wrapper {
  background-color: v-bind(background_color);
  box-shadow: 0 0 0 10px v-bind(background_color);
  width: 350px;
  height: 75px;
  border: 3px solid v-bind(border_color);
  padding: 10px;
  margin: 10px;
}

.cover_name {
  display: flex;
  align-items: center;
  gap: 15px;
  margin-top: -10px;
}

.name {
  display: flex;
  flex-direction: column;
  justify-content: center;
  gap: 10px;
  min-height: 1.4em;
}

h1 {
  color: v-bind(border_color);
  margin-top: -22px;
  margin-left: -5px;
  background-color: v-bind(background_color);
  width: fit-content;
  padding: 0 5px;
  font-size: medium;
  min-height: 1.4em;
}

p {
  color: v-bind(primary_color);
  margin: 0;
  min-height: 1.4em;
}

.track_name {
  font-weight: bolder;
}

img {
  width: 75px;
  height: auto;
}

.wave-text {
  background: linear-gradient(
    90deg,
    v-bind(border_color),
    v-bind(primary_color),
    v-bind(border_color)
  );
  background-size: 200% auto;
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  animation: wave-animation 2s linear infinite;
}

@keyframes wave-animation {
  0% {
    background-position: 0% center;
  }
  100% {
    background-position: -200% center;
  }
}
</style>

<template>
  <div class="wrapper">
    <h1>
      <span :class="{ 'wave-text': header === 'now playing' }">{{ header }}</span>
    </h1>

    <div class="cover_name">
      <img :src="labelurl" @error="labelurl = '/default-cover.png'" />
      <div class="name">
        <p class="track_name">{{ track }}</p>
        <p>{{ artist }}</p>
      </div>
    </div>
  </div>
</template>
