(function ($) {
    'use strict';

    // Lazy lookups so the script works whether it runs before or after DOM-ready.
    function modal()      { return $('#sbuy-bulk-price-modal'); }
    function previewBox() { return $('#sbuy-price-preview'); }
    function applyBtn()   { return $('#sbuy-price-apply-btn'); }

    function currentMode() {
        return $('input[name="sbuy-price-mode"]:checked').val() || 'percent';
    }

    function adjustmentPayload() {
        var mode = currentMode();
        if (mode === 'fixed') {
            var amount = parseFloat($('#sbuy-price-amount').val());
            if (!amount || amount <= 0) return null;
            return {
                mode: 'fixed',
                amount: amount,
                direction: $('#sbuy-price-direction').val()
            };
        }
        var percent = parseFloat($('#sbuy-price-percent').val());
        if (!percent || percent <= 0) return null;
        return {
            mode: 'percent',
            percent: percent,
            direction: $('#sbuy-price-direction').val()
        };
    }

    function openModal() {
        previewBox().hide().empty();
        applyBtn().prop('disabled', true);
        modal().css('display', 'block');
    }

    function closeModal() {
        modal().css('display', 'none');
    }

    function renderPreview(data) {
        var currency = sbuy_bulk_price.currency || '';
        var sign = (data.direction === 'decrease' ? '-' : '+');
        var label = (data.mode === 'fixed')
            ? (sign + data.value + currency)
            : (sign + data.value + '%');

        var lines = [];
        lines.push('<strong>' + data.total + ' ' + sbuy_bulk_price.i18n.willAdjust +
            ' (' + label + ')</strong>');

        if (data.samples && data.samples.length) {
            lines.push('<p style="margin:8px 0 4px;"><em>' + sbuy_bulk_price.i18n.examples + '</em></p>');
            lines.push('<ul style="margin:0 0 8px 18px;">');
            data.samples.forEach(function (s) {
                lines.push('<li>' + $('<div>').text(s.title).html() +
                    ' &nbsp; ' + s.old + currency + ' → ' + s.new + currency + '</li>');
            });
            lines.push('</ul>');
        }

        lines.push('<p style="color:#d63638; margin:8px 0 0; font-size:12px;">⚠️ ' +
            sbuy_bulk_price.i18n.cannotUndo + '</p>');

        previewBox().html(lines.join('')).show();
        applyBtn().prop('disabled', false);
    }

    // Mode toggle: enable the active input, disable the other.
    // Use vanilla DOM API — more reliable than jQuery .prop/.attr in edge cases
    // where another script or stylesheet has fiddled with the disabled attribute.
    function syncModeInputs() {
        var fixed = currentMode() === 'fixed';
        var amountEl  = document.getElementById('sbuy-price-amount');
        var percentEl = document.getElementById('sbuy-price-percent');
        if (amountEl)  amountEl.disabled  = !fixed;
        if (percentEl) percentEl.disabled = fixed;
        previewBox().hide().empty();
        applyBtn().prop('disabled', true);
    }

    // Attach listeners via vanilla JS too — independent of jQuery version quirks.
    $(function () {
        var radios = document.querySelectorAll('input[name="sbuy-price-mode"]');
        radios.forEach(function (r) {
            r.addEventListener('change', syncModeInputs);
            r.addEventListener('click',  syncModeInputs);
        });
        syncModeInputs(); // enforce correct state on page load
    });

    $(document).on('click', '#sbuy-bulk-price-btn', openModal);
    $(document).on('click', '#sbuy-price-cancel-btn', closeModal);

    $(document).on('click', '#sbuy-price-preview-btn', function () {
        var payload = adjustmentPayload();
        if (!payload) return;
        payload.action = 'sbuy_bulk_price_preview';
        payload.nonce = sbuy_bulk_price.nonce;

        $.ajax({ method: 'POST', url: sbuy_bulk_price.ajaxUrl, data: payload })
            .done(function (response) {
                if (response && response.success && response.data) {
                    renderPreview(response.data);
                } else {
                    alert((response && response.data && response.data.message) || sbuy_bulk_price.i18n.requestFailed);
                }
            })
            .fail(function () { alert(sbuy_bulk_price.i18n.requestFailed); });
    });

    $(document).on('click', '#sbuy-price-apply-btn', function () {
        if (!confirm(sbuy_bulk_price.i18n.confirmApply)) return;
        var payload = adjustmentPayload();
        if (!payload) return;
        payload.action = 'sbuy_bulk_price_apply';
        payload.nonce = sbuy_bulk_price.nonce;

        var $btn = $(this).prop('disabled', true);
        $.ajax({ method: 'POST', url: sbuy_bulk_price.ajaxUrl, data: payload })
            .done(function (response) {
                if (response && response.success && response.data && response.data.message) {
                    alert(response.data.message);
                }
                closeModal();
                window.location.reload();
            })
            .fail(function () {
                alert(sbuy_bulk_price.i18n.requestFailed);
                $btn.prop('disabled', false);
            });
    });

})(jQuery);
