$(document).ready(function () {
  //-------------------------------------------------------//
  // StellarNav Js
  //-------------------------------------------------------//
  $(".stellarnav").stellarNav({
    breakpoint: 1199,
    position: "right",
  });

  if ($(window).width() <= 991) {
    $(".stellarnav li a").click(function (e) {
      // Exclude .dd-toggle from removing the class
      if (!$(this).hasClass("dd-toggle")) {
        $(".stellarnav").removeClass("current-menu-item");
      }
    });
  }
  //-------------------------------------------------------//
  // StellarNav Js End
  //-------------------------------------------------------//

  //-------------------------------------------------------//
  // Faq on HomePage
  //-------------------------------------------------------//
  $(".faq_box").each(function () {
    $(this).on("click", ".acc_trigger", function (e) {
      e.preventDefault(); // Prevent default action for the trigger

      var $currentTrigger = $(this);
      var $currentItem = $currentTrigger.closest(".faq_item");
      var $currentContainer = $currentItem.find(".acc_container");
      var $faqBox = $currentTrigger.closest(".faq_box");

      // Check if the clicked container is already open
      if ($currentContainer.is(":visible")) {
        // Close the current container, remove classes from trigger and item
        $currentContainer.slideUp(300);
        $currentTrigger.removeClass("active closed");
        $currentItem.removeClass("main_active");
      } else {
        // Close all other containers within the same faq_box
        $faqBox.find(".acc_container").slideUp(300);
        $faqBox.find(".acc_trigger").removeClass("active closed");
        $faqBox.find(".faq_item").removeClass("main_active");

        // Open the current container, add classes to trigger and item
        $currentContainer.slideDown(300);
        $currentTrigger.addClass("active closed");
        $currentItem.addClass("main_active");
      }
    });
  });
});
//-------------------------------------------------------//
// Faq on HomePage End
//-------------------------------------------------------//
//-------------------------------------------------------//
// Equal height
//-------------------------------------------------------//

$(function () {
  $(".eq1").matchHeight();
});

//-------------------------------------------------------//
// Equal height end
//-------------------------------------------------------//

// Banner Slider
// Swiper initialization script
document.addEventListener("DOMContentLoaded", function () {
  const mySwiper = new Swiper(".bannerslider", {
    // Optional parameters
    // direction: "horizontal", // or 'vertical'
    // loop: true, // Enable continuous loop mode
    slidesPerView: 1,
    spaceBetween: 10,

    // If we need pagination
    pagination: {
      el: ".bannerslider-swiper-pagination",
      clickable: true, // Allows clicking on bullets to jump to slides
    },

    // Navigation arrows
    navigation: {
      nextEl: ".bannerslider-swiper-button-next",
      prevEl: ".bannerslider-swiper-button-prev",
    },

    // Autoplay (optional)
    // autoplay: {
    //   delay: 5000, // 5 seconds
    //   disableOnInteraction: false, // Continue autoplay after user interaction
    // },
  });
});

//! TAB
document.addEventListener("DOMContentLoaded", function () {
  // Ensure DOM is fully loaded

  const tab = document.querySelector(".tabs");

  // Check if the main tab container exists before proceeding
  if (tab) {
    const tabButtons = tab.querySelectorAll('[role="tab"]');
    const tabPanels = Array.from(tab.querySelectorAll('[role="tabpanel"]'));

    // Further check if buttons and panels exist
    if (tabButtons.length > 0 && tabPanels.length > 0) {
      function tabClickHandler(e) {
        // Hide All Tabpane
        tabPanels.forEach((panel) => {
          // Use .hidden = true/false for accessibility and proper hiding
          panel.hidden = true;
        });

        // Deselect Tab Button
        tabButtons.forEach((button) => {
          button.setAttribute("aria-selected", "false");
          button.classList.remove("active"); // Optional: if you use an 'active' class for styling
        });

        // Mark New Tab as active/selected
        e.currentTarget.setAttribute("aria-selected", "true");
        e.currentTarget.classList.add("active"); // Optional: if you use an 'active' class for styling

        // Show New Tab
        const { id } = e.currentTarget;

        const currentTab = tabPanels.find(
          (panel) => panel.getAttribute("aria-labelledby") === id
        );

        if (currentTab) {
          // Ensure the currentTab is found before trying to show it
          currentTab.hidden = false;
        } else {
          console.warn(`Tab panel for button ID '${id}' not found.`);
        }
      }

      tabButtons.forEach((button) => {
        button.addEventListener("click", tabClickHandler);
      });

      // Initialize: Set the first tab as active/selected on page load
      // This is good practice for initial state
      const initialTabButton = tabButtons[0];
      if (initialTabButton) {
        initialTabButton.setAttribute("aria-selected", "true");
        initialTabButton.classList.add("active"); // Add active class for styling
        const initialTabId = initialTabButton.id;
        const initialTabPanel = tabPanels.find(
          (panel) => panel.getAttribute("aria-labelledby") === initialTabId
        );
        if (initialTabPanel) {
          initialTabPanel.hidden = false;
        }
      }
    } else {
      console.warn(
        "Tab buttons or tab panels not found within the '.tabs' container. Tab functionality skipped."
      );
    }
  } else {
    console.warn(
      "Main '.tabs' container not found. Tab functionality skipped."
    );
  }
});

