// Set the Listenbrainz username
const username = "pogmommy";

// Set displayElement to the now-playing widget text from the now_playing.html file
const displayTitle = document.getElementById("np-title");
//displayTitle.href = ""
const displayArtist = document.getElementById("np-artist");
const displayCover = document.getElementById("np-cover");
const displayStatus = document.getElementById("np-heading");
const displayTimestamp = document.getElementById("np-timestamp");

const widget = document.getElementById("now-playing");

// Update the widget attributes for the username set above
//displayTitle.href = `https://listenbrainz.org/user/${username}/`;
//displayElement.dataset.username = username;

// Define endpoints from Listenbrainz API
const endpoints = {
  nowPlaying: `https://api.listenbrainz.org/1/user/${username}/playing-now`,
  recentTrack: `https://api.listenbrainz.org/1/user/${username}/listens?count=1`,
};

// Function to check the API response and fail gracefully if it doesn't work
async function fetchJson(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  return response.json();
}

// Function to get the artwork via API response and fail gracefully if it doesn't work
async function fetchArtwork(url) {
  const response = await fetch(url);
  if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);
  return response.json();
}

// Function to set the artist and track title returned from Listenbrainz (or set it to Unknown if nothing is found)
function renderTrack(nowPlaying, track, cover, timestamp) {
    const artist = track?.artist_name || "Unknown Artist";
    const title = track?.track_name || "Unknown Track";
    displayTitle.textContent = `${title}`;
    displayArtist.textContent = `${artist}`;

    if (nowPlaying) {
        displayStatus.innerHTML = "<span class=\"breather\"></span>Now Playing";
        displayTimestamp.hidden = true;
    } else {
        displayStatus.innerHTML = "Last Played"
        displayTimestamp.textContent = `${timestamp}`;
        displayTimestamp.hidden = false;
    }
    if (cover) {
        const coverUrl = cover.images?.[0]?.thumbnails?.[500] || "";
        displayCover.setAttribute("alt", `Album artwork for ${title} by ${artist}`);
        displayCover.setAttribute("src", coverUrl.replace("http://", "https://"));
        displayCover.hidden = false;
    } else {
        displayCover.hidden = true;
    }
    widget.hidden = false;
}

// Function to update the widget
async function updateNowPlayingWidget() {
  try {
    // Fetch and parse data from the nowPlaying endpoint
    const nowPlayingData = await fetchJson(endpoints.nowPlaying);
    const playingNow = nowPlayingData?.payload?.playing_now;
    const currentTrack = nowPlayingData?.payload?.listens?.[0]?.track_metadata;

    // If something is currently playing, update the widget with Now Playing: currentTrack
    if (playingNow && currentTrack) {
      const coverData = await fetchJson(`https://coverartarchive.org/release/${currentTrack?.additional_info.release_mbid}`);
      renderTrack(true, currentTrack, coverData, "");
      return;
    }

    // Fetch and parse data from the recentTrack endpoint
    const recentData = await fetchJson(endpoints.recentTrack);
    const recentTrack = recentData?.payload?.listens?.[0]?.track_metadata;
    const listenTimestamp = new Date(recentData?.payload?.listens?.[0]?.listened_at * 1000);
    const timestampFormatted = `(${listenTimestamp.getUTCFullYear()}-${listenTimestamp.getMonth() + 1}-${listenTimestamp.getUTCDate()})`;

    // If nothing is currently playing, update the widget with Last Played: recentTrack
    if (recentTrack) {
      const coverData = await fetchJson(`https://coverartarchive.org/release/${recentTrack?.additional_info.release_mbid}`);
      renderTrack(false, recentTrack, coverData, timestampFormatted);
    }
    // If there is no recent track, update the widget to say This user has no listens yet
    else {
      displayStatus.textContent = "🎧 This user has no listens yet";
    }
  }
  // If the script can't fetch the data, update the widget to say Error loading track info. 
  // Also give more details in the console
  catch (error) {
    console.error("Failed to update Now Playing widget:", error);
    displayStatus.textContent = "🎧 Error loading track info";
  }
}

// Update the widget when the page loads, and then every minute after
updateNowPlayingWidget();
setInterval(updateNowPlayingWidget, 60000);