jQuery(function($) {
    function copyText(value) {
        if (!value) return;
        if (navigator.clipboard && navigator.clipboard.writeText) {
            navigator.clipboard.writeText(value);
            return;
        }
        var input = $('<input>').val(value).appendTo('body').select();
        try { document.execCommand('copy'); } catch (e) {}
        input.remove();
    }

    $(document).on('click', '[data-ghostonix-fib-copy]', function(e) {
        e.preventDefault();
        copyText($(this).attr('data-ghostonix-fib-copy') || '');
        var button = $(this);
        var oldText = button.text();
        button.text('Copied');
        setTimeout(function() { button.text(oldText); }, 1200);
    });

    var box = $('[data-ghostonix-fib-status]');
    if (!box.length) return;

    var orderId = box.attr('data-order-id') || '';
    var key = box.attr('data-order-key') || '';
    var statusUrl = box.attr('data-status-url') || '';
    var nonce = box.attr('data-status-nonce') || '';
    var timer = null;

    function setLabel(text, spin) {
        $('[data-ghostonix-fib-label]').text(text);
        box.html('<span>' + (spin ? '<i></i> ' : '') + text + '</span>');
    }

    function poll() {
        if (!statusUrl || !orderId || !key || !nonce) return;
        $.ajax({
            url: statusUrl,
            method: 'GET',
            cache: false,
            data: { order_id: orderId, key: key, nonce: nonce }
        }).done(function(response) {
            if (response && response.label) setLabel(response.label, !response.final);
            if (response && response.redirect) {
                clearInterval(timer);
                window.location.href = response.redirect;
            }
        }).fail(function() {
            setLabel('Waiting for FIB payment confirmation...', true);
        });
    }

    $(document).on('click', '[data-ghostonix-fib-check]', function(e) {
        e.preventDefault();
        poll();
    });

    setTimeout(function() {
        poll();
        timer = setInterval(function() {
            if (document.visibilityState === 'visible') poll();
        }, 5000);
    }, 3000);

    document.addEventListener('visibilitychange', function() {
        if (document.visibilityState === 'visible') poll();
    });
    window.addEventListener('focus', poll);
});