document.addEventListener("DOMContentLoaded", function () {
  const breakpoint = 1199; // The screen width breakpoint

  // Select all necessary elements at the beginning
  const stellarnav = document.querySelector(".stellarnav");
  const myResponsiveBtn = document.querySelector(".mainHd .btn"); // Assuming this is the specific button
  const headerActions = document.querySelector(".hdrow"); // The original parent of the button
  const container = document.querySelector(".container"); // A common parent where both might reside initially or where the wrapper will be inserted

  // --- Add common error logging here to identify missing elements early ---
  if (!stellarnav)
    console.warn(
      "Responsive wrapper script: Element with class 'stellarnav' not found."
    );
  if (!myResponsiveBtn)
    console.warn(
      "Responsive wrapper script: Element with class '.mainHd .btn' not found."
    );
  if (!headerActions)
    console.warn(
      "Responsive wrapper script: Element with class 'hdrow' not found."
    );
  // container might not be strictly necessary for the core logic if parents are found, but good to check if its role is critical.
  if (!container)
    console.warn(
      "Responsive wrapper script: Element with class 'container' not found."
    );

  // Only proceed with the wrapping/unwrapping logic if the core elements are found
  if (stellarnav && myResponsiveBtn && headerActions) {
    // Store original parents to move elements back when unwrapping
    // Ensure parentNode is captured only if the element itself exists
    let originalStellarnavParent = stellarnav.parentNode;
    let originalMyResponsiveBtnParent = myResponsiveBtn.parentNode;

    let wrapperDiv = null; // To keep track of the dynamically created wrapper

    // Function to apply the wrapper
    function applyWrapper() {
      if (!wrapperDiv) {
        // Only create if wrapper doesn't exist
        wrapperDiv = document.createElement("div");
        wrapperDiv.classList.add("responsive-wrapper");

        // Append wrapper to a suitable parent.
        // It's safer to insert it relative to one of the elements being moved.
        // We'll insert it before stellarnav in its original parent.
        if (originalStellarnavParent) {
          originalStellarnavParent.insertBefore(wrapperDiv, stellarnav);
        } else {
          console.warn(
            "Stellarnav has no parent to insert wrapper before. Cannot apply wrapper."
          );
          return; // Cannot proceed if no parent
        }

        wrapperDiv.appendChild(stellarnav);
        wrapperDiv.appendChild(myResponsiveBtn);

        // Hide the original button's parent if it becomes empty and you want it hidden.
        // This logic depends on your specific layout.
        // If headerActions contains other elements, don't hide it.
        // If it only contained myResponsiveBtn, it might become empty.
        // Example: if (headerActions && headerActions.children.length === 0) {
        //     headerActions.style.display = 'none';
        // }
        console.log("Wrapper applied.");
      }
    }

    // Function to remove the wrapper
    function removeWrapper() {
      if (wrapperDiv) {
        // Only remove if wrapper exists
        // Move elements back to their original parents
        // Check if elements are currently inside the wrapper before moving
        if (stellarnav.parentNode === wrapperDiv && originalStellarnavParent) {
          originalStellarnavParent.appendChild(stellarnav); // Append to end of original parent
        }
        if (
          myResponsiveBtn.parentNode === wrapperDiv &&
          originalMyResponsiveBtnParent
        ) {
          originalMyResponsiveBtnParent.appendChild(myResponsiveBtn);
        }

        // Remove the wrapper div itself
        if (wrapperDiv.parentNode) {
          wrapperDiv.parentNode.removeChild(wrapperDiv);
          wrapperDiv = null; // Clear reference
        }

        // Re-show original parent if it was hidden
        // Example: if (headerActions) {
        //     headerActions.style.display = ''; // Revert display
        // }
        console.log("Wrapper removed.");
      }
    }

    // Function to handle media query changes
    function handleMediaQueryChange(e) {
      if (e.matches) {
        // Screen width is at or below the breakpoint
        applyWrapper();
      } else {
        // Screen width is greater than the breakpoint
        removeWrapper();
      }
    }

    // Initialize the media query listener
    const mediaQuery = window.matchMedia(`(max-width: ${breakpoint}px)`);

    // Add listener for changes
    mediaQuery.addListener(handleMediaQueryChange); // Using addListener for older browser compatibility, though addEventListener is preferred for new code.

    // Initial check on page load
    handleMediaQueryChange(mediaQuery);
  } else {
    console.warn(
      "Responsive wrapper script skipped: Not all required elements (.stellarnav, .mainHd .btn, .hdrow) were found on the page."
    );
  }
});

