jQuery(function() {
    window.tfreeAjax = function(opts) {
        opts = opts || {};
        opts.url = (typeof ajax_object !== 'undefined' && ajax_object.ajax_url) ? ajax_object.ajax_url : opts.url;
        opts.headers = opts.headers || {};
        if (typeof ajax_object !== 'undefined' && ajax_object.nonce) {
            opts.headers['X-WP-Nonce'] = ajax_object.nonce;
        }
        return jQuery.ajax(opts);
    };
});

jQuery(document).ready(function($) {
    function tfreeGetVisibleOrderIds() {
        var ids = [];

        jQuery('input[name="post[]"], input[name="id[]"], input[name="order_id[]"], input[name="orders[]"]').each(function() {
            var val = parseInt(jQuery(this).val(), 10);
            if (val > 0) {
                ids.push(val);
            }
        });

        jQuery('table.wp-list-table tbody tr').each(function() {
            var rowId = jQuery(this).attr('id') || '';
            var match = rowId.match(/(?:post|order)-(\d+)/);
            if (match && match[1]) {
                ids.push(parseInt(match[1], 10));
            }
        });

        var unique = [];
        var seen = {};
        ids.forEach(function(id) {
            if (id > 0 && !seen[id]) {
                seen[id] = true;
                unique.push(id);
            }
        });

        return unique;
    }

    function tfreeInjectOrdersListSyncButton() {
        var isLegacyOrdersPage = jQuery('body.post-type-shop_order').length > 0;
        var isHposOrdersPage = jQuery('body.woocommerce_page_wc-orders').length > 0;
        if (!isLegacyOrdersPage && !isHposOrdersPage) {
            return;
        }
        var tfreeOptions = (typeof ajax_object !== 'undefined' && ajax_object) ? ajax_object : {};
        var labels = {
            button: tfreeOptions.sync_this_page_label || 'Sync Shipment Statuses (This Page)',
            noOrders: tfreeOptions.no_orders_on_page_message || 'No orders found on this page.',
            syncing: tfreeOptions.syncing_label || 'Syncing...',
            inProgress: tfreeOptions.sync_in_progress_message || 'Sync in progress...',
            failed: tfreeOptions.sync_failed_message || 'Sync failed.',
            done: tfreeOptions.sync_complete_message || 'Sync complete.',
            partialError: tfreeOptions.sync_partial_error_message || 'Some orders could not be synced.',
            retry: tfreeOptions.sync_retry_message || 'Sync failed. Please try again.',
            busyFallback: tfreeOptions.sync_busy_fallback_message || 'Shipment status sync is already running. Please retry in a few seconds.'
        };
        var autoOrderStatusUpdateEnabled = parseInt(tfreeOptions.auto_order_status_update || 0, 10) === 1;
        var shipmentStatusInOrdersEnabled = parseInt(tfreeOptions.shipment_status_in_orders || 0, 10) === 1;
        if (!autoOrderStatusUpdateEnabled || !shipmentStatusInOrdersEnabled) {
            return;
        }

        if (jQuery('#tfree-sync-this-page-orders').length) {
            return;
        }

        var $target = jQuery('.tablenav.top .alignleft.actions.bulkactions').first();
        if (!$target.length) {
            $target = jQuery('.tablenav.top .alignleft.actions').first();
        }
        if (!$target.length) {
            return;
        }

        var $btn = jQuery('<button/>', {
            id: 'tfree-sync-this-page-orders',
            type: 'button',
            class: 'button',
            text: labels.button
        });
        var $msg = jQuery('<span/>', {
            id: 'tfree-sync-this-page-orders-msg',
            style: 'margin-left:8px;display:inline-flex;align-items:center;min-height:32px;line-height:1.3;'
        });

        $target.append($btn).append($msg);

        $btn.on('click', function() {
            var orderIds = tfreeGetVisibleOrderIds();
            if (!orderIds.length) {
                $msg.text(labels.noOrders).css('color', '#b32d2e');
                return;
            }

            $btn.prop('disabled', true).text(labels.syncing);
            $msg.text(labels.inProgress).css('color', '#646970');

            tfreeAjax({
                type: 'POST',
                data: {
                    action: 'tfree_manual_sync_orders_ids',
                    order_ids: orderIds
                },
                success: function(response) {
                    var data = response && response.data ? response.data : {};
                    if (data.status !== 'success') {
                        $msg.text(data.message || labels.failed).css('color', '#b32d2e');
                        return;
                    }
                    if (data.busy === 1) {
                        $msg.text(data.message || labels.busyFallback).css('color', '#b32d2e');
                        return;
                    }

                    var text = labels.done;
                    if ((data.order_errors || 0) > 0) {
                        text += ' ' + labels.partialError;
                    }
                    $msg.text(text).css('color', '#2271b1');

                    window.setTimeout(function() {
                        window.location.reload();
                    }, 1400);
                },
                error: function() {
                    $msg.text(labels.retry).css('color', '#b32d2e');
                },
                complete: function() {
                    $btn.prop('disabled', false).text(labels.button);
                }
            });
        });
    }

    tfreeInjectOrdersListSyncButton();

    $('#tfree_live_chat, #tfree_support_widget').click(function() {
        FreshworksWidget('show', 'launcher');
        FreshworksWidget('open');
        FreshworksWidget('identify', 'ticketForm', {
          name: ajax_object.store_name,
          email: ajax_object.admin_email,
        });
    });

    function updateActiveSubmenu() {
        const currentHash = window.location.hash || '#/home';
        const submenuItems = $('#toplevel_page_trackfree .wp-submenu li a');
        submenuItems.removeClass('tfree-current');
        submenuItems.each(function() {
            const href = $(this).attr('href');
            if (href.endsWith(currentHash)) {
                $(this).addClass('tfree-current');
            }
        });
    }

    updateActiveSubmenu();

    $(window).on('hashchange', function() {
        updateActiveSubmenu();
    });

    $(document).on('click', '.tfree_nav_shipments', function() {
        updateActiveSubmenu();
    });

    var modal = $('#tfree-add-track-modal');
    $(document).on('click', '.tf-show-add-track', function() {
        var id = this.id;
        modal.show();
        $('#tfree-add-ship-cont').html('<img src="https://tfree.sfo2.cdn.digitaloceanspaces.com/default/tf-wp-preloader.gif" alt="Please wait...">');
        tfreeAjax({
            type: 'POST',
            data: {
                action: 'tfree_add_shipment',
                order_id: id
            },
            success: function(data) {
                data = (data || '').toString();
                if (!data.trim()) {
                    $('#tfree-add-ship-cont').html('<div class="tfree-error-notification"><p>Unable to load tracking form. Please refresh and try again.</p></div>');
                    return;
                }
                $('#tfree-add-ship-cont').html(data);
                var total_order_items = $('#total_order_items').val();
                if (total_order_items == 0) {
                    $('#trackfree_btn_add_tracking').attr('disabled', true);
                } else {
                    $('#trackfree_btn_add_tracking').attr('disabled', false);
                }
            },
            error: function() {
                $('#tfree-add-ship-cont').html('<div class="tfree-error-notification"><p>Unable to load tracking form. Please refresh and try again.</p></div>');
            }
        });
    });

    var modal2 = $('#tfree-edit-track-modal');
    $(document).on('click', '.trackfree_edit_tracking', function(e) {
        e.preventDefault();
        e.stopPropagation();
        var id = this.id;
        var order_id = $(this).data('order-id') || $('#order_id').val() || $('#post_ID').val() || $('input[name="post_ID"]').val();
        order_id = parseInt(order_id, 10) || 0;
        if (!order_id) {
            modal2.show();
            $('#tfree-edit-ship-cont').html('<div class="tfree-error-notification"><p>Unable to identify this order. Please refresh and try again.</p></div>');
            return;
        }
        modal2.show();
        $('#tfree-edit-ship-cont').html('<img src="https://tfree.sfo2.cdn.digitaloceanspaces.com/default/tf-wp-preloader.gif" alt="Please wait...">');
        tfreeAjax({
            type: 'POST',
            data: {
                action: 'tfree_edit_shipment',
                shipment_id: id,
                order_id: order_id
            },
            success: function(data) {
                data = (data || '').toString();
                if (!data.trim()) {
                    $('#tfree-edit-ship-cont').html('<div class="tfree-error-notification"><p>Unable to load shipment details. Please refresh and try again.</p></div>');
                    return;
                }
                $('#tfree-edit-ship-cont').html(data);
            },
            error: function() {
                $('#tfree-edit-ship-cont').html('<div class="tfree-error-notification"><p>Unable to load shipment details. Please refresh and try again.</p></div>');
            }
        });
    });

    $('.tfree-cm-modal-close').on('click', function() {
        modal.hide();
        modal2.hide();
        $('.tfree-empty-line-error').hide();
    });

    $(window).on('click', function(event) {
        if ($(event.target).is(modal)) {
            modal.hide();
        }
        if ($(event.target).is(modal2)) {
            modal2.hide();
        }
    });

    $(document).on('change', '.tfree-product-qty', function() {
        $('.tfree-empty-line-error').hide();
    });

    $(document).on('change', '.tfree-edit-product-qty', function() {
        $('.tfree-empty-line-error').hide();
    });

    $('#trackfree_btn_add_tracking').click(function() {
        $('.tfree-add-shipment-error').hide();
        $('.tfree-invalid-shipment-error').hide();
        let products = [];
        let totalQty = 0;
        $('.tfree-prd-items tbody tr').each(function() {
            let product = {};
            product.id = $(this).find('.tfree-product-id').val();
            product.variation_id = $(this).find('.tfree-variation-id').val();
            product.quantity = $(this).find('.tfree-product-qty').val();
            product.order_items = $(this).find('.tfree-order-items').val();
            products.push(product);
            totalQty += Number(product.quantity);
        });

        var trackfree_tracking_number = $('#trackfree_tracking_number').val();
        var trackfree_courier_name = $("select#trackfree_courier_name option").filter(":selected").val();
        var trackfree_order_status = $("select#trackfree_order_status option").filter(":selected").val();
        var ord_id = $('#ord_id').val();
        var redirect_url = $('#redirect_url').val();
        if (trackfree_tracking_number) {
            if (trackfree_tracking_number.length > 40) {
                $('.tfree-invalid-shipment-error').show();
                return false;
            }

            if (totalQty == 0) {
                $('.tfree-empty-line-error').show();
                return false;
            }

            tfreeAjax({
                type: 'POST',
                data: {
                    action: 'add_new_shipment',
                    ord_id: ord_id,
                    trackfree_tracking_number: trackfree_tracking_number,
                    trackfree_courier_name: trackfree_courier_name,
                    trackfree_order_status: trackfree_order_status,
                    fulfilment_items: products
                },
                success: function(data) {
                    if (data != 'success') {
                        $('.tfree-add-shipment-error').show();
                        $('.tfree-add-shipment-data').html(data);
                    } else {
                        window.location.href=redirect_url;
                    }
                }
            });
        }
    });

    $('#trackfree_btn_update_tracking').click(function() {
        $('.tfree-invalid-shipment-error').hide();
        $('.tfree-add-shipment-error').hide();
        let products = [];
        let totalQty = 0;
        $('.tfree-edit-prd-items tbody tr').each(function() {
            let product = {};
            product.quantity = $(this).find('.tfree-edit-product-qty').val();
            product.total_quantity = $(this).find('.edit-total-qty').val();
            products.push(product);
            totalQty += Number(product.quantity);
        });

        var trackfree_tracking_number = $('#tfree_edit_track_num').val();
        var trackfree_courier_name = $("select#tfree_edit_courier_name option").filter(":selected").val();
        var trackfree_order_status = $("select#trackfree_edit_order_status option").filter(":selected").val();
        var ord_id = $('#edit_ord_id').val();
        var shipment_id = $('#edit_shipment_id').val();

        if (trackfree_tracking_number) {
            if (trackfree_tracking_number.length > 40) {
                $('.tfree-invalid-shipment-error').show();
                return false;
            }

            if (totalQty == 0) {
                $('.tfree-empty-line-error').show();
                return false;
            }

            tfreeAjax({
                type: 'POST',
                data: {
                    action: 'tfree_update_shipment',
                    ord_id: ord_id,
                    shipment_id: shipment_id,
                    trackfree_tracking_number: trackfree_tracking_number,
                    trackfree_courier_name: trackfree_courier_name,
                    trackfree_order_status: trackfree_order_status,
                    fulfilment_items: products
                },
                success: function(data) {
                    if (data != 'success') {
                        $('.tfree-add-shipment-error').show();
                        $('.tfree-add-shipment-data').html(data);
                    } else {
                        window.location.reload()
                    }
                }
            });
        }
    });
});

