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

let postPerPage = 10;           // Default posts per page is 10
let selectedPostIds = [];       // Stores IDs of posts whose checkboxes are selected
let orderBy = "date";           // Default table order by date
let orderDirection = "DESC";    // Default table order direction is descending
let search_key = "";            // Global variable to get store search value
let postStatus = "all";         // Table fetch all posts as per default

// Permissions allowed against a user
let is_admin = author_kit_post_table_vars.is_admin;
let is_edit_posts = author_kit_post_table_vars.is_edit_posts;
let is_edit_others_posts = author_kit_post_table_vars.is_edit_others_posts;
let is_edit_published_posts = author_kit_post_table_vars.is_edit_published_posts;
let is_edit_private_posts = author_kit_post_table_vars.is_edit_private_posts;
let is_publish_posts = author_kit_post_table_vars.is_publish_posts;
let is_delete_posts = author_kit_post_table_vars.is_delete_posts;
let is_delete_others_posts = author_kit_post_table_vars.is_delete_others_posts;
let is_delete_published_posts = author_kit_post_table_vars.is_delete_published_posts;
let is_delete_private_posts = author_kit_post_table_vars.is_delete_private_posts;
let is_read_private_posts = author_kit_post_table_vars.is_read_private_posts;


document.addEventListener('DOMContentLoaded', function () {
    initialize();
});

// Function to initialize and load post data
function initialize() {
    load_post_table();

    get_total_posts_by_status();

    add_new_post_on_click();

    // Debounced search function
    const debouncedLoadPostTable = debounce(() => load_post_table(), 750);

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

    initialize_sorting();
    on_change_option();
    on_click_next();
    on_click_previous();
    post_filter_active_tab();


    document.getElementById('trash-all-posts').addEventListener('click', function (e) {
        e.preventDefault();
        trash_posts(selectedPostIds);
    });

    document.getElementById('restore-all-posts').addEventListener('click', function (e) {
        e.preventDefault();
        restore_posts(selectedPostIds);
    });

    document.getElementById('delete-all-posts').addEventListener('click', function (e) {
        e.preventDefault();
        delete_posts_permanently(selectedPostIds);
    });

}

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

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

function reload() {
    postStatus = 'all';
    load_post_table();
    get_total_posts_by_status();
}

// 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 Post table
function load_post_table(page_id = 1) {

    selectedPostIds = [];
    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_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_load_posts',
            pageId: page_id,
            order_by: orderBy,
            order_direction: orderDirection,
            limit: postPerPage,
            nonce: author_kit_post_table_vars.nonce,
            search: search_key,
            postStatus: postStatus,
        })
    })
        .then(response => response.json())
        .then(data => {

            // Post data table is formed by calling this function
            form_post_table(data.post_data, data.pagination_data);
        })
        .catch(error => {
            // Hide the loader if there's an error
            loader.style.display = "none";

            show_author_kit_toast(__('Error in Loading Post Table', 'author-kit'), 'error')
        });

}