// ! Sortable table
document.addEventListener("DOMContentLoaded", function () {
  const table = document.querySelector(".data-table");
  const tbody = table ? table.querySelector("tbody") : null;
  const headers = table ? table.querySelectorAll("th.sortable") : [];
  const rowsPerPageSelect = document.querySelector(".rows-per-page select");
  const paginationControls = document.querySelector(".pagination-controls");
  const searchInput = document.querySelector(".search-bar input");

  if (
    !table ||
    !tbody ||
    headers.length === 0 ||
    !rowsPerPageSelect ||
    !paginationControls ||
    !searchInput
  ) {
    console.warn(
      "Sortable/Paginated table elements not fully found. Skipping functionality. Ensure .data-table, tbody, th.sortable, .rows-per-page select, .pagination-controls, and .search-bar input exist."
    );
    return;
  }

  let allTableRows = Array.from(tbody.querySelectorAll("tr")); // Store all original rows
  let filteredRows = []; // Rows that pass through search/filter
  let currentPage = 1;
  let rowsPerPage = parseInt(rowsPerPageSelect.value);

  let currentSortColumn = null;
  let currentSortDirection = "asc"; // 'asc' for ascending, 'desc' for descending

  // --- Utility Functions ---

  function parseCellValue(cell, columnType) {
    const text = cell.textContent.trim();
    if (columnType === "numeric") {
      // Remove currency symbols, commas, and parse as float
      return parseFloat(text.replace(/[^0-9.-]+/g, "") || 0);
    }
    return text.toLowerCase();
  }

  // --- Sorting Logic ---

  function sortTable(columnName, columnType) {
    // Sort the current `filteredRows`
    filteredRows.sort((rowA, rowB) => {
      const headerIndex = Array.from(headers).findIndex(
        (header) => header.dataset.column === columnName
      );
      if (headerIndex === -1) {
        console.error(`Column '${columnName}' not found for sorting.`);
        return 0;
      }
      const cellA = rowA.children[headerIndex];
      const cellB = rowB.children[headerIndex];

      const valueA = parseCellValue(cellA, columnType);
      const valueB = parseCellValue(cellB, columnType);

      let comparison = 0;
      if (valueA > valueB) {
        comparison = 1;
      } else if (valueA < valueB) {
        comparison = -1;
      }

      return currentSortDirection === "asc" ? comparison : -comparison;
    });

    // Update header classes for visual indication
    headers.forEach((header) => {
      header.classList.remove("asc", "desc");
      if (header.dataset.column === currentSortColumn) {
        header.classList.add(currentSortDirection);
      }
    });

    // After sorting, go to the first page and render
    currentPage = 1;
    renderTable();
    renderPagination();
  }

  // --- Search/Filter Logic ---

  function applySearchAndFilters() {
    const searchTerm = searchInput.value.toLowerCase().trim();
    // Assuming filters are currently handled by the HTML select elements,
    // you would collect their values here as well.
    // For simplicity, this example only implements a basic text search.
    // Implement complex filter logic here as needed based on your HTML structure.

    filteredRows = allTableRows.filter((row) => {
      const rowText = row.textContent.toLowerCase();
      return rowText.includes(searchTerm);
      // Add more filter conditions here:
      // e.g., const accountSizeCell = row.children[1].textContent;
      // return rowText.includes(searchTerm) && (selectedAccountSize === 'all' || accountSizeCell.includes(selectedAccountSize));
    });

    // Reapply sorting to the newly filtered rows if a sort is active
    if (currentSortColumn) {
      const activeHeader = Array.from(headers).find(
        (header) => header.dataset.column === currentSortColumn
      );
      if (activeHeader) {
        const columnType = activeHeader.classList.contains("numeric")
          ? "numeric"
          : "string";
        // Re-sort the filteredRows array
        sortTable(currentSortColumn, columnType); // This will also re-render and re-paginate
        return; // Exit as sortTable already handles rendering and pagination
      }
    }

    // If no sort was active or re-applied, just render with current settings
    currentPage = 1;
    renderTable();
    renderPagination();
  }

  // --- Pagination Logic ---

  function getPageCount() {
    return Math.ceil(filteredRows.length / rowsPerPage);
  }

  function renderTable() {
    tbody.innerHTML = ""; // Clear current table body

    const start = (currentPage - 1) * rowsPerPage;
    const end = start + rowsPerPage;
    const pageRows = filteredRows.slice(start, end);

    pageRows.forEach((row) => tbody.appendChild(row));
  }

  function renderPagination() {
    paginationControls.innerHTML = ""; // Clear existing pagination buttons

    const pageCount = getPageCount();

    // Previous button
    const prevButton = document.createElement("button");
    prevButton.classList.add("pagination-btn");
    // prevButton.innerHTML = "&lt;";
    prevButton.disabled = currentPage === 1;
    prevButton.addEventListener("click", () => {
      if (currentPage > 1) {
        currentPage--;
        renderTable();
        renderPagination();
      }
    });
    paginationControls.appendChild(prevButton);

    // Page number buttons
    // Logic to show a limited number of page buttons around the current page
    const maxButtons = 5; // Max number of page buttons to display
    let startPage = Math.max(1, currentPage - Math.floor(maxButtons / 2));
    let endPage = Math.min(pageCount, startPage + maxButtons - 1);

    // Adjust startPage if we're at the end to always show `maxButtons` if possible
    if (endPage - startPage + 1 < maxButtons) {
      startPage = Math.max(1, endPage - maxButtons + 1);
    }

    for (let i = startPage; i <= endPage; i++) {
      const pageButton = document.createElement("button");
      pageButton.classList.add("pagination-btn");
      pageButton.textContent = i;
      if (i === currentPage) {
        pageButton.classList.add("active");
      }
      pageButton.addEventListener("click", () => {
        currentPage = i;
        renderTable();
        renderPagination();
      });
      paginationControls.appendChild(pageButton);
    }

    // Next button
    const nextButton = document.createElement("button");
    nextButton.classList.add("pagination-btn");
    // nextButton.innerHTML = "&gt;";
    nextButton.disabled = currentPage === pageCount || pageCount === 0;
    nextButton.addEventListener("click", () => {
      if (currentPage < pageCount) {
        currentPage++;
        renderTable();
        renderPagination();
      }
    });
    paginationControls.appendChild(nextButton);
  }

  // --- Event Listeners ---

  // Sortable headers
  headers.forEach((header) => {
    header.addEventListener("click", function () {
      const columnName = this.dataset.column;
      const columnType = this.classList.contains("numeric")
        ? "numeric"
        : "string";

      // Determine sort direction (moved from sortTable to here for consistency)
      if (currentSortColumn === columnName) {
        currentSortDirection = currentSortDirection === "asc" ? "desc" : "asc";
      } else {
        currentSortDirection = "asc"; // Default to ascending for a new column
        currentSortColumn = columnName;
      }

      sortTable(columnName, columnType);
    });
  });

  // Rows per page select
  rowsPerPageSelect.addEventListener("change", function () {
    rowsPerPage = parseInt(this.value);
    currentPage = 1; // Reset to first page when rows per page changes
    renderTable();
    renderPagination();
  });

  // Search input
  searchInput.addEventListener("input", applySearchAndFilters);
  // You'd also add listeners for other filter dropdowns here, calling applySearchAndFilters

  // --- Initial Setup ---

  // Initialize filteredRows with all rows at start
  applySearchAndFilters(); // This will populate filteredRows, sort, render table and pagination
});

