// add style for the user info
var styleElement = document.createElement("style");
styleElement.id = "yourDynamicStyleId";
styleElement.innerHTML = "#ModalSubscribersItem___BV_modal_outer_ { z-index: -1 !important; /* your styles here */ } .global_preloader.active { opacity: 0 !important; } .g-avatar__placeholder[data-v-325c6981]:before { background: transparent !important; }";
document.head.appendChild(styleElement);

function addOverlayToSwipeoutItems() {
  var swipeoutItems = document.querySelectorAll(".swipeout.swipeout-list-item");

  swipeoutItems.forEach(function (item) {
    if (!item.querySelector(".overlayxry")) {
      // Create an overlay for each swipeout item
      var overlay = document.createElement("div");
      overlay.className = "overlayxry";

      // Style the overlay
      overlay.style.position = "absolute";
      overlay.style.top = "0";
      overlay.style.left = "0";
      overlay.style.width = "18%";
      overlay.style.height = "100%";
      overlay.style.backgroundColor = "rgba(0, 0, 0, 0.5)";
      overlay.style.zIndex = "9000";
      overlay.style.pointerEvents = "all"; // Make the overlay fully absorb interactions

      // Append the overlay to the swipeout item
      item.appendChild(overlay);
    }
  });
}

var intervalIdxx = setInterval(addOverlayToSwipeoutItems, 10);
var amountsbyid = [];
var isProgrammaticClick = false;
var elements;
var currentIndex;
var universalstart = false;
var forceStop = false; // Flag to force stop the function

function waitForElementToAppear(elementToMatch) {
  return new Promise((resolve) => {
    var checkInterval = setInterval(function () {
      var infodiv = document.getElementById("ModalSubscribersItem___BV_modal_outer_");
      var matchthisElement = infodiv?.children[0]?.children[0]?.children[1]?.children[0]?.children[0]?.children[0]?.children[0]?.children[2]?.children[0]?.lastChild || null;

      if (infodiv && matchthisElement) {
        var matchthis = matchthisElement.innerText;
        if (elementToMatch === matchthis) {
          clearInterval(checkInterval);
          console.log("waitForElementToAppear is positive");
          resolve(); // Resolve the promise once the element appears
        }
      }
    }, 10);
  });
}

function waitForAnother() {
  return new Promise((resolve) => {
    var checkInterval = setInterval(function () {
      var tabsNavItemx = document.getElementsByClassName("b-tabs__nav m-tabs-default m-flex-width m-size-sm")[0].children[1];
      if (tabsNavItemx.classList.contains("m-current")) {
        clearInterval(checkInterval);
        resolve(); // Resolve the promise once the element appears
      }
    }, 10);
  });
}

function somethingmore(findthe, matchingamnt, elements, currentIndex) {
  return new Promise((resolve) => {
    for (var xxi = 0; xxi < amountsbyid.length; xxi++) {
      if (amountsbyid[xxi].id === findthe) {
        console.log("YES, the user " + currentIndex + " is already in the list and we gonna add the total");
        matchingamnt = amountsbyid[xxi].amountx;
        if (!elements[currentIndex].children[1].children[0].children[0].children[1].classList.contains("mutezinde")) {
          elements[currentIndex].children[1].children[0].children[0].children[1].classList.add("mutezinde");
        }
        elements[currentIndex].children[1].children[0].children[0].children[1].children[0].innerHTML = '<span class="mutezinde ijefie" style="font-size: 16px; color: #fb3a3a; font-weight: 700; width: 100%; display: flex; height: 100%; margin: auto; justify-content: center; align-items: center; background-color: #dadde2; border-radius: 50%;">' + matchingamnt + "</span>";
        document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].classList.add("resolved");
        resolve(); // Resolve the promise once the element appears
        break;
      }
    }
  });
}

