document.addEventListener("DOMContentLoaded", function () {
  if (document.readyState == "interactive") {
    var reviewLists = document.getElementsByClassName("review-hub-wrapper");
    Array.from(reviewLists).forEach(function (currentReviewList) {
      var hub_data = get_hub_wrapper_data(currentReviewList);
      var search_input = hub_data["search_input"];
      var search_button = hub_data["search_button"];

      //Set the search button functionality
      search_button.addEventListener("click", function (event) {
        var button = this;

        var parent = button.parentNode;
        var searchInput = parent.querySelector('input[type="text"]');
        var searchText = searchInput.value;
        filter_reviews_by_search(currentReviewList, searchText);
      });

      search_input.addEventListener("input", (sender) => {
        watchSearchChange(sender);
      });

      ftm_get_reviews_list(
        hub_data["hub_id"],
        hub_data["hub_container"],
        hub_data["post_per_page"],
        hub_data["current_page"],
        "",
        hub_data["review_types"],
        hub_data["specifc_reviews"]
      );
    });
  }
});

function ftm_get_reviews_list(
  hub_id = null,
  hub_container = "",
  postsPerPage = 4,
  page = 1,
  search_name = "",
  review_types = "",
  specifc_reviews = "-1"
) {
  var xhr = new XMLHttpRequest();

  var reviews_hub_wrapper = document.getElementById(hub_id);
  var review_hub = reviews_hub_wrapper.querySelector(".review-hub");
  var paginationContainer = reviews_hub_wrapper.querySelector(
    ".pagination-container"
  );
  review_hub.classList.add("loading");

  xhr.onreadystatechange = function () {
    handle_reviews_ajax_call(
      xhr,
      reviews_hub_wrapper,
      review_hub,
      hub_container,
      paginationContainer
    );
  };

  xhr.open("POST", review_hub_vars.url, true);
  xhr.setRequestHeader("Content-Type", "application/x-www-form-urlencoded");
  xhr.send(
    "action=get_reviews&nonce=" +
      review_hub_vars.nonce +
      "&posts_per_page=" +
      postsPerPage +
      "&page=" +
      page +
      "&hub_id=" +
      hub_id +
      "&search_name=" +
      search_name +
      "&review_types=" +
      review_types +
      "&specifc_reviews=" +
      specifc_reviews
  );
}

function handle_reviews_ajax_call(
  xhr,
  reviews_hub_wrapper,
  review_hub,
  hub_container,
  paginationContainer
) {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var response = JSON.parse(xhr.responseText);
    var reviewList = hub_container;

    reviewList.innerHTML = "";
    paginationContainer.innerHTML = "";

    for (var bookie in response.reviews) {
      if (response.reviews.hasOwnProperty(bookie)) {
        var review_div = document.createElement("div");
        review_div.classList.add("review-box");
        var bookieData = response.reviews[bookie];

        // Create elements for each piece of data
        var bookieName = document.createElement("span");
        bookieName.textContent = bookie;

        var bookieLogo = document.createElement("img");
        bookieLogo.src = bookieData.book_logo_url;
        bookieLogo.alt = bookie;

        var welcomeBonus = document.createElement("p");
        welcomeBonus.textContent = bookieData.book_welcome_bonus;

        var bookie_rating_html = document.createElement("div");
        bookie_rating_html.innerHTML = bookieData.book_rating_html;

        var bookie_visit_link = document.createElement("a");
        bookie_visit_link.href = bookieData.book_review_url;
        bookie_visit_link.classList.add("read-review-btn");
        bookie_visit_link.textContent = "Read Review";

        // Append elements to the review_div container
        review_div.appendChild(bookieLogo);
        review_div.appendChild(bookieName);
        review_div.appendChild(bookie_rating_html);
        review_div.appendChild(welcomeBonus);

        // Iterate over key features and add them to the list
        if (bookieData && bookieData.book_key_features) {
          if (
            Array.isArray(bookieData.book_key_features) &&
            bookieData.book_key_features.length > 0
          ) {
            var keyFeaturesList = document.createElement("ul");
            bookieData.book_key_features.forEach(function (feature) {
              var featureItem = document.createElement("li");
              featureItem.textContent =
                feature.key_feature_name + ": " + feature.key_feature_value;
              keyFeaturesList.appendChild(featureItem);
            });
            //review_div.appendChild(keyFeaturesList);
          }
        }

        // Render categories
        renderCategories(review_div, bookieData.book_categories);

        //Add review button
        review_div.appendChild(bookie_visit_link);

        //review_div.innerHTML = reviewData;
        reviewList.appendChild(review_div);

        // Update pagination links
        paginationContainer.innerHTML = response.pagination_links;

        // Attach click event to custom buttons
        var buttons = paginationContainer.querySelectorAll(
          ".pagination-container > a"
        );
        buttons.forEach(function (button) {
          button.addEventListener("click", function (e) {
            e.preventDefault();
            var hub_id = button.getAttribute("data-hub-id");
            var pageNumber = this.getAttribute("data-page-number");
            paginate_hub(hub_id, pageNumber);
            return false;
          });
        });
      }
    }

    if (reviewList.innerHTML == "") {
      reviewList.innerHTML = response.no_results_text;
    }

    review_hub.classList.remove("loading");
  }
}

