const { __, _x, _n, sprintf } = wp.i18n;

let userPerPage = 10;           // Default Users per page is 10
let selectedIds = [];           // Stores IDs of users whose checkboxes are selected
let orderBy = "user_login";     // Default table order by user_login
let orderDirection = "ASC";     // Default table order direction is ascending
let search_key = "";            // Global variable to get store search value
let userRole = "all";           // Table fetch all users as per default
let onlineUserIDs = [];         // Stores currently online users from the latest API response
let lastOnlineUserIDs = [];     // Stores user IDs from the last request

// Permissions allowed against a user
let is_admin = author_kit_user_table_vars.is_admin;
let is_edit_users = author_kit_user_table_vars.is_edit_users;
let is_delete_users = author_kit_user_table_vars.is_delete_users;
let is_manage_options = author_kit_user_table_vars.is_manage_options;
let is_create_users = author_kit_user_table_vars.author_kit_is_create_users;
let current_user_id = author_kit_user_table_vars.current_user_id;
let author_kit_add_new_user_url = author_kit_user_table_vars.author_kit_add_new_user_url;

// Get the IDs of online users on heartbeat API ticking
document.addEventListener("DOMContentLoaded", function () {
    if (window.jQuery) {
        window.jQuery(document).on("heartbeat-tick", function (event, data) {
            if (data.user_online && Array.isArray(data.user_online.online_users)) {
                onlineUserIDs = data.user_online.online_users;
            }
        });
    }
});


// Event listener for DOM content loaded
document.addEventListener("DOMContentLoaded", function () {
    initialize();
});


// Function to initialize and load user data
function initialize() {

    // initialize the table after loading
    load_dashboard_table();

    // load the total number of users for each role
    get_total_users_by_role();

    add_new_user_button_on_click()

    // Debounced search function
    const debouncedLoadDashboardTable = debounce(() => load_dashboard_table(), 750);

    // Search user with debouncing
    document.getElementById('users-search').addEventListener('keyup', function () {
        search_key = this.value;
        debouncedLoadDashboardTable();
    });

    on_change_option();
    on_click_next();
    on_click_previous();
    initialize_sorting();
    user_filter_active_tab();

    // Run the function every 5 seconds
    setInterval(updateUserStatus, 5000);


    document.getElementById('delete-all-users').addEventListener('click', function (e) {
        e.preventDefault();
        if (is_delete_users) {
            openDeleteUserModal(selectedIds);
        } else {
            show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
        }
    });

    document.getElementById('send-all-password-reset').addEventListener('click', function (e) {
        e.preventDefault();
        if (is_edit_users) {
            send_password_reset(selectedIds);
        } else {
            show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
        }
    });

    document.getElementById('block-all-users').addEventListener('click', function (e) {
        e.preventDefault();
        if (is_admin) {
            block_user(selectedIds);
        } else {
            show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
        }
    });

    document.getElementById('unblock-all-users').addEventListener('click', function (e) {
        e.preventDefault();
        if (is_admin) {
            un_block_user(selectedIds);
        } else {
            show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
        }
    });

}

function add_new_user_button_on_click() {
    const buttons = document.querySelectorAll('#add-new-user-button');

    buttons.forEach(function (button) {
        button.addEventListener('click', function (e) {
            if (is_create_users) {
                window.location.href = author_kit_add_new_user_url;
            } else {
                e.preventDefault();
                show_author_kit_toast(__('You do not have permission to access this page.', 'author-kit'), 'error');
            }
        });
    });
}

function reload() {
    userRole = 'all';
    load_dashboard_table();
    get_total_users_by_role();
}

// Debounce function to limit frequent calls
function debounce(func, delay) {
    let timer;
    return function (...args) {
        clearTimeout(timer);
        timer = setTimeout(() => func.apply(this, args), delay);
    };
}


// Function to load dashboard table with loader functionality
function load_dashboard_table(page_id = 1) {

    selectedIds = [];
    reset_selection();

    // Get the loader element (assuming it exists in your HTML)
    const loader = document.getElementById("loader");

    // Show the loader before making the AJAX request
    loader.style.display = "block";

    fetch(author_kit_user_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_load_users',
            pageId: page_id,
            limit: userPerPage,
            order_by: orderBy,
            order_direction: orderDirection,
            nonce: author_kit_user_table_vars.nonce,
            search: search_key,
            userRole: userRole,
        })
    })
        .then(async response => await response.json())
        .then(data => {

            form_user_table(data.user_data, data.pagination_data); // Only call here

        })
        .catch(error => {
            // Hide the loader if there's an error
            loader.style.display = "none";

            // Display error toast
            show_author_kit_toast(__('Error in Loading User Table', 'author-kit'), 'error');
        });
}



