(function($) {
    'use strict';

    var cfg = window.askagentoInstallStatus || {};
    var pollTimer = null;
    var pollStartedAt = 0;
    var consecutiveErrors = 0;
    var activePoll = null;

    function escapeHtml(value) {
        return $('<div>').text(value == null ? '' : String(value)).html();
    }

    function defaultContainer() {
        var $plugins = $('#askagento-install-poll-status');
        if ($plugins.length) {
            return $plugins;
        }
        var $status = $('#askagento-install-status');
        if ($status.length) {
            return $status;
        }
        return $('#askagento-sync-data-status');
    }

    function showCompletionBanner() {
        if ($('.askagento-install-completion-notice').length) {
            return;
        }

        var html =
            '<div class="notice notice-success is-dismissible askagento-install-completion-notice">' +
            '<p><strong>' + escapeHtml(cfg.i18n.completedBanner || cfg.i18n.completed || 'AskAgento installation complete.') + '</strong> ' +
            escapeHtml(cfg.i18n.completedDetail || 'Your product catalogue is ready for AI search.') +
            '</p></div>';

        var $anchor = $('#askagento-install-poll-status').closest('.notice');
        if ($anchor.length) {
            $anchor.replaceWith(html);
        } else {
            var $wrap = $('#wpbody-content .wrap').first();
            if ($wrap.length) {
                $wrap.prepend(html);
            } else {
                $('#wpbody-content').prepend(html);
            }
        }

        if (cfg.ajaxUrl && cfg.nonce) {
            $.post(cfg.ajaxUrl, {
                action: 'askagento_dismiss_install_completion_notice',
                nonce: cfg.nonce
            });
        }
    }

    function renderProcessing($out, data) {
        var html = '<div><span class="askagento-status-meta">' + escapeHtml(cfg.i18n.processing || 'Processing…') + '</span></div>';
        if (data && data.status_message) {
            html += '<div class="askagento-status-meta"><strong>' + escapeHtml(cfg.i18n.statusLine || 'Status') + ': ' + escapeHtml(String(data.status_message).replace('Installation:', 'Installation')) + '</strong></div>';
        }
        $out.html(html);
    }

    function renderCompleted($out, data) {
        var html = '<div><span style="color:#1d7f1d;font-weight:600;">✓ ' + escapeHtml(cfg.i18n.completed || 'AskAgento installation complete. Your product catalogue is ready for AI search.') + '</span></div>';
        if (data && (data.installed_at_display || data.installed_at)) {
            html += '<div class="askagento-status-meta">' + escapeHtml(cfg.i18n.installedAt || 'Installed at') + ': ' + escapeHtml(data.installed_at_display || data.installed_at) + '</div>';
        } else if (data && data.status_message) {
            html += '<div class="askagento-status-meta">' + escapeHtml(data.status_message) + '</div>';
        }
        $out.html(html);
        showCompletionBanner();
    }

    function renderFailed($out, message) {
        $out.html('<div><span style="color:#b32d2e;font-weight:600;">' + escapeHtml(cfg.i18n.failed || 'Installation failed.') + '</span></div>' +
            (message ? '<div class="askagento-status-meta">' + escapeHtml(message) + '</div>' : ''));
    }

    function renderTimeout($out) {
        $out.html('<div><span style="color:#b32d2e;font-weight:600;">' + escapeHtml(cfg.i18n.timeout || 'Timed out.') + '</span></div>');
    }

    function stopPoll() {
        if (pollTimer) {
            clearTimeout(pollTimer);
            pollTimer = null;
        }
        if (activePoll && activePoll.$btn) {
            activePoll.$btn.prop('disabled', false);
        }
        activePoll = null;
    }

    function scheduleNextTick() {
        if (!activePoll) {
            return;
        }
        pollTimer = setTimeout(pollOnce, cfg.intervalMs || 4000);
    }

    function pollOnce() {
        if (!activePoll) {
            return;
        }

        var maxMs = cfg.maxMs || 900000;
        if (pollStartedAt && (Date.now() - pollStartedAt) > maxMs) {
            renderTimeout(activePoll.$out);
            stopPoll();
            return;
        }

        $.post(cfg.ajaxUrl, {
            action: 'askagento_check_install_status',
            nonce: cfg.nonce
        }).done(function(resp) {
            consecutiveErrors = 0;
            if (!resp || !resp.success || !resp.data) {
                renderFailed(activePoll.$out, (resp && resp.data && resp.data.message) ? resp.data.message : (cfg.i18n.error || 'Error'));
                stopPoll();
                return;
            }

            var phase = resp.data.install_phase || '';
            if (phase === 'completed') {
                renderCompleted(activePoll.$out, resp.data);
                stopPoll();
                return;
            }
            if (phase === 'failed') {
                renderFailed(activePoll.$out, resp.data.status_message || '');
                stopPoll();
                return;
            }

            renderProcessing(activePoll.$out, resp.data);
            scheduleNextTick();
        }).fail(function(xhr) {
            consecutiveErrors += 1;
            var message = cfg.i18n.error || 'Error';
            if (xhr && xhr.responseJSON && xhr.responseJSON.data && xhr.responseJSON.data.message) {
                message = xhr.responseJSON.data.message;
            }
            if (consecutiveErrors >= 5) {
                renderFailed(activePoll.$out, message);
                stopPoll();
                return;
            }
            renderProcessing(activePoll.$out, { status_message: message });
            scheduleNextTick();
        });
    }

    function startPoll(options) {
        options = options || {};
        var $out = options.$out || defaultContainer();
        if (!$out.length) {
            return;
        }

        stopPoll();
        activePoll = {
            $out: $out,
            $btn: options.$btn || null
        };
        pollStartedAt = Date.now();
        consecutiveErrors = 0;

        if (activePoll.$btn) {
            activePoll.$btn.prop('disabled', true);
        }

        $out.html('<span class="askagento-status-meta">' + escapeHtml(cfg.i18n.checking || 'Checking…') + '</span>');
        pollOnce();
    }

    window.askagentoPollInstallStatus = startPoll;

    $(function() {
        if (cfg.autoStart) {
            startPoll();
        }

        $(document).on('click', '.askagento-install-processing-notice .notice-dismiss', function() {
            if (!cfg.ajaxUrl || !cfg.nonce) {
                return;
            }
            $.post(cfg.ajaxUrl, {
                action: 'askagento_dismiss_install_processing_notice',
                nonce: cfg.nonce
            });
        });
    });
})(jQuery);
