jQuery(function ($) {
    var W5EAdmin = window.W5E || {};
    var ajaxUrl = W5EAdmin.ajax || window.ajaxurl || '';
    var nonce = W5EAdmin.nonce || '';
    var $envSelect = $('#w5e_env');
    var $stagingUrlRow = $('#w5e_orders_base_url_staging').closest('tr');
    var $productionUrlRow = $('#w5e_orders_base_url_production').closest('tr');
    var $statusTriggerRow = $('#w5e_order_export_statuses').closest('tr');
    var $settingsTable = $('#w5e_settings_section').closest('table');

    $('#w5e-fetch-btn').on('click', function () {
        var $btn = $(this);
        var $status = $('#w5e-fetch-status');
        var i18n = W5EAdmin.i18n || {};
        $btn.prop('disabled', true);
        $status.text(i18n.fetching || 'Working...');

        if (!ajaxUrl) {
            $btn.prop('disabled', false);
            return;
        }

        $.post(ajaxUrl, {
            action: 'w5e_fetch_couriers',
            nonce: nonce
        }).done(function (resp) {
            if (resp && resp.success) {
                var count = (resp.data && resp.data.count) ? resp.data.count : 0;
                var tmpl = i18n.success || 'Done: %d items cached. Reload the page.';
                $status.text(tmpl.replace('%d', count));
            } else {
                var errorPrefix = i18n.errorPrefix || 'Error:';
                var unknown = i18n.unknownError || 'Unknown';
                var message = (resp && resp.data && resp.data.message) ? resp.data.message : unknown;
                $status.text(errorPrefix + ' ' + message);
            }
        }).fail(function () {
            $status.text(i18n.requestError || 'Request failed.');
        }).always(function () {
            $btn.prop('disabled', false);
        });
    });

    $(document).on('change', '.w5e-courier-default', function () {
        var $row = $(this).closest('tr');
        var $enable = $row.find('.w5e-courier-enable');
        if ($enable.length) {
            $enable.prop('checked', true);
        }
    });

    $('#w5e-fetch-warehouses-btn').on('click', function () {
        var $btn = $(this);
        var $status = $('#w5e-fetch-warehouses-status');
        var i18n = W5EAdmin.i18n || {};
        $btn.prop('disabled', true);
        $status.text(i18n.fetching || 'Working...');

        if (!ajaxUrl) {
            $btn.prop('disabled', false);
            return;
        }

        $.post(ajaxUrl, {
            action: 'w5e_fetch_warehouses',
            nonce: nonce
        }).done(function (resp) {
            if (resp && resp.success) {
                var count = (resp.data && resp.data.count) ? resp.data.count : 0;
                var tmpl = i18n.successWarehouses || 'Done: %d warehouses cached. Reload the page.';
                $status.text(tmpl.replace('%d', count));
            } else {
                var errorPrefix = i18n.errorPrefix || 'Error:';
                var unknown = i18n.unknownError || 'Unknown';
                var message = (resp && resp.data && resp.data.message) ? resp.data.message : unknown;
                $status.text(errorPrefix + ' ' + message);
            }
        }).fail(function () {
            $status.text(i18n.requestError || 'Request failed.');
        }).always(function () {
            $btn.prop('disabled', false);
        });
    });

    $(document).on('change', '.w5e-warehouse-default', function () {
        var $this = $(this);
        if (!$this.is(':checked')) {
            return;
        }
        var $table = $this.closest('table');
        var $scope = $table.length ? $table : $(document);
        $scope.find('.w5e-warehouse-default').not($this).prop('checked', false);
    });

    function toggleEnvironmentFields() {
        if (!$envSelect.length) {
            return;
        }
        var env = $envSelect.val();
        if ($stagingUrlRow.length) {
            $stagingUrlRow.toggle(env === 'staging');
        }
        if ($productionUrlRow.length) {
            $productionUrlRow.toggle(env === 'production');
        }
    }

    if ($statusTriggerRow.length) {
        $statusTriggerRow.hide();
    }
    if ($envSelect.length) {
        toggleEnvironmentFields();
        $envSelect.on('change', toggleEnvironmentFields);
    }

    function hideSettingsRows() {
        var ids = [
            'w5e_flat_price',
            'w5e_order_forwarding_enabled',
            'w5e_client_user_id',
            'w5e_created_user_id',
            'w5e_recipient_pre_notification',
            'w5e_return_doc',
            'w5e_del_payment_by',
            'w5e_shipment_type',
            'w5e_delivery_type'
        ];
        var cssRules = [];
        ids.forEach(function (id) {
            var $field = $('#' + id);
            var $row = $field.closest('tr');
            if ($row.length) {
                $row.addClass('w5e-hidden-row').hide();
            } else {
                // Fall back to hiding label/field wrapper if not in a <tr>.
                $field.closest('.form-field, fieldset, p').addClass('w5e-hidden-row').hide();
            }
            cssRules.push('tr:has(#' + id + '), .form-field:has(#' + id + '), fieldset:has(#' + id + '), p:has(#' + id + '){display:none !important;}');
        });
        if (cssRules.length && document.head) {
            var style = document.createElement('style');
            style.textContent = cssRules.join('\n');
            document.head.appendChild(style);
        }
    }
    hideSettingsRows();
    setTimeout(hideSettingsRows, 300); // in case Woo renders after ready.

    /**
     * Shipping method modal (zone) conditional fields.
     */
    function toggleMethodField($container, fieldId, visible) {
        if (!$container || !$container.length) return;
        var $field = $container.find('#' + fieldId);
        if (!$field.length) return;

        // Try common wrappers in the WC modal.
        var $wrapper = $field.closest('tr, .form-field, fieldset');
        var $label = $container.find('label[for="' + fieldId + '"]');

        if ($wrapper.length) {
            $wrapper.toggle(visible);
        } else {
            $field.toggle(visible);
        }

        if ($label.length && !$label.closest('tr, .form-field, fieldset').is($wrapper)) {
            $label.toggle(visible);
        }
    }

    function togglePricingModeFields($container) {
        var $select = $container.find('select[name^="woocommerce_w5e_pricing_mode"]');
        if (!$select.length) return;
        var mode = $select.val();
        var requiresVal = $container.find('select[name^="woocommerce_w5e_requires"]').val() || '';
        var showFixed = mode === 'fixed_price';
        var showRequires = mode === 'free_over';
        var showMin = mode === 'free_over' && requiresVal === 'min_amount';
        var showAutoAndFixedExtras = mode !== 'free_over';
        var showRecipientPays = mode === 'recipient_pays';
        var showWeightThreshold = mode === 'free_over' && requiresVal === 'weight_over';

        toggleMethodField($container, 'woocommerce_w5e_fixed_price', showFixed);
        toggleMethodField($container, 'woocommerce_w5e_requires', showRequires);
        toggleMethodField($container, 'woocommerce_w5e_min_amount', showMin);
        toggleMethodField($container, 'woocommerce_w5e_recipient_pays_limit', showRecipientPays);
        toggleMethodField($container, 'woocommerce_w5e_free_shipping_over', showAutoAndFixedExtras);
        toggleMethodField($container, 'woocommerce_w5e_free_shipping_weight_over', showWeightThreshold);
    }

    function fixW5EModalTitle($context) {
        var $scope = $context && $context.length ? $context : $(document);

        $scope.find('.wc-backbone-modal-shipping-method-settings').each(function () {
            var $modal = $(this);
            if (!$modal.find('[id^="woocommerce_w5e_"], [name^="woocommerce_w5e_"]').length) {
                return;
            }
            var $title = $modal.find('.wc-backbone-modal-header h1');
            if (!$title.length) return;
            if (!$title.data('w5eTitleObserver')) {
                var observer = new MutationObserver(function () {
                    var current = $title.text();
                    var replaced = current.replace(/5e/g, '5E');
                    if (replaced !== current) {
                        $title.text(replaced);
                    }
                });
                observer.observe($title.get(0), { childList: true, characterData: true, subtree: true });
                $title.data('w5eTitleObserver', observer);
            }
            var text = $title.text();
            var updated = text.replace(/5e/g, '5E');
            if (updated !== text) {
                $title.text(updated);
            }
        });
    }

    function bindPricingModeHandlers($root) {
        $root.find('.wc-shipping-zone-method-fields').each(function () {
            var $container = $(this);
            togglePricingModeFields($container);
            fixW5EModalTitle($container);
            $container.off('change.w5ePricing').on('change.w5ePricing', 'select[name^="woocommerce_w5e_pricing_mode"], select[name^="woocommerce_w5e_requires"]', function () {
                togglePricingModeFields($container);
            });
        });
    }

    bindPricingModeHandlers($(document));
    $(document.body).on('wc_backbone_modal_loaded', function () {
        fixW5EModalTitle($(document));
        setTimeout(function () { fixW5EModalTitle($(document)); }, 60);
    });

    var modalObserver = new MutationObserver(function (mutations) {
        mutations.forEach(function (mutation) {
            $(mutation.addedNodes).each(function () {
                var $node = $(this);
                if ($node.hasClass('wc-shipping-zone-method-fields') || $node.find('.wc-shipping-zone-method-fields').length) {
                    bindPricingModeHandlers($node);
                }
                if ($node.hasClass('wc-backbone-modal-shipping-method-settings') || $node.find('.wc-backbone-modal-shipping-method-settings').length) {
                    fixW5EModalTitle($node);
                    setTimeout(function () { fixW5EModalTitle($node); }, 60);
                }
            });
        });
    });
    modalObserver.observe(document.body, { childList: true, subtree: true });

    var $pricing = $('#w5e-pricing-matrix');
    var $pricingToggle = $('#w5e-toggle-pricing-matrix');
    if ($pricing.length) {
        function setPricingVisibility(show) {
            $pricing.toggle(!!show);
            if ($pricingToggle.length) {
                $pricingToggle.attr('aria-expanded', !!show);
                var hideText = $pricingToggle.data('hide') || 'Hide pricing matrix';
                var showText = $pricingToggle.data('show') || 'Show pricing matrix';
                $pricingToggle.text(show ? hideText : showText);
            }
        }

        setPricingVisibility(false);

        if ($pricingToggle.length) {
            $pricingToggle.on('click', function (e) {
                e.preventDefault();
                var isOpen = $pricing.is(':visible');
                setPricingVisibility(!isOpen);
            });
        }

        var templates = {
            group: $('#w5e-pricing-group-template').html() || '',
            row: $('#w5e-pricing-row-template').html() || ''
        };

        var groupIndex = -1;
        $pricing.find('.w5e-pricing-group').each(function () {
            var $group = $(this);
            var idx = parseInt($group.data('index'), 10);
            if (!isNaN(idx)) {
                groupIndex = Math.max(groupIndex, idx);
                $group.data('index', idx);
            }
            cacheCounts($group);
        });
        groupIndex++;

        function cacheCounts($group) {
            $group.data('standard-count', $group.find('.w5e-standard-rows tr').length);
        }

        function nextGroupIndex() {
            return groupIndex++;
        }

        function nextRowIndex($group) {
            var current = parseInt($group.data('standard-count'), 10);
            if (isNaN(current)) {
                current = 0;
            }
            $group.data('standard-count', current + 1);
            return current;
        }

        function replaceAll(template, index, row, note) {
            var output = template.replace(/__INDEX__/g, index);
            if (typeof row !== 'undefined') {
                output = output.replace(/__ROW__/g, row);
            }
            if (typeof note !== 'undefined') {
                output = output.replace(/__NOTE__/g, note);
            }
            return output;
        }

        $('#w5e-add-pricing-group').on('click', function (e) {
            e.preventDefault();
            if (!templates.group) {
                return;
            }
            var index = nextGroupIndex();
            var html = replaceAll(templates.group, index);
            var $group = $(html);
            $group.attr('data-index', index);
            cacheCounts($group);
            $pricing.append($group);
        });

        $pricing.on('click', '.w5e-add-row', function (e) {
            e.preventDefault();
            var $group = $(this).closest('.w5e-pricing-group');
            var tpl = templates.row;
            if (!tpl) {
                return;
            }
            var groupId = $group.data('index');
            var rowIdx = nextRowIndex($group);
            var html = replaceAll(tpl, groupId, rowIdx);
            $group.find('.w5e-standard-rows').append(html);
        });

        $pricing.on('click', '.w5e-remove-row', function (e) {
            e.preventDefault();
            $(this).closest('tr').remove();
        });

        $pricing.on('click', '.w5e-remove-group', function (e) {
            e.preventDefault();
            $(this).closest('.w5e-pricing-group').remove();
        });

    }

    // Tweak description spacing in shipping modals.
    if (document.head) {
        var style = document.createElement('style');
        style.textContent = '.wc-shipping-zone-method-fields p.description{margin-top:0;}';
        document.head.appendChild(style);
    }
});