function renderCategories(container, categories) {
  if (categories) {
    if (categories.length > 0) {
      var categoriesList = document.createElement("ul");
      categoriesList.classList.add("categories");
      categories.forEach(function (category) {
        var categoryItem = document.createElement("li");
        var itemCssClass = "";
        switch (category) {
          case "poker":
            itemCssClass = "poker";
            break;
          case "sports":
            itemCssClass = "sports";
            break;
          case "casino":
            itemCssClass = "casino";
            break;
        }
        categoryItem.classList.add(itemCssClass);
        categoryItem.textContent = category;
        categoriesList.appendChild(categoryItem);
      });

      container.appendChild(categoriesList);
    }
  }
}

function get_hub_wrapper_data(hub) {
  var result = new Array();

  result["hub_id"] = hub.getAttribute("data-hub-id");
  result["post_per_page"] = hub.getAttribute("data-ppp");
  result["current_page"] = hub.getAttribute("data-page");
  result["review_types"] = hub.getAttribute("data-reviews-cat");
  result["specifc_reviews"] = hub.getAttribute("data-specifc-reviews");
  result["hub_container"] = hub.querySelector(".reviews-list-wrapper");
  result["search_input"] = hub.querySelector(
    '.search-box > .search_controls > input[type="text"]'
  );
  result["search_button"] = hub.querySelector(
    ".search-box > .search_controls > button.search_button"
  );

  return result;
}

function paginate_hub(hub_id, new_page) {
  var hub_wrapper = document.getElementById(hub_id);
  var searchInput = hub_wrapper.querySelector('input[type="text"]');
  var searchText = searchInput.value;

  hub_wrapper.setAttribute("data-page", new_page);
  var hub_data = get_hub_wrapper_data(hub_wrapper);
  ftm_get_reviews_list(
    hub_data["hub_id"],
    hub_data["hub_container"],
    hub_data["post_per_page"],
    hub_data["current_page"],
    searchText,
    hub_data["review_types"],
    hub_data["specifc_reviews"]
  );
}

function filter_reviews_by_search(hub_wrapper, search_text) {
  hub_wrapper.setAttribute("data-page", 1);
  var hub_data = get_hub_wrapper_data(hub_wrapper);
  ftm_get_reviews_list(
    hub_data["hub_id"],
    hub_data["hub_container"],
    hub_data["post_per_page"],
    hub_data["current_page"],
    search_text,
    hub_data["review_types"],
    hub_data["specifc_reviews"]
  );
}

function watchSearchChange(sender) {
  //Variables declaration
  var textbox = sender.target;
  var parent = textbox.parentNode;
  var buttonElement = parent.querySelector("button.search_button");
  var inputValue = textbox.value;
  var minLength = 3;

  // Check if the input length is greater than the threshold
  if (inputValue.length >= minLength) {
    // Add the class to the button
    buttonElement.classList.add("ready");
  } else {
    // Remove the class to the button
    buttonElement.classList.remove("ready");
  }
}