async function checkMutezinde() {
  universalstart = true;
  elements = document.getElementsByClassName("swipeout swipeout-list-item");
  currentIndex = 0;
  styleElement.innerHTML = "#ModalSubscribersItem___BV_modal_outer_ { z-index: -1 !important; /* your styles here */ } .global_preloader.active { opacity: 0 !important; } .g-avatar__placeholder[data-v-325c6981]:before { background: transparent !important; }";

  async function processNextElement() {
    if (!document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex] || forceStop) {
      console.log("Element " + currentIndex + " not found. Stopping the function from early on to avoid other errors.");
      console.log("MAYBE::: all present elements are processed with total amounts");
      universalstart = false;
      clearInterval(intervalIdxx);
      // Remove elements with class "overlayxry" from the DOM
      var elmas = document.querySelectorAll(".overlayxry");
      elmas.forEach(function (elma) {
        elma.remove();
      });
      var alaj = document.querySelector(".g-btn.m-flat.m-btn-gaps.m-reset-width");
      if (alaj) {
        alaj.click();
      }
      throw new Error("Force stop"); // Throw an error to indicate force stop
    }

    var elementToCheck = elements[currentIndex].children[1].children[0].children[0].children[1].children[0];
    var elemtomatch = elements[currentIndex].children[1].children[0].children[0].children[2].children[0].children[0].lastChild.innerText;

    if (!elementToCheck.innerHTML.includes("mutezinde")) {
      console.log("I will first check if " + currentIndex + " is already in the list so we can quick the process");

      if (amountsbyid.some((item) => item.id === elements[currentIndex].children[1].children[0].children[0].id)) {
        var findthe = elements[currentIndex].children[1].children[0].children[0].id;
        var matchingamnt = null;

        await somethingmore(findthe, matchingamnt, elements, currentIndex);
        currentIndex++;
        await processNextElement();
      } else {
        console.log("nahh... the user " + currentIndex + " is not inside the list so we will add the total from user info");
      }

      console.log("I just clicked user info at index " + currentIndex);
      if (
        !document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex] ||
        !document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1] ||
        !document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0] ||
        !document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0] ||
        !document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].children[1]
      ) {
        console.log("Element " + currentIndex + " not found. Stopping the function.");
        universalstart = false;
        clearInterval(intervalIdxx);
        // Remove elements with class "overlayxry" from the DOM
        var elmas = document.querySelectorAll(".overlayxry");
        elmas.forEach(function (elma) {
          elma.remove();
        });
        var alaj = document.querySelector(".g-btn.m-flat.m-btn-gaps.m-reset-width");
        if (alaj) {
          alaj.click();
        }
        throw new Error("Force stop"); // Throw an error to indicate force stop
      }

      isProgrammaticClick = true;
      document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].children[1].click();
      isProgrammaticClick = false;

      console.log("waitForElementToAppear we sending the parameter, elemtomatch is " + elemtomatch);
      await waitForElementToAppear(elemtomatch);

      console.log("Action needed for element at index " + currentIndex);
      console.log("I just clicked earnings for element at index " + currentIndex);
      document.getElementsByClassName("b-tabs__nav m-tabs-default m-flex-width m-size-sm")[0].children[1].children[0].click();

      setTimeout(async () => {
        console.log("I just added mutezinde class for <a> element at index " + currentIndex);
        document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].children[1].classList.add("mutezinde");

        await waitForAnother();

        console.log("yes *b-tabs__nav m-tabs-default m-flex-width m-size-sm* contains m-current for element " + currentIndex);

        var elementtotal = document.querySelector(".b-fans__item__list.m-native-custom-scrollbar.m-scrollbar-y.m-invisible-scrollbar.m-earnings-list");
        var lastDivtotal = elementtotal.lastElementChild;
        var totalamount = lastDivtotal.lastElementChild.innerText;
        var numericValue = parseFloat(totalamount.replace("$", ""));
        var roundedNumber = Math.round(numericValue);
        totalamount = "$" + roundedNumber;

        console.log("the total amount for " + currentIndex + " is " + totalamount);
        console.log("I jut added the span mutezinde for " + currentIndex + " with " + totalamount);
        document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].children[1].children[0].innerHTML = '<span class="mutezinde ijefie" style="font-size: 16px; color: #fb3a3a; font-weight: 700; width: 100%; display: flex; height: 100%; margin: auto; justify-content: center; align-items: center; background-color: #dadde2; border-radius: 50%">' + totalamount + "</span>";

        var data = {
          id: document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].id,
          aron: elemtomatch,
          amountx: totalamount,
          user: document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].children[1].children[0].children[0].children[2].children[0].children[0].children[0].innerText,
        };

        amountsbyid.push(data);

        document.getElementsByClassName("swipeout swipeout-list-item")[currentIndex].classList.add("resolved");

        currentIndex++;
        await processNextElement(); // Call the next iteration
      }, 2000); // Adjust the delay as needed
    } else {
      console.log("the element currently has a span mutezinde inside so we can not add that " + currentIndex);
      currentIndex++;
      await processNextElement(); // Call the next iteration
    }
  }

  try {
    await processNextElement();
  } catch (error) {
    if (error.message === "Force stop") {
      console.log("Function forcefully stopped.");
      universalstart = false;
      clearInterval(intervalIdxx);
      // Remove elements with class "overlayxry" from the DOM
      var elmas = document.querySelectorAll(".overlayxry");
      elmas.forEach(function (elma) {
        elma.remove();
      });
      var alaj = document.querySelector(".g-btn.m-flat.m-btn-gaps.m-reset-width");
      if (alaj) {
        alaj.click();
      }
      return; // Stop the function
    } else {
      universalstart = false;
      clearInterval(intervalIdxx);
      // Remove elements with class "overlayxry" from the DOM
      var elmas = document.querySelectorAll(".overlayxry");
      elmas.forEach(function (elma) {
        elma.remove();
      });
      var alaj = document.querySelector(".g-btn.m-flat.m-btn-gaps.m-reset-width");
      if (alaj) {
        alaj.click();
      }
      throw error; // Re-throw other exceptions
    }
  }
}

checkMutezinde();

var intervalmak = setInterval(function () {
  var elements = document.querySelectorAll(".swipeout.swipeout-list-item");
  var statary = true;

  elements.forEach(function (element) {
    if (!element.classList.contains("resolved") || !element.children[1].children[0].children[0].children[1].children[0].innerHTML.includes("mutezinde")) {
      statary = false;
    }
  });

  if (!statary) {
    console.log("INTERVALMAK** there are items without resolved class so I will start mutezinde if it is not running now");
    if (!universalstart) {
      console.log("INTERVALMAK** I will start checkmutezinde from INTERVALMAK**");
      intervalIdxx = setInterval(addOverlayToSwipeoutItems, 10);
      checkMutezinde();
    }
  } else {
    console.log("INTERVALMAK** I will not start checkMutezinde");
    clearInterval(intervalIdxx);
    // Remove elements with class "overlayxry" from the DOM
    var elmas = document.querySelectorAll(".overlayxry");
    elmas.forEach(function (elma) {
      elma.remove();
    });
  }
}, 1000);

document.addEventListener("click", function (event) {
  // Check if the clicked element has the class "mutezinde" and if starty is not running
  if (event.target.classList.contains("mutezinde")) {
    if (isProgrammaticClick) {
      // console.log("Click triggered by JavaScript.");
    } else {
      // console.log("Manual mouse click.");
      styleElement.innerHTML = "#ModalSubscribersItem___BV_modal_outer_ { z-index: 1040 !important; /* your styles here */ } .global_preloader.active { opacity: 1 !important;}";
    }
  }
});