// Function to form Authors Table
function form_user_table(user_data, pagination_data) {

    try {
        view_profile_text = __('View Profile', 'author-kit');
        edit_user_text = __('Edit User', 'author-kit');
        delete_text = __('Delete User', 'author-kit');
        block_text = __('Block', 'author-kit');
        unblock_text = __('Unblock', 'author-kit');

        // Get table body element
        const tableBody = document.querySelector("#authorTable tbody");
        tableBody.innerHTML = ''; // Clear existing table rows before inserting new ones

        if (user_data.length != 0) {
            // Use DocumentFragment to improve performance by reducing reflows and repaints
            const fragment = document.createDocumentFragment();

            user_data.forEach(item => {
                // Create a new row element
                const row = document.createElement("tr");
                row.id = `user-row-${item.ID}`;

                // Checkbox column
                const checkboxCell = document.createElement("td");
                const checkbox = document.createElement("input");
                checkbox.type = "checkbox";
                checkbox.className = "row-checkbox";
                checkbox.value = item.ID;
                checkbox.setAttribute("user-role", item.role);
                checkboxCell.appendChild(checkbox);
                row.appendChild(checkboxCell);

                // Avatar and Username column
                const avatarCell = document.createElement("td");
                const avatarWrapper = document.createElement("div");
                avatarWrapper.id = "first-row-avatar-name-style";

                const avatarDiv = document.createElement("div");
                const avatarImg = document.createElement("img");
                avatarImg.src = item.avatar;
                avatarImg.className = "avatar";
                avatarImg.id = "avatar-img";
                avatarDiv.appendChild(avatarImg);

                const nameContainer = document.createElement("div");
                const nameDiv = document.createElement("div");
                nameDiv.textContent = item.display_name;
                const usernameSpan = document.createElement("span");
                usernameSpan.id = "user-name-display";
                usernameSpan.textContent = `@${item.username}`;
                nameContainer.appendChild(nameDiv);
                nameContainer.appendChild(usernameSpan);

                avatarWrapper.appendChild(avatarDiv);
                avatarWrapper.appendChild(nameContainer);
                avatarCell.appendChild(avatarWrapper);
                row.appendChild(avatarCell);

                // Role column
                const roleCell = document.createElement("td");
                const roleBtn = document.createElement("button");
                roleBtn.id = "blue-btn";
                roleBtn.className = item.role.toLowerCase();
                roleBtn.textContent = item.role;
                roleCell.appendChild(roleBtn);
                row.appendChild(roleCell);

                // Email column
                const emailCell = document.createElement("td");
                emailCell.textContent = item.email;
                row.appendChild(emailCell);

                // Contribution column
                const contributionCell = document.createElement("td");
                contributionCell.textContent = `${item.contribution} ${__('Posts', 'author-kit')}`;
                row.appendChild(contributionCell);

                // Status column
                const statusCell = document.createElement("td");
                statusCell.id = `status-${item.ID}`;
                statusCell.className = item.status.toLowerCase() === 'online' ? 'status-active' : 'status-inactive';
                const statusSpan = document.createElement("span");
                statusSpan.textContent = item.status;
                statusCell.appendChild(statusSpan);
                row.appendChild(statusCell);

                // Actions column with dropdown menu
                const actionsCell = document.createElement("td");
                const dropdown = document.createElement("div");
                dropdown.className = "dropdown";
                const toggleBtn = document.createElement("button");
                toggleBtn.className = "dropdown-toggle";
                toggleBtn.innerHTML = "<i class='fa-solid fa-ellipsis-vertical'></i>";
                const dropdownMenu = document.createElement("div");
                dropdownMenu.className = "dropdown-menu";

                // View Profile link
                const viewProfileLink = document.createElement("a");
                viewProfileLink.className = "dropdown-item";
                viewProfileLink.href = item.userProfile;
                viewProfileLink.target = "_blank";
                viewProfileLink.innerHTML = `<i class="fa-solid fa-eye"></i> <span style="margin-left: 8px;">${view_profile_text}</span>`;
                dropdownMenu.appendChild(viewProfileLink);

                // Edit User link
                if (is_edit_users || item.ID == current_user_id) {
                    const editUserLink = document.createElement("a");
                    editUserLink.className = "dropdown-item edit-user-button";
                    editUserLink.href = `admin.php?page=author-kit-edit-user&user-id=${item.ID}&edit-user-nonce=${author_kit_user_table_vars.edit_user_nonce}`;
                    editUserLink.innerHTML = `<i class="fa-solid fa-pen-to-square"></i> <span style="margin-left: 8px;">${edit_user_text}</span>`;
                    dropdownMenu.appendChild(editUserLink);
                }
                // Delete user link (only visible for admins)
                if (is_delete_users && item.ID != current_user_id) {
                    const deleteUserLink = document.createElement("a");
                    deleteUserLink.className = "dropdown-item delete-user-button";
                    deleteUserLink.href = "#";
                    deleteUserLink.setAttribute("delete-user-id", item.ID);
                    deleteUserLink.innerHTML = `<i class='fa-regular fa-trash-can'></i> <span style="margin-left: 8px;">${delete_text}</span>`;
                    dropdownMenu.appendChild(deleteUserLink);
                }

                // Block User Option
                if (is_admin && item.ID !== current_user_id && item.role !== 'Blocked' && item.role !== 'Administrator') {
                    const blockUserLink = document.createElement("a");
                    blockUserLink.className = "dropdown-item block-user-button";
                    blockUserLink.href = "#";
                    blockUserLink.setAttribute("block-user-id", item.ID);
                    blockUserLink.setAttribute("block-user-role", item.role);
                    blockUserLink.innerHTML = `<i class="fa-solid fa-ban"></i> <span style="margin-left: 8px;">${block_text}</span>`;
                    dropdownMenu.appendChild(blockUserLink);
                }

                // Unblock User Option
                if (is_admin && item.role === 'Blocked') {
                    const unblockUserLink = document.createElement("a");
                    unblockUserLink.className = "dropdown-item unblock-user-button";
                    unblockUserLink.href = "#";
                    unblockUserLink.setAttribute("unblock-user-id", item.ID);
                    unblockUserLink.innerHTML = `<i class="fa-solid fa-user-check"></i> <span style="margin-left: 8px;">${unblock_text}</span>`;
                    dropdownMenu.appendChild(unblockUserLink);
                }

                dropdown.appendChild(toggleBtn);
                dropdown.appendChild(dropdownMenu);
                actionsCell.appendChild(dropdown);
                row.appendChild(actionsCell);

                // Append row to fragment
                fragment.appendChild(row);
            });

            // Append all rows at once to minimize reflow/repaint
            tableBody.appendChild(fragment);


            select_boxes_functionality();
        } else {
            const row = document.createElement("tr");
            const cell = document.createElement("td");
            const paragraph = document.createElement("p");

            paragraph.textContent = __("No users found. Try a different search terms", "author-kit");
            cell.setAttribute("colspan", "7"); // our table has 7 columns
            cell.style.textAlign = "center";
            cell.style.padding = "20px";

            cell.appendChild(paragraph);
            row.appendChild(cell);
            tableBody.appendChild(row);
        }

        // Add Pagination *****************************************************************


        const pageNumbersSpan = document.getElementById('pageNumbers');
        const prevPageButton = document.getElementById('prevPage');
        const nextPageButton = document.getElementById('nextPage');

        pageNumbersSpan.innerHTML = sprintf(
            /* translators: 1: current page number, 2: total number of pages */
            __('Page %1$s of %2$s', 'author-kit'),
            pagination_data.total_pages != 0 ? pagination_data.current_page : 0,
            pagination_data.total_pages
        );
        prevPageButton.disabled = pagination_data.current_page === 1;
        nextPageButton.disabled = pagination_data.current_page === pagination_data.total_pages || pagination_data.total_pages === 0;

        if (pagination_data.current_page == 1) {
            prevPageButton.setAttribute("prev-page-id", `${pagination_data.current_page}`)
        } else {
            prevPageButton.setAttribute("prev-page-id", `${pagination_data.current_page - 1}`)
        }

        nextPageButton.setAttribute("next-page-id", `${pagination_data.current_page + 1}`);

        const pageInfoSpan = document.getElementById('pageInfo');

        pageInfoSpan.textContent = sprintf(
            /* translators: 1: start index, 2: ending index, 3: total users */
            __('Showing %1$s to %2$s of %3$s users', 'author-kit'),
            pagination_data.start_index,
            pagination_data.ending_index,
            pagination_data.total_users
        );

        // Sorting ************************************************************************* //

        const tableHead = document.querySelector("#authorTable thead");
        tableHead.setAttribute("current-page-id", `${pagination_data.current_page}`);

        // *************************************************************************************** //

        // Add Delete Button Event Listener
        const deleteButtons = document.querySelectorAll('.delete-user-button');
        deleteButtons.forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const userId = button.getAttribute('delete-user-id');
                if (is_delete_users) {
                    openDeleteUserModal([userId]);
                } else {
                    show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
                }
            });
        });

        // Add event listeners for blocking users
        const blockButtons = document.querySelectorAll('.block-user-button');
        blockButtons.forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const userId = button.getAttribute('block-user-id');
                if (is_admin) {
                    block_user([userId]);
                } else {
                    show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
                }
            });
        });

        // Add event listeners for unblocking users
        const unblockButtons = document.querySelectorAll('.unblock-user-button');
        unblockButtons.forEach(button => {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const userId = button.getAttribute('unblock-user-id');
                if (is_admin) {
                    un_block_user([userId]);
                } else {
                    show_author_kit_toast(__('Permission Not Allowed', 'author-kit'), 'error');
                }
            });
        });


        // Add event listeners for dropdown toggles
        const toggleButtons = document.querySelectorAll('.dropdown-toggle');
        toggleButtons.forEach(button => {
            button.addEventListener('click', function (e) {
                e.stopPropagation();
                const dropdownMenu = this.nextElementSibling;
                dropdownMenu.style.display = dropdownMenu.style.display === 'block' ? 'none' : 'block';

                // Hide all other dropdown menus
                toggleButtons.forEach(otherButton => {
                    if (otherButton !== button) {
                        otherButton.nextElementSibling.style.display = 'none';
                    }
                });
            });
        });

        // Close dropdowns when clicking outside
        document.addEventListener('click', function () {
            toggleButtons.forEach(button => {
                button.nextElementSibling.style.display = 'none';
            });
        });

    }
    finally {
        // Get the loader element
        const loader = document.getElementById("loader");

        // hide the loader after forming table
        loader.style.display = "none";
    }
}


