const params = (new URL(document.location)).searchParams;
let user = params.get('user');
if (!user) {
  user = 'atbseefeldt';
}
const disc = './img/disc.webp';
const lastfm_default_image = 'https://lastfm.freetls.fastly.net/i/u/64s/2a96cbd8b46e442fc41c2b86b821562f.png';
fetch(`https://ws.audioscrobbler.com/2.0/?method=user.getrecenttracks&user=${user}&api_key=5460c3381d64e7e9908b9fdfc5559747&format=json`)
.then(r => r.json())
.then(lastfm => {
  if (!lastfm.error) {
    const listening = document.getElementById('listening');
    document.getElementById('listening-title').innerHTML = 'Listening to';

    const add_track = (track, all_loaded) => {
      let trackHTML = '';
      let classes = 'listening-item';
      const attr = track['@attr'];
      if (attr && attr.nowplaying) {
        classes += ' now-playing';
      }
      if (all_loaded) {
        classes += ' all-loaded';
      }
      trackHTML += `<div class='${classes}' title='${track.name.replaceAll("'","&apos;")} — ${track.artist['#text'].replaceAll("'","&apos;")}' onclick='if (!this.nextElementSibling) more_tracks(6)'>`;
      let image = track.image[1]['#text'];
      if (image === lastfm_default_image) {
        image = disc;
      }
      trackHTML += `<img width=34 height=34 src='${image}' onload='if (!this.src.endsWith("${disc.substring(1)}")) this.classList.add("loaded")' onerror='this.src = "${disc}"' />`;
      trackHTML += `<span class='listening-track'><span class='track-title'>${track.name}</span> — <span class='track-artist'>${track.artist['#text']}</span></span>`;
      trackHTML += `</div>`;

      listening.innerHTML += trackHTML;
    }

    let track_index = 0;
    const more_tracks = count => {
      const tracks = lastfm.recenttracks.track.slice(track_index, track_index + count);
      track_index += count;
      for (const track of tracks) {
        add_track(track, track_index >= lastfm.recenttracks.track.length);
      }
    }
    more_tracks(5);
    window.more_tracks = more_tracks;
  }
});