function form_post_table(post_data, pagination_data) {

    try {
        const tbody = document.querySelector('#postTable tbody');
        tbody.innerHTML = '';

        publish_text = __('Publish Post', 'author-kit');
        review_text = __('Submit for Review', 'author-kit');
        view_post_text = __('View Post', 'author-kit');
        preview_post_text = __('Preview Post', 'author-kit');
        edit_post_text = __('Edit Post', 'author-kit');
        trash_post_text = __('Trash Post', 'author-kit');
        restore_post_text = __('Restore Post', 'author-kit');
        delete_post_text = __('Delete Post', 'author-kit');

        if (post_data.length != 0) {
            const fragment = document.createDocumentFragment(); // Use DocumentFragment to minimize reflows

            post_data.forEach(item => {

                const row = document.createElement("tr");

                // Create checkbox cell
                const checkboxCell = document.createElement("td");
                const checkbox = document.createElement("input");
                checkbox.type = "checkbox";
                checkbox.className = "row-checkbox";
                checkbox.id = "row-checkbox";
                checkbox.value = item.ID;
                checkbox.setAttribute("post-status", item.status.toLowerCase());

                /* 
                this commented line is added to trash and restore condition 
                because checkbox will only be added when these conditions met 
                due to proper functionality of multi select options 
                */
                // checkboxCell.appendChild(checkbox); 

                row.appendChild(checkboxCell);

                // Create post title and thumbnail cell
                const titleCell = document.createElement("td");
                titleCell.id = "author-kit-post-title";
                const contentWrapper = document.createElement("div");
                contentWrapper.className = "post-content-wrapper";
                const thumbnail = document.createElement("img");
                thumbnail.src = item.postThumbnail;
                thumbnail.alt = item.postTitle;
                thumbnail.className = "post-thumbnail";
                const title = document.createElement("h6");
                title.className = "post-title";
                title.textContent = item.postTitle;
                contentWrapper.appendChild(thumbnail);
                contentWrapper.appendChild(title);
                titleCell.appendChild(contentWrapper);
                row.appendChild(titleCell);


                // Create author cell
                const authorCell = document.createElement("td");
                authorCell.classList.add("post-contributors");
                const avatar = document.createElement("img");
                avatar.src = item.avatar;
                avatar.alt = item.author_name;
                avatar.width = 35;
                avatar.height = 35;
                avatar.style = "border-radius: 50%; vertical-align: middle; margin-right: 10px;";
                authorCell.appendChild(avatar);
                // Handle coauthors text logic (based on the coauthors array)
                const coauthors = item.coauthors || []; // Array of coauthors
                let authorText;
                if (coauthors.length === 1) {
                    authorText = `${item.author_name} & ${coauthors[0].name}`;
                } else if (coauthors.length > 1) {
                    authorText = sprintf(
                        /* translators: 1: Author Name, 2: No of Coauthors */
                        __('%1$s & %2$s others', 'author-kit'),
                        item.author_name,
                        coauthors.length
                    )
                } else {
                    authorText = item.author_name; // No coauthors case
                }
                // Append the dynamic author/coauthor text
                authorCell.appendChild(document.createTextNode(authorText));
                // Add post ID for dynamic identification when clicking the author cell
                authorCell.dataset.postId = item.ID;
                // Append the author cell to the current row
                row.appendChild(authorCell);



                // Create status cell
                const statusCell = document.createElement("td");
                const statusLabel = document.createElement("span");
                statusLabel.className = `status-label ${item.status.toLowerCase().replace(' ', '-')}`;
                statusLabel.textContent = item.status;
                statusCell.appendChild(statusLabel);
                row.appendChild(statusCell);

                // Create post date cell
                const dateCell = document.createElement("td");
                dateCell.textContent = item.postDate;
                row.appendChild(dateCell);

                // Create actions dropdown cell
                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";

                // Conditional action buttons

                // Publish Post button
                if (item.status.toLowerCase() !== 'publish' && item.status.toLowerCase() !== 'trash' && item.status.toLowerCase() !== 'private') {
                    let canPublish = false;

                    // Case 1: User can publish their own posts
                    if (is_publish_posts && item.author_id == item.current_user_id) {
                        canPublish = true;
                    }

                    // Case 2: User can publish others' posts
                    if (is_publish_posts && is_edit_others_posts && item.author_id != item.current_user_id) {
                        canPublish = true;
                    }

                    // Append the publish option only if they are allowed
                    if (canPublish) {
                        const publishOption = document.createElement("a");
                        publishOption.className = "dropdown-item publish-post-button";
                        publishOption.setAttribute("post-id", item.ID);
                        publishOption.innerHTML = `<i class="fa-solid fa-arrow-up-from-bracket"></i> <span style="margin-left: 8px;">${is_publish_posts ? publish_text : review_text}</span>`;
                        dropdownMenu.appendChild(publishOption);
                    }
                }

                // View and Preview button
                if (item.status.toLowerCase() !== 'trash') {
                    let canPreview = false;
                    let canViewPrivate = false;
                    let viewOption = document.createElement("a");
                    viewOption.className = "dropdown-item view-post-button";
                    viewOption.target = "_blank";

                    const isOwnPost = item.author_id == item.current_user_id;

                    // Case 1: Publicly published post
                    if (item.status.toLowerCase() === 'publish') {
                        viewOption.href = item.url;
                        viewOption.innerHTML = `<i class="fa-solid fa-eye"></i> <span style="margin-left: 8px;">${view_post_text}</span>`;
                        dropdownMenu.appendChild(viewOption);
                    }

                    // Case 2: Private post
                    else if (item.status.toLowerCase() === 'private') {
                        if (
                            isOwnPost ||
                            is_admin ||
                            is_read_private_posts
                        ) {
                            canViewPrivate = true;
                        }

                        if (canViewPrivate) {
                            viewOption.href = item.url;
                            viewOption.innerHTML = `<i class="fa-solid fa-eye"></i> <span style="margin-left: 8px;">${view_post_text}</span>`;
                            dropdownMenu.appendChild(viewOption);
                        }
                    }

                    // Case 3: Draft, pending, or future post
                    else {
                        if (isOwnPost && is_edit_posts) {
                            canPreview = true;
                        }
                        if (is_admin) {
                            canPreview = true;
                        }
                        if (is_edit_others_posts && !isOwnPost) {
                            canPreview = true;
                        }

                        if (canPreview) {
                            viewOption.href = item.url; // Should be preview URL
                            viewOption.innerHTML = `<i class="fa-solid fa-eye"></i> <span style="margin-left: 8px;">${preview_post_text}</span>`;
                            dropdownMenu.appendChild(viewOption);
                        }
                    }
                }

                // Edit Post Button
                if (item.status.toLowerCase() !== 'trash') {
                    let canEdit = false;

                    // Case 1: User can edit their own posts
                    if (is_edit_posts && item.author_id == item.current_user_id) {
                        canEdit = true;
                    }

                    // Case 2: User can edit others' posts
                    if (is_edit_others_posts && item.author_id != item.current_user_id) {
                        canEdit = true;
                    }

                    // Case 3: User can edit private posts of others only when it will  have capability to edit others and private posts
                    if (item.status.toLowerCase() === 'private' && item.author_id != item.current_user_id && (!is_edit_others_posts || !is_edit_private_posts)) {
                        canEdit = false;
                    }

                    // Case 4: User can edit published posts (but only if they meet one of the above conditions)
                    if (item.status.toLowerCase() === 'publish' && !is_edit_published_posts) {
                        canEdit = false; // If they don't have `is_edit_published_posts`, they can't edit published posts
                    }

                    // Append the edit option only if they are allowed
                    if (canEdit) {
                        const editOption = document.createElement("a");
                        editOption.className = "dropdown-item edit-post-button";
                        editOption.href = `post.php?post=${item.ID}&action=edit`;
                        editOption.innerHTML = `<i class="fa-solid fa-pen-to-square"></i> <span style="margin-left: 8px;">${edit_post_text}</span>`;
                        dropdownMenu.appendChild(editOption);
                    }
                }

                // trash post button
                if (item.status.toLowerCase() !== 'trash') {
                    let canTrash = false;

                    // Case 1: User can delete their own posts
                    if (is_delete_posts && item.author_id == item.current_user_id) {
                        canTrash = true;
                    }

                    // Case 2: User can delete others' posts
                    if (is_delete_others_posts && item.author_id != item.current_user_id) {
                        canTrash = true;
                    }

                    // Case 3: If post is private than it will only be deleted when user have capability to delete others and private posts
                    if (item.status.toLowerCase() === 'private' && item.author_id != item.current_user_id && (!is_delete_others_posts || !is_delete_private_posts)) {
                        canTrash = false;
                    }

                    // Case 4: If post is published, ensure `delete_published_posts` is also checked
                    if (item.status.toLowerCase() === 'publish' && !is_delete_published_posts) {
                        canTrash = false; // User cannot trash published posts unless they have the capability
                    }

                    // Append the trash option only if the user is allowed to delete
                    if (canTrash) {
                        const trashOption = document.createElement("a");
                        trashOption.className = "dropdown-item trash-post-button";
                        trashOption.setAttribute("post-id", item.ID);
                        trashOption.innerHTML = `<i class="fa-solid fa-trash-can-arrow-up"></i> <span style="margin-left: 8px;">${trash_post_text}</span>`;
                        dropdownMenu.appendChild(trashOption);

                        /* 
                        this below line is added to trash and restore condition 
                        because checkbox will only be added when these conditions met 
                        due to proper functionality of multi select options rather than adding it above in 1st td 
                        */
                        checkboxCell.appendChild(checkbox);
                    }
                }

                // restore post button
                if (item.status.toLowerCase() === 'trash') {
                    let canRestore = false;

                    // Case 1: User can restore their own posts
                    if (is_delete_posts && item.author_id == item.current_user_id) {
                        canRestore = true;
                    }

                    // Case 2: User can restore others' posts
                    if (is_delete_others_posts && item.author_id != item.current_user_id) {
                        canRestore = true;
                    }

                    // Case 3: If the post was published before trashing, check `delete_published_posts`
                    if (item.was_published && !is_delete_published_posts) {
                        canRestore = false; // Prevent restoring previously published posts without permission
                    }

                    // Append Restore Option if the user has permission
                    if (canRestore) {
                        const restoreOption = document.createElement("a");
                        restoreOption.className = "dropdown-item restore-post-button";
                        restoreOption.setAttribute("post-id", item.ID);
                        restoreOption.innerHTML = `<i class="fa-solid fa-arrow-rotate-left"></i> <span style="margin-left: 8px;">${restore_post_text}</span>`;

                        dropdownMenu.appendChild(restoreOption);

                        /* 
                        this below line is added to trash and restore condition 
                        because checkbox will only be added when these conditions met 
                        due to proper functionality of multi select options rather than adding it above in 1st td 
                        */
                        checkboxCell.appendChild(checkbox);

                    }
                }

                // delete post button
                if (item.status.toLowerCase() === 'trash') {
                    let canDeletePermanently = false;

                    // Case 1: User can permanently delete their own posts
                    if (is_delete_posts && item.author_id == item.current_user_id) {
                        canDeletePermanently = true;
                    }

                    // Case 2: User can permanently delete others' posts
                    if (is_delete_others_posts && item.author_id != item.current_user_id) {
                        canDeletePermanently = true;
                    }

                    // Case 3: If the post was published before trashing, check `delete_published_posts`
                    if (item.was_published && !is_delete_published_posts) {
                        canDeletePermanently = false; // Prevent deletion of previously published posts without permission
                    }

                    // Append Delete Permanently Option if the user has permission
                    if (canDeletePermanently) {
                        const deleteOption = document.createElement("a");
                        deleteOption.className = "dropdown-item delete-post-button";
                        deleteOption.setAttribute("post-id", item.ID);
                        deleteOption.innerHTML = `<i class="fa-solid fa-trash-can"></i> <span style="margin-left: 8px;">${delete_post_text}</span>`;
                        dropdownMenu.appendChild(deleteOption);
                    }
                }


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

                fragment.appendChild(row);
            });

            tbody.appendChild(fragment); // Batch insert all rows at once

            select_boxes_functionality();

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

            paragraph.textContent = __("No posts match your search. Try a different keyword.", "author-kit");
            cell.setAttribute("colspan", "6"); // our table has 6 columns
            cell.style.textAlign = "center";
            cell.style.padding = "20px";

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

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

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

        /* translators: 1: current page number, 2: total number of pages */
        pageNumbersSpan.innerHTML = sprintf(
            __('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 posts */
            __('Showing %1$s to %2$s of %3$s Posts', 'author-kit'),
            pagination_data.start_index,
            pagination_data.ending_index,
            pagination_data.total_posts
        );

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

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

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

        document.querySelectorAll('.publish-post-button').forEach(function (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const postId = this.getAttribute('post-id');
                publish_post(postId);

            });
        });
        document.querySelectorAll('.trash-post-button').forEach(function (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const postId = this.getAttribute('post-id');
                trash_posts([postId]);

            });
        });
        document.querySelectorAll('.restore-post-button').forEach(function (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const postId = this.getAttribute('post-id');
                restore_posts([postId]);

            });
        });
        document.querySelectorAll('.delete-post-button').forEach(function (button) {
            button.addEventListener('click', function (e) {
                e.preventDefault();
                const postId = this.getAttribute('post-id');
                delete_posts_permanently([postId]);

            });
        });

        // Add event listener to open the relevant contributors card when the author cell is clicked
        document.querySelectorAll(".post-contributors").forEach(cell => {
            cell.addEventListener("click", function () {
                const postId = this.dataset.postId; // Get the post ID from dataset
                const post = post_data.find(p => p.ID === parseInt(postId, 10)); // Find matching post

                if (post) {
                    updateContributorsCard(post); // Update and open contributors card
                }
            });
        });

        // Add event listener to close the card (using existing 'close-btn')
        document.getElementById('close-btn').addEventListener('click', function () {
            const contributorsCard = document.getElementById('contributors-card');
            contributorsCard.style.display = 'none'; // Hide the card on close
        });


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

        document.querySelectorAll('.tooltip-container').forEach(container => {
            const tooltipText = container.querySelector('.tooltip-text');
            container.addEventListener('mouseover', () => {
                tooltipText.style.visibility = 'visible';
                tooltipText.style.opacity = '1';
            });
            container.addEventListener('mouseout', () => {
                tooltipText.style.visibility = 'hidden';
                tooltipText.style.opacity = '0';
            });
        });
    }
    finally {
        // Get the loader element
        const loader = document.getElementById("loader");
        // hide the loader after forming table
        loader.style.display = "none";
    }
}

