(function () {
    // Run only on Blocks checkout UI; skip classic checkout.
    if (!document.querySelector('.wp-block-woocommerce-checkout, .wc-block-checkout')) {
        return;
    }

    const cfg = window.plantshop_wc_er_info || {};
    if (!cfg || !cfg.description) {
        return;
    }

    const FIELD_ID = 'plantshop-wc/equivalent_replacement_consent';

    function applyDescriptionToFields(fields) {
        if (!fields || typeof fields !== 'object') {
            return fields;
        }
        // Ensure containers exist
        fields.order = fields.order || {};

        // Common containers used by different WC Blocks versions
        const containers = [
            fields.order.other,
            fields.order.additionalFields,
            fields.order
        ];

        for (let i = 0; i < containers.length; i++) {
            const bucket = containers[i];
            if (bucket && typeof bucket === 'object' && bucket[FIELD_ID]) {
                bucket[FIELD_ID].description = cfg.description;
                return fields;
            }
        }

        // Fallback: deep search for the field id key anywhere in fields
        try {
            (function deepAssign(obj) {
                if (!obj || typeof obj !== 'object') {
                    return;
                }
                if (obj[FIELD_ID]) {
                    obj[FIELD_ID].description = cfg.description;
                    return;
                }
                for (const k in obj) {
                    if (Object.prototype.hasOwnProperty.call(obj, k)) {
                        deepAssign(obj[k]);
                    }
                }
            })(fields);
        } catch (e) {
        }
        return fields;
    }

    // Newer API: wc.blocksCheckout.registerCheckoutFilters
    try {
        const wc = window.wc || {};
        const blocksCheckout = wc.blocksCheckout || {};
        const registerCheckoutFilters = blocksCheckout.registerCheckoutFilters;
        if (typeof registerCheckoutFilters === 'function') {
            registerCheckoutFilters('plantshop-wc-er-info', {
                checkoutFields: function (fields /*, context */) {
                    return applyDescriptionToFields(fields);
                }
            });
        }
    } catch (e) {
    }

    // Legacy API: wp.hooks filter
    try {
        if (window.wp && window.wp.hooks && typeof window.wp.hooks.addFilter === 'function') {
            window.wp.hooks.addFilter(
                'experimental__woocommerce_blocks_checkout_fields',
                'plantshop-wc-er-info',
                function (fields) {
                    return applyDescriptionToFields(fields);
                }
            );
        }
    } catch (e) {
    }

    // DOM-based fallback: inject the helper link inside the checkbox label text.
    function domInject() {
        try {
            const input = document.querySelector(
                'input[type="checkbox"][name*="equivalent_replacement_consent"], ' +
                'input[type="checkbox"][id*="equivalent_replacement_consent"], ' +
                '[data-id*="equivalent_replacement_consent"] input[type="checkbox"], ' +
                '[data-key*="equivalent_replacement_consent"] input[type="checkbox"]'
            );
            if (!input) {
                return false;
            }
            // Find the closest field wrapper
            const fieldWrapper = input.closest('.wc-block-components-text-input, .wc-block-components-checkbox, .wc-block-components-form-row, .wc-block-components-form__input');
            let container = fieldWrapper || input.parentElement;
            if (!container) {
                container = input.parentElement;
            }

            const label = container ? container.querySelector('label') : null;
            if (!container || !label) {
                return false;
            }

            const marker = 'equivalent_replacement_consent';
            const existing = container.querySelector('.plantshop-wc-er-info[data-pswc-er-for="' + marker + '"]');

            // Avoid duplicates
            if (!existing) {
                const desc = document.createElement('p');
                desc.className = 'plantshop-wc-er-info';
                desc.setAttribute('data-pswc-er-for', marker);
                desc.innerHTML = cfg.description;
                desc.style.display = 'block';
                desc.style.margin = '6px 0 0 28px';
                desc.style.fontSize = '0.875em';
                desc.style.lineHeight = '1.4';
                container.appendChild(desc);
            }
            return true;
        } catch (e) {
            return false;
        }
    }

    // Bounded retries to survive async React render without endless reinjection side-effects.
    let attempts = 0;
    function tryInject() {
        if (domInject()) {
            return;
        }
        if (attempts < 15) {
            attempts++;
            setTimeout(tryInject, 300);
        }
    }

    if (document.readyState === 'complete' || document.readyState === 'interactive') {
        setTimeout(tryInject, 0);
    } else {
        document.addEventListener('DOMContentLoaded', tryInject);
    }
})();