// Function to check and update user status
function updateUserStatus() {
    const newOnlineSet = new Set(onlineUserIDs);
    const lastOnlineSet = new Set(lastOnlineUserIDs);

    // Users that are now online (newly added)
    onlineUserIDs.forEach(userId => {
        if (!lastOnlineSet.has(userId)) {
            updateStatusElement(userId, __("Online", "author-kit"), "status-active");
        }
    });

    // Users that are now offline (need removal from table if in online filter)
    lastOnlineUserIDs.forEach(userId => {
        if (!newOnlineSet.has(userId)) {
            updateStatusElement(userId, __("Offline", "author-kit"), "status-inactive");
        }
    });

    lastOnlineUserIDs = [...onlineUserIDs];
}



// Helper function to update status
function updateStatusElement(userId, statusText, statusClass) {
    const userStatusElement = document.querySelector(`#status-${userId}`);
    if (userStatusElement) {
        const currentStatusText = userStatusElement.textContent.trim().toLowerCase();

        if (currentStatusText !== statusText) {
            userStatusElement.innerHTML = "";

            const statusSpan = document.createElement("span");
            statusSpan.textContent = statusText;
            userStatusElement.appendChild(statusSpan);

            userStatusElement.className = statusClass;
        }
    }
}

// Count total numbers of users against each role to show in filter tab
function get_total_users_by_role() {

    fetch(author_kit_user_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_load_total_no_of_users',
            nonce: author_kit_user_table_vars.nonce,
        })
    })
        .then(response => response.json())
        .then(data => {


            if (data.success) {
                // Get the filter-tabs element
                const filterTabs = document.getElementById('filter-tabs');
                if (!filterTabs) {
                    show_author_kit_toast(__('Filter Tabs Not Found', 'author-kit'), 'error');
                    return;
                }

                // Clear existing content (optional, based on your requirement)
                filterTabs.innerHTML = '';

                // Loop through each role in the response and create a tab
                Object.keys(data.data).forEach(role => {
                    // Create the role paragraph element
                    const roleTab = document.createElement('p');
                    roleTab.id = `${role}-users`; // Set a unique ID for each role
                    roleTab.textContent = `${role.charAt(0).toUpperCase() + role.slice(1)}`; // Add role name and user count
                    roleTab.style.cursor = 'pointer';

                    roleTab.onclick = () => {
                        // Add your onclick logic here
                        userRole = role;
                        load_dashboard_table(1);
                    };

                    // Add a span for additional information (if required)
                    const roleInfo = document.createElement('span');
                    roleInfo.id = `${role}-information`; // Unique ID for the span
                    roleInfo.textContent = ` (${data.data[role]}) `; // You can customize this content as needed

                    // Append the role tab and its span to the filter-tabs div
                    filterTabs.appendChild(roleTab);
                    filterTabs.appendChild(roleInfo);
                });
            } else {
                show_author_kit_toast(__('Error in loading Filter Tabs User Count', 'author-kit'), 'error');
            }
        })
        .catch(error => show_author_kit_toast(__('Failed to Load Filter Tabs User Count', 'author-kit'), 'error'));
}