jQuery(function () {
    var appendthis =  ("<div class='trackfree-modal-overlay trackfree-modal-close'></div>");

    jQuery('a[data-tf-modal-id]').click(function(e) {
        e.preventDefault();
        e.stopPropagation();
        jQuery(".trackfree-modal-overlay").remove();
        jQuery(".trackfree-modal-box").hide();
        jQuery("body").append(appendthis);
        jQuery(".trackfree-modal-overlay").fadeTo(500, 0.7);
        var modalBox = jQuery(this).attr('data-tf-modal-id');
        jQuery('#'+modalBox).fadeIn(jQuery(this).data());
    });

    jQuery('a[data-modal-id]').click(function(e) {
        var id = this.id;
        e.preventDefault();
        e.stopPropagation();

        jQuery(".trackfree-modal-overlay").remove();
        jQuery(".trackfree-modal-box").hide();
        jQuery("body").append(appendthis);
        var modalBox = jQuery(this).attr('data-modal-id');
        var $modal = jQuery('#' + modalBox);

        // Ensure overlay exists/styled and modal is visible on top.
        jQuery(".trackfree-modal-overlay").fadeTo(200, 0.55);
        $modal.fadeIn(jQuery(this).data());

        // Load into the order-specific container to avoid duplicate-ID collisions.
        var $content = $modal.find('#trackfree-shipment-content-' + id).first();
        if ($content.length) {
            $content.html('<img src="https://tfree.sfo2.cdn.digitaloceanspaces.com/default/tf-wp-preloader.gif" alt="Please wait...">');
        }

        tfreeAjax({
            type: 'POST',
            data: {
                action: 'get_shipment_action',
                order_id: id
            },
            success: function(data) {
                if ($content && $content.length) {
                    $content.html(data);
                }
            },
            error: function() {
                if ($content && $content.length) {
                    $content.html("<div class=\"trackfree-error-container\">Unable to load shipment status. Please refresh and try again.</div>");
                }
            }
        });
    });

    jQuery(document).on('click', '.trackfree-modal-close, .trackfree-modal-overlay', function(e) {
        e.preventDefault();
        e.stopPropagation();
        jQuery(".trackfree-modal-box, .trackfree-modal-overlay").fadeOut(200, function() {
            jQuery(".trackfree-modal-overlay").remove();
        });
    });

    jQuery(document).on('click', '.trackfree-modal-box', function(e) {
        e.stopPropagation();
    });

    jQuery('.trackfree_delete_tracking').click(function() {
        var cfm = confirm('Are you sure you want to delete?');
        if (cfm) {
            var id = this.id;
            var order_id = jQuery(this).data('order-id') || jQuery('#order_id').val() || jQuery('#post_ID').val() || jQuery('input[name="post_ID"]').val();
            order_id = parseInt(order_id, 10) || 0;
            if (!order_id) {
                return;
            }
            tfreeAjax({
                type: 'POST',
                data: {
                    action: 'tracking_delete_action',
                    track_id: id,
                    order_id: order_id
                },
                success: function(data) {
                    location.reload();
                }
            });
        }
    });

    jQuery('.trackfree_show_shipment_detail').click(function() {
        jQuery("#tf_ship_detail_" + this.id).html('<img src="https://tfree.sfo2.cdn.digitaloceanspaces.com/default/tf-wp-preloader.gif" alt="Please wait...">');
        var shipment_id = this.id;
        var order_id = jQuery(this).data('order-id') || jQuery('#order_id').val() || jQuery('#post_ID').val() || jQuery('input[name="post_ID"]').val();
        order_id = parseInt(order_id, 10) || 0;
        if (!order_id) {
            return;
        }
        tfreeAjax({
            type: 'POST',
            data: {
                action: 'show_shipment_detail_action',
                shipment_id: shipment_id,
                order_id: order_id
            },
            success: function(data) {
                jQuery("#tf_ship_detail_" + shipment_id).html(data);
            }
        });
    });
});