// Count total number of posts against each status
function get_total_posts_by_status() {
    fetch(author_kit_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: new URLSearchParams({
            action: 'author_kit_get_total_posts_by_status',
            nonce: author_kit_post_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 post status in the response and create a tab
                Object.keys(data.data).forEach(status => {
                    // Create the status paragraph element
                    const statusTab = document.createElement('p');
                    statusTab.id = `${status}-posts`; // Set a unique ID for each status
                    statusTab.textContent = `${status.charAt(0).toUpperCase() + status.slice(1)}`; // Add status name and post count
                    statusTab.onclick = () => {
                        // Add your onclick logic here
                        postStatus = status;
                        load_post_table(1);
                    };

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

                    // Append the status tab and its span to the filter-tabs div
                    filterTabs.appendChild(statusTab);
                    filterTabs.appendChild(statusInfo);
                });

            } else {
                show_author_kit_toast(__('Error in Loading Filter Tabs Post Count', 'author-kit'), 'error');
            }
        })
        .catch(error => show_author_kit_toast(__('Failed to Load Filter Tabs Post Count', 'author-kit'), 'error'));
}

// Function to dynamically populate contributors card based on post data
function updateContributorsCard(post) {
    const contributorsList = document.getElementById("contributors-list");

    // Clear previous data to avoid duplication
    contributorsList.innerHTML = "";

    // Add the main author (preserving your example structure)
    const authorData = {
        avatar: post.avatar,
        name: post.author_name,
        title: "Author"
    };
    appendContributorRow(contributorsList, authorData);

    // Add coauthors dynamically
    post.coauthors.forEach(coauthor => {
        const coauthorData = {
            avatar: coauthor.avatar,
            name: coauthor.name,
            title: "Coauthor"
        };
        appendContributorRow(contributorsList, coauthorData);
    });

    // Display the contributors card
    document.getElementById("contributors-card").style.display = "block";
}