// Manages the sorting of table
function initialize_sorting() {
    const sortableHeaders = document.querySelectorAll(".sortable");

    // Default sorting based on global variables
    sortableHeaders.forEach(header => {
        const column = header.getAttribute("data-column");
        const sortIcons = header.querySelector(".sort-icons");
        const ascIcon = sortIcons.querySelector(".asc");
        const descIcon = sortIcons.querySelector(".desc");

        if (column === orderBy) {
            if (orderDirection === "ASC") {
                ascIcon.classList.add("active");
                descIcon.classList.remove("active");
            } else if (orderDirection === "DESC") {
                descIcon.classList.add("active");
                ascIcon.classList.remove("active");
            }
        } else {
            ascIcon.classList.remove("active");
            descIcon.classList.remove("active");
        }
    });

    // Add event listeners for sorting
    sortableHeaders.forEach(header => {
        const sortIcons = header.querySelector(".sort-icons");
        const ascIcon = sortIcons.querySelector(".asc");
        const descIcon = sortIcons.querySelector(".desc");
        const column = header.getAttribute("data-column");

        sortIcons.addEventListener("click", () => {
            // Determine current state and toggle between ASC and DESC
            if (orderBy === column && orderDirection === "ASC") {
                orderDirection = "DESC"; // Switch to descending
            } else {
                orderDirection = "ASC"; // Default to ascending
                orderBy = column; // Update to the selected column
            }

            // Reset all icons
            sortableHeaders.forEach(h => {
                const otherSortIcons = h.querySelector(".sort-icons");
                otherSortIcons.querySelector(".asc").classList.remove("active");
                otherSortIcons.querySelector(".desc").classList.remove("active");
            });

            // Activate the appropriate icon for the selected column
            if (orderDirection === "ASC") {
                ascIcon.classList.add("active");
                descIcon.classList.remove("active");
            } else {
                descIcon.classList.add("active");
                ascIcon.classList.remove("active");
            }

            // Reload the table with updated sorting
            const tableHead = document.querySelector("#authorTable thead");
            current_page_ID = tableHead.getAttribute("current-page-id");

            load_dashboard_table(current_page_ID);
        });
    });
}




