(function ($) {
    'use strict';

    function cfg() {
        return (typeof window.askagentoAutoFilteringAdmin === 'object' && window.askagentoAutoFilteringAdmin) || {};
    }

    function i18n(key, fallback) {
        var c = cfg();
        var dict = c.i18n || {};
        return dict[key] || fallback || '';
    }

    function ajaxUrl() {
        return cfg().ajaxUrl || (typeof window.ajaxurl !== 'undefined' ? window.ajaxurl : '');
    }

    function nonce() {
        return cfg().nonce || '';
    }

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

    function showError($out, message) {
        $out.html('<span style="color:#b32d2e;">' + escapeHtml(message) + '</span>');
    }

    function syncCanonicalToggleWrap($input) {
        var $wrap = $input.closest('.askagento-ai-text-live-switch-wrap');
        if (!$wrap.length) {
            return;
        }
        $wrap.toggleClass('askagento-ai-text-live-switch-wrap--on', $input.prop('checked'));
        $wrap.find('.askagento-ai-text-live-switch__state').text(
            $input.prop('checked')
                ? i18n('toggleOn', 'On')
                : i18n('toggleOff', 'Off')
        );
    }

    function renderCanonicalToggles(filters) {
        var $list = $('#askagento-auto-filtering-canonical-filters');
        var items = Array.isArray(filters) ? filters : [];
        var html = [];

        items.forEach(function (filterName, index) {
            var name = String(filterName || '').trim();
            if (!name) {
                return;
            }
            var inputId = 'askagento-auto-filtering-canonical-' + index;
            html.push(
                '<div class="askagento-auto-filtering-canonical-item">' +
                    '<div class="askagento-ai-text-live-switch-wrap askagento-ai-text-live-switch-wrap--on">' +
                        '<label class="askagento-ai-text-live-switch" for="' + escapeHtml(inputId) + '">' +
                            '<input type="checkbox" class="askagento-ai-text-live-switch__input askagento-auto-filtering-canonical-input" id="' +
                            escapeHtml(inputId) +
                            '" value="' +
                            escapeHtml(name) +
                            '" checked />' +
                            '<span class="askagento-ai-text-live-switch__track" aria-hidden="true">' +
                                '<span class="askagento-ai-text-live-switch__thumb"></span>' +
                            '</span>' +
                            '<span class="askagento-ai-text-live-switch__text">' + escapeHtml(name) + '</span>' +
                        '</label>' +
                        '<span class="askagento-ai-text-live-switch__state">' + escapeHtml(i18n('toggleOn', 'On')) + '</span>' +
                    '</div>' +
                '</div>'
            );
        });

        $list.html(html.join(''));
    }

    function getSelectedCanonicalFilters() {
        var out = [];
        var seen = {};
        $('#askagento-auto-filtering-canonical-filters .askagento-auto-filtering-canonical-input:checked').each(function () {
            var v = String($(this).val() || '').trim();
            if (!v) {
                return;
            }
            var low = v.toLowerCase();
            if (seen[low]) {
                return;
            }
            seen[low] = true;
            out.push(v);
        });
        return out;
    }

    function summaryHtml(data, action) {
        var lines = [];
        if (action === 'analyze') {
            lines.push('<li><strong>' + escapeHtml(i18n('filterPosts', 'Filter posts')) + ':</strong> ' + escapeHtml(data.filter_posts_total || 0) + '</li>');
            lines.push('<li><strong>' + escapeHtml(i18n('filtersFound', 'Filters found')) + ':</strong> ' + escapeHtml(data.existing_filters_total || 0) + '</li>');
            var availableTotal = data.available_attributes_total != null
                ? data.available_attributes_total
                : data.suggested_filters_total;
            lines.push('<li><strong>Available attributes:</strong> ' + escapeHtml(availableTotal || 0) + '</li>');
            if (Array.isArray(data.existing_filters) && data.existing_filters.length) {
                lines.push(
                    '<li><strong>' +
                    escapeHtml(i18n('configuredFilterFields', 'Fields on existing filter posts')) +
                    ':</strong> ' +
                    escapeHtml(data.existing_filters.join(', ')) +
                    '</li>'
                );
            }
            if (Array.isArray(data.suggested_filters) && data.suggested_filters.length) {
                lines.push('<li><strong>Suggestions:</strong> ' + escapeHtml(data.suggested_filters.join(', ')) + '</li>');
            }
            if (data.message) {
                lines.push('<li><strong>Info:</strong> ' + escapeHtml(data.message) + '</li>');
            }
        } else if (action === 'generate') {
            lines.push('<li><strong>Selected filters:</strong> ' + escapeHtml((Array.isArray(data.generated_filters) ? data.generated_filters.length : 0)) + '</li>');
            if (Array.isArray(data.generated_filters) && data.generated_filters.length) {
                lines.push('<li><strong>Filters:</strong> ' + escapeHtml(data.generated_filters.join(', ')) + '</li>');
            }
        } else if (action === 'upload') {
            lines.push('<li><strong>Uploaded filters:</strong> ' + escapeHtml(data.uploaded_filters || 0) + '</li>');
            if (data.cache && data.cache.success) {
                lines.push(
                    '<li><strong>Filter index:</strong> ' +
                    escapeHtml(String(data.cache.products || 0)) +
                    ' products, ' +
                    escapeHtml(String(data.cache.cache || 0)) +
                    ' cache rows, ' +
                    escapeHtml(String(data.cache.terms || 0)) +
                    ' term rows' +
                    (data.cache.time != null ? ' (' + escapeHtml(String(data.cache.time)) + 's)' : '') +
                    '</li>'
                );
            } else if (data.cache && data.cache.success === false && data.cache.message) {
                lines.push(
                    '<li><strong>Filter index:</strong> <span style="color:#b32d2e;">' +
                        escapeHtml(data.cache.message) +
                        '</span></li>'
                );
            }
            if (data.filter_name) {
                lines.push('<li><strong>Filter name:</strong> ' + escapeHtml(data.filter_name) + '</li>');
            }
            if (data.edit_url) {
                lines.push('<li><strong>Edit filter:</strong> <a href="' + escapeHtml(data.edit_url) + '">Open filter post</a></li>');
            }
        }
        return '<div class="askagento-status-ok">✓ ' + escapeHtml((data.action || action) + ' completed') + '</div><ul>' + lines.join('') + '</ul>';
    }

    function requestAction(action, $button, $out) {
        var url = ajaxUrl();
        var n = nonce();
        if (!url || !n) {
            showError($out, i18n('missingConfig', 'Missing configuration.'));
            return;
        }

        var payload = {
            action: 'askagento_auto_filtering_action',
            nonce: n,
            filter_action: action
        };
        if (action === 'generate') {
            payload.canonical_filters = getSelectedCanonicalFilters();
            if (!payload.canonical_filters.length) {
                showError($out, i18n('selectOneFilter', 'Select at least one filter before Generate.'));
                return;
            }
        } else if (action === 'upload') {
            payload.canonical_filters = getSelectedCanonicalFilters();
            if (!payload.canonical_filters.length) {
                showError($out, i18n('selectOneFilterUpload', 'Select at least one filter before Upload.'));
                return;
            }
            payload.filter_name = String($('#askagento-auto-filtering-target-name').val() || '').trim();
            if (!payload.filter_name) {
                showError($out, 'Enter a filter name before Upload.');
                return;
            }
        }

        var workingKey = 'working' + action.charAt(0).toUpperCase() + action.slice(1);
        $button.prop('disabled', true);
        $out.html('<span>' + escapeHtml(i18n(workingKey, 'Working…')) + '</span>');

        $.post(url, payload, function (resp) {
            if (resp && resp.success && resp.data) {
                $out.html(summaryHtml(resp.data, action));
                if (action === 'analyze') {
                    var prefill = [];
                    if (Array.isArray(resp.data.prefill_filters) && resp.data.prefill_filters.length) {
                        prefill = resp.data.prefill_filters;
                    } else if (Array.isArray(resp.data.suggested_filters) && resp.data.suggested_filters.length) {
                        prefill = resp.data.suggested_filters;
                    }
                    renderCanonicalToggles(prefill);
                    $('#askagento-auto-filtering-canonical-wrap').show();
                    $('#askagento-auto-filtering-generate-btn').prop('disabled', false);
                    // Upload only after Generate completes successfully.
                    $('#askagento-auto-filtering-upload-btn').prop('disabled', true);
                } else if (action === 'generate') {
                    $('#askagento-auto-filtering-upload-btn').prop('disabled', false);
                }
                return;
            }
            var msg = (resp && resp.data && resp.data.message) ? resp.data.message : i18n('requestFailed', 'Request failed.');
            showError($out, msg);
        }).fail(function () {
            showError($out, i18n('requestFailed', 'Request failed.'));
        }).always(function () {
            $button.prop('disabled', false);
        });
    }

    function triggerJsonDownload(contents, filename) {
        try {
            var blob = new Blob([contents], { type: 'application/json;charset=utf-8' });
            var url = window.URL.createObjectURL(blob);
            var a = document.createElement('a');
            a.href = url;
            a.download = filename || 'generated-filters.json';
            a.style.display = 'none';
            document.body.appendChild(a);
            a.click();
            document.body.removeChild(a);
            window.URL.revokeObjectURL(url);
        } catch (e) {}
    }

    function bindExportButton() {
        $('#askagento-export-generated-filters-json').on('click', function () {
            var $btn = $(this);
            var $out = $('#askagento-auto-filtering-generate-out');
            var url = ajaxUrl();
            var n = nonce();
            if (!url || !n) {
                showError($out, i18n('missingConfig', 'Missing configuration.'));
                return;
            }
            if ($btn.prop('disabled')) {
                return;
            }
            $btn.prop('disabled', true);
            $out.html('<span>Preparing JSON download…</span>');
            $.post(url, {
                action: 'askagento_auto_filtering_action',
                nonce: n,
                filter_action: 'export',
                canonical_filters: getSelectedCanonicalFilters()
            }, function (resp) {
                if (!resp || !resp.success || !resp.data) {
                    var message = (resp && resp.data && resp.data.message) ? resp.data.message : i18n('requestFailed', 'Request failed.');
                    showError($out, message);
                    return;
                }
                var body = JSON.stringify(resp.data, null, 2);
                var filename = (resp.data.filename && String(resp.data.filename).trim())
                    ? String(resp.data.filename).trim()
                    : 'generated-filters.json';
                triggerJsonDownload(body, filename);
                $out.html('<span class="askagento-status-ok">✓ ' + escapeHtml('File download started: ' + filename) + '</span>');
            }).fail(function () {
                showError($out, i18n('requestFailed', 'Request failed.'));
            }).always(function () {
                $btn.prop('disabled', false);
            });
        });
    }

    $(function () {
        $('#askagento-auto-filtering-generate-btn').prop('disabled', true);
        $('#askagento-auto-filtering-upload-btn').prop('disabled', true);
        $('#askagento-auto-filtering-canonical-wrap').hide();
        $('#askagento-auto-filtering-canonical-filters').empty();

        $(document).on('change', '.askagento-auto-filtering-canonical-input', function () {
            syncCanonicalToggleWrap($(this));
        });

        $('#askagento-auto-filtering-analyze-btn').on('click', function () {
            requestAction('analyze', $(this), $('#askagento-auto-filtering-analyze-out'));
        });
        $('#askagento-auto-filtering-generate-btn').on('click', function () {
            requestAction('generate', $(this), $('#askagento-auto-filtering-generate-out'));
        });
        $('#askagento-auto-filtering-upload-btn').on('click', function () {
            requestAction('upload', $(this), $('#askagento-auto-filtering-upload-out'));
        });
        bindExportButton();
    });
})(jQuery);