// Function to append a single contributor row (matches your structure)
function appendContributorRow(contributorsList, contributor) {
    const item = document.createElement('div');
    item.classList.add('contributor');

    item.innerHTML = `
        <img class="avatar" src="${contributor.avatar}" alt="${contributor.name}">
        <div class="details">
            <span class="name">${contributor.name}</span>
            <span class="title">${contributor.title}</span>
        </div>
    `;

    contributorsList.appendChild(item);
}

// 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("#postTable thead");
            current_page_ID = tableHead.getAttribute("current-page-id");

            load_post_table(current_page_ID);
        });
    });
}

function publish_post(postId) {

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

    fetch(author_kit_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'author_kit_publish_post',
            nonce: author_kit_post_table_vars.nonce,
            post_id: postId,
        })
    })
        .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 Publish Post', 'author-kit'), 'error'));

}

function trash_posts(postIds) {
    if (!confirm(__('Are you sure you want to trash the selected posts?', 'author-kit'))) {
        return; // Exit the function if the user cancels
    }

    show_author_kit_toast(__('Trashing the Post(s)... Please Wait!', 'author-kit'), 'performing');

    fetch(author_kit_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'author_kit_trash_posts',
            nonce: author_kit_post_table_vars.nonce,
            post_ids: JSON.stringify(postIds),
        })
    })
        .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 Trash Post(s)', 'author-kit'), 'error'));
}