function on_change_option() {
    const rowsPerPageSelect = document.getElementById('rowsPerPage');

    // Add an event listener for the 'change' event
    rowsPerPageSelect.addEventListener('change', function () {
        // Get the selected value
        userPerPage = this.value;
        load_dashboard_table(1);

    });

}

function on_click_next() {
    nextPageBtn = document.getElementById("nextPage");
    nextPageBtn.addEventListener('click', function () {

        nextPageId = nextPageBtn.getAttribute("next-page-id");
        load_dashboard_table(nextPageId);

    });
}

function on_click_previous() {
    prevPageBtn = document.getElementById("prevPage");
    prevPageBtn.addEventListener('click', function () {

        prevPageId = prevPageBtn.getAttribute("prev-page-id");
        load_dashboard_table(prevPageId);

    })
}


function delete_user(userIds, attribute_user) {

    show_author_kit_toast(__('Deleting the User... Please Wait!', 'author-kit'), 'performing');

    // Prepare data to send
    fetch(author_kit_user_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_delete_user',
            nonce: author_kit_user_table_vars.nonce,
            delete_user_ids: JSON.stringify(userIds), // Send array as JSON
            attribute_user: attribute_user
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                show_author_kit_toast(data.data.message, 'success')
                setTimeout(function () {
                    reload();
                }, 3000);
            } else {
                show_author_kit_toast(data.data.message, 'error');
                setTimeout(function () {
                    reload();
                }, 3000);
            }
        })
        .catch(error => {
            show_author_kit_toast(__('Failed to Delete User(s)', 'author-kit'), 'error');
        });

}

function send_password_reset(userIds) {
    // Confirm password reset
    if (confirm(__("Are you sure you want to send password reset emails to the selected user(s)?", 'author-kit'))) {

        show_author_kit_toast(__('Sending Password Reset Emails... Please Wait!', 'author-kit'), 'performing')

        // Prepare data to send
        fetch(author_kit_user_table_vars.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: new URLSearchParams({
                action: 'author_kit_send_password_reset',
                nonce: author_kit_user_table_vars.nonce,
                reset_user_ids: JSON.stringify(userIds) // Send array as JSON
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    show_author_kit_toast(data.data.message, 'success');
                    setTimeout(function () {
                        reload();

                    }, 3000);
                } else {
                    show_author_kit_toast(data.data.message, 'error');
                    setTimeout(function () {
                        reload();

                    }, 3000);
                }
            })
            .catch(error => {
                show_author_kit_toast(__('Failed to Send Password Reset Email(s)', 'author-kit'), 'error');
            });
    }
}


