// Wrap the entire content inside an async function
(async () => {
  // Function to initialize the contract
  async function initializeContract() {
    try {
      if (window.ethereum) {
        const accounts = await window.ethereum.request({
          method: 'eth_requestAccounts',
        });
        userAddress = accounts[0];
        console.log('MetaMask is activated');
        console.log('Wallet Address:', userAddress);

        // Initialize the contractInstance
        contractInstance = new web3.eth.Contract(contractAbi, contractAddress);
        console.log('Contract initialized:', contractInstance);

        const addr = web3.utils.toChecksumAddress(userAddress);

        getAllAvailableChickens();
        // Call the function to set the prices
        updateChickenPrices();

        // NEW: Load and display the user's current state
        loadAndDisplayUserState(userAddress);

        // Display prices for each chicken during initialization
        displayAllChickenPrices();

        // NEW: Start automatic refresh for golden eggs and chickens
        // refreshAllData();

        return true; // Indicates successful initialization
      } else {
        console.error('MetaMask is not installed.');
        throw new Error('MetaMask is not installed.');
      }
    } catch (error) {
      console.error('Error during contract initialization:', error);
      throw error;
    }
  }

  // Call initializeContract in your document ready event
  document.addEventListener('DOMContentLoaded', async function () {
  try {
    const isInitialized = await initializeContract();

    if (isInitialized) {
      // Access elements and perform actions dependent on contract initialization
      const displayElement = document.getElementById('displayVIPInfo');
      console.log('Display Element:', displayElement);

      if (displayElement) {
        // Await the completion of recognizeUserVIPs before proceeding
        await recognizeUserVIPs(userAddress, 'displayVIPInfo');

        // Call the function to handle button click or content generation
        handleButtonClick();

        // Debugging: Check if the element exists before updating
        console.log('Before getElementById');
        const totalEggsElement = document.getElementById('totalGoldenEggs');
        console.log('After getElementById');

        if (totalEggsElement) {
          console.log('Element found:', totalEggsElement);
          totalEggsElement.textContent = `Total Golden Eggs: ${allGoldenEggInfo}`;
        } else {
          console.error('Total golden eggs element not found.');
        }
      } else {
        console.error('Display element is null. Skipping rendering.');
      }
    }
  } catch (error) {
    console.error('Error during initialization:', error);
  }
});


  // Function to handle button click or content generation function handleButtonClick() {
    // Add your logic for button click or content generation here
    // This function should be called at the appropriate time
 }
)();


async function updateConnectButton(userAddress) {
  return new Promise(resolve => {
    const connectButton = document.getElementById('fetchChickenInfoButton');
    if (connectButton) {
      const formattedWallet = formatWalletAddress(userAddress);
      connectButton.textContent = `Connected to Chicken Farm: ${formattedWallet}`;
      showHiddenContent(); // Оваа линија го повикува прикажувањето на скриената игра

      // Смали ги буквите ако има потреба
      if (connectButton.scrollWidth > connectButton.clientWidth) {
        connectButton.style.fontSize = '0.8em'; // Поставете го желениот размер
      }

      resolve();
    }
  });
}

// Функција за прикажување на скриената игра
function showHiddenContent() {
  const hiddenContent = document.getElementById('hiddenContent');
  if (hiddenContent) {
    hiddenContent.style.display = 'block';
  }
}

function formatWalletAddress(walletAddress) {
  // Проверете дали walletAddress е валиден адрес
  if (/^0x[a-fA-F0-9]{40}$/.test(walletAddress)) {
    // Одделете првите четири бројки и последните бројки со точки
    const firstFour = walletAddress.slice(2, 6);
    const lastDigits = walletAddress.slice(-4);
    return `${firstFour}....${lastDigits}`;
  } else {
    // Вратете оригинален адрес ако не е валиден
    return walletAddress;
  }
}


