
(function($) {
    'use strict';

    var InstinctorAddons = {
        config: {},

        init: function() {
            this.config = window.instinctorAddons || {};

            if (this.config.wishlist) this.initWishlist();
            if (this.config.oneClick) this.initOneClickCheckout();
            if (this.config.badges) this.initBadges();
            if (this.config.volumeDiscounts) this.initVolumeDiscounts();
            if (this.config.productAddons) this.initProductAddons();
        },

        
        
        initProductAddons: function() {
            
            $(document).on('change input', '.instinctor-product-addons .ia-addon-check, .instinctor-product-addons .ia-addon-select, .instinctor-product-addons .ia-addon-text', function() {
                var $wrap = $(this).closest('.instinctor-product-addons');
                var productId = $wrap.data('product-id');
                var basePrice = 0;

                var $card = $wrap.closest('.instinctor-card-designed, .impulse-quickview-details');
                var priceText = $card.find('.instinctor-product-price span:last, .impulse-quickview-price .sale, .impulse-quickview-price').first().text().replace(/[^0-9.]/g, '');
                basePrice = parseFloat(priceText) || 0;

                var addonTotal = 0;
                $wrap.find('.instinctor-addon-item').each(function() {
                    var $item   = $(this);
                    var price   = parseFloat($item.data('price')) || 0;
                    var ptype   = $item.data('price-type');
                    var $check  = $item.find('.ia-addon-check');
                    var $text   = $item.find('.ia-addon-text');
                    var $sel    = $item.find('.ia-addon-select');
                    var hasVal  = false;

                    if ($check.length)      hasVal = $check.is(':checked');
                    else if ($sel.length)   hasVal = !!$sel.val();
                    else if ($text.length)  hasVal = !!$text.val();

                    if (hasVal && price > 0) {
                        addonTotal += ptype === 'percent' ? basePrice * (price / 100) : price;
                    }
                });

                var $btn = $card.find('.instinctor-add-to-cart-btn, .impulse-quickview-add-btn').first();
                var $badge = $card.find('.ia-addon-total-badge');
                if (addonTotal > 0) {
                    var sym = (window.instinctorFrontend && instinctorFrontend.currencySymbol) || '$';
                    var dec = (window.instinctorFrontend && instinctorFrontend.currencyDecimals) || 2;
                    var label = '+' + sym + addonTotal.toFixed(dec) + ' in add-ons';
                    if ($badge.length) {
                        $badge.text(label);
                    } else {
                        $btn.before('<div class="ia-addon-total-badge" style="font-size:11px;color:#888;margin-bottom:4px">' + label + '</div>');
                    }
                } else {
                    $badge.remove();
                }
            });
        },

        initWishlist: function() {
            var self = this;

            $(document).on('click', '.instinctor-wishlist-btn', function(e) {
                e.preventDefault();
                e.stopPropagation();
                
                var $btn = $(this);
                var productId = $btn.data('product-id');
                var isInWishlist = $btn.hasClass('in-wishlist');
                
                $btn.addClass('loading');
                
                $.ajax({
                    url: instinctorFrontend.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: isInWishlist ? 'instinctor_remove_from_wishlist' : 'instinctor_add_to_wishlist',
                        product_id: productId,
                        nonce: instinctorFrontend.nonce
                    },
                    success: function(response) {
                        $btn.removeClass('loading');
                        if (response.success) {
                            $btn.toggleClass('in-wishlist');
                            if ($btn.hasClass('in-wishlist')) {
                                $btn.find('.instinctor-wishlist-text').text(self.config.wishlist.addedText || 'Added');
                                $btn.attr('title', 'Remove from wishlist');
                            } else {
                                $btn.find('.instinctor-wishlist-text').text(self.config.wishlist.buttonText || 'Add to Wishlist');
                                $btn.attr('title', 'Add to wishlist');
                            }
                            self.showToast(response.data.message || 'Wishlist updated');

                            if (response.data.count !== undefined) {
                                $('.instinctor-wishlist-count').text(response.data.count);
                            }
                        }
                    },
                    error: function() {
                        $btn.removeClass('loading');
                        self.showToast('Error updating wishlist', 'error');
                    }
                });
            });
        },

        
        
        initOneClickCheckout: function() {
            var self = this;

            $(document).on('click', '.instinctor-buy-now-btn', function(e) {
                e.preventDefault();
                
                var $btn = $(this);
                var productId = $btn.data('product-id');
                var quantity = $btn.data('quantity') || 1;
                var variationId = $btn.data('variation-id') || 0;
                
                $btn.addClass('loading').prop('disabled', true);
                
                $.ajax({
                    url: instinctorFrontend.ajaxUrl,
                    type: 'POST',
                    data: {
                        action: 'instinctor_buy_now',
                        product_id: productId,
                        quantity: quantity,
                        variation_id: variationId,
                        nonce: instinctorFrontend.nonce
                    },
                    success: function(response) {
                        if (response.success && response.data.redirect) {
                            window.location.href = response.data.redirect;
                        } else {
                            $btn.removeClass('loading').prop('disabled', false);
                            self.showToast(response.data.message || 'Error', 'error');
                        }
                    },
                    error: function() {
                        $btn.removeClass('loading').prop('disabled', false);
                        self.showToast('Error processing request', 'error');
                    }
                });
            });
        },

        
        
        initBadges: function() {
            
            var $badges = $('.instinctor-product-badge');
            if ($badges.length && 'IntersectionObserver' in window) {
                var observer = new IntersectionObserver(function(entries) {
                    entries.forEach(function(entry) {
                        if (entry.isIntersecting) {
                            $(entry.target).addClass('visible');
                            observer.unobserve(entry.target);
                        }
                    });
                }, { threshold: 0.1 });
                
                $badges.each(function() {
                    observer.observe(this);
                });
            } else {
                $badges.addClass('visible');
            }
        },

        
        
        initVolumeDiscounts: function() {
            var self = this;

            $(document).on('change input', '.instinctor-quantity-input', function() {
                var $input = $(this);
                var $product = $input.closest('.instinctor-product-single, .instinctor-product-card');
                var qty = parseInt($input.val()) || 1;
                var productId = $product.data('product-id') || $input.data('product-id');
                
                self.updateVolumeDiscount(productId, qty);
            });
        },

        updateVolumeDiscount: function(productId, qty) {
            var $discountRow = $('.instinctor-volume-discount[data-product-id="' + productId + '"]');
            if (!$discountRow.length) return;

            var tiers = $discountRow.data('tiers') || [];
            var currentTier = null;
            var nextTier = null;

            for (var i = 0; i < tiers.length; i++) {
                var minQty = parseInt(tiers[i].min_quantity || tiers[i].min) || 0;
                if (qty >= minQty) {
                    currentTier = tiers[i];
                } else if (!nextTier) {
                    nextTier = tiers[i];
                }
            }

            if (currentTier) {
                var discVal = parseFloat(currentTier.discount_value || currentTier.discount) || 0;
                var discType = currentTier.discount_type || 'percent';
                var sym = (window.instinctorFrontend && instinctorFrontend.currencySymbol) || '$';
                var saveText = discType === 'percent' ? discVal + '%' : sym + discVal.toFixed(2);
                $discountRow.find('.instinctor-current-discount').text('You save ' + saveText + '!').show();
            } else {
                $discountRow.find('.instinctor-current-discount').hide();
            }

            if (nextTier) {
                var nextMin = parseInt(nextTier.min_quantity || nextTier.min) || 0;
                var needed = nextMin - qty;
                var nextVal = parseFloat(nextTier.discount_value || nextTier.discount) || 0;
                var nextType = nextTier.discount_type || 'percent';
                var nextSym = (window.instinctorFrontend && instinctorFrontend.currencySymbol) || '$';
                var nextText = nextType === 'percent' ? nextVal + '% off' : nextSym + nextVal.toFixed(2) + ' off';
                $discountRow.find('.instinctor-next-tier').text('Add ' + needed + ' more for ' + nextText).show();
            } else {
                $discountRow.find('.instinctor-next-tier').hide();
            }
        },

        
        
        showToast: function(message, type) {
            type = type || 'success';
            var $toast = $('<div class="instinctor-toast instinctor-toast-' + type + '">' + message + '</div>');
            $('body').append($toast);
            
            setTimeout(function() { $toast.addClass('visible'); }, 10);
            setTimeout(function() { 
                $toast.removeClass('visible');
                setTimeout(function() { $toast.remove(); }, 300);
            }, 3000);
        }
    };

    $(document).ready(function() {
        InstinctorAddons.init();
    });

    window.InstinctorAddons = InstinctorAddons;

})(jQuery);