// block user
function block_user(userIds) {
    // Ensure we have an array of user IDs
    if (!Array.isArray(userIds) || userIds.length === 0) {
        show_author_kit_toast(__("No users selected to block.", 'author-kit'), 'error');
        return;
    }

    // Ask for confirmation before proceeding
    if (confirm(__("Are you sure you want to block the selected users?", 'author-kit'))) {

        show_author_kit_toast(__('Blocking the User... Please Wait!', 'author-kit'), 'performing')
        // Proceed with the fetch request
        fetch(author_kit_user_table_vars.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: new URLSearchParams({
                action: 'author_kit_block_user',
                nonce: author_kit_user_table_vars.nonce,
                block_user_ids: JSON.stringify(userIds), // Pass IDs as JSON
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const responseData = data.data;
                    const blockedUsers = responseData.blocked_users || [];
                    const failedUsers = responseData.failed_users || [];

                    show_author_kit_toast(data.data.message, 'success')
                    setTimeout(function () {
                        reload();

                    }, 3000); // 3000 milliseconds = 3 seconds


                } else {
                    show_author_kit_toast(data.data.message, 'error');
                    setTimeout(function () {
                        reload();

                    }, 3000);
                }
            })
            .catch(error => {
                show_author_kit_toast(__("Failed to Block User(s)", 'author-kit'), 'error');
            });
    } else {
        // User canceled, do nothing
        show_author_kit_toast(__("Blocking Action Canceled", 'author-kit'), 'error');
    }
}

function un_block_user(userIds) {
    // Ensure we have an array of user IDs
    if (!Array.isArray(userIds) || userIds.length === 0) {
        show_author_kit_toast(__("No users selected to unblock.", 'author-kit'), 'error');
        return;
    }

    // Ask for confirmation before proceeding
    if (confirm(__("Are you sure you want to unblock the selected users?", 'author-kit'))) {

        show_author_kit_toast(__('Unblocking the User... Please Wait!', 'author-kit'), 'performing')

        // Proceed with the fetch request
        fetch(author_kit_user_table_vars.ajax_url, {
            method: 'POST',
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
            },
            body: new URLSearchParams({
                action: 'author_kit_unblock_user',
                nonce: author_kit_user_table_vars.nonce,
                unblock_user_ids: JSON.stringify(userIds), // Pass IDs as JSON
            })
        })
            .then(response => response.json())
            .then(data => {
                if (data.success) {
                    const responseData = data.data;
                    const unblockedUsers = responseData.unblocked_users || [];
                    const failedUsers = responseData.failed_users || [];

                    show_author_kit_toast(data.data.message, 'success')
                    setTimeout(function () {
                        reload();

                    }, 3000);


                } else {
                    show_author_kit_toast(data.data.message, 'error')
                    setTimeout(function () {
                        reload();

                    }, 3000);
                }
            })
            .catch(error => {
                show_author_kit_toast(__("Failed to Unblock User(s)", 'author-kit'), 'error');
            });
    } else {
        // User canceled, do nothing
        show_author_kit_toast(__("Unlocking Action Canceled", 'author-kit'), 'error');
    }
}


// Manages the working and synchronization of select boxes of table
function select_boxes_functionality() {
    const selectAllCheckbox = document.getElementById('select-all');
    const multiSelectOptionsDiv = document.getElementById('multi-select-options');
    const blockOption = document.getElementById('block-all-users');
    const unblockOption = document.getElementById('unblock-all-users');
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    // "Select All" checkbox event
    selectAllCheckbox.addEventListener('change', function () {
        let selectAllIds = [];

        rowCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
            if (this.checked) {
                selectAllIds.push(checkbox.value);
            }
        });

        selectedIds = selectAllIds;
        update_multi_select_options();


    });

    // Row checkboxes event
    rowCheckboxes.forEach(checkbox => {
        checkbox.addEventListener('change', function () {
            const checkboxId = this.value;

            if (this.checked) {
                if (!selectedIds.includes(checkboxId)) {
                    selectedIds.push(checkboxId);
                }
            } else {
                selectedIds = selectedIds.filter(id => id !== checkboxId);
            }

            update_multi_select_options();
            selectAllCheckbox.checked = selectedIds.length === rowCheckboxes.length;


        });
    });
}