// NEW: Function to load and display the user's current state
function loadAndDisplayUserState(userAddress) {
  // Call your contract functions to read the user's state
  // Example:
  // const userState = await contractInstance.methods.getUserState(userAddress).call();
  // Display the user's state in the HTML
  // Example:
  // const userStateElement = document.getElementById('userState');
  // userStateElement.textContent = `User State: ${userState}`;
}

// Главна функција за освежување на сите информации
// async function refreshAllData() {
//    setInterval(async () => {
// Освежување на информациите за златните јајца
// await refreshGoldenEggsValues();

// Додадете повици за освежување на другите делови на вашата апликација

// Пример: Освежување на информациите за токени
//        const userTokens = await contract.methods.getUserTokens(userAddress).call();
//        document.getElementById('userTokens').innerText = `Tokens: ${userTokens}`;

// Пример: Освежување на информациите за други објекти во играта
//        const otherObjectInfo = await contract.methods.getOtherObjectInfo().call();
//        document.getElementById('otherObjectInfo').innerText = `Other Object Info: ${otherObjectInfo}`;
//    }, 10000); // Освежување на секои 10 секунди (10000 милисекунди)
//}

// Повик на функцијата за автоматско освежување на сите информации
// refreshAllData();
// Function to set chicken prices
async function updateChickenPrices() {
  try {
    if (!contractInstance || !contractInstance.methods) {
      console.error(
        'Error: contractInstance is not initialized or does not have "methods".'
      );
      return;
    }

    const chickenTypes = [
      'Cute Chicken',
      'Sage Chicken',
      'Pirate Chicken',
      'Hero Chicken',
      'Knight Chicken',
      'King Chicken',
    ];

    for (let i = 0; i < chickenTypes.length; i++) {
      const chickenType = chickenTypes[i];
      const chickenInfo = await contractInstance.methods
        .getChickenInfo(chickenType)
        .call();

      // After obtaining information, display the price on the frontend
      displayChickenPrice(
        chickenType,
        web3.utils.fromWei(chickenInfo.price.toString(), 'ether')
      );
    }
  } catch (error) {
    console.error('Error updating chicken prices:', error);
  }
}

// Пример за добивање информации за златни јајца за одреден пакет
//const packageName = 'Booststar'; // Заменете со соодветен пакет
//contractInstance.methods.getGoldenEggInfo(packageName).call()
//    .then(result => console.log(`${packageName} Golden Eggs:`, result))
//    .catch(error => console.error("Error:", error));

document.addEventListener('DOMContentLoaded', async function () {
  try {
    // Your existing code here

    // Ажурирање на HTML со вкупниот број на златни јајца
    console.log('Before getElementById');
    const totalEggsElement = document.getElementById('totalGoldenEggs'); // Update the ID here
    console.log('After getElementById');
    if (totalEggsElement) {
      totalEggsElement.textContent = `Total Golden Eggs: ${allGoldenEggInfo}`;
    } else {
      console.error('Total golden eggs element not found.');
    }
  } catch (error) {
    console.error('Error:', error);
  }
});

// This part is to indicate where the catch should be for the getTotalGoldenChickenEggs call.
contractInstance.methods
  .getTotalGoldenChickenEggs()
  .call()
  .then(result => console.log('Total Golden Eggs:', result))
  .catch(error => console.error('Error:', error)); // This is correctly placed.

