document.addEventListener('DOMContentLoaded', function () {
    var couponBtn = document.getElementById('bwp-copy-coupon');

    if (!couponBtn) {
        return;
    }

    var couponMsg = document.getElementById('bwp-copy-coupon-msg');
    var resetTimer;

    function showCopied() {
        couponBtn.classList.add('is-copied');

        if (couponMsg) {
            couponMsg.classList.add('is-visible');
        }

        clearTimeout(resetTimer);
        resetTimer = setTimeout(function () {
            couponBtn.classList.remove('is-copied');

            if (couponMsg) {
                couponMsg.classList.remove('is-visible');
            }
        }, 1800);
    }

    function fallbackCopy(text) {
        var tempInput = document.createElement('input');
        tempInput.type = 'text';
        tempInput.value = text;
        tempInput.setAttribute('readonly', 'readonly');
        tempInput.style.position = 'absolute';
        tempInput.style.left = '-9999px';
        document.body.appendChild(tempInput);
        tempInput.select();
        tempInput.setSelectionRange(0, text.length);

        try {
            document.execCommand('copy');
            showCopied();
        } catch (err) {
            // Copying isn't supported in this browser; fail silently.
        }

        document.body.removeChild(tempInput);
    }

    function copyCouponCode(text) {
        if (navigator.clipboard && window.isSecureContext) {
            navigator.clipboard.writeText(text).then(showCopied, function () {
                fallbackCopy(text);
            });
        } else {
            fallbackCopy(text);
        }
    }

    couponBtn.addEventListener('click', function () {
        copyCouponCode(couponBtn.getAttribute('data-coupon') || '');
    });
});
