jQuery(document).ready(function($) {
    // Function to load posts
    function loadPosts(container, page, search = '', category = '', author = '', sortOrder = '') {
        var $container = $('#' + container);
        var $postsList = $container.find('.rswpthemes-awt-posts-list');
        var postsPerPage = $postsList.data('posts-per-page');
        var categories = $postsList.data('categories');
        var postsPerRow = $postsList.data('posts-per-row');
        var layout = $postsList.data('layout');

        $.ajax({
            url: rswpthemes_awt_filerable_posts_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'rswpthemes_awt_filerable_posts_load',
                page: page,
                search: search,
                posts_per_page: postsPerPage,
                categories: categories,
                posts_per_row: postsPerRow,
                category: category,
                author: author,
                sort_order: sortOrder,
                layout: layout,
                container: container
            },
            success: function(response) {
                if (response.success) {
                    if (page === 1) {
                        $postsList.html(response.data.html);
                    } else {
                        $postsList.append(response.data.html);
                    }

                    var $loadMore = $container.find('.rswpthemes-awt-load-more-posts');
                    if (page >= response.data.max_pages) {
                        $loadMore.hide();
                    } else {
                        $loadMore.show().data('page', page + 1);
                    }
                } else {
                    console.error('Failed to load posts:', response.data);
                }
            },
            error: function(xhr, status, error) {
                console.error('AJAX error loading posts:', error);
            }
        });
    }

    // Function to load a post in the popup
    function loadPostInPopup($container, postId) {
        var $popup = $container.find('.rswpthemes-awt-post-popup');
        var $popupBody = $popup.find('.rswpthemes-awt-post-popup-body');
        var $form = $container.find('.rswpthemes-awt-posts-search-form');
        var search = $form.find('input[name="s"]').val();
        var category = $form.find('select[name="category"]').val();
        var author = $form.find('select[name="author"]').val();
        var sortOrder = $form.find('select[name="sort_order"]').val();

        $popupBody.html('<p>Loading...</p>');
        $popup.addClass('active');

        $.ajax({
            url: rswpthemes_awt_filerable_posts_vars.ajax_url,
            type: 'POST',
            data: {
                action: 'rswpthemes_awt_fetch_full_post',
                post_id: postId,
                search: search,
                category: category,
                author: author,
                sort_order: sortOrder
            },
            success: function(response) {
                if (response.success) {
                    $popupBody.html(response.data.html);
                    repositionPopupNavigation();
                } else {
                    $popupBody.html('<p>Error loading post: ' + response.data.message + '</p>');
                }
            },
            error: function(xhr, status, error) {
                $popupBody.html('<p>Error loading post: ' + error + '</p>');
            }
        });
    }

    // Initial load for all containers
    $('.rswpthemes-awt-filterable-posts-container').each(function() {
        loadPosts($(this).attr('id'), 1);
        console.log('Initialized container:', $(this).attr('id'));
    });

    // Load more button click
    $('.rswpthemes-awt-load-more-posts').on('click', function() {
        var $this = $(this);
        var container = $this.data('container');
        var page = $this.data('page');
        var $form = $('#' + container).find('.rswpthemes-awt-posts-search-form');
        var search = $form.find('input[name="s"]').val();
        var category = $form.find('select[name="category"]').val();
        var author = $form.find('select[name="author"]').val();
        var sortOrder = $form.find('select[name="sort_order"]').val();
        loadPosts(container, page, search, category, author, sortOrder);
    });

    // Search form submit
    $('.rswpthemes-awt-posts-search-form').on('submit', function(e) {
        e.preventDefault();
        var $this = $(this);
        var container = $this.data('container');
        var search = $this.find('input[name="s"]').val();
        var category = $this.find('select[name="category"]').val();
        var author = $this.find('select[name="author"]').val();
        var sortOrder = $this.find('select[name="sort_order"]').val();
        loadPosts(container, 1, search, category, author, sortOrder);
    });

    // Handle post title click to show popup
    $(document).on('click', '.post-title-link', function(e) {
        e.preventDefault();
        var $this = $(this);
        var postId = $this.data('post-id');
        var $container = $this.closest('.rswpthemes-awt-filterable-posts-container');
        loadPostInPopup($container, postId);
    });

    // Handle next/previous post navigation
    $(document).on('click', '.rswpthemes-awt-post-popup-prev, .rswpthemes-awt-post-popup-next', function() {
        var $this = $(this);
        if ($this.hasClass('disabled')) return; // Do nothing if disabled

        var postId = $this.data('post-id');
        var $container = $this.closest('.rswpthemes-awt-filterable-posts-container');
        loadPostInPopup($container, postId);
    });

    // Handle related post click
    $(document).on('click', '.related-post-link', function(e) {
        e.preventDefault();
        var $this = $(this);
        var postId = $this.data('post-id');
        var $container = $this.closest('.rswpthemes-awt-filterable-posts-container');
        loadPostInPopup($container, postId);
    });

    // Close the popup when the close button is clicked
    $(document).on('click', '.rswpthemes-awt-post-popup-close', function() {
        var $popup = $(this).closest('.rswpthemes-awt-post-popup');
        $popup.removeClass('active');
    });

    // Close the popup when the overlay is clicked
    $(document).on('click', '.rswpthemes-awt-post-popup-overlay', function() {
        var $popup = $(this).closest('.rswpthemes-awt-post-popup');
        $popup.removeClass('active');
    });

    // Handle category click to filter posts
    $(document).on('click', '.filter-category', function() {
        var $this = $(this);
        var categoryId = $this.data('category-id');
        var $container = $this.closest('.rswpthemes-awt-filterable-posts-container');
        var $form = $container.find('.rswpthemes-awt-posts-search-form');

        $form.find('input[name="s"]').val('');
        $form.find('select[name="author"]').val('');
        $form.find('select[name="category"]').val(categoryId);
        $form.trigger('submit');

        $container.find('.rswpthemes-awt-post-popup').removeClass('active');
    });

    // Handle author click to filter posts
    $(document).on('click', '.filter-author', function() {
        var $this = $(this);
        var authorId = $this.data('author-id');
        var $container = $this.closest('.rswpthemes-awt-filterable-posts-container');
        var $form = $container.find('.rswpthemes-awt-posts-search-form');

        $form.find('input[name="s"]').val('');
        $form.find('select[name="category"]').val('');
        $form.find('select[name="author"]').val(authorId);
        $form.trigger('submit');

        $container.find('.rswpthemes-awt-post-popup').removeClass('active');
    });
    $(document).on('keydown', function(e) {
        if ($('.rswpthemes-awt-post-popup.active').length) {
            if (e.key === 'ArrowLeft') {
                $('.rswpthemes-awt-post-popup-prev:not(.disabled)').trigger('click');
            } else if (e.key === 'ArrowRight') {
                $('.rswpthemes-awt-post-popup-next:not(.disabled)').trigger('click');
            }
        }
    });
    // Close the popup with the "Esc" key
    $(document).on('keydown', function(e) {
        if (e.key === 'Escape') {
            $('.rswpthemes-awt-post-popup.active').removeClass('active');
        }
    });
});