(function($) {
    'use strict';

    var BulkGenerator = {
        postIds: [],
        postTitles: {},
        currentIndex: 0,
        results: { success: 0, skipped: 0, failed: 0 },
        cancelled: false,
        overwrite: false,
        generatePrompt: false,
        currentPage: 1,
        totalPages: 1,
        isProcessing: false,

        init: function() {
            this.bindEvents();
            this.renderUsageBanner();

            // Auto-start if redirected from bulk action
            if (aifiBulkData.autoStart && aifiBulkData.postIds.length) {
                this.postIds = aifiBulkData.postIds;
                this.overwrite = aifiBulkData.overwrite;
                this.startProcessing();
            }
        },

        bindEvents: function() {
            $('#aifi-bulk-load-posts').on('click', this.loadPosts.bind(this));
            $('#aifi-bulk-start').on('click', this.onStartClick.bind(this));
            $('#aifi-bulk-cancel').on('click', this.onCancelClick.bind(this));
            $('#aifi-bulk-select-all').on('change', this.onSelectAll.bind(this));
            $(document).on('change', '.aifi-bulk-post-cb', this.onPostCheckChange.bind(this));
        },

        renderUsageBanner: function() {
            if (aifiBulkData.isPremium) return;

            var usage = aifiBulkData.bulkUsage || 0;
            var limit = aifiBulkData.batchLimit || 50;
            var postLimit = aifiBulkData.postLimit || 5;
            var remaining = Math.max(0, limit - usage);

            var html = '<div class="aifi-bulk-usage-banner">' +
                '<div class="aifi-bulk-usage-info">' +
                '<span class="dashicons dashicons-info-outline"></span>' +
                '<strong>Free Plan:</strong> ' + postLimit + ' posts per batch &middot; ' +
                remaining + ' of ' + limit + ' batches remaining' +
                '</div>';

            if (remaining === 0) {
                html += '<div class="aifi-bulk-usage-exhausted">' +
                    '<span class="dashicons dashicons-warning"></span>' +
                    'You have used all your free bulk batches. ' +
                    '<a href="' + this.escHtml(aifiBulkData.upgradeUrl) + '">Upgrade to Pro</a> for unlimited bulk generation.' +
                    '</div>';
            } else {
                html += '<div class="aifi-bulk-usage-cta">' +
                    '<a href="' + this.escHtml(aifiBulkData.upgradeUrl) + '">Upgrade to Pro</a> for unlimited posts, all filters, and overwrite support.' +
                    '</div>';
            }

            html += '</div>';
            $('.aifi-bulk-content').prepend(html);

            // Disable start if exhausted
            if (remaining === 0) {
                $('#aifi-bulk-load-posts').prop('disabled', true);
            }
        },

        loadPosts: function() {
            var self = this;
            var $btn = $('#aifi-bulk-load-posts');
            var $card = $('.aifi-bulk-posts-card');

            $btn.prop('disabled', true).text(aifiBulkData.i18n.loadingPosts);

            $.ajax({
                url: aifiBulkData.restUrl + '/bulk-posts',
                method: 'GET',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', aifiBulkData.nonce);
                },
                data: {
                    post_type: $('#aifi-bulk-post-type').val() || 'post',
                    post_status: $('#aifi-bulk-post-status').val(),
                    has_thumbnail: $('#aifi-bulk-thumbnail-filter').val() || 'no',
                    date_from: $('#aifi-bulk-date-from').val() || '',
                    date_to: $('#aifi-bulk-date-to').val() || '',
                    per_page: 50,
                    page: this.currentPage
                },
                success: function(response) {
                    self.renderPostTable(response);
                    $card.show();
                },
                error: function(xhr) {
                    var msg = (xhr.responseJSON && xhr.responseJSON.message)
                        ? xhr.responseJSON.message : 'Error loading posts.';
                    alert(msg);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                    $btn.html('<span class="dashicons dashicons-search"></span> ' + 'Load Posts');
                }
            });
        },

        renderPostTable: function(response) {
            var $list = $('#aifi-bulk-posts-list');
            var $count = $('#aifi-bulk-post-count');
            var posts = response.posts;

            this.totalPages = response.total_pages;
            var countText = response.total + ' posts found';
            $count.text(countText);

            if (!posts.length) {
                $list.html(
                    '<div class="aifi-bulk-empty">' +
                    '<span class="dashicons dashicons-format-image"></span>' +
                    aifiBulkData.i18n.noPostsFound +
                    '</div>'
                );
                $('#aifi-bulk-start').hide();
                $('#aifi-bulk-posts-header, #aifi-bulk-pagination').hide();
                return;
            }

            var html = '';
            for (var i = 0; i < posts.length; i++) {
                var post = posts[i];
                var thumbHtml = post.has_thumbnail
                    ? '<span class="aifi-bulk-has-thumb"><img src="' + this.escHtml(post.thumbnail_url) + '" alt=""> </span>'
                    : '<span class="aifi-bulk-no-thumb"><span class="dashicons dashicons-minus"></span></span>';

                html += '<div class="aifi-bulk-post-item">' +
                    '<input type="checkbox" class="aifi-bulk-post-cb" value="' + post.id + '" data-title="' + this.escHtml(post.title) + '" checked>' +
                    '<span class="aifi-bulk-post-title">' + this.escHtml(post.title || '(No title)') + '</span>' +
                    '<span class="aifi-bulk-post-date">' + this.escHtml(post.date) + '</span>' +
                    '<span class="aifi-bulk-post-thumb">' + thumbHtml + '</span>' +
                    '</div>';
            }

            $list.html(html);
            // For free users, only keep the first postLimit checked; disable the rest
            if (!aifiBulkData.isPremium) {
                $('.aifi-bulk-post-cb').slice(aifiBulkData.postLimit).prop('checked', false);
                this.enforceSelectionLimit();
            }
            $('#aifi-bulk-select-all').prop('checked', true);
            $('#aifi-bulk-start').show();
            this.updateSelectedCount();
            this.renderPagination(response);
        },

        renderPagination: function(response) {
            var $pagination = $('#aifi-bulk-pagination');

            // Free users don't get pagination (limited to 5 posts)
            if (response.total_pages <= 1) {
                $pagination.empty();
                return;
            }

            var self = this;
            var html = '';
            for (var p = 1; p <= response.total_pages; p++) {
                var activeClass = p === response.page ? ' active' : '';
                html += '<button type="button" class="aifi-bulk-page-btn' + activeClass + '" data-page="' + p + '">' + p + '</button>';
            }
            html += '<span class="aifi-bulk-page-info">' + response.total + ' total</span>';
            $pagination.html(html);

            $pagination.off('click', '.aifi-bulk-page-btn').on('click', '.aifi-bulk-page-btn', function() {
                self.currentPage = parseInt($(this).data('page'), 10);
                self.loadPosts();
            });
        },

        onSelectAll: function(e) {
            var checked = $(e.target).prop('checked');
            if (!aifiBulkData.isPremium && checked) {
                $('.aifi-bulk-post-cb').prop('disabled', false).prop('checked', false);
                $('.aifi-bulk-post-cb').slice(0, aifiBulkData.postLimit).prop('checked', true);
            } else {
                $('.aifi-bulk-post-cb').prop('disabled', false).prop('checked', checked);
            }
            if (!aifiBulkData.isPremium) {
                this.enforceSelectionLimit();
            }
            this.updateSelectedCount();
        },

        onPostCheckChange: function() {
            this.updateSelectedCount();
            if (!aifiBulkData.isPremium) {
                this.enforceSelectionLimit();
            }
        },

        enforceSelectionLimit: function() {
            var selected = $('.aifi-bulk-post-cb:checked').length;
            var atLimit = selected >= aifiBulkData.postLimit;
            $('.aifi-bulk-post-cb:not(:checked)').prop('disabled', atLimit);

            if (atLimit) {
                if (!$('#aifi-bulk-select-limit-msg').length) {
                    var html = '<div id="aifi-bulk-select-limit-msg" class="aifi-bulk-select-limit-msg">' +
                        '<span class="dashicons dashicons-lock"></span>' +
                        'Free plan allows up to ' + aifiBulkData.postLimit + ' posts per batch. ' +
                        '<a href="' + this.escHtml(aifiBulkData.upgradeUrl) + '">Upgrade to Pro</a> for unlimited.' +
                        '</div>';
                    $('#aifi-bulk-posts-list').after(html);
                }
            } else {
                $('#aifi-bulk-select-limit-msg').remove();
            }
        },

        updateSelectedCount: function() {
            var selected = $('.aifi-bulk-post-cb:checked').length;
            var total = $('.aifi-bulk-post-cb').length;
            var text = selected + ' / ' + total + ' selected';
            $('#aifi-bulk-selected-count').text(text);
        },

        onStartClick: function() {
            var selected = $('.aifi-bulk-post-cb:checked');
            if (!selected.length) {
                alert(aifiBulkData.i18n.selectPosts);
                return;
            }

            this.postIds = [];
            this.postTitles = {};
            var self = this;
            selected.each(function() {
                var id = parseInt($(this).val(), 10);
                self.postIds.push(id);
                self.postTitles[id] = $(this).data('title') || '';
            });

            this.overwrite       = $('#aifi-bulk-overwrite').prop('checked');
            this.generatePrompt  = $('#aifi-bulk-generate-prompt').prop('checked');

            // Stability AI does not support text generation; disable generate_prompt silently
            if (this.generatePrompt && aifiBulkData.provider === 'stability') {
                alert('Generate prompt from content is not available with Stability AI. Please switch to OpenAI, Gemini, or Grok in the plugin settings, or uncheck that option.');
                this.generatePrompt = false;
            }

            this.startProcessing();
        },

        startProcessing: function() {
            this.currentIndex = 0;
            this.cancelled = false;
            this.results = { success: 0, skipped: 0, failed: 0 };
            this.isProcessing = true;

            var self = this;
            $(window).on('beforeunload.aifiBulk', function() {
                if (self.isProcessing) return '';
            });

            // Show progress, hide posts card actions
            $('.aifi-bulk-progress-card').show();
            $('.aifi-bulk-summary-card').hide();
            $('#aifi-bulk-start').prop('disabled', true);
            $('#aifi-bulk-cancel').prop('disabled', false);
            $('#aifi-bulk-results-log').empty();
            $('#aifi-bulk-progress-bar').css('width', '0%');
            $('#aifi-bulk-page-warning').show();

            this.processNext();
        },

        processNext: function() {
            if (this.cancelled || this.currentIndex >= this.postIds.length) {
                this.showSummary();
                return;
            }

            var postId = this.postIds[this.currentIndex];
            var self = this;
            this.updateProgress(postId);

            $.ajax({
                url: aifiBulkData.restUrl + '/bulk-generate',
                method: 'POST',
                beforeSend: function(xhr) {
                    xhr.setRequestHeader('X-WP-Nonce', aifiBulkData.nonce);
                    xhr.setRequestHeader('Content-Type', 'application/json');
                },
                data: JSON.stringify({
                    post_id:         postId,
                    overwrite:       self.overwrite,
                    generate_prompt: self.generatePrompt
                }),
                success: function(response) {
                    var title = response.post_title || self.postTitles[postId] || 'Post #' + postId;
                    if (response.skipped) {
                        self.logResult(title, 'skipped', response.reason);
                        self.results.skipped++;
                    } else {
                        self.logResult(title, 'success', aifiBulkData.i18n.success);
                        self.results.success++;
                        // Update local usage count for free users
                        if (!aifiBulkData.isPremium) {
                            aifiBulkData.bulkUsage = (aifiBulkData.bulkUsage || 0) + 1;
                        }
                    }
                },
                error: function(xhr) {
                    var title = self.postTitles[postId] || 'Post #' + postId;
                    var msg = (xhr.responseJSON && xhr.responseJSON.message)
                        ? xhr.responseJSON.message : 'Unknown error';
                    self.logResult(title, 'error', msg);
                    self.results.failed++;
                },
                complete: function() {
                    self.currentIndex++;
                    self.processNext();
                }
            });
        },

        updateProgress: function(postId) {
            var total = this.postIds.length;
            var current = this.currentIndex + 1;
            var percent = Math.round((this.currentIndex / total) * 100);
            var title = this.postTitles[postId] || 'Post #' + postId;

            $('#aifi-bulk-progress-bar').css('width', percent + '%');
            $('#aifi-bulk-progress-text').text(
                aifiBulkData.i18n.processing + ': "' + title + '" (' + current + ' ' + aifiBulkData.i18n.of + ' ' + total + ')'
            );
        },

        logResult: function(title, status, detail) {
            var $log = $('#aifi-bulk-results-log');
            var icon, className;

            if (status === 'success') {
                icon = 'dashicons-yes-alt';
                className = 'aifi-bulk-result-success';
            } else if (status === 'skipped') {
                icon = 'dashicons-marker';
                className = 'aifi-bulk-result-skipped';
            } else {
                icon = 'dashicons-dismiss';
                className = 'aifi-bulk-result-error';
            }

            var html = '<div class="aifi-bulk-result-item ' + className + '">' +
                '<span class="dashicons ' + icon + '"></span>' +
                '<span class="aifi-bulk-result-title">' + this.escHtml(title) + '</span>' +
                '<span class="aifi-bulk-result-detail">' + this.escHtml(detail) + '</span>' +
                '</div>';

            $log.append(html);
            $log.scrollTop($log[0].scrollHeight);
        },

        onCancelClick: function() {
            if (confirm(aifiBulkData.i18n.confirmCancel)) {
                this.cancelled = true;
                $('#aifi-bulk-cancel').prop('disabled', true);
            }
        },

        showSummary: function() {
            this.isProcessing = false;
            $(window).off('beforeunload.aifiBulk');
            $('#aifi-bulk-page-warning').hide();

            var $summary = $('#aifi-bulk-summary');
            var total = this.results.success + this.results.skipped + this.results.failed;
            var statusText = this.cancelled ? aifiBulkData.i18n.cancelled : aifiBulkData.i18n.completed;

            // Update progress bar to 100% if completed
            if (!this.cancelled) {
                $('#aifi-bulk-progress-bar').css('width', '100%');
                $('#aifi-bulk-progress-text').text(aifiBulkData.i18n.completed);
            }

            $('#aifi-bulk-cancel').hide();

            var html = '<div class="aifi-bulk-summary-title">' + statusText + '</div>' +
                '<div class="aifi-bulk-summary-stats">' +
                '<div class="aifi-bulk-stat aifi-bulk-stat-success">' +
                '<span class="aifi-bulk-stat-number">' + this.results.success + '</span>' +
                '<span class="aifi-bulk-stat-label">' + aifiBulkData.i18n.succeeded + '</span>' +
                '</div>' +
                '<div class="aifi-bulk-stat aifi-bulk-stat-skipped">' +
                '<span class="aifi-bulk-stat-number">' + this.results.skipped + '</span>' +
                '<span class="aifi-bulk-stat-label">' + aifiBulkData.i18n.skipped + '</span>' +
                '</div>' +
                '<div class="aifi-bulk-stat aifi-bulk-stat-failed">' +
                '<span class="aifi-bulk-stat-number">' + this.results.failed + '</span>' +
                '<span class="aifi-bulk-stat-label">' + aifiBulkData.i18n.failed + '</span>' +
                '</div>' +
                '</div>';

            // Show usage update for free users
            if (!aifiBulkData.isPremium) {
                var remaining = Math.max(0, (aifiBulkData.batchLimit || 50) - (aifiBulkData.bulkUsage || 0));
                html += '<div class="aifi-bulk-summary-usage">' +
                    remaining + ' batches remaining &middot; ' +
                    '<a href="' + this.escHtml(aifiBulkData.upgradeUrl) + '">Upgrade to Pro</a> for unlimited' +
                    '</div>';
            }

            $summary.html(html);
            $('.aifi-bulk-summary-card').show();

            // Re-enable start button
            $('#aifi-bulk-start').prop('disabled', false);
        },

        escHtml: function(str) {
            if (!str) return '';
            var div = document.createElement('div');
            div.appendChild(document.createTextNode(str));
            return div.innerHTML;
        }
    };

    $(document).ready(function() {
        if (typeof aifiBulkData !== 'undefined') {
            BulkGenerator.init();
        }
    });

})(jQuery);
