jQuery(function ($) {
    // Supports multiple AJAX objects: use one that's present
    const AJAX = window.LCPN_PAGE_VARS;

    if (!AJAX) {
        $('#ai-list-status').text('AJAX configuration not found.');
        return;
    }

    function escapeHtml(text) {
        return $('<div>').text(text).html();
    }

    function renderPagination(totalPages, currentPage) {
        const maxVisible = 7;
        let start = Math.max(1, currentPage - Math.floor(maxVisible / 2));
        let end = start + maxVisible - 1;

        if (end > totalPages) {
            end = totalPages;
            start = Math.max(1, end - maxVisible + 1);
        }

        let html = `<div class="ai-pagination">`;

        // Prev button
        if (currentPage > 1) {
            html += `<button class="pagination-btn" data-page="${currentPage - 1}">«</button>`;
        }

        // First page and left ellipsis
        if (start > 1) {
            html += `<button class="pagination-btn" data-page="1">1</button>`;
            if (start > 2) {
                html += `<span class="pagination-ellipsis">…</span>`;
            }
        }

        // Middle pages
        for (let i = start; i <= end; i++) {
            html += `<button class="pagination-btn${i === currentPage ? ' current' : ''}" data-page="${i}">${i}</button>`;
        }

        // Right ellipsis and last page
        if (end < totalPages) {
            if (end < totalPages - 1) {
                html += `<span class="pagination-ellipsis">…</span>`;
            }
            html += `<button class="pagination-btn" data-page="${totalPages}">${totalPages}</button>`;
        }

        // Next button
        if (currentPage < totalPages) {
            html += `<button class="pagination-btn" data-page="${currentPage + 1}">»</button>`;
        }


        if (totalPages > 10) {
            html += `
                <div class="pagination-jump">
                    &nbsp;|&nbsp; <input type="number" id="pagination-jump-input" min="1" max="${totalPages}" placeholder="Page#" />
                    <button id="pagination-jump-btn" style="display: none;">Go</button>
                </div>
            `;
        }

        html += `</div>`;
        return html;
    }


    function renderTable(items, totalPages = 1, currentPage = 1) {
        const statusEmoji = {
            'publish': '✅',
            'private': '🔒',
            'draft': '📝',
            'pending': '⏳',
            'future': '📅',
            'trash': '🗑️',
            'inherit': '↩️',
            'auto-draft': '⚙️',
            'any': '❓'
        };

        let html = `
        <div id="ai-list-table-wrapper">
            <table class="ai-list-table">
                <thead>
                    <tr>
                        <th></th>
                        <th>Title</th>
                        <th>ID</th>
                        <th>Last Modified</th>
                        <th>Actions</th>
                    </tr>
                </thead>
                <tbody>
    `;

        items.forEach(function (item) {
            const rawTitle = item.post_title || '(Untitled)';
            const title = escapeHtml(rawTitle);
            const date = escapeHtml(item.post_modified || item.post_date || '');
            const postId = item.ID;
            const status = item.post_status || 'draft';
            const emoji = statusEmoji[status] || '📝';
            const permalink = item.permalink || '#';

            const titleHtml = (status !== 'draft')
                ? `<a href="${permalink}" target="_blank" rel="noopener noreferrer">${emoji} ${title}</a>`
                : `${emoji} ${title}`;

            const previewButton = (status === 'draft')
                ? `<button class="icon-btn view-btn" data-post-id="${postId}">
                    👁️<span class="icon-tooltip">Preview</span>
            </button>`
                : `<button class="icon-btn view-btn" data-post-id="${postId}" disabled style="opacity: 0.4; cursor: not-allowed;">
                    👁️<span class="icon-tooltip">Preview</span>
            </button>`;

            html += `
            <tr>
                <td><input type="checkbox" class="row-checkbox" data-post-id="${postId}"></td>
                <td>${titleHtml}</td>
                <td>${postId}</td>
                <td>${date}</td>
                <td>
                    ${previewButton}
                    <a class="icon-btn edit-btn" href="${AJAX.edit_url_prefix}${postId}/edit/">
                        ✏️<span class="icon-tooltip">Edit</span>
                    </a>
                    <button class="icon-btn delete-btn" data-post-id="${postId}">
                        🗑️<span class="icon-tooltip">Delete</span>
                    </button>
                </td>
            </tr>
        `;
        });

        html += `
            </tbody>
        </table>
    </div>
    `;

        // Add pagination below the table
        if (totalPages > 1) {
            html += renderPagination(totalPages, currentPage);
        }

        $('#ai-list').html(html);
    }


    function loadList(showDraftsOnly = true, keyword = '', page = 1) {

        $('#ai-list').html('<div id="ai-list-table-wrapper"><table class="ai-list-table"><tbody><tr><td colspan="5" style="text-align:center;">Loading...</td></tr></tbody></table></div>');

        $.post(AJAX.ajax_url, {
            action: AJAX.prefix + '_list',
            nonce: AJAX.nonce,
            drafts_only: showDraftsOnly ? 1 : 0,
            keyword: keyword,
            page: page
        }, function (res) {
            if (res.success && Array.isArray(res.data.drafts) && res.data.drafts.length > 0) {
                renderTable(res.data.drafts, res.data.total_pages || 1, page);
            } else {
                $('#ai-list').html('<div id="ai-list-table-wrapper"><table class="ai-list-table"><tbody><tr><td colspan="5" style="text-align:center;">No items found.</td></tr></tbody></table></div>');
            }
        });
    }

    // Handle jump to page
    $(document).on('click', '#pagination-jump-btn', function () {
        const pageInput = parseInt($('#pagination-jump-input').val(), 10);
        const keyword = $('#ai-list-search-keyword').val();
        const showDrafts = $('#toggle-drafts-only').is(':checked');

        if (!isNaN(pageInput) && pageInput >= 1 && pageInput <= totalPages) {
            loadList(showDrafts, keyword, pageInput);
        } else {
            alert(`Please enter a number between 1 and ${totalPages}`);
        }
    });
    $(document).on('keypress', '#pagination-jump-input', function (e) {
        if (e.which === 13) {
            $('#pagination-jump-btn').click();
        }
    });

    $(document).on('click', '.pagination-btn', function () {
        const page = $(this).data('page');
        const keyword = $('#ai-list-search-keyword').val();
        const showDrafts = $('#toggle-drafts-only').is(':checked');
        loadList(showDrafts, keyword, page);
    });

    $(document).on('click', '#ai-list-search-btn', function () {
        const keyword = $('#ai-list-search-keyword').val();
        const showDrafts = $('#toggle-drafts-only').is(':checked');
        loadList(showDrafts, keyword);
    });

    //  trigger search on "Enter" key:
    $(document).on('keypress', '#ai-list-search-keyword', function (e) {
        if (e.which === 13) {
            $('#ai-list-search-btn').click();
        }
    });


    // Handle toggle to show drafts only
    $(document).on('change', '#toggle-drafts-only', function () {
        const showDrafts = $(this).is(':checked');
        loadList(showDrafts);
    });

    // Handle select-all checkbox
    $(document).on('change', '#select-all-checkbox', function () {
        $('.row-checkbox').prop('checked', this.checked);
    });

    $(document).on('click', '#ai-list-new-btn', function (e) {
        e.preventDefault();
        window.open('new', '_blank');
    });

    // Handle bulk delete
    $(document).on('click', '#bulk-delete-btn', function () {
        e.preventDefault(); // Prevent default action

        const selectedIds = $('.row-checkbox:checked').map(function () {
            return $(this).data('post-id');
        }).get();

        if (selectedIds.length === 0) {
            alert('No items selected.');
            return;
        }

        if (!confirm(`Delete ${selectedIds.length} selected item(s)? This cannot be undone.`)) return;

        $('#ai-list-status').text('Deleting...');

        $.post(AJAX.ajax_url, {
            action: AJAX.prefix + '_bulk_delete',
            nonce: AJAX.nonce,
            post_ids: selectedIds
        }, function (res) {
            if (res.success) {
                $('#ai-list-status').text('Deleted selected items.');
                loadList($('#toggle-drafts-only').is(':checked'));
            } else {
                $('#ai-list-status').text(res.data && res.data.message || 'Bulk delete failed.');
            }
        }).fail(function () {
            $('#ai-list-status').text('Server error during bulk delete.');
        });
    });

    // Handle preview button click (👁️)
    $(document).on('click', '.view-btn', function (e) {
        e.preventDefault();
        const postId = $(this).data('post-id');
        $('#ai-list-status').text('Loading details...');

        $.post(AJAX.ajax_url, {
            action: AJAX.prefix + '_load',
            nonce: AJAX.nonce,
            post_id: postId
        }, function (res) {
            $('#ai-list-status').text('');
            if (res.success) {
                const item = res.data.draft || {};
                const chatHistoryHtml = res.data.history_html || [];
                const title = item.title || '(Untitled)';
                const content = (item.content || '').trim();

                $('#list-item-title').text(title);

                let contentHtml = '';
                if (content) {
                    contentHtml = content;
                } else if (chatHistoryHtml.length > 0) {
                    contentHtml = chatHistoryHtml.map(msg => `
                        <div style="margin-bottom:8px;">
                            <strong style="color:${msg.role === 'user' ? '#2d7b2d' : '#2d437b'}">${msg.role}:</strong>
                            <div class="ai-msg-html">${msg.content_html}</div>
                        </div>
                    `).join('');
                } else {
                    contentHtml = '<p><em>No content available.</em></p>';
                }

                $('#list-item-content').html(contentHtml);
                $('#resume-item-btn')
                    .attr('href', AJAX.edit_url_prefix + postId + '/edit/')
                    .show();
                $('#ai-list-preview').slideDown();
            } else {
                alert(res.data.message || 'Failed to load.');
            }
        });
    });


    // Handle delete button click (🗑️)
    $(document).on('click', '.delete-btn', function (e) {
        e.preventDefault();
        const postId = $(this).data('post-id');
        if (!confirm('Delete this item? This cannot be undone.')) return;

        $('#ai-list-status').text('Deleting...');

        $.post(AJAX.ajax_url, {
            action: AJAX.prefix + '_delete', // AJAX handler must exist server-side!
            nonce: AJAX.nonce,
            post_id: postId
        }, function (res) {
            if (res.success) {
                $('#ai-list-status').text('Deleted.');
                loadList();
                $('#ai-list-preview').hide(); // Hide preview if open
            } else {
                $('#ai-list-status').text(res.data && res.data.message || 'Delete failed.');
            }
        }).fail(function () {
            $('#ai-list-status').text('Server error during delete.');
        });
    });

    $(document).on('mouseenter focus', '.icon-btn', function () {
        const $btn = $(this);
        const offset = $btn.offset();
        const tooltipHeight = $btn.find('.icon-tooltip').outerHeight();
        if (offset.top - $(window).scrollTop() < tooltipHeight + 10) {
            // Not enough space above, show below
            $btn.attr('data-tooltip-position', 'bottom');
        } else {
            $btn.removeAttr('data-tooltip-position');
        }
    });


    loadList();
});
