(function ($, window) {
    var prodigy_cart_widget = {
        header_cart_block: $('.header-cart-block-js'),
        timeoutId: '',
        errors: {422: 'Cannot remove item — minimum cart quantity required'},
        _loading: false,
        _cartLoaded: false,


        init: function () {
            // Use PHP-inlined cart count to update badge immediately — no AJAX on page load.
            // Full cart HTML is fetched lazily on first widget open.
            if (typeof window.data !== 'undefined' && window.data.initial_cart_count !== undefined) {
                var count = parseInt(window.data.initial_cart_count, 10);
                $('.cart-count-js').html(count);
                this.check_hide_counter();
                if (count > 0) {
                    $('.widget-cart-subtotal-js').show();
                    $('.widget-cart-checkout-block-js').show();
                    $('.widget-cart-empty-cart-message-js').hide();
                } else {
                    $('.widget-cart-subtotal-js').hide();
                    $('.widget-cart-checkout-block-js').hide();
                    $('.widget-cart-empty-cart-message-js').show();
                }
            } else {
                this.load_cart_data();
            }
            this.open_widget();
            this.open_slide_widget();
            this.close_widget();
            this.remove_item();
            this.add_item();
            this.set_aria_expanded();
            this.set_aria_busy();
            this.redirect_to_checkout()
        },

        redirect_to_checkout: function () {
            $(document).on('click', '.checkout-url-js, .checkout-button-js', function () {
                const $button = $(this);
                const defaultText = $button.text();
                $button.prop('disabled', true).attr('aria-busy', 'true').text('Processing...');

                let post_data = {
                    action: "prodigy-get-checkout-url"
                };

                $.ajax(
                    {
                        type: "post",
                        data: post_data,
                        dataType: "json",
                        url: ajax_url,
                        success: function (data) {
                            if (data && data.success && data.data && data.data.checkout_url) {
                                window.location.href = data.data.checkout_url;
                                return;
                            }

                            const message = data && data.data && data.data.message
                                ? data.data.message
                                : 'Unable to proceed to checkout. Please try again.';
                            alert(message);
                            $button.prop('disabled', false).attr('aria-busy', 'false').text(defaultText);
                        },
                        error: function (jqXHR) {
                            let message = 'Unable to proceed to checkout. Please try again.';
                            if (jqXHR && jqXHR.responseJSON && jqXHR.responseJSON.data && jqXHR.responseJSON.data.message) {
                                message = jqXHR.responseJSON.data.message;
                            }

                            alert(message);
                            $button.prop('disabled', false).attr('aria-busy', 'false').text(defaultText);
                        }
                    }
                );
            });
        },

        set_aria_expanded: function (element, expanded) {
            $(element).attr('aria-expanded', expanded ? 'true' : 'false');
        },

        set_aria_busy: function (elem, loading) {
            $(elem).attr('aria-busy', loading ? 'true' : 'false');
        },

        get_toggle_element: function (el) {
            return $(el);
        },

        show_cart_window: function ($toggle, $dropdown) {
            $dropdown.show();
            $('.prodigy-cart-widget-js').show();
            $toggle.addClass('prodigy-navbar-cart--open');
            this.set_aria_expanded($toggle, true);
        },

        hide_cart_window: function ($toggle, $dropdown) {
            $dropdown.hide();
            $('.prodigy-cart-widget-js').hide();
            $toggle.removeClass('prodigy-navbar-cart--open');
            this.set_aria_expanded($toggle, false);
        },

        open_slide_widget: function () {
            let self = this;
            $('.prodigy-cart-slide__toggle').on(
                'click',
                function () {
                    $('.prodigy-cart-slide-js').addClass('prodigy-cart-slide--open');
                    $('body').addClass('overflow-hidden');
                    self.set_aria_expanded(this, true);
                }
            );
            $('.prodigy-cart-slide__close, .prodigy-cart-slide__container').on(
                'click',
                function () {
                    $('.prodigy-cart-slide-js').removeClass('prodigy-cart-slide--open');
                    $('body').removeClass('overflow-hidden');
                    self.set_aria_expanded('.prodigy-cart-slide__toggle', false);
                }
            );
            $('.cart-close-js').click(function () {
                $('.prodigy-cart-widget-js').hide();
                $('.header-cart-block-js').removeClass('prodigy-navbar-cart--open');
                $('body').removeClass('overflow-hidden');
                self.set_aria_expanded(self.header_cart_block, false);
            });
            $('.counter-plus-js').click(function () {
                self.load_cart_data();
            });
            $('.counter-minus-js').click(function () {
                self.load_cart_data();
            });
        },

        close_widget: function () {
            let self = this;
            $(document).on('click', '.close-cart-widget-js', function (e) {
                self.set_aria_expanded('.prodigy-cart-dropdown__toggle', false);
                $('.prodigy-dropdown-cart-widget-js').hide();
            });
        },

        open_widget: function () {
            var self = this;
            $(document).off('click', '.header-cart-block-js').on('click', '.header-cart-block-js', function (e) {
                if (self.check_menu()) {
                    e.preventDefault();
                    var $toggle = self.get_toggle_element(this);
                    var $dropdown = $toggle.parent().find('.prodigy-dropdown-cart-widget-js');
                    const isOpen = $dropdown.is(':visible');

                    if (isOpen) {
                        self.hide_cart_window($toggle, $dropdown);
                    } else {
                        self.show_cart_window($toggle, $dropdown);

                        self.show_widget_block(0, false);
                        // Lazy load: only fetch full cart HTML on first open
                        if (!self._cartLoaded) {
                            self.load_cart_data();
                        }
                    }
                }
            });
        },

        remove_item: function () {
            let self = this;

            $(document).on('click', ".widget-remove-item-js", function () {
                let remote_product_id = $(this).data('remote-id');
                let line_item_id = $(this).data('line-item-id');

                self.remove_from_cart(line_item_id, remote_product_id);

                self.check_hide_counter();
                if ($('.widget-cart-item-js').length === 0) {
                    $('.continue-cart-js').hide();
                }
            });
        },

        recalculate_subtotal_amount: function (container) {
            var subtotal_amount = 0;

            container.find('.widget-cart-product-price-js').each(function () {
                let amount = parse_price($(this).find('.widget-total-price-js').text());
                let count = parseInt($(this).find('.widget-cart-count-item-js').text());
                subtotal_amount += amount * count;
            });

            container.find('.widget-subtotal-price-js').text('$' + prodigy_price_format(subtotal_amount));
            localStorage.setItem("subtotal_amount", "$" + prodigy_price_format(subtotal_amount));
        },

        change_widget_blocks: function (data_id) {
            let delete_button = $('.widget-remove-item-js[data-line-item-id=' + data_id + ']');
            delete_button.parent().parent().remove();
            if (parseInt($('.widget-cart-item-js').length) === 0) {
                $('.widget-cart-checkout-block-js').hide();
                $('.widget-cart-subtotal-js').hide();
                $('.widget-cart-empty-cart-message-js').show();
            }
        },

        remove_from_cart: function (line_item_id, remote_id, callback) {
            let self = this;
            let post_data = {
                action: 'prodigy-remove-item-cart',
                line_item_id: line_item_id,
                remote_id: remote_id,
                nonce: settings.nonce
            };

            $.ajax({
                    type: 'post',
                    data: post_data,
                    url: ajax_url,
                    dataType: 'json',
                    error: function (jqXHR, textStatus, message) {
                        self.show_error(404, message, 'error');
                    },
                    success: function (data) {
                        if (!data.success) {
                            self.show_error(data.data[0].code,);
                        } else {
                            self._cartLoaded = false;
                            self.load_cart_data(function () {
                                self.change_widget_blocks(line_item_id);
                            });
                        }
                    },
                }
            );
        },

        show_error: function (code, message, type = "success") {
            let self = this;
            let add_to_cart_message = $(".widget-cart-message-error-js");
            let error_message = message;
            if (typeof self.errors[code] !== "undefined") {
                error_message = self.errors[code];
            }
            add_to_cart_message.find("span").html(error_message);
            add_to_cart_message.show();
            add_to_cart_message.delay(5000).fadeOut("slow");
            if (type === "error") {
                add_to_cart_message.addClass("prodigy-cart-dropdown__error-alert");
            }
        },

        cart_modal_trigger: function (is_error) {
            let self = this;
            if (!is_error) {
                if (self.check_menu()) {
                    $('.prodigy-dropdown-cart-widget-js').show();
                    self.set_aria_expanded('.prodigy-cart-dropdown__toggle', true);
                    self.show_widget_block(5000, true);
                }
                self._cartLoaded = false;
                self.load_cart_data();
            }
        },

        show_widget_block: function (time, show_alert) {
            let self = this;
            var $dropdown = $('.prodigy-dropdown-cart-widget-js');
            var $toggle = $('.prodigy-cart-dropdown__toggle');

            if (time) {
                $dropdown.delay(time).fadeOut('slow', function () {
                    self.set_aria_expanded($toggle, false);
                });
            } else {
                $dropdown.fadeIn('fast');
                self.set_aria_expanded($toggle, true);
            }
            if (show_alert) {
                    $('.add-to-cart-alert-js').show();
                } else {
                    $('.add-to-cart-alert-js').hide();
                }
        },

        load_cart_data: function (callback) {
            // Prevent concurrent duplicate AJAX requests
            if (this._loading) {
                return;
            }
            this._loading = true;

            let self = this;
            $('.prodigy-cart-loading__element-js').show();
            self.set_aria_busy('.prodigy-cart-loading__element-js', true);
            $('.prodigy-cart-total').addClass('prodigy-cart-loading__element');
            $('.widget-cart-item-js').hide();
            $.ajax({
                type: "post",
                data: {action: "prodigy-load-cart-data"},
                dataType: "json",
                url: ajax_url,
                cache: false,
                success: function (data) {
                    self._loading = false;
                    self._cartLoaded = true;
                    $('.prodigy-cart-loading__element-js').hide();
                    self.set_aria_busy('.prodigy-cart-loading__element-js', false);
                    $('.prodigy-cart-total').removeClass('prodigy-cart-loading__element');
                    $('.cart-count-js').html(data.cart_items_count);
                    $('.cart-dropdown-widget-item-list-js').html(data.cart_items);
                    const parsedTotal = parseFloat(data.total_price);
                    $('.widget-subtotal-price-js').html("$" + prodigy_price_format(parsedTotal));
                    if ((isNaN(parsedTotal) || parsedTotal <= 0) && parseInt(data.cart_items_count, 10) > 0) {
                        self.recalculate_subtotal_amount($('.prodigy-cart-slide-js'));
                        self.recalculate_subtotal_amount($('.prodigy-cart-widget-js'));
                        self.recalculate_subtotal_amount($('.prodigy-dropdown-cart-widget-js'));
                    }
                    self.check_hide_counter();
                    if ($('.widget-cart-item-js').length === 0) {
                        $('.continue-cart-js').hide();
                    }

                    if (data.cart_items_count) {
                        $('.widget-cart-subtotal-js').show();
                        $('.widget-cart-checkout-block-js').show();
                        $('.widget-cart-empty-cart-message-js').hide();
                    } else {
                        $('.widget-cart-subtotal-js').hide();
                        $('.widget-cart-checkout-block-js').hide();
                        $('.widget-cart-empty-cart-message-js').show();
                    }

                    if (callback !== undefined) {
                        callback();
                    }
                },
                error: function () {
                    self._loading = false;
                }
            });
        },

        add_item: function () {
            let self = this;
            $(document).on('click', '.add-to-cart-js', function () {
                $('.widget-cart-subtotal-js').show();
                $('.widget-cart-checkout-block-js').show();
                $('.widget-cart-empty-cart-message-js').hide();
                self.recalculate_subtotal_amount($('.prodigy-cart-slide-js'));
                self.recalculate_subtotal_amount($('.prodigy-cart-widget-js'));
                self.recalculate_subtotal_amount($('.prodigy-dropdown-cart-widget-js'));
                self.check_hide_counter();
            });
        },

        show_add_to_cart_message() {
            var add_to_cart_message = $('.widget-cart-add-item-message-js');
            add_to_cart_message.show();
            add_to_cart_message.delay(5000).fadeOut('slow');
        },

        check_hide_counter: function () {
            $('.cart-count-js').each(function () {
                if (parseInt($(this).text()) === 0) {
                    const hide_empty = $(this).data('hide-empty')
                    if (hide_empty !== 'no') {
                        $(this).hide();
                    } else {
                        $(this).show();
                    }
                } else {
                    $(this).show();
                }
            });
        },

        check_menu: function () {
            const self = this;
            if (typeof (document.querySelector('.prodigy-navbar-cart')) !== "undefined" &&
                document.querySelector('.prodigy-navbar-cart') !== null
            ) {
                const theme_name = window.getComputedStyle(document
                    .querySelector('.prodigy-navbar-cart'), ':before')
                    .getPropertyValue('content').replace(/^"|"$/g, '');
                const width = window.innerWidth;
                const handlers = {
                    'astra': () => {
                        return self.header_cart_block.parents('.ast-header-break-point').length === 0;
                    },
                    'twenty-twenty-one': () => width > 481,
                    'twenty-twenty': () => width > 999,
                    'twenty-nineteen': () => {
                        return self.header_cart_block.parents('.hidden-links').length === 0;
                    },
                    'oceanwp': () => width > 959,
                    'hello-elementor': () => width > 767,
                    'flatsome': () => width > 849,
                    'divi': () => {
                        return self.header_cart_block.parents('.et_mobile_menu').length === 0;
                    },
                    DEFAULT: () => true
                }
                const handler = handlers[theme_name] || handlers.DEFAULT;

                return handler();
            }

            return true;
        }

    };
    window.prodigy_cart_widget = prodigy_cart_widget;
})(jQuery, window);
jQuery(function ($) {
    window.prodigy_cart_widget.init();
});
