/**
 * Order Admin JS — Handles Label Generation AJAX and Clipboard.
 */
jQuery(function($) {
    const $box = $('.ps-inpost-details-box');
    if (!$box.length) return;

    // Handle Label Generation
    $(document).on('click', '.ps-gen-label-btn', function(e) {
        e.preventDefault();
        const $btn = $(this);
        const orderId = $btn.data('order-id');
        const payCrypto = $btn.data('crypto') ? 1 : 0;

        if ($btn.prop('disabled')) return;

        $btn.prop('disabled', true).text('Generowanie...');

        $.post(ajaxurl, {
            action: 'parcselect_generate_label',
            nonce: parcselectOrderAdmin.nonce,
            order_id: orderId,
            pay_crypto: payCrypto
        }, function(res) {
            if (res.success) {
                alert(res.data.message);
                $btn.text('Etykieta Gotowa').addClass('ps-btn-success');
                // Optional: location.reload();
            } else {
                alert('Błąd: ' + (res.data.message || 'Nieznany błąd'));
                $btn.prop('disabled', false).text('Spróbuj ponownie');
            }
        }).fail(function() {
            alert('Błąd serwera. Spróbuj ponownie później.');
            $btn.prop('disabled', false).text('Spróbuj ponownie');
        });
    });

    // Clipboard for copy-to-clipboard buttons
    $(document).on('click', '.ps-copy-btn', function() {
        const text = $(this).data('copy');
        const $btn = $(this);
        
        navigator.clipboard.writeText(text).then(() => {
            const oldText = $btn.html();
            $btn.html('✅ Skopiowano!');
            setTimeout(() => $btn.html(oldText), 2000);
        });
    });
});