// Добивање информации за златна кокошка за одреден корисник
const userChickenType = 'golden_cuteChicken';
contractInstance.methods
  .getGoldenChickenInfo(userChickenType)
  .call()
  .then(result => {
    // Вашиот код за обработка на резултатите и ажурирање на HTML
    const goldencuteChickenQtyElement = document.getElementById(
      'goldencutechickenQty'
    );
    const goldencuteEggsQtyElement =
      document.getElementById('goldencuteeggsQty');

    // Проверете дали елементите се најдени пред да ги ажурирате
    if (goldencuteChickenQtyElement && goldencuteEggsQtyElement) {
      // Ажурирајте ги HTML елементите со добиените податоци
      goldencuteChickenQtyElement.textContent = `Chicken Qty: ${String(
        goldenChickenInfo.qty
      )}`;
      goldencuteEggsQtyElement.textContent = `Eggs Qty: ${String(
        goldenChickenInfo.eggsQty
      )}`;

      console.log(`Chicken Qty: ${String(result.qty)}`);
      console.log(`Eggs Qty: ${String(result.eggsQty)}`);
    } else {
      console.error('One or both elements not found.');
    }
  })
  .catch(error => console.error('Error:', error));

async function getAllGoldenEggInfo() {
  try {
    // Assuming there is some function in your contractInstance to get all golden egg info
    const goldenEggInfo = await contractInstance.methods
      .getAllGoldenEggInfo()
      .call();
    console.log('All Golden Egg Info:', goldenEggInfo);

    return goldenEggInfo; // You may need to transform or process the data based on your actual requirements
  } catch (error) {
    console.error('Error getting all golden egg info:', error);
    throw error; // Handle the error as needed
  }
}

let totalEggsElement;

const vipImages = {
  Starwood: 'img/package/starwood.png',
  Booststar: 'img/package/booststar.png',
  Tristar: 'img/package/tristar.png',
  Armada: 'img/package/armada.png',
  Envoy: 'img/package/envoy.png',
  Wiser: 'img/package/wiser.png',
};
const MINIMUM_QLITE_BALANCE = 100; // Add your minimum balance