function restore_posts(postIds) {
    if (!confirm(__('Are you sure you want to restore the selected posts?', 'author-kit'))) {
        return; // Exit if the user cancels the confirmation
    }

    show_author_kit_toast(__('Restoring the Post(s)... Please Wait!', 'author-kit'), 'performing');

    fetch(author_kit_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'author_kit_restore_posts',
            nonce: author_kit_post_table_vars.nonce,
            post_ids: JSON.stringify(postIds),
        })
    })
        .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 Restore Post(s)', 'author-kit'), 'error'));
}

function delete_posts_permanently(postIds) {
    if (!confirm(__('Are you sure you want to permanently delete the selected posts? This action cannot be undone!', 'author-kit'))) {
        return; // Exit if the user cancels the confirmation
    }

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

    fetch(author_kit_post_table_vars.ajax_url, {
        method: 'POST',
        headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
        },
        body: new URLSearchParams({
            action: 'author_kit_delete_posts_permanently',
            nonce: author_kit_post_table_vars.nonce,
            post_ids: JSON.stringify(postIds),
        })
    })
        .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 Post(s)', 'author-kit'), 'error'));
}


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
        postPerPage = this.value;
        load_post_table(1);
    });
}

function on_click_next() {
    nextPageBtn = document.getElementById("nextPage");
    nextPageBtn.addEventListener('click', function () {
        nextPageId = nextPageBtn.getAttribute("next-page-id");
        // Function to check and run the pagination for desired table loader funtion based upon attribute
        load_post_table(nextPageId);;
    });
}