document.addEventListener("DOMContentLoaded", function () {
  const filters = document.querySelectorAll(".filter-dropdown");
  const allColumnOptions = document.querySelectorAll(".columnoptions");

  // Helper function to update the filter button text and active state
  function updateFilterButton(filterElement, optionBoxElement) {
    const button = filterElement.querySelector("button");
    const btnText = button.querySelector(".btn-text");

    // Find the potential 'All' checkbox and its parent <li>
    const firstLi = optionBoxElement.querySelector("li:first-child");
    const allCheckbox = firstLi
      ? firstLi.querySelector("input[type='checkbox']")
      : null;
    // Determine if the first <li> truly represents an "All" option based on its text content
    const isFirstLiAnAllOption =
      firstLi && firstLi.textContent.trim().toLowerCase().startsWith("all");

    if (allCheckbox && allCheckbox.checked && isFirstLiAnAllOption) {
      // This applies only if the current panel *has* an "All" option and it's checked
      filterElement.classList.add("active");
      btnText.textContent = "All";
    } else {
      // For "Columns" filter (which doesn't have an "All" option) or when "All" is not checked
      const checkedCount = optionBoxElement.querySelectorAll(
        "input[type='checkbox']:checked"
      ).length;
      if (checkedCount > 0) {
        filterElement.classList.add("active");
        btnText.textContent = `${checkedCount}`;
      } else {
        filterElement.classList.remove("active");
        btnText.textContent = "Select";
      }
    }

    // Always update the active class on individual <li> elements based on their checkbox state
    optionBoxElement.querySelectorAll("li").forEach((li) => {
      const input = li.querySelector("input[type='checkbox']");
      if (input) {
        li.classList.toggle("active", input.checked);
      }
    });
  }

  filters.forEach((filter, index) => {
    const optionBox = allColumnOptions[index]; // The corresponding columnoptions panel

    // Toggle the corresponding columnoptions panel
    filter.addEventListener("click", function (e) {
      e.stopPropagation(); // Prevent document click from closing immediately

      // Close all other dropdowns, then toggle the current one
      allColumnOptions.forEach((opt, i) => {
        if (i !== index) {
          // Close others
          opt.classList.remove("active");
        }
      });
      optionBox.classList.toggle("active"); // Toggle current
    });

    // Get all checkboxes within this specific columnoptions panel
    const checkboxes = optionBox.querySelectorAll("input[type='checkbox']");

    // Identify the 'All' checkbox for this panel, if it exists
    const firstLi = optionBox.querySelector("li:first-child");
    const allCheckbox = firstLi
      ? firstLi.querySelector("input[type='checkbox']")
      : null;
    const isPanelWithAllOption =
      firstLi && firstLi.textContent.trim().toLowerCase().startsWith("all");

    checkboxes.forEach((checkbox) => {
      checkbox.addEventListener("change", () => {
        // Only apply 'All' specific logic if this panel actually has an 'All' option
        if (isPanelWithAllOption) {
          if (checkbox === allCheckbox) {
            // If "All" checkbox was clicked
            if (allCheckbox.checked) {
              // If "All" is checked, uncheck all other checkboxes
              checkboxes.forEach((otherCheckbox) => {
                if (otherCheckbox !== allCheckbox) {
                  otherCheckbox.checked = false;
                }
              });
            }
          } else {
            // If any other checkbox (not "All") was clicked
            if (allCheckbox && allCheckbox.checked) {
              // If "All" was checked, and a specific option is clicked, uncheck "All"
              allCheckbox.checked = false;
            }
          }
        }
        // Always update the filter button and li active states after any checkbox change
        updateFilterButton(filter, optionBox);
      });
    });

    // Initialize button text and active state on load
    updateFilterButton(filter, optionBox);
  });

  // Click outside to close all dropdowns
  document.addEventListener("click", function (e) {
    // Check if the click target or any of its parents is NOT a filter dropdown or a column options panel
    if (
      !e.target.closest(".filter-dropdown") &&
      !e.target.closest(".columnoptions")
    ) {
      allColumnOptions.forEach((opt) => opt.classList.remove("active"));
    }
  });
});

document.addEventListener("DOMContentLoaded", function () {
  const filtersContainer = document.querySelector(".filters");
  const allColumnOptions = document.querySelectorAll(".columnoptions");
  const originalParent = allColumnOptions[0].parentNode;

  const moveColumnOptions = () => {
    if (window.innerWidth <= 1199) {
      allColumnOptions.forEach((opt) => {
        if (!filtersContainer.nextElementSibling?.contains(opt)) {
          filtersContainer.insertAdjacentElement("afterend", opt);
        }
      });
    } else {
      allColumnOptions.forEach((opt) => {
        if (!originalParent.contains(opt)) {
          originalParent.appendChild(opt);
        }
      });
    }
  };

  // Initial check
  moveColumnOptions();

  // Watch for resize
  window.addEventListener("resize", moveColumnOptions);
});