async function recognizeUserVIPs(
  userAddress,
  displayElementId,
  goldenChickenInfo
) {
  try {
    const userVIP = await contractInstance.methods.userVIPs(userAddress).call();
    console.log('User VIP Data:', userVIP);

    if (userVIP[2] && parseInt(userVIP[1], 10) >= MINIMUM_QLITE_BALANCE) {
      console.log('User has enough QLite tokens. Recognizing VIP status...');

      try {
        const allGoldenEggInfo = await getAllGoldenEggInfo();
        console.log('Using allGoldenEggInfo:', allGoldenEggInfo);

        // Additional code for recognizing VIP status...

        const tokenBalance = parseInt(userVIP[1], 10);
        const qliteTokensSpent = parseInt(userVIP[4], 10);
        const userPackage = userVIP[7];

        console.log(`User has ${tokenBalance} QLite tokens.`);
        console.log(`User has spent ${qliteTokensSpent} QLite tokens.`);
        console.log(`User has the following package: ${userPackage}.`);
        console.log(`Wallet of this VIP user is: ${userAddress}`);

        console.log('Using allGoldenEggInfo:', allGoldenEggInfo);
        console.log('totalEggsElement:', totalEggsElement);

        // Update HTML elements with the obtained data
const goldencuteChickenQtyElement = document.getElementById('goldencutechickenQty');
const goldencuteEggsQtyElement = document.getElementById('goldencuteeggsQty');

console.log('goldencuteChickenQtyElement:', goldencuteChickenQtyElement);
console.log('goldencuteEggsQtyElement:', goldencuteEggsQtyElement);

if (!goldencuteChickenQtyElement || !goldencuteEggsQtyElement) {
    throw new Error('One or both elements not found.');
}

// Check if goldenChickenInfo is defined and has 'qty' and 'eggsQty' properties
if (goldenChickenInfo && 'qty' in goldenChickenInfo && 'eggsQty' in goldenChickenInfo) {
    // Use the 'qty' property if it exists, otherwise default to 0
    const chickenQty = goldenChickenInfo.qty || 0;
    const eggsQty = goldenChickenInfo.eggsQty || 0;

    goldencuteChickenQtyElement.textContent = `Chicken Qty: ${String(chickenQty)}`;
    goldencuteEggsQtyElement.textContent = `Eggs Qty: ${String(eggsQty)}`;
} else {
    throw new Error('goldenChickenInfo is undefined or has missing properties.');
}

// Update elements after successfully obtaining data
const displayElement = document.getElementById(displayElementId);
if (displayElement) {
    displayElement.innerHTML = `
        <!-- Your HTML content here -->
        <div class="row">
            <!-- 1 картичка -->
            <div class="col-md-12 col-lg-3 mb-4">
                <div class="card">
                    <div class="card-body">
                        <h4 class="card-title mb-1">Status MGI</h4>
                        <p class="pb-0"><span style="color: green;">Active</span></p>
                        <h4 class="text-primary mb-1 card-title">${userPackage}</h4>
                    </div>
                    <img src="../assets/img/icons/misc/triangle-light.png" class="scaleX-n1-rtl position-absolute bottom-0 end-0" width="166" alt="triangle background" data-app-light-img="icons/misc/triangle-light.png" data-app-dark-img="icons/misc/triangle-dark.png">
                    <img id="vipImage" class="card-img scaleX-n1-rtl position-absolute bottom-0 end-0 me-4 mb-4 pb-2" src="${vipImages[userPackage]}" alt="VIP Image" style="max-width: 80px; height: auto;">
                </div>
            </div>
        </div
                        <!-- 2 картичка -->
                        <div class="col-md-12 col-lg-3 mb-4">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title mb-1">Qlite Token</h4>
                                    <p class="pb-0">Balance:</p>
                                    <h4 class="text-primary mb-1 card-title">${tokenBalance}</h4>
                                </div>
                                <img src="../assets/img/icons/misc/triangle-light.png" class="scaleX-n1-rtl position-absolute bottom-0 end-0" width="166" alt="triangle background" data-app-light-img="icons/misc/triangle-light.png" data-app-dark-img="icons/misc/triangle-dark.png">
                                <img src="img/LogoQlite_ok.png" alt="QLite Logo" class="scaleX-n1-rtl position-absolute bottom-0 end-0 me-4 mb-4 pb-2" width="80">
                            </div>
                        </div>

                        <!-- 3 картичка -->
                        <div class="col-md-12 col-lg-3 mb-4">
                            <div class="card">
                                <div class="card-body">
                                    <h4 class="card-title mb-1">Spent Qlite</h4>
                                    <p class="pb-0">Spent Balance:</p>
                                    <h4 class="text-primary mb-1 card-title">${qliteTokensSpent}</h4>
                                </div>
                                <img src="../assets/img/icons/misc/triangle-light.png" class="scaleX-n1-rtl position-absolute bottom-0 end-0" width="166" alt="triangle background" data-app-light-img="icons/misc/triangle-light.png" data-app-dark-img="icons/misc/triangle-dark.png">
                                <img src="img/LogoQlite_ok.png" alt="QLite Logo" class="scaleX-n1-rtl position-absolute bottom-0 end-0 me-4 mb-4 pb-2" width="80">
                            </div>
                        </div>

                        <!-- 4 картичка -->
                          <!-- 4 картичка -->
            <div class="col-md-12 col-lg-3 mb-4">
                <div class="card position-relative">
                    <div class="card-body">
                        <h4 class="card-title mb-1">Total Eggs</h4>
                        <p class="pb-0">Quantity:</p>
                        <h4 id="totalGoldenEggs" class="text-primary mb-1 card-title"></h4>
                    </div>
                    <div class="position-absolute bottom-0 end-0 me-4 mb-4 pb-2" style="z-index: 1;">
                        <a class="btn btn-outline-primary d-block mt-2" href="javascript:void(0);">Sell</a>
                    </div>
                    <img src="../assets/img/icons/misc/triangle-light.png" class="scaleX-n1-rtl position-absolute bottom-0 end-0" width="166" alt="triangle background" data-app-light-img="icons/misc/triangle-light.png" data-app-dark-img="icons/misc/triangle-dark.png">
                </div>
            </div>
        </div>

                    <!-- Row за картичките со златни кокошки -->
                    <div class="row row-cols-md-6 row-cols-2 g-2 g-lg-3">
                        <!-- Прва картичка со златна кокошка Cute -->
                        <div class="col mb-4">
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-3.jpg" alt="Gold Sage Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Cute</h4>
                                    <p id="goldencutechickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldencuteeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                    
                                    <p id="goldencutechickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldencuteeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading

                                    
                                    
                                </div>
                            </div>
                        </div>
                        <div class="col mb-4">
                            <!-- Втора картичка -->
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-4.jpg" alt="Gold Sage Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Sage</h4>
                                    <p id="goldensagechickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldensageeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col mb-4">
                            <!-- Трета картичка -->
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-2.jpg" alt="Gold Cute Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Cute</h4>
                                    <p id="goldenpiratechickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldenpirateeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col mb-4">
                            <!-- Четврта картичка -->
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-1.jpg" alt="Gold Cute Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Cute</h4>
                                    <p id="goldenherochickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldenheroeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col mb-4">
                            <!-- Петта картичка -->
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-5.jpg" alt="Gold Cute Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Cute</h4>
                                    <p id="goldenknightchickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldenknighteggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                </div>
                            </div>
                        </div>
                        <div class="col mb-4">
                            <!-- Шеста картичка -->
                            <div class="card text-center w-100">
                                <div class="card-body d-flex flex-column align-items-center">
                                    <img class="card-img" src="img/classes-6.jpg" alt="Gold Cute Image" style="max-width: 70px; height: auto; margin-bottom: 10px;">
                                    <h4 class="card-title mb-1">Gold Cute</h4>
                                    <p id="goldenkingchickenQty" class="pb-0 mb-1">Chicken Qty: ${goldenChickenInfo.qty}<span>Loading...</span></p>
                                    <p id="goldenkingeggsQty" class="pb-0 mb-0">Eggs Qty: ${goldenChickenInfo.eggsQty}<span>Loading...</span></p>
                                </div>
                            </div>
                        </div>
                    </div>
                   
                  `;
        }
      } catch (error) {
        console.error('Error in recognizeUserVIPs (inner try block):', error);
        // Handle the error here if needed
      }
    }
  } catch (error) {
    console.error('Error in recognizeUserVIPs:', error);
    // Handle the error here if needed
  }
}