function on_click_previous() {
    prevPageBtn = document.getElementById("prevPage");
    prevPageBtn.addEventListener('click', function () {
        prevPageId = prevPageBtn.getAttribute("prev-page-id");
        // Function to check and run the pagination for desired table loader funtion based upon attribute
        load_post_table(prevPageId);
    })
}


// Select CheckBoxes functionality for the 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'); // Adjusted ID for 'Unblock' option
    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    // "Select All" checkbox change event
    selectAllCheckbox.addEventListener('change', function () {
        let selectAllIds = []; // Temporary array to store IDs of selected checkboxes

        // Check/uncheck all row checkboxes based on the header checkbox
        rowCheckboxes.forEach(checkbox => {
            checkbox.checked = this.checked;
            if (this.checked) {
                selectAllIds.push(checkbox.value);
            }
        });

        selectedPostIds = selectAllIds;
        update_multi_select_options();
    });

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

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

            update_multi_select_options();
            selectAllCheckbox.checked = selectedPostIds.length === rowCheckboxes.length;
        });
    });
}

// Function to update multi-select options display
function update_multi_select_options() {

    const rowCheckboxes = document.querySelectorAll('.row-checkbox');

    // Retrieve statuses for selected checkboxes
    const selectedPostStatus = Array.from(rowCheckboxes)
        .filter(checkbox => checkbox.checked) // Get only checked checkboxes
        .map(checkbox => checkbox.getAttribute('post-status')); // Get post-status attribute directly

    const totalSelected = selectedPostStatus.length;
    const allTrash = totalSelected > 0 && selectedPostStatus.every(status => status === 'trash');
    const noneTrash = totalSelected > 0 && selectedPostStatus.every(status => status !== 'trash');
    const mixedTrash = totalSelected > 0 && !allTrash && !noneTrash; // Some are trash, some are not

    // Select elements
    const multiSelectOptionsDiv = document.getElementById('multi-select-options');
    const trashOption = document.getElementById('trash-all-posts');
    const restoreOption = document.getElementById('restore-all-posts');
    const deleteOption = document.getElementById('delete-all-posts');

    // Hide all options by default
    trashOption.style.display = 'none';
    restoreOption.style.display = 'none';
    deleteOption.style.display = 'none';
    multiSelectOptionsDiv.style.display = 'none';

    if (totalSelected > 0) {
        if (allTrash) {
            // If all selected posts are in trash, show Restore & Delete based on permissions
            if (is_delete_posts || is_delete_others_posts || is_delete_published_posts) {
                restoreOption.style.display = 'block'; // User can restore posts
                deleteOption.style.display = 'block'; // User can permanently delete
            }
        } else if (noneTrash) {
            // If no selected posts are in trash, show Trash option based on permissions
            if (is_delete_posts || is_delete_others_posts || is_delete_published_posts) {
                trashOption.style.display = 'block';
            }
        } else {
            // If both trashed & non-trashed posts are selected, hide all options
            trashOption.style.display = 'none';
            restoreOption.style.display = 'none';
            deleteOption.style.display = 'none';
        }

        // Show the multi-select options div only if any option is visible
        if (trashOption.style.display === 'block' || restoreOption.style.display === 'block' || deleteOption.style.display === 'block') {
            multiSelectOptionsDiv.style.display = 'block';
        }
    }
}


function set_active_tab(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 post_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 after statuses are loaded
    const observer = new MutationObserver(() => {
        const firstTab = filterTabs.querySelector('p');
        if (firstTab) {
            handleTabClick({ target: firstTab });
            observer.disconnect();
        }
    });

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

// Function to reset checkboxes and multi-select options when switching filter tabs
function reset_selection() {
    const tableBody = document.querySelector("#postTable tbody");
    tableBody.innerHTML = "";

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