jQuery(document).ready(function ($) {
    // 1. Open guest lookup modal from footer link
    $(document).on('click', '.grcop-open-guest-modal', function (e) {
        e.preventDefault();
        var lookupHtml = '<div class="grcop-form-header">' +
            '<h2>' + grcop_ajax.strings.confirm_title + '</h2>' +
            '<p>Vnesite številko naročila in e-poštni naslov za začetek odstopa.</p>' +
            '</div>' +
            '<form id="grcop-modal-lookup-form" class="grcop-form-box">' +
            '<div class="grcop-input-group">' +
            '<label>Številka naročila (Order ID) <span class="required">*</span></label>' +
            '<input type="number" id="grcop_modal_order_id" required placeholder="npr. 12345">' +
            '</div>' +
            '<div class="grcop-input-group">' +
            '<label>E-poštni naslov za račun <span class="required">*</span></label>' +
            '<input type="email" id="grcop_modal_email" required placeholder="ime@domena.si">' +
            '</div>' +
            '<button type="submit" class="grcop-btn grcop-btn-primary">Išči naročilo</button>' +
            '<div class="grcop-loader" style="display:none;"></div>' +
            '</form>' +
            '<div id="grcop-modal-result" style="display:none; margin-top:20px;"></div>';

        $('#grcop-modal-inner').html(lookupHtml);
        $('#grcop-modal').fadeIn(200);
    });

    // 2. Open modal from My Account order actions
    $(document).on('click', '.grcop-open-modal-btn', function (e) {
        e.preventDefault();
        var orderId = $(this).data('order-id');
        var email = $(this).data('email');

        // If not present in attributes, try to find it on My Account page
        if (!orderId) {
            // If clicked from order table action row
            var $row = $(this).closest('tr');
            if ($row.length) {
                // WooCommerce orders table usually has class .woocommerce-orders-table__row
                // and the order number is inside .woocommerce-orders-table__cell-order-number a
                var orderNumText = $row.find('.woocommerce-orders-table__cell-order-number a').text().trim();
                orderId = orderNumText.replace('#', '');
            }
        }

        if (!orderId) {
            alert('Napaka: Številke naročila ni bilo mogoče zaznati.');
            return;
        }

        $('#grcop-modal-inner').html('<div class="grcop-loader"></div>');
        $('#grcop-modal').fadeIn(200);

        // Fetch order details via AJAX
        $.post(grcop_ajax.ajax_url, {
            action: 'grcop_lookup_order',
            order_id: orderId,
            email: email || '',
            security: grcop_ajax.nonce
        }, function (response) {
            if (response.success) {
                $('#grcop-modal-inner').html(response.data.html);
            } else {
                $('#grcop-modal-inner').html('<div class="grcop-badge grcop-badge-danger" style="display:block; padding:15px; margin: 15px 0;">' + response.data.message + '</div>');
            }
        }).fail(function () {
            $('#grcop-modal-inner').html('<div class="grcop-badge grcop-badge-danger" style="display:block; padding:15px; margin: 15px 0;">Strežniška napaka. Poskusite ponovno.</div>');
        });
    });

    // Close Modal actions
    $(document).on('click', '.grcop-modal-close', function () {
        $('#grcop-modal').fadeOut(200);
    });

    $(document).on('click', function (e) {
        if ($(e.target).is('#grcop-modal')) {
            $('#grcop-modal').fadeOut(200);
        }
    });

    // 3. Handle modal-based lookup form submit
    $(document).on('submit', '#grcop-modal-lookup-form', function (e) {
        e.preventDefault();
        var $form = $(this);
        var orderId = $('#grcop_modal_order_id').val();
        var email = $('#grcop_modal_email').val();
        var $loader = $form.find('.grcop-loader');
        var $btn = $form.find('button[type="submit"]');

        $btn.hide();
        $loader.show();

        $.post(grcop_ajax.ajax_url, {
            action: 'grcop_lookup_order',
            order_id: orderId,
            email: email,
            security: grcop_ajax.nonce
        }, function (response) {
            $loader.hide();
            if (response.success) {
                $('#grcop-modal-inner').html(response.data.html);
            } else {
                $btn.show();
                alert(response.data.message);
            }
        }).fail(function () {
            $loader.hide();
            $btn.show();
            alert('Napaka pri poizvedbi.');
        });
    });

    // 4. Handle shortcode lookup form submit (guest lookup on a page)
    $(document).on('submit', '#grcop-lookup-form', function (e) {
        e.preventDefault();
        var orderId = $('#grcop_order_id').val();
        var email = $('#grcop_email').val();
        var $loader = $('.grcop-loader');
        var $btn = $('#grcop-lookup-submit');
        var $result = $('#grcop-lookup-result');

        $btn.hide();
        $loader.show();
        $result.hide();

        $.post(grcop_ajax.ajax_url, {
            action: 'grcop_lookup_order',
            order_id: orderId,
            email: email,
            security: grcop_ajax.nonce
        }, function (response) {
            $loader.hide();
            if (response.success) {
                $result.html(response.data.html).slideDown(250);
                $('#grcop-lookup-form').slideUp(250);
            } else {
                $btn.show();
                alert(response.data.message);
            }
        }).fail(function () {
            $loader.hide();
            $btn.show();
            alert('Napaka pri povezavi s strežnikom.');
        });
    });

    // 5. Checkbox toggles quantity dropdown status
    $(document).on('change', '.grcop-item-checkbox', function () {
        var $row = $(this).closest('.grcop-item-row');
        var isChecked = $(this).is(':checked');
        $row.find('.grcop-qty-dropdown').prop('disabled', !isChecked);
        if (isChecked) {
            $row.css('border-color', 'var(--grcop-primary)');
        } else {
            $row.css('border-color', 'var(--grcop-border)');
        }
    });

    // 6. Refund method radio buttons show/hide IBAN text area
    $(document).on('change', 'input[name="refund_method"]', function () {
        var val = $(this).val();
        if (val === 'iban') {
            $('.grcop-iban-input-container').slideDown(200);
            $('#grcop_iban').prop('required', true);
        } else {
            $('.grcop-iban-input-container').slideUp(200);
            $('#grcop_iban').prop('required', false);
        }
    });

    // 7. Step 1: Click verification button (Verify input details and request two-step confirm)
    $(document).on('click', '#grcop-submit-verification-btn', function (e) {
        e.preventDefault();
        var $form = $(this).closest('form');

        // Check if at least one checkbox is checked
        if ($form.find('.grcop-item-checkbox:checked').length === 0) {
            alert(grcop_ajax.strings.error_select_item);
            return;
        }

        // Check IBAN if selected
        var refMethod = $form.find('input[name="refund_method"]:checked').val();
        if (refMethod === 'iban' && $('#grcop_iban').val().trim() === '') {
            alert('Prosimo, vnesite vaš TRR (IBAN) račun za vračilo kupnine.');
            $('#grcop_iban').focus();
            return;
        }

        // Transition to confirmation state (Step 2 - confirmation overlay / buttons)
        $(this).hide();
        
        var confirmHtml = '<div class="grcop-confirmation-block" style="background: hsl(210, 20%, 98%); border: 1px solid var(--grcop-border); padding: 15px; border-radius: 6px; margin-top: 15px; text-align: center;">' +
            '<p style="margin: 0 0 12px 0; font-weight: 600; font-size: 0.95rem; color: var(--grcop-text);">' + grcop_ajax.strings.confirm_text + '</p>' +
            '<div style="display:flex; justify-content:center; gap:10px;">' +
            '<button type="button" class="grcop-btn grcop-btn-primary" id="grcop-final-confirm-btn">' + grcop_ajax.strings.confirm_button + '</button>' +
            '<button type="button" class="grcop-btn grcop-btn-secondary" id="grcop-final-cancel-btn" style="background:#ddd; color:#333;">' + grcop_ajax.strings.cancel_button + '</button>' +
            '</div>' +
            '</div>';

        $form.append(confirmHtml);
    });

    // Step 2: Cancel confirmation
    $(document).on('click', '#grcop-final-cancel-btn', function (e) {
        e.preventDefault();
        var $form = $(this).closest('form');
        $form.find('.grcop-confirmation-block').remove();
        $form.find('#grcop-submit-verification-btn').show();
    });

    // Step 2: Final submit confirm click
    $(document).on('click', '#grcop-final-confirm-btn', function (e) {
        e.preventDefault();
        var $btn = $(this);
        var $form = $btn.closest('form');
        var $loader = $form.find('.grcop-submit-loader');

        $form.find('.grcop-confirmation-block').hide();
        $loader.show();

        // AJAX submit form details
        var formData = $form.serialize();
        formData += '&action=grcop_submit_withdrawal&security=' + grcop_ajax.nonce;

        $.post(grcop_ajax.ajax_url, formData, function (response) {
            $loader.hide();
            if (response.success) {
                // Show beautiful success screen
                var successHtml = '<div style="text-align:center; padding: 1.5rem 1rem;">' +
                    '<div style="color: var(--grcop-success); font-size: 3.5rem; margin-bottom: 0.5rem;">✓</div>' +
                    '<h3 style="font-weight:700; margin-bottom:0.5rem;">Zahtevek uspešno oddan!</h3>' +
                    '<p style="color: var(--grcop-text-light); margin-bottom:1.5rem;">' + response.data.message + '</p>';

                if (response.data.instructions) {
                    successHtml += '<div class="grcop-instructions-block" style="text-align:left; background:#f8fafc; border:1px solid var(--grcop-border); padding:15px; border-radius:6px; margin-bottom:1.5rem; font-size:0.9em; line-height:1.5; color: var(--grcop-text);">' +
                        '<h4 style="margin:0 0 8px 0; font-weight:700; color: var(--grcop-text);">' + 'Navodila za vračilo paketa:' + '</h4>' +
                        '<div>' + response.data.instructions + '</div>' +
                        '</div>';
                }

                successHtml += '<div style="display:flex; justify-content:center; gap:10px; flex-wrap:wrap; margin-top: 15px;">';
                if (response.data.label_html) {
                    successHtml += '<button type="button" class="grcop-btn grcop-btn-primary" id="grcop-print-label-btn" style="background:#10b981;">Natisni nalepko za paket</button>';
                }
                successHtml += '<button type="button" class="grcop-btn" style="background:#ddd; color:#333;" onclick="window.location.reload();">Zapri</button>' +
                    '</div>' +
                    '</div>';

                // Save label html locally in window to fetch easily
                if (response.data.label_html) {
                    window.grcop_label_html = response.data.label_html;
                }

                // Update container
                var $modalInner = $('#grcop-modal-inner');
                var $shortcodeResult = $('#grcop-lookup-result');

                if ($modalInner.is(':visible')) {
                    $modalInner.html(successHtml);
                } else {
                    $shortcodeResult.html(successHtml);
                }
            } else {
                $form.find('.grcop-confirmation-block').show();
                alert(response.data.message);
            }
        }).fail(function () {
            $loader.hide();
            $form.find('.grcop-confirmation-block').show();
            alert('Napaka pri oddaji zahtevka. Poskusite znova.');
        });
    });

    // 8. Print label click handler
    $(document).on('click', '#grcop-print-label-btn', function (e) {
        e.preventDefault();
        var labelHtml = window.grcop_label_html;
        if (labelHtml) {
            var printWin = window.open('', '_blank', 'width=600,height=500');
            if (printWin) {
                printWin.document.open();
                printWin.document.write('<html><head><title>Nalepka za vračilo blaga</title></head><body onload="window.print(); window.close();" style="display:flex; justify-content:center; align-items:center; min-height:90vh; margin:0; background:#fff;">');
                printWin.document.write(labelHtml);
                printWin.document.write('</body></html>');
                printWin.document.close();
            } else {
                alert('Prosimo, omogočite pojavna okna (pop-ups) v vašem brskalniku za tisk nalepke.');
            }
        }
    });
});
