var elements = document.getElementsByClassName("swipeout swipeout-list-item");
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; }";

if (!document.getElementById("yourDynamicStyleId")) {
  document.head.appendChild(styleElement);
}

(async () => {
  // Your code before the delay

  function bigreset() {
    console.log("we are going to apply a big reset first for deleting the existing classes if any");

    var swipeoutItemsx = document.getElementsByClassName("swipeout swipeout-list-item");
    setTimeout(function () {
      // Loop through each element and remove the class "resolved"
      for (var i = 0; i < swipeoutItemsx.length; i++) {
        if (swipeoutItemsx[i].classList.contains("resolved")) {
          swipeoutItemsx[i].classList.remove("resolved");
          console.log("removed class resolved from element " + i);
        } else {
          console.log("the element " + i + " has no class called resolved");
        }
      }
    }, 100);

    setTimeout(function () {
      var elementsToDelete = document.querySelectorAll(".mutezinde.ijefie");
      var jy = 0;
      elementsToDelete.forEach(function (element) {
        element.remove();
        console.log("we are going to remove the element with .mutezinde.ijefie class " + jy);
        jy++;
      });
      if (!elementsToDelete.length > 0) {
        console.log("no element with class .mutezinde.ijefie was found");
      }
    }, 1000);

    var swipeoutElements = document.getElementsByClassName("swipeout swipeout-list-item");
    setTimeout(function () {
      // Loop through each element and remove the class "mutezinde"
      for (var i = 0; i < swipeoutElements.length; i++) {
        var element = swipeoutElements[i].children[1].children[0].children[0].children[1];

        if (element.classList.contains("mutezinde")) {
          // Remove the class "mutezinde" if it exists
          element.classList.remove("mutezinde");
          console.log("removed class mutezinde from element <a of index " + i);
        } else {
          console.log("the element <a " + i + " has no class called mutezinde");
        }
      }
    }, 1500);
  }

  setTimeout(function () {
    clearInterval(intervalIdxx);
    clearInterval(intervalmak);
  }, 100);

  setTimeout(function () {
    amountsbyid = [];
    isProgrammaticClick = false;
    universalstart = false;
    forceStop = false;
  }, 500);

  setTimeout(function () {
    bigreset();
  }, 1000);

  // Wait for 3 seconds
  await new Promise((resolve) => setTimeout(resolve, 3000));

  // Your code after the delay
  console.log("3,5 seconds passed above and we going to add the amounts for every element");

  // add style for the user info

  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);
      }
    });
  }

  window.intervalIdxx = setInterval(addOverlayToSwipeoutItems, 10);
  window.amountsbyid = [];
  window.isProgrammaticClick = false;
  // elements;
  window.currentIndex;
  window.universalstart = false;
  window.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(somenr) {
    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")) {
          if (!document.getElementsByClassName("swipeout swipeout-list-item")[somenr].children[1].children[0].children[0].children[1].classList.contains("mutezinde")) {
            clearInterval(checkInterval);
            document.getElementsByClassName("swipeout swipeout-list-item")[somenr].children[1].children[0].children[0].children[1].classList.add("mutezinde");
            console.log("waitForAnother::: the <a> from " + somenr + " had no class mutezinde and we tried to add it");
            resolve(); // Resolve the promise once the element appears
          } else {
            console.log("waitForAnother::: the <a> from " + somenr + " had class mutezinde");
            // console.log(document.getElementsByClassName("swipeout swipeout-list-item")[somenr].children[1].children[0].children[0].children[1].classList);
            clearInterval(checkInterval);
            resolve();
          }
        }
      }, 10);
    });
  }

  function somethingmore(findthe, matchingamnt, elements, currentIndex) {
    return new Promise((resolve) => {
      for (var xxi = 0; xxi < window.amountsbyid.length; xxi++) {
        if (window.amountsbyid[xxi].id === findthe) {
          console.log("YES, the user " + currentIndex + " is already in the list and we gonna add the total");
          matchingamnt = window.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() {
    window.universalstart = true;
    elements = document.getElementsByClassName("swipeout swipeout-list-item");
    window.currentIndex = 0;
    document.getElementById("yourDynamicStyleId").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")[window.currentIndex] || window.forceStop) {
        console.log("Element " + window.currentIndex + " not found. Stopping the function from early on to avoid other errors.");
        console.log("MAYBE::: all present elements are processed with total amounts");
        window.universalstart = false;
        clearInterval(window.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[window.currentIndex].children[1].children[0].children[0].children[1].children[0];
      var elemtomatch = elements[window.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 " + window.currentIndex + " is already in the list so we can quick the process");

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

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

        console.log("I just clicked user info at index " + window.currentIndex);
        if (
          !document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex] ||
          !document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1] ||
          !document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1].children[0] ||
          !document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1].children[0].children[0] ||
          !document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1].children[0].children[0].children[1]
        ) {
          console.log("Element " + window.currentIndex + " not found. Stopping the function.");
          window.universalstart = false;
          clearInterval(window.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
        }

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

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

        console.log("Action needed for element at index " + window.currentIndex);
        console.log("I just clicked earnings for element at index " + window.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 " + window.currentIndex);
          document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1].children[0].children[0].children[1].classList.add("mutezinde");

          await waitForAnother(window.currentIndex);

          console.log("yes *b-tabs__nav m-tabs-default m-flex-width m-size-sm* contains m-current for element " + window.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 " + window.currentIndex + " is " + totalamount);
          console.log("I jut added the span mutezinde for " + window.currentIndex + " with " + totalamount);
          document.getElementsByClassName("swipeout swipeout-list-item")[window.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")[window.currentIndex].children[1].children[0].children[0].id,
            aron: elemtomatch,
            amountx: totalamount,
            user: document.getElementsByClassName("swipeout swipeout-list-item")[window.currentIndex].children[1].children[0].children[0].children[2].children[0].children[0].children[0].innerText,
          };

          window.amountsbyid.push(data);

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

          window.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 " + window.currentIndex);
        window.currentIndex++;
        await processNextElement(); // Call the next iteration
      }
    }

    try {
      await processNextElement();
    } catch (error) {
      if (error.message === "Force stop") {
        console.log("Function forcefully stopped.");
        window.universalstart = false;
        clearInterval(window.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 {
        window.universalstart = false;
        clearInterval(window.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();

  window.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 (!window.universalstart) {
        console.log("INTERVALMAK** I will start checkmutezinde from INTERVALMAK**");
        window.intervalIdxx = setInterval(addOverlayToSwipeoutItems, 10);
        checkMutezinde();
      }
    } else {
      console.log("INTERVALMAK** I will not start checkMutezinde");
      clearInterval(window.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 (window.isProgrammaticClick) {
        // console.log("Click triggered by JavaScript.");
      } else {
        // console.log("Manual mouse click.");
        document.getElementById("yourDynamicStyleId").innerHTML = "#ModalSubscribersItem___BV_modal_outer_ { z-index: 1040 !important; /* your styles here */ } .global_preloader.active { opacity: 1 !important;}";
      }
    }
  });
})();