async function getAllAvailableChickens() {
  try {
    const chickenTypes = [
      'Cute Chicken',
      'Sage Chicken',
      'Pirate Chicken',
      'Hero Chicken',
      'Knight Chicken',
      'King Chicken',
    ];

    for (let i = 0; i < chickenTypes.length; i++) {
      const chickenType = chickenTypes[i];
      const availableQuantity = await contractInstance.methods
        .getAvailableChickens(chickenType)
        .call();

      // Update HTML with the quantity
      const quantityElement = document.getElementById(
        `${chickenType}-chickenQuantity`
      );
      if (quantityElement) {
        quantityElement.textContent = availableQuantity;
      } else {
        console.error(
          `Element with id ${chickenType}-chickenQuantity not found`
        );
      }

      // Log the quantity
      console.log(`${chickenType}: ${availableQuantity}`);
    }
  } catch (error) {
    console.error('Error in getAllAvailableChickens:', error.message);
  }
}


farm.js:2528 Error in recognizeUserVIPs (inner try block): Error: One or both elements not found.
    at recognizeUserVIPs (farm.js:2372:11)
    at async HTMLDocument.<anonymous> (farm.js:2105:9)
recognizeUserVIPs @ farm.js:2528
await in recognizeUserVIPs (async)
(anonymous) @ farm.js:2105
farm.js:2126 Error during initialization: ReferenceError: handleButtonClick is not defined
    at HTMLDocument.<anonymous> (farm.js:2108:9)