// Function to update multi-select options display based on checked users
function update_multi_select_options() {
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    const selectedRoles = Array.from(rowCheckboxes)
        .filter(checkbox => checkbox.checked)
        .map(checkbox => checkbox.getAttribute('user-role'));

    const allBlocked = selectedRoles.every(role => role === 'Blocked');
    const noneBlocked = selectedRoles.every(role => role !== 'Blocked');
    const hasAdmin = selectedRoles.includes('Administrator');

    const includesCurrentUser = selectedIds.map(String).includes(String(current_user_id)); // Ensure same type

    const multiSelectOptionsDiv = document.getElementById('multi-select-options');
    const blockOption = document.getElementById('block-all-users');
    const unblockOption = document.getElementById('unblock-all-users');
    const deleteOption = document.getElementById('delete-all-users');
    const passwordResetOption = document.getElementById('send-all-password-reset');

    if (selectedRoles.length > 0) {
        if (allBlocked) {
            unblockOption.style.display = 'block';
            blockOption.style.display = 'none';
        } else if (noneBlocked) {
            blockOption.style.display = 'block';
            unblockOption.style.display = 'none';
        } else {
            blockOption.style.display = 'none';
            unblockOption.style.display = 'none';
        }

        multiSelectOptionsDiv.style.display = 'block';

    } else {
        multiSelectOptionsDiv.style.display = 'none';
    }
}


// Function to reset checkboxes and multi-select options when switching filter tabs
function reset_selection() {

    const tableBody = document.querySelector("#authorTable tbody");
    tableBody.innerHTML = "";

    const selectAllCheckbox = document.getElementById('select-all');
    if (selectAllCheckbox && selectAllCheckbox.checked) {
        selectAllCheckbox.checked = false;
    }
    document.getElementById('multi-select-options').style.display = 'none';
}




// the code for image and other function 
document.addEventListener('DOMContentLoaded', function () {
    var profileImages = document.querySelectorAll('#avatar-img');
    var modal = document.getElementById('modal');
    var modalImg = document.getElementById('modalImg');
    var closeBtn = document.querySelector('.close');

    profileImages.forEach(function (img) {
        img.onclick = function () {
            modal.style.display = "flex"; // Use flex to align center
            modalImg.src = this.src;
        };
    });

    if (closeBtn && modal) {
        closeBtn.onclick = function () {
            modal.style.display = "none";
        };
    }

    // Close the modal if the user clicks anywhere outside of the modal content
    window.onclick = function (event) {
        if (event.target === modal) {
            modal.style.display = "none";
        }
    };
});

document.addEventListener('DOMContentLoaded', (event) => {
    const mainContentElement = document.querySelector('.main-content');
    if (mainContentElement) {
        const images = mainContentElement.getElementsByTagName('img');
        for (let img of images) {
            img.addEventListener('contextmenu', (e) => {
                e.preventDefault();
            });
        }
    }
});


// function for formatting date
function format_date(dateString) {
    // Check if the date string is not empty
    if (dateString) {
        // Create a Date object from the date string
        const date = new Date(dateString);

        // Define an array with month names
        const monthNames = [
            "January", "February", "March", "April", "May", "June",
            "July", "August", "September", "October", "November", "December"
        ];

        // Get month name, day, and year
        const month = monthNames[date.getMonth()]; // Months are zero-based
        const day = date.getDate();
        const year = date.getFullYear();

        // Format the date into "Month day, year"
        const formattedDate = `${month} ${day}, ${year}`;

        return formattedDate;
    }

    // Return false if the date string is empty or not valid
    return false;
}


function user_filter_active_tab() {
    const filterTabs = document.getElementById('filter-tabs');

    if (!filterTabs) {
        show_author_kit_toast(__('Filter Tabs Not Found', 'author-kit'), 'error');
        return;
    }

    function handleTabClick(event) {
        // Remove active styles from all tabs
        filterTabs.querySelectorAll('p').forEach(element => {
            element.style.color = 'black';
            element.style.fontWeight = 'normal';
        });

        // Add active styles to the clicked tab
        event.target.style.color = '#4e6fe7';
        event.target.style.fontWeight = 'bolder';
    }

    // Attach click event dynamically for all tabs
    filterTabs.addEventListener('click', function (event) {
        if (event.target.tagName === 'P') {
            handleTabClick(event);
        }
    });

    // Set the first tab as active by default after roles are loaded
    const observer = new MutationObserver(() => {
        const firstTab = filterTabs.querySelector('p');
        if (firstTab) {
            handleTabClick({ target: firstTab });
            observer.disconnect();
        }
    });

    observer.observe(filterTabs, { childList: true });
}