jQuery(document).on('click', '.trackfree_ord_det_menu_item', function() {
    var id  = this.id.split('_');
    if (id[0] == 'shipping-link')
    {
        jQuery('#carrier-link_' + id[1]).removeClass('active');
        jQuery('#carrier-detail_' + id[1]).removeClass('trackfree_active');
        jQuery('#shipping-detail_' + id[1]).addClass('trackfree_active');
    }
    if (id[0] == 'carrier-link')
    {
        jQuery('#shipping-link_' + id[1]).removeClass('active');
        jQuery('#shipping-detail_' + id[1]).removeClass('trackfree_active');
        jQuery('#carrier-detail_' + id[1]).addClass('trackfree_active');
    }
    jQuery(this).addClass('active');
});

jQuery(document).on('click', '.trackfree_shipement_menu_item', function(e) {
    e.preventDefault();
    var id = this.id;
    var new_id = id.replace('shipment-item-link_', 'shipment-detail_');

    // Scope tab switching to the currently opened modal to avoid cross-order collisions.
    var $modal = jQuery(this).closest('.trackfree-modal-box');
    var $scope = $modal.length ? $modal : jQuery(document);

    $scope.find('.trackfree_shipement_menu_item').removeClass('active');
    jQuery(this).addClass('active');

    $scope.find('.trackfree-shipment-content').removeClass('trackfree_active');
    // Use attribute selector so we stay within $scope even with duplicate ids elsewhere in DOM.
    $scope.find('[id="' + new_id + '"]').addClass('trackfree_active');
});

// Support legacy "See all shipping activity" buttons generated with {type}-btn-show-more_{row}.
jQuery(document).on('click', 'input[id*=\"-btn-show-more_\"]', function(e) {
    e.preventDefault();
    var parts = this.id.split('_');
    if (parts.length < 2) return;
    var row = parts[1];
    var type = parts[0].replace('-btn-show-more', '');
    jQuery('#' + type + '-show-more-data_' + row).show();
    jQuery(this).hide();
    jQuery('#' + type + '-btn-hide-more_' + row).show();
});

jQuery(document).on('click', 'input[id*=\"-btn-hide-more_\"]', function(e) {
    e.preventDefault();
    var parts = this.id.split('_');
    if (parts.length < 2) return;
    var row = parts[1];
    var type = parts[0].replace('-btn-hide-more', '');
    jQuery('#' + type + '-show-more-data_' + row).hide();
    jQuery(this).hide();
    jQuery('#' + type + '-btn-show-more_' + row).show();
});
