
const jsonUrl = 'https://raw.githubusercontent.com/BredOS/Download-Page-Assets/main/devices_list.json';

// Function to handle errors during JSON fetch
const handleFetchError = (error) => {
  console.error(`Error fetching JSON: ${error.message}`);
  // Provide fallback content or show an error message on the page
  const errorMessage = document.createElement('p');
  errorMessage.textContent = 'Failed to fetch device data. Please try again later.';
};

fetch(jsonUrl)
  .then(response => {
    // Check if the request was successful (status code 200)
    if (!response.ok) {
      throw new Error(`Failed to fetch data: ${response.status} ${response.statusText}`);
    }
    return response.json(); // Parse the JSON response
  })
  .then(devicesData => {
    // Access the keys (board names) in the devicesData object
    const boardNames = Object.keys(devicesData);

    // Get the device list container
    const deviceListContainer = document.getElementById('boardList');
    // Get the card container
    const cardContainer = document.getElementById('cardContainer');

    const displayFirstBoardOnLoad = () => {
      const firstBoardName = boardNames[0]; // Get the name of the first board
      const firstBoard = devicesData[firstBoardName]; // Get the data of the first board
      displayCard(firstBoard); // Display the card for the first board
    };

    // Event listener function to display card when a list item is clicked
    const displayCard = (board) => {
      // Remove "active" class from all devices
      removeActive();
      cardContainer.innerHTML = '';

      // Create a card element
      const card = cardContainer;
      card.innerHTML = `
        <strong>${board.name}</strong>
        <br>
        <img src="${board.image}" alt="${board.name}" style="max-width: 100%;">
        <p>${board.board_description}</p>
        <p><strong>Latest Release:</strong></p>
        <ul>
        `;
        //<p><strong>Latest Release:</strong> <a href="${board.download_links.latest.link}" target="_blank">${board.download_links.latest.name}</a></p>
      //`;
        if (typeof board.download_links === 'object') {
            if (board.download_links.latest) {
                // If board.download_links has a 'latest' key
                const latestLink = board.download_links.latest;
                card.innerHTML += '<li><a href="' + latestLink.link + '" target="_blank">' + latestLink.name + '</a><p> - md5sum: ' + latestLink.check_sum + '</p></li>';
            } else {
                // If board.download_links does not have a 'latest' key, assuming it's an object with multiple links
                for (const key in board.download_links) {
                    const link = board.download_links[key];
                    card.innerHTML += '<li><a href="' + link.link + '" target="_blank">' + link.name + '</a><p> - md5sum: ' + link.check_sum + '</p></li>';
                }
            }
        } else {
            console.log(board);
            card.innerHTML += '<li><a href="' + board.download_links.link + '" target="_blank">' + board.download_links.name + '</a></li>';
        }

      
      card.innerHTML = card.innerHTML + "</ul>"
        
      // Clear existing cards and display the new card
      //cardContainer.innerHTML = '';
      //cardContainer.appendChild(card);
    };

    // Function to filter devices based on search input
    window.filterDevices = () => {
      const searchTerm = document.getElementById('searchInput').value.toLowerCase();
      const deviceListContainer = document.getElementById('boardList');
      const cardContainer = document.getElementById('cardContainer');

      // Check if the containers exist before proceeding
      if (!deviceListContainer || !cardContainer) {
        console.error('Containers not found in the DOM');
        return;
      }

      deviceListContainer.innerHTML = '';

      // Iterate through board names and create list items
      boardNames.forEach(boardName => {
        const board = devicesData[boardName];

        // Check if the board name or description contains the search term
        if (
          board.name.toLowerCase().includes(searchTerm) //||
          //board.board_description.toLowerCase().includes(searchTerm)
        ) {
          // Create list item
          const listItem = document.createElement('li');
          listItem.className = 'list-group-item list-group-item-action bg-dark text-white';
          listItem.innerHTML = `${board.name}`;
          listItem.addEventListener('click', function() {
            removeActive();
            displayCard(board);
          });

          // Append list item to the device list container
          deviceListContainer.appendChild(listItem);
        }
      });
    };

    // Initial display of devices without filtering
    filterDevices();
    displayFirstBoardOnLoad();
  })
  .catch(handleFetchError); // Handle errors during fetch

// Function to remove "active" class from all devices
function removeActive() {
  const deviceListContainer = document.getElementById("boardList");
  const devices = deviceListContainer.getElementsByTagName("li");

  for (let i = 0; i < devices.length; i++) {
    devices[i].classList.remove("active");
  }
}


// function changeCard(selectedDevice) {
//   var cardContainer = document.getElementById("cardContainer");
//   removeActive();
//   var element = document.getElementById(selectedDevice);
//   element.classList.add("active");
//   element.classList.remove("bg-dark");
//
//   // Clear existing cards
//   cardContainer.innerHTML = "";
//
//   // Create and append the new card based on the selected device
//   var card = document.createElement("div");
//   card.className = "card bg-dark";
//
//   // Retrieve device data from the dictionary
//   var device = deviceData[selectedDevice];
//
//   // Create card body
//   var cardBody = document.createElement("div");
//   cardBody.className = "dev-card-body p-4 bg-dark";
//
//
//   // Create card title
//   var cardTitle = document.createElement("h4");
//   cardTitle.className = "dev-card-title bg-dark";
//   cardTitle.textContent = device.title;
//
//   // Create card text
//   var cardText = document.createElement("p");
//   cardText.className = "dev-card-text bg-dark";
//   cardText.textContent = device.text;
//
//   var cardText2 = document.createElement("p");
//   cardText2.className = "dev-card-text bg-dark bold";
//   cardText2.textContent = "The download for "+ device.title + " has a checksum of " + device.checksum;
//
//   // Create download link
//   var downloadLink = document.createElement("a");
//   downloadLink.onclick = function () {
//       javascript:$('#downloadprompt').modal('show');
//   }
//   downloadLink.textContent = "Download";
//   downloadLink.className = "btn btn-primary ";
//   downloadLink.style = "background: rgb(153,186,221);border-radius: 10px;";
//
//   // Create card image
//   var cardImage = document.createElement("img");
//   cardImage.src = device.img;
//   cardImage.className = "card-img-top bg-dark";
//
//   // Append card elements
//   cardBody.appendChild(cardTitle);
//   cardBody.appendChild(cardText);
//   cardBody.appendChild(downloadLink);
//   card.appendChild(cardImage);
//   card.appendChild(cardBody);
//   cardContainer.appendChild(card);
//
//   element = document.getElementById("checksum");
//   element.innerText = "The download for "+ device.title + " has a checksum of " + device.checksum;
//
//   element = document.getElementById("active_download");
//   element.href = device.dlLink;
//   element = document.getElementById("active_download2");
//   element.href = device.dlLink2;
// }