function setActiveTab(button) {
    // Get all buttons
    const buttons = document.querySelectorAll('#tab-nav-top > button');

    // Remove active class from all buttons
    buttons.forEach(btn => btn.classList.remove('active'));

    // Add active class to the clicked button
    button.classList.add('active');
}


// Function that open confirmation delete modal
function openDeleteUserModal(userIds) {
    const modal = document.getElementById('delete-user-modal');
    const confirmDeleteBtn = document.getElementById('confirm-delete');
    const cancelDeleteBtn = document.getElementById('cancel-delete');
    const attributeUserSelect = document.getElementById('attribute-user-select');
    const modalHeading = document.getElementById('modal-heading');
    const modalUserSpecify = document.getElementById('modal-user-specify');
    const modalDescription = document.getElementById('modal-description');
    const deleteAllContentRadio = document.querySelector('input[value="delete_all_content"]');

    // Function to get username from the table row
    function getUsernameFromTable(userId) {
        const userRow = document.querySelector(`input.row-checkbox[value="${userId}"]`)?.closest('tr');
        if (userRow) {
            const username = userRow.querySelector('#user-name-display')?.textContent.trim().replace('@', '');
            return username || `User #${userId}`;
        }
        return `User #${userId}`;
    }

    // Set default radio selection to "Delete all content"
    deleteAllContentRadio.checked = true;
    attributeUserSelect.disabled = true;

    if (userIds.length === 1) {
        const username = getUsernameFromTable(userIds[0]);
        modalHeading.textContent = __('Delete User', 'author-kit');

        modalUserSpecify.innerHTML = sprintf(
            // translators: 1: user ID, 2: display name.
            __('You have specified this user for deletion:<br>ID #%1$s: %2$s', 'author-kit'),
            userIds[0],
            username
        );

        modalDescription.textContent = __('What should be done with content owned by this user?', 'author-kit');
    } else {
        modalHeading.textContent = __('Delete Users', 'author-kit');

        modalUserSpecify.innerHTML = sprintf(
            // translators: %s is the list of the users selected for deletion.
            __('You have specified these users for deletion:<br>%s', 'author-kit'),
            userIds.map(id => {
                const userIdNum = parseInt(id); // Ensure it's a number
                const isCurrentUser = userIdNum === parseInt(current_user_id); // Compare properly
                const label = sprintf(
                    // translators: 1: user ID, 2: display name.
                    __('ID #%1$s: %2$s', 'author-kit'),
                    userIdNum,
                    getUsernameFromTable(userIdNum));
                return isCurrentUser ? `${label} <strong>(${__('Current User cannot be deleted', 'author-kit')})</strong>` : label;
            }).join('<br>')
        );


        modalDescription.textContent = __('What should be done with content owned by these users?', 'author-kit');
    }

    // Show the modal
    modal.style.display = 'block';

    // Fetch users for selection dropdown
    fetch(author_kit_user_table_vars.ajax_url, {
        method: 'POST',
        headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
        body: new URLSearchParams({
            action: 'author_kit_get_users_list',
            nonce: author_kit_user_table_vars.nonce
        })
    })
        .then(response => response.json())
        .then(data => {
            if (data.success) {
                data.data.users.forEach(user => {
                    if (!userIds.includes(user.id)) { // Exclude selected users from dropdown
                        const option = document.createElement('option');
                        option.value = user.id;
                        option.textContent = `${user.display_name} (${user.username})`;
                        attributeUserSelect.appendChild(option);
                    }
                });
            } else {
                show_author_kit_toast(data.data.message, 'error');
            }
        })
        .catch(error => show_author_kit_toast(__('Failed to Load Users List', 'author-kit'), 'error'));


    // Handle confirm delete
    confirmDeleteBtn.onclick = function () {
        const action = document.querySelector('input[name="delete_action"]:checked').value;
        if (action === "attribute_content") {
            const attributeUser = attributeUserSelect.value;
            delete_user(userIds, attributeUser);
        } else if (action === "delete_all_content") {
            delete_user(userIds, null);
        } else {
            show_author_kit_toast(__('Error in Deleting User', 'author-kit'), 'error');
        }
        closeModal();
    };

    // Hide modal on cancel
    cancelDeleteBtn.onclick = closeModal;

    // Enable/disable user select based on radio selection
    document.querySelectorAll('input[name="delete_action"]').forEach(input => {
        input.addEventListener('change', function () {
            attributeUserSelect.disabled = this.value !== 'attribute_content';
        });
    });

    // Close modal function (clears user select)
    function closeModal() {
        modal.style.display = 'none';
        attributeUserSelect.innerHTML = ''; // Ensure dropdown resets
    }
}

