
(function($) {
    'use strict';

        $(document).on('submit', '.instinctor-coupon-form', function(e) {
            e.preventDefault();
            var $form = $(this);
            var $btn = $form.find('button[type="submit"]');
            var $input = $form.find('input[name="coupon_code"]');
            var code = $input.val().trim();
            
            if (!code) {
                $input.css('border-color', '#dc3545');
                return;
            }
            
            $btn.prop('disabled', true).text('Applying...');
            $input.css('border-color', '#ddd');
            
            $.ajax({
                url: instinctorFrontend.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'instinctor_apply_coupon',
                    nonce: instinctorFrontend.nonce,
                    coupon_code: code
                },
                success: function(response) {
                    if (response.success) {
                        $input.val('').css('border-color', '#28a745');
                        $btn.text('Applied!');
                        setTimeout(function() {
                            $btn.text($btn.data('original') || 'Apply');
                            $input.css('border-color', '#ddd');
                        }, 2000);
                        
                        $(document).trigger('instinctor:coupon:applied');
                        
                        $(document).trigger('instinctor_coupon_applied', [response.data]);
                    } else {
                        $input.css('border-color', '#dc3545');
                        $btn.text(response.data?.message || 'Invalid');
                        setTimeout(function() {
                            $btn.text($btn.data('original') || 'Apply');
                        }, 2000);
                    }
                },
                error: function() {
                    $btn.text('Error');
                    setTimeout(function() {
                        $btn.text($btn.data('original') || 'Apply');
                    }, 2000);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        $('.instinctor-coupon-form button[type="submit"]').each(function() {
            $(this).data('original', $(this).text());
        });

        $(document).on('submit', '.impulse-form', function(e) {
            e.preventDefault();
            var $form = $(this);
            var $btn = $form.find('button[type="submit"]');
            var $fields = $form.find('input, textarea, select').not('[type="submit"], [type="hidden"]');

            var isValid = true;
            $fields.each(function() {
                var $field = $(this);
                var $wrapper = $field.closest('.impulse-form-field');

                $field.css('border-color', '');
                $wrapper.find('.impulse-field-error').remove();

                if ($field.prop('required') && !$field.val().trim()) {
                    isValid = false;
                    $field.css('border-color', '#dc3545');
                    $wrapper.append('<span class="impulse-field-error" style="color:#dc3545;font-size:12px;margin-top:4px;display:block">This field is required</span>');
                }

                if ($field.attr('type') === 'email' && $field.val()) {
                    var emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/;
                    if (!emailRegex.test($field.val())) {
                        isValid = false;
                        $field.css('border-color', '#dc3545');
                        $wrapper.append('<span class="impulse-field-error" style="color:#dc3545;font-size:12px;margin-top:4px;display:block">Please enter a valid email</span>');
                    }
                }
            });
            
            if (!isValid) {
                
                var $firstError = $form.find('.impulse-field-error').first().closest('.impulse-form-field');
                if ($firstError.length) {
                    $('html, body').animate({ scrollTop: $firstError.offset().top - 100 }, 300);
                }
                return;
            }

            var originalText = $btn.data('original') || $btn.text();
            $btn.data('original', originalText);

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

            var formData = $form.serializeArray();
            formData.push({ name: 'action', value: 'instinctor_submit_form' });
            formData.push({ name: 'nonce', value: instinctorFrontend.nonce });
            
            $.ajax({
                url: instinctorFrontend.ajaxUrl,
                type: 'POST',
                data: formData,
                success: function(response) {
                    if (response.success) {
                        var action = $form.data('action') || 'message';
                        var successMsg = $form.data('success') || 'Thank you! Your message has been sent.';
                        var redirectUrl = $form.data('redirect') || '';
                        
                        if (action === 'redirect' && redirectUrl) {
                            window.location.href = redirectUrl;
                            return;
                        }

                        $form.find('.impulse-form-success').remove();
                        $form.prepend('<div class="impulse-form-success" style="background:#d4edda;color:#155724;padding:14px 18px;border-radius:6px;margin-bottom:16px;font-size:14px">' + successMsg + '</div>');

                        $form[0].reset();
                        $btn.text('Sent!');

                        $(document).trigger('instinctor_form_submitted', [response.data]);
                        
                        setTimeout(function() {
                            $btn.text(originalText);
                            
                            $form.find('.impulse-form-success').fadeOut(300, function() {
                                $(this).remove();
                            });
                        }, 3000);
                    } else {
                        
                        $form.find('.impulse-form-error').remove();
                        $form.prepend('<div class="impulse-form-error" style="background:#f8d7da;color:#721c24;padding:14px 18px;border-radius:6px;margin-bottom:16px;font-size:14px">' + (response.data?.message || 'Something went wrong. Please try again.') + '</div>');
                        $btn.text(originalText);
                        
                        setTimeout(function() {
                            $form.find('.impulse-form-error').fadeOut(300, function() {
                                $(this).remove();
                            });
                        }, 5000);
                    }
                },
                error: function() {
                    $form.find('.impulse-form-error').remove();
                    $form.prepend('<div class="impulse-form-error" style="background:#f8d7da;color:#721c24;padding:14px 18px;border-radius:6px;margin-bottom:16px;font-size:14px">Connection error. Please try again.</div>');
                    $btn.text(originalText);
                    
                    setTimeout(function() {
                        $form.find('.impulse-form-error').fadeOut(300, function() {
                            $(this).remove();
                        });
                    }, 5000);
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        });

        $('.impulse-form button[type="submit"]').each(function() {
            $(this).data('original', $(this).text());
        });
    });

(function($) {
    'use strict';

    var ImpulseQuickView = {
        overlay: null,
        modal: null,
        currentProduct: null,
        currentImageIndex: 0,

        init: function() {
            this.createModal();
            this.bindEvents();
        },

        createModal: function() {
            if ($('.impulse-quickview-overlay').length) {
                
                this.overlay = $('.impulse-quickview-overlay');
                this.modal   = $('.impulse-quickview-modal');
                return;
            }

            var html = '<div class="impulse-quickview-overlay">' +
                '<div class="impulse-quickview-modal">' +
                    '<button class="impulse-quickview-close" aria-label="Close">' +
                        '<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"></line><line x1="6" y1="6" x2="18" y2="18"></line></svg>' +
                    '</button>' +
                    '<div class="impulse-quickview-body">' +
                        '<div class="impulse-quickview-loading"><div class="impulse-quickview-spinner"></div></div>' +
                    '</div>' +
                '</div>' +
            '</div>';

            $('body').append(html);
            this.overlay = $('.impulse-quickview-overlay');
            this.modal = $('.impulse-quickview-modal');

            if (!$('#impulse-qv-preview').length) {
                $('body').append('<img id="impulse-qv-preview" class="impulse-qv-preview" src="" alt="">');
            }
            this.$preview = $('#impulse-qv-preview');
        },

        bindEvents: function() {
            var self = this;

            
            $(document).on('click', '.impulse-pcard a', function(e) {
                if (window.impulseIsPreview) return;
                e.preventDefault();
                e.stopPropagation();
                
                $(this).closest('.impulse-pcard').trigger('_open');
            });

            $(document).on('click _open', '.impulse-pcard', function(e) {
                
                if (window.impulseIsPreview) return;
                
                if ($(e.target).closest('.impulse-pcard-btn, .impulse-pcard-btn-wrap, .instinctor-add-to-cart-btn, .ia-addons-toggle').length) return;
                e.preventDefault();
                e.stopPropagation();
                var productId = parseInt($(this).data('product-id')) || 0;
                
                var $grid = $(this).closest('[data-qv]');
                var qvFlagsLocal = {};
                if ($grid.length) { try { qvFlagsLocal = JSON.parse($grid.attr('data-qv')); } catch(e) {} }
                var modalEnabled = qvFlagsLocal.enable_modal !== false && qvFlagsLocal.enable_modal !== '' && qvFlagsLocal.enable_modal !== '0'; 
                if (!modalEnabled) return; 
                if (productId > 0) {
                    self.$sourceGrid = $grid; 
                    self.open(productId);
                } else {
                    self.openPreview($(this));
                }
            });

            $(document).on('click', '.impulse-quickview-close', function() {
                self.close();
                
                if (window !== window.top) {
                    window.parent.postMessage({ type: 'impulse-quickview-closed' }, '*');
                }
            });

            $(document).on('click', '.impulse-quickview-overlay', function(e) {
                if ($(e.target).hasClass('impulse-quickview-overlay')) {
                    self.close();
                }
            });

            $(document).on('keydown', function(e) {
                if (e.key === 'Escape' && self.overlay && self.overlay.hasClass('active')) {
                    if (self.overlay.hasClass('impulse-editor-qv-preview')) return;
                    self.close();
                }
            });

            $(document).on('click', '.impulse-quickview-thumb', function() {
                var index = $(this).data('index');
                self.showImage(index);
            });

            $(document).on('click', '.impulse-quickview-zoom-btn', function(e) {
                e.stopPropagation();
                if (!self.$preview) return;
                if (self.$preview.hasClass('active')) {
                    self.$preview.removeClass('active');
                } else if (self.$preview.attr('src')) {
                    self.$preview.addClass('active');
                }
            });
            
            $(document).on('click', 'img.impulse-qv-preview', function() {
                $(this).removeClass('active');
            });

            
            var swipeStartX = 0;
            var swipeStartY = 0;
            var isSwiping = false;

            $(document).on('mousedown', '.impulse-quickview-gallery-main', function(e) {
                swipeStartX = e.clientX;
                swipeStartY = e.clientY;
                isSwiping = true;
                e.preventDefault();
            });

            $(document).on('mouseup mouseleave', '.impulse-quickview-gallery-main', function(e) {
                if (!isSwiping) return;
                isSwiping = false;
                var dx = e.clientX - swipeStartX;
                var dy = e.clientY - swipeStartY;
                var $imgs = self.modal.find('.impulse-quickview-gallery-main img');
                var total = $imgs.length;
                if (Math.abs(dx) < 6 && Math.abs(dy) < 6) {
                    
                    if (total > 1) self.showImage((self.currentImageIndex + 1) % total);
                } else if (total > 1 && Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
                    var next = dx < 0
                        ? (self.currentImageIndex + 1) % total
                        : (self.currentImageIndex - 1 + total) % total;
                    self.showImage(next);
                }
            });

            $(document).on('touchstart', '.impulse-quickview-gallery-main', function(e) {
                var t = e.originalEvent.touches[0];
                swipeStartX = t.clientX;
                swipeStartY = t.clientY;
                isSwiping = true;
            }, { passive: true });

            $(document).on('touchend', '.impulse-quickview-gallery-main', function(e) {
                if (!isSwiping) return;
                isSwiping = false;
                var t = e.originalEvent.changedTouches[0];
                var dx = t.clientX - swipeStartX;
                var dy = t.clientY - swipeStartY;
                if (Math.abs(dx) > 40 && Math.abs(dx) > Math.abs(dy)) {
                    var $imgs = self.modal.find('.impulse-quickview-gallery-main img');
                    var total = $imgs.length;
                    if (total < 2) return;
                    var next = dx < 0
                        ? (self.currentImageIndex + 1) % total
                        : (self.currentImageIndex - 1 + total) % total;
                    self.showImage(next);
                }
            });

            $(document).on('click', '.impulse-quickview-qty-btn', function() {
                var $input = $(this).siblings('.impulse-quickview-qty-input');
                var val = parseInt($input.val()) || 1;
                var min = parseInt($input.attr('min')) || 1;
                var max = parseInt($input.attr('max')) || 999;

                if ($(this).data('action') === 'minus') {
                    val = Math.max(min, val - 1);
                } else {
                    val = Math.min(max, val + 1);
                }
                $input.val(val);

                var $priceEl = $(this).closest('.impulse-quickview-actions').find('.impulse-quickview-price');
                var base = parseFloat($priceEl.data('base-price'));
                if (!isNaN(base)) {
                    var total = (base * val).toFixed(2);
                    var $sale = $priceEl.find('.sale');
                    var $del  = $priceEl.find('del');
                    if ($sale.length) {
                        $sale.text('$' + total);
                    } else {
                        $priceEl.contents().filter(function() { return this.nodeType === 3; }).first()
                            .replaceWith('$' + total);
                    }
                }
            });

            $(document).on('click', '.impulse-quickview-add-btn', function() {
                self.addToCart($(this));
            });

            $(document).on('click', '.impulse-quickview-variant-btn', function() {
                $(this).siblings().removeClass('active');
                $(this).addClass('active');
            });

            
            $(document).on('click', '.instinctor-add-to-cart-btn[data-buy-now]', function(e) {
                e.stopPropagation();
                var $btn = $(this);
                var productId = $btn.data('product-id');
                if (!productId) return;
                $btn.prop('disabled', true).text('Please wait...');
                $.ajax({
                    url: instinctorFrontend.ajaxUrl,
                    type: 'POST',
                    data: { action: 'instinctor_buy_now', product_id: productId, quantity: 1, nonce: instinctorFrontend.nonce },
                    success: function(response) {
                        if (response.success && response.data.redirect) {
                            window.location.href = response.data.redirect;
                        } else {
                            $btn.prop('disabled', false).text('Enroll Now');
                        }
                    },
                    error: function() { $btn.prop('disabled', false).text('Enroll Now'); }
                });
            });

            $(document).on('click', '.instinctor-add-to-cart-btn', function(e) {
                e.stopPropagation();
                var $btn = $(this);
                if ($btn.data('buy-now')) return; 
                var productId = $btn.data('product-id');
                if (!productId) return;

                var originalText = $btn.text();
                $btn.prop('disabled', true).text('Adding...');

                

                
                var apiBase = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.apiUrl) || '/wp-json/instinctor/v1/';
                var nonce   = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.nonce) || '';
                fetch(apiBase + 'cart/add', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
                    body: JSON.stringify({ product_id: productId, quantity: 1 })
                }).then(function(r){ return r.json(); }).then(function(data){
                    if (data && data.error) { $btn.prop('disabled', false).text(originalText); return; }
                    $btn.text('Added!');
                    setTimeout(function() { $btn.prop('disabled', false).text(originalText); }, 1500);
                    var cart = data && data.cart, count = 0;
                    if (cart && cart.items) Object.keys(cart.items).forEach(function(k){ count += cart.items[k].quantity || 0; });
                    $('.instinctor-cart-count, .impulse-cart-count').text(count);
                    if (window.jQuery) window.jQuery(document).trigger('instinctor:added_to_cart', [cart]);
                    document.dispatchEvent(new CustomEvent('instinctor:cart:updated', { detail: { cart: cart } }));
                }).catch(function(){ $btn.prop('disabled', false).text(originalText); });
            });

        }, 

        openPreview: function($card) {
            var self = this;
            this.overlay = $('.impulse-quickview-overlay');
            this.modal   = $('.impulse-quickview-modal');
            this.$preview = $('#impulse-qv-preview');
            if (!this.overlay.length) this.createModal();
            this.overlay.addClass('active');
            $('body').css('overflow', 'hidden');

            var title = $card.find('.impulse-pcard-title').text() || 'Product Name';
            var priceHtml = $card.find('.impulse-pcard-price').html() || '$29.99';
            var imgSrc = $card.find('.impulse-pcard-image img').first().attr('src') || '';
            var pluginUrl = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.pluginUrl) ? instinctorFrontend.pluginUrl : '';

            var html = '<div class="impulse-quickview-content">';
            html += '<div class="impulse-quickview-gallery">';
            html += '<div class="impulse-quickview-gallery-main">';
            if (imgSrc) {
                html += '<img src="' + imgSrc + '" class="active">';
            } else {
                html += '<img src="' + pluginUrl + 'assets/images/placeholder-logo.svg" class="active impulse-qv-placeholder-img">';
            }
            html += '<button class="impulse-quickview-zoom-btn" aria-label="Zoom"><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><circle cx="11" cy="11" r="8"/><line x1="21" x2="16.65" y1="21" y2="16.65"/><line x1="11" x2="11" y1="8" y2="14"/><line x1="8" x2="14" y1="11" y2="11"/></svg></button>';
            html += '</div></div>';
            html += '<div class="impulse-quickview-details">';
            html += '<h2 class="impulse-quickview-title">' + title + '</h2>';
            html += '<div class="impulse-quickview-desc">Preview — full product details shown on live page.</div>';
            html += '<div class="impulse-quickview-actions">';
            html += '<div class="impulse-quickview-price-qty-row">';
            html += '<div class="impulse-quickview-qty-control">';
            html += '<button class="impulse-quickview-qty-btn" data-action="minus" disabled>−</button>';
            html += '<input type="number" class="impulse-quickview-qty-input" value="1" min="1" max="999" disabled>';
            html += '<button class="impulse-quickview-qty-btn" data-action="plus" disabled>+</button>';
            html += '</div>';
            html += '<div class="impulse-quickview-price">' + priceHtml + '</div>';
            html += '</div>';
            html += '<button class="impulse-quickview-add-btn" disabled style="opacity:0.5;cursor:not-allowed;">Add to Cart</button>';
            html += '</div>';
            html += '</div></div>';

            this.modal.find('.impulse-quickview-body').html(html);
            if (this.$preview && imgSrc) this.$preview.attr('src', imgSrc);
        },

        open: function(productId) {
            var self = this;
            
            this.overlay = $('.impulse-quickview-overlay');
            this.modal   = $('.impulse-quickview-modal');
            this.$preview = $('#impulse-qv-preview');
            if (!this.overlay.length) this.createModal();
            this.overlay.addClass('active');
            $('body').css('overflow', 'hidden');

            this.modal.find('.impulse-quickview-body').html(
                '<div class="impulse-quickview-loading"><div class="impulse-quickview-spinner"></div></div>'
            );

            var $grid = (self.$sourceGrid && self.$sourceGrid.length)
                ? self.$sourceGrid
                : $('.impulse-product-grid[data-qv], .impulse-product-carousel[data-qv]').first();
            self.$sourceGrid = null; 
            self.$lastGrid = $grid; 
            var qvFlags = {};
            if ($grid.length) {
                try { qvFlags = JSON.parse($grid.attr('data-qv')); } catch(e) {}
            }

            
            $.ajax({
                url: instinctorFrontend.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'impulse_get_quickview',
                    product_id: productId,
                    nonce: instinctorFrontend.nonce,
                    show_desc:      qvFlags.show_desc      !== undefined ? qvFlags.show_desc      : true,
                    show_desc_type: qvFlags.show_desc_type || 'short',
                    show_price:     qvFlags.show_price      !== undefined ? qvFlags.show_price      : true,
                    show_qty:       qvFlags.show_qty        !== undefined ? qvFlags.show_qty        : true,
                    btn_bg:         qvFlags.btn_bg         || '',
                    btn_text:       qvFlags.btn_text       || '',
                    btn_radius:     qvFlags.btn_radius      !== undefined ? qvFlags.btn_radius      : '',
                    addon_defs:     JSON.stringify(qvFlags.addons || []),
                },
                success: function(response) {
                    if (response.success && response.data.html) {
                        self.modal.find('.impulse-quickview-body').html(response.data.html);
                        self.currentProduct = response.data.product;
                        self.currentImageIndex = 0;
                        
                        var firstSrc = self.modal.find('.impulse-quickview-gallery-main img').first().attr('src');
                        if (firstSrc && self.$preview) self.$preview.attr('src', firstSrc);
                    } else {
                        self.modal.find('.impulse-quickview-body').html(
                            '<div style="padding:40px;text-align:center;color:#666;">Product not found</div>'
                        );
                    }
                },
                error: function() {
                    self.modal.find('.impulse-quickview-body').html(
                        '<div style="padding:40px;text-align:center;color:#666;">Failed to load product</div>'
                    );
                }
            });
        },

        close: function() {
            this.overlay.removeClass('active');
            $('body').css('overflow', '');
            this.currentProduct = null;
            if (this.$preview) this.$preview.removeClass('active').attr('src', '');
        },

        showImage: function(index) {
            this.currentImageIndex = index;
            var $images = this.modal.find('.impulse-quickview-gallery-main img');
            var $thumbs = this.modal.find('.impulse-quickview-thumb');

            $images.removeClass('active').eq(index).addClass('active');
            $thumbs.removeClass('active').eq(index).addClass('active');

            var activeSrc = $images.eq(index).attr('src');
            if (activeSrc && this.$preview) this.$preview.attr('src', activeSrc);

            var $active = $thumbs.eq(index);
            if ($active.length) {
                var strip = $active.closest('.impulse-quickview-thumbs')[0];
                if (strip) {
                    var thumbLeft = $active[0].offsetLeft;
                    var thumbWidth = $active[0].offsetWidth;
                    var stripWidth = strip.offsetWidth;
                    var scrollTarget = thumbLeft - (stripWidth / 2) + (thumbWidth / 2);
                    strip.scrollLeft = scrollTarget;
                }
            }
        },

        addToCart: function($btn) {
            var self = this;
            var productId = $btn.data('product-id');
            var quantity = this.modal.find('.impulse-quickview-qty-input').val() || 1;
            var $variants = this.modal.find('.impulse-quickview-variant-btn.active');
            var variations = {};

            $variants.each(function() {
                var attr = $(this).closest('.impulse-quickview-variant-group').data('attribute');
                variations[attr] = $(this).data('value');
            });

            var addon_values = {};
            this.modal.find('.instinctor-addon-item').each(function() {
                var $item = $(this);
                var idx   = $item.data('addon-idx');
                var type  = $item.data('type');
                if (idx === undefined) return;
                if (type === 'checkbox') {
                    if ($item.find('.ia-addon-check').is(':checked')) addon_values[idx] = '1';
                } else {
                    var val = $item.find('.ia-addon-input').val();
                    if (val) addon_values[idx] = val;
                }
            });

            var missingRequired = false;
            this.modal.find('.instinctor-addon-item[data-required="1"]').each(function() {
                var $item = $(this);
                var type  = $item.data('type');
                var idx   = $item.data('addon-idx');
                var filled = false;
                if (type === 'checkbox') filled = $item.find('.ia-addon-check').is(':checked');
                else filled = !!(addon_values[idx]);
                if (!filled) {
                    missingRequired = true;
                    $item.css('outline', '2px solid #e74c3c');
                } else {
                    $item.css('outline', '');
                }
            });
            if (missingRequired) return;

            var $atcGrid = (quickView && quickView.$lastGrid && quickView.$lastGrid.length)
                ? quickView.$lastGrid
                : $('.impulse-product-grid[data-qv], .impulse-product-carousel[data-qv]').first();
            var addonDefs = [];
            if ($atcGrid.length) { try { addonDefs = JSON.parse($atcGrid.attr('data-qv')).addons || []; } catch(e) {} }

            var originalText = $btn.text();
            var originalBg = $btn.css('background-color');
            $btn.prop('disabled', true).text('Adding...').css('background', '#aaa').css('color', '#fff').css('cursor', 'not-allowed');

            $.ajax({
                url: instinctorFrontend.ajaxUrl,
                type: 'POST',
                data: {
                    action: 'impulse_add_to_cart',
                    product_id: productId,
                    quantity: quantity,
                    variations: variations,
                    addon_defs:   JSON.stringify(addonDefs),
                    addon_values: JSON.stringify(addon_values),
                    nonce: instinctorFrontend.nonce
                },
                success: function(response) {
                    if (response.success) {
                        $btn.text('Added!');
                        setTimeout(function() {
                            $btn.prop('disabled', false).text(originalText).css({'background': '', 'color': '', 'cursor': ''});
                            if (response.data.cart_count !== undefined) {
                                $('.instinctor-cart-count, .impulse-cart-count').text(response.data.cart_count);
                            }
                        }, 1500);
                    } else {
                        $btn.prop('disabled', false).text(originalText).css({'background': '', 'color': '', 'cursor': ''});
                        console.error(response.data.message || 'Failed to add to cart');
                    }
                },
                error: function() {
                    $btn.prop('disabled', false).text(originalText).css({'background': '', 'color': '', 'cursor': ''});
                    console.error('Failed to add to cart');
                }
            });
        }
    };

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

    window.ImpulseQuickView = ImpulseQuickView;

    var ImpulseCardSlideshow = {
        intervals: {},
        
        init: function() {
            var self = this;

            $(document).on('mouseenter', '.impulse-pcard-image.has-slideshow', function() {
                var $container = $(this);
                var cardId = $container.closest('.impulse-pcard').data('product-id') || Math.random();
                var slideCount = parseInt($container.data('slideshow-count')) || 2;

                $container.find('.impulse-pcard-dots').css('opacity', '1');

                var currentIndex = 0;
                self.intervals[cardId] = setInterval(function() {
                    currentIndex = (currentIndex + 1) % slideCount;
                    self.showSlide($container, currentIndex);
                }, 2000); 
            });
            
            $(document).on('mouseleave', '.impulse-pcard-image.has-slideshow', function() {
                var $container = $(this);
                var cardId = $container.closest('.impulse-pcard').data('product-id') || 0;

                $container.find('.impulse-pcard-dots').css('opacity', '0');

                if (self.intervals[cardId]) {
                    clearInterval(self.intervals[cardId]);
                    delete self.intervals[cardId];
                }

                self.showSlide($container, 0);
            });

            $(document).on('click', '.impulse-pcard-dot', function(e) {
                e.stopPropagation();
                var $container = $(this).closest('.impulse-pcard-image');
                var index = parseInt($(this).data('slide-index')) || 0;
                var cardId = $container.closest('.impulse-pcard').data('product-id') || 0;

                if (self.intervals[cardId]) {
                    clearInterval(self.intervals[cardId]);
                }

                self.showSlide($container, index);

                var slideCount = parseInt($container.data('slideshow-count')) || 2;
                var currentIndex = index;
                self.intervals[cardId] = setInterval(function() {
                    currentIndex = (currentIndex + 1) % slideCount;
                    self.showSlide($container, currentIndex);
                }, 2000);
            });
        },
        
        showSlide: function($container, index) {
            var $images = $container.find('.impulse-pcard-slide-img');
            var $dots = $container.find('.impulse-pcard-dot');

            $images.css('opacity', '0').removeClass('active');
            $images.filter('[data-slide-index="' + index + '"]').css('opacity', '1').addClass('active');

            $dots.css('background', 'rgba(255,255,255,0.5)').removeClass('active');
            $dots.filter('[data-slide-index="' + index + '"]').css('background', 'rgba(255,255,255,1)').addClass('active');
        }
    };

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

    
    
    var ImpulseCouponField = {
        init: function() {
            var self = this;

            $(document).on('click', '.impulse-coupon-apply', function(e) {
                e.preventDefault();
                var $wrapper = $(this).closest('.impulse-coupon-wrapper');
                var $input = $wrapper.find('.impulse-coupon-input');
                var code = $input.val().trim();
                
                if (!code) {
                    self.showError($wrapper, 'Please enter a coupon code');
                    return;
                }
                
                self.applyCoupon($wrapper, code);
            });

            $(document).on('keypress', '.impulse-coupon-input', function(e) {
                if (e.which === 13) {
                    e.preventDefault();
                    $(this).closest('.impulse-coupon-wrapper').find('.impulse-coupon-apply').trigger('click');
                }
            });

            $(document).on('click', '.impulse-coupon-remove', function(e) {
                e.preventDefault();
                var $wrapper = $(this).closest('.impulse-coupon-wrapper');
                self.removeCoupon($wrapper);
            });
        },
        
        applyCoupon: function($wrapper, code) {
            var self = this;
            var $btn = $wrapper.find('.impulse-coupon-apply');
            var originalText = $btn.text();

            $btn.prop('disabled', true).text('Applying...');
            self.hideMessages($wrapper);
            
            $.ajax({
                url: instinctorFrontend.apiUrl + 'coupon/apply',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': instinctorFrontend.nonce
                },
                data: JSON.stringify({ code: code }),
                success: function(response) {
                    if (response.success) {
                        
                        $wrapper.find('.impulse-coupon-form').hide();
                        $wrapper.find('.impulse-coupon-applied').show();
                        $wrapper.find('.impulse-coupon-code').text(response.coupon.code);
                        $wrapper.find('.impulse-coupon-input').val('');

                        var discount = response.discount;
                        var msg = 'Coupon applied! ';
                        if (response.coupon.discount_type === 'percent') {
                            msg += response.coupon.amount + '% off';
                        } else {
                            msg += '$' + parseFloat(discount).toFixed(2) + ' off';
                        }
                        self.showSuccess($wrapper, msg);

                        $(document).trigger('instinctor:coupon:applied', [response]);
                    } else {
                        self.showError($wrapper, response.error || 'Invalid coupon code');
                    }
                },
                error: function(xhr) {
                    var msg = 'Failed to apply coupon';
                    try {
                        var resp = JSON.parse(xhr.responseText);
                        if (resp.error) msg = resp.error;
                    } catch(e) {}
                    self.showError($wrapper, msg);
                },
                complete: function() {
                    $btn.prop('disabled', false).text(originalText);
                }
            });
        },
        
        removeCoupon: function($wrapper) {
            var self = this;
            var $btn = $wrapper.find('.impulse-coupon-remove');
            
            $btn.prop('disabled', true);
            self.hideMessages($wrapper);
            
            $.ajax({
                url: instinctorFrontend.apiUrl + 'coupon/remove',
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'X-WP-Nonce': instinctorFrontend.nonce
                },
                success: function(response) {
                    if (response.success) {
                        
                        $wrapper.find('.impulse-coupon-applied').hide();
                        $wrapper.find('.impulse-coupon-form').css('display', $wrapper.data('layout') === 'inline' ? 'flex' : 'block');

                        $(document).trigger('instinctor:coupon:removed', [response]);
                    }
                },
                complete: function() {
                    $btn.prop('disabled', false);
                }
            });
        },
        
        showError: function($wrapper, message) {
            $wrapper.find('.impulse-coupon-error').text(message).show();
            $wrapper.find('.impulse-coupon-success').hide();
        },
        
        showSuccess: function($wrapper, message) {
            $wrapper.find('.impulse-coupon-success').text(message).show();
            $wrapper.find('.impulse-coupon-error').hide();

            setTimeout(function() {
                $wrapper.find('.impulse-coupon-success').fadeOut();
            }, 5000);
        },
        
        hideMessages: function($wrapper) {
            $wrapper.find('.impulse-coupon-error, .impulse-coupon-success').hide();
        }
    };
    
    $(document).ready(function() {
        ImpulseCouponField.init();
    });

})(jQuery);

(function($) {
    'use strict';
    
    $(document).on('submit', '.impulse-login-form', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $btn = $form.find('button[type="submit"]');
        var $msg = $form.find('.impulse-form-message');
        var originalText = $btn.text();

        $btn.prop('disabled', true).text('Logging in...');
        $msg.hide().removeClass('success error');
        
        $.ajax({
            url: instinctorFrontend.ajaxUrl,
            type: 'POST',
            data: {
                action: 'instinctor_ajax_login',
                nonce: instinctorFrontend.nonce,
                username: $form.find('input[name="username"]').val(),
                password: $form.find('input[name="password"]').val(),
                remember: $form.find('input[name="remember"]').is(':checked') ? 1 : 0,
                redirect: $form.data('redirect') || ''
            },
            success: function(response) {
                if (response.success) {
                    $msg.addClass('success').css({background:'#d4edda',color:'#155724'}).text(response.data.message).show();

                    setTimeout(function() {
                        if (response.data.redirect) {
                            window.location.href = response.data.redirect;
                        } else {
                            window.location.reload();
                        }
                    }, 500);
                } else {
                    $msg.addClass('error').css({background:'#f8d7da',color:'#721c24'}).text(response.data.message).show();
                    $btn.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                $msg.addClass('error').css({background:'#f8d7da',color:'#721c24'}).text('Connection error. Please try again.').show();
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });
    
    $(document).on('submit', '.impulse-register-form', function(e) {
        e.preventDefault();
        
        var $form = $(this);
        var $btn = $form.find('button[type="submit"]');
        var $msg = $form.find('.impulse-form-message');
        var originalText = $btn.text();

        $btn.prop('disabled', true).text('Creating account...');
        $msg.hide().removeClass('success error');
        
        $.ajax({
            url: instinctorFrontend.ajaxUrl,
            type: 'POST',
            data: {
                action: 'instinctor_ajax_register',
                nonce: instinctorFrontend.nonce,
                email: $form.find('input[name="email"]').val(),
                password: $form.find('input[name="password"]').val(),
                first_name: $form.find('input[name="first_name"]').val() || '',
                last_name: $form.find('input[name="last_name"]').val() || '',
                redirect: $form.data('redirect') || ''
            },
            success: function(response) {
                if (response.success) {
                    $msg.addClass('success').css({background:'#d4edda',color:'#155724'}).text(response.data.message).show();

                    setTimeout(function() {
                        if (response.data.redirect) {
                            window.location.href = response.data.redirect;
                        } else {
                            window.location.reload();
                        }
                    }, 500);
                } else {
                    $msg.addClass('error').css({background:'#f8d7da',color:'#721c24'}).text(response.data.message).show();
                    $btn.prop('disabled', false).text(originalText);
                }
            },
            error: function() {
                $msg.addClass('error').css({background:'#f8d7da',color:'#721c24'}).text('Connection error. Please try again.').show();
                $btn.prop('disabled', false).text(originalText);
            }
        });
    });

    
    $(document).on('click', '.impulse-forgot-trigger', function(e) {
        e.preventDefault();
        var $wrap = $(this).closest('.impulse-login-wrapper');
        $wrap.find('.impulse-login-fields').hide();
        $wrap.find('.impulse-forgot-fields').show().find('input[name="forgot_email"]').focus();
    });

    $(document).on('click', '.impulse-forgot-back', function(e) {
        e.preventDefault();
        var $wrap = $(this).closest('.impulse-login-wrapper');
        $wrap.find('.impulse-forgot-fields').hide();
        $wrap.find('.impulse-login-fields').show();
        $wrap.find('.impulse-forgot-msg').hide().text('').removeClass('success error');
    });

    $(document).on('submit', '.impulse-forgot-form', function(e) {
        e.preventDefault();
        var $form  = $(this);
        var $wrap  = $form.closest('.impulse-login-wrapper');
        var $btn   = $form.find('button[type="submit"]');
        var $msg   = $wrap.find('.impulse-forgot-msg');
        var orig   = $btn.text();

        $btn.prop('disabled', true).text('Sending...');
        $msg.hide().removeClass('success error');

        $.ajax({
            url: instinctorFrontend.ajaxUrl,
            type: 'POST',
            data: {
                action: 'instinctor_forgot_password',
                nonce: instinctorFrontend.nonce,
                email: $form.find('input[name="forgot_email"]').val()
            },
            success: function(response) {
                $msg.css({background:'#d4edda', color:'#155724', padding:'10px 12px',
                    borderRadius:'4px', fontSize:'13px'})
                    .text(response.success
                        ? (response.data.message || 'Check your email for a reset link.')
                        : (response.data.message || 'Something went wrong.'))
                    .addClass(response.success ? 'success' : 'error')
                    .show();
                $btn.prop('disabled', false).text(orig);
                if (response.success) {
                    $form.find('input[name="forgot_email"]').val('');
                }
            },
            error: function() {
                $msg.css({background:'#f8d7da', color:'#721c24', padding:'10px 12px',
                    borderRadius:'4px', fontSize:'13px'})
                    .text('Connection error. Please try again.').addClass('error').show();
                $btn.prop('disabled', false).text(orig);
            }
        });
    });

    
    $(document).on('click', '.impulse-announcement-close', function() {
        var $bar = $(this).closest('.impulse-announcement-bar');
        var barId = $bar.closest('.impulse-el').data('id') || 'default';

        document.cookie = 'impulse_announcement_' + barId + '=dismissed;max-age=86400;path=/';
        
        $bar.slideUp(200, function() {
            $(this).remove();
        });
    });

    $(document).ready(function() {
        $('.impulse-announcement-bar').each(function() {
            var $bar = $(this);
            var barId = $bar.closest('.impulse-el').data('id') || 'default';
            
            if (document.cookie.indexOf('impulse_announcement_' + barId + '=dismissed') !== -1) {
                $bar.remove();
            }
        });

        $('.impulse-announcement-countdown').each(function() {
            var $el = $(this);
            var endDate = new Date($el.data('date')).getTime();
            
            function updateCountdown() {
                var now = new Date().getTime();
                var diff = endDate - now;
                
                if (diff <= 0) {
                    $el.text('Ended');
                    return;
                }
                
                var days = Math.floor(diff / (1000 * 60 * 60 * 24));
                var hours = Math.floor((diff % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
                var mins = Math.floor((diff % (1000 * 60 * 60)) / (1000 * 60));
                var secs = Math.floor((diff % (1000 * 60)) / 1000);
                
                var text = '';
                if (days > 0) text += days + 'd ';
                text += hours.toString().padStart(2, '0') + ':' + mins.toString().padStart(2, '0') + ':' + secs.toString().padStart(2, '0');
                
                $el.text(text);
            }
            
            updateCountdown();
            setInterval(updateCountdown, 1000);
        });
    });

})(jQuery);

(function($) {
    'use strict';

    function initProductSection($section) {
        var productId = parseInt($section.data('product-id'));
        if (!productId) return;
        if ($section.data('impulse-product-init')) return;
        $section.data('impulse-product-init', true);

        var apiBase = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.apiUrl) || '/wp-json/instinctor/v1/';

        fetch(apiBase + 'products/' + productId + '/addons')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var addons = (data && data.addons) || [];
                if (addons.length === 0) return;
                var $btn = $section.find('.impulse-pcard-btn');
                if (!$btn.length) return;
                var html = renderAddonsForm(addons);
                $btn.closest('.impulse-pcard').find('.impulse-pcard-content').after(html);
            })
            .catch(function() {});

        fetch(apiBase + 'products/' + productId + '/volume-tiers')
            .then(function(r) { return r.json(); })
            .then(function(data) {
                var tiers = (data && data.tiers) || [];
                if (tiers.length === 0) return;
                var $btn = $section.find('.impulse-pcard-btn');
                if (!$btn.length) return;
                var html = renderVolumeTierTable(tiers);
                $btn.closest('.impulse-pcard-btn-wrap').before(html);
            })
            .catch(function() {});
    }

    function renderAddonsForm(addons) {
        var html = '<div class="impulse-addons-form" style="padding:0 16px 8px;font-size:12px">';
        addons.forEach(function(addon) {
            html += '<div class="impulse-addon-field" style="margin-bottom:8px" data-addon-id="' + addon.id + '">';
            var priceLabel = parseFloat(addon.price) > 0
                ? ' <span style="color:#888;font-size:11px">(+$' + parseFloat(addon.price).toFixed(2) + ')</span>'
                : '';
            switch (addon.type) {
                case 'checkbox':
                    html += '<label style="display:flex;align-items:center;gap:6px;cursor:pointer">';
                    html += '<input type="checkbox" class="impulse-addon-input" data-addon-id="' + addon.id + '" data-price="' + addon.price + '" data-price-type="' + addon.price_type + '"' + (addon.required ? ' required' : '') + '>';
                    html += '<span>' + escHtml(addon.name) + priceLabel + '</span>';
                    html += '</label>';
                    break;
                case 'text':
                    html += '<div>' + escHtml(addon.name) + priceLabel + '</div>';
                    html += '<input type="text" class="impulse-addon-input" data-addon-id="' + addon.id + '" data-price="' + addon.price + '" data-price-type="' + addon.price_type + '"' + (addon.max_length ? ' maxlength="' + addon.max_length + '"' : '') + (addon.required ? ' required' : '') + ' style="width:100%;border:1px solid #ddd;padding:5px 8px;border-radius:3px;font-size:12px;margin-top:3px">';
                    break;
                case 'textarea':
                    html += '<div>' + escHtml(addon.name) + priceLabel + '</div>';
                    html += '<textarea class="impulse-addon-input" data-addon-id="' + addon.id + '" data-price="' + addon.price + '" data-price-type="' + addon.price_type + '"' + (addon.required ? ' required' : '') + ' rows="2" style="width:100%;border:1px solid #ddd;padding:5px 8px;border-radius:3px;font-size:12px;margin-top:3px;resize:vertical"></textarea>';
                    break;
                case 'select':
                    html += '<div>' + escHtml(addon.name) + priceLabel + '</div>';
                    html += '<select class="impulse-addon-input" data-addon-id="' + addon.id + '" data-price="' + addon.price + '" data-price-type="' + addon.price_type + '"' + (addon.required ? ' required' : '') + ' style="width:100%;border:1px solid #ddd;padding:5px 8px;border-radius:3px;font-size:12px;margin-top:3px">';
                    html += '<option value="">Select…</option>';
                    (addon.options || []).forEach(function(opt) {
                        html += '<option value="' + escHtml(opt) + '">' + escHtml(opt) + '</option>';
                    });
                    html += '</select>';
                    break;
            }
            if (addon.description) {
                html += '<div style="font-size:11px;color:#888;margin-top:3px">' + escHtml(addon.description) + '</div>';
            }
            html += '</div>';
        });
        html += '</div>';
        return html;
    }

    function renderVolumeTierTable(tiers) {
        var html = '<div class="impulse-volume-tiers" style="padding:0 16px 8px">';
        html += '<table style="width:100%;font-size:11px;border-collapse:collapse">';
        html += '<thead><tr><th style="text-align:left;color:#888;font-weight:400;padding-bottom:4px">Qty</th><th style="text-align:right;color:#888;font-weight:400;padding-bottom:4px">Discount</th></tr></thead>';
        html += '<tbody>';
        tiers.forEach(function(tier) {
            var range = tier.max_quantity ? tier.min_quantity + '–' + tier.max_quantity : tier.min_quantity + '+';
            var disc = tier.discount_type === 'percent' ? tier.discount_value + '%' : '$' + parseFloat(tier.discount_value).toFixed(2);
            html += '<tr><td style="color:#555;padding:2px 0">' + range + '</td><td style="text-align:right;color:#555;padding:2px 0">Save ' + disc + '</td></tr>';
        });
        html += '</tbody></table></div>';
        return html;
    }

    function escHtml(str) {
        if (!str) return '';
        var d = document.createElement('div');
        d.textContent = String(str);
        return d.innerHTML;
    }

    function collectAddons($pcard) {
        var addons = {};
        $pcard.find('.impulse-addon-input').each(function() {
            var id = $(this).data('addon-id');
            var val;
            if ($(this).is('[type="checkbox"]')) {
                val = $(this).is(':checked') ? '1' : '';
            } else {
                val = $(this).val();
            }
            addons[id] = val;
        });
        return addons;
    }

    $(document).on('click', '.impulse-pcard-btn', function() {
        var $btn = $(this);
        var $pcard = $btn.closest('.impulse-pcard');
        var productId = parseInt($pcard.data('product-id'));
        if (!productId) return;

        var valid = true;
        $pcard.find('.impulse-addon-input[required]').each(function() {
            var v = $(this).is('[type="checkbox"]') ? $(this).is(':checked') : $(this).val();
            if (!v) { valid = false; }
        });
        if (!valid) {
            $btn.text('Fill required fields').css('background', '#dc2626');
            setTimeout(function() { $btn.text($btn.data('orig-text') || 'Add to Cart').css('background', ''); }, 2000);
            return;
        }

        var origText = $btn.text();
        $btn.data('orig-text', origText).prop('disabled', true).text('Adding…');

        var addons = collectAddons($pcard);
        var quantity = parseInt($pcard.find('.impulse-qty-input').val()) || 1;
        var apiBase = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.apiUrl) || '/wp-json/instinctor/v1/';
        var nonce   = (typeof instinctorFrontend !== 'undefined' && instinctorFrontend.nonce) || '';

        fetch(apiBase + 'cart/add', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce },
            body: JSON.stringify({ product_id: productId, quantity: quantity, addons: addons })
        })
        .then(function(r) { return r.json(); })
        .then(function(data) {
            $btn.prop('disabled', false);
            if (data.error) {
                $btn.text(data.error).css('background', '#dc2626');
                setTimeout(function() { $btn.text(origText).css('background', ''); }, 2500);
            } else {
                $btn.text('Added!');
                setTimeout(function() { $btn.text(origText); }, 1500);
                
                var items = data.cart && data.cart.items ? Object.values(data.cart.items) : [];
                var total = items.reduce(function(n, i) { return n + (i.quantity || 0); }, 0);
                $('.instinctor-cart-count, .impulse-cart-count').text(total);
                $(document).trigger('instinctor:added_to_cart', [data.cart]);
            }
        })
        .catch(function() {
            $btn.prop('disabled', false).text(origText);
        });
    });

    $(document).ready(function() {
        $('.impulse-pcard').each(function() { initProductSection($(this)); });
    });

    $(document).on('impulse:products:rendered', function() {
        $('.impulse-pcard').each(function() { initProductSection($(this)); });
    });

})(jQuery);

(function($) {
    var IF      = (typeof instinctorFrontend !== 'undefined') ? instinctorFrontend : {};
    var apiBase = IF.apiUrl || '/wp-json/instinctor/v1/';
    var cartUrl = IF.cartUrl || '/cart';
    var sym     = IF.currencySymbol || '$';
    var pos     = IF.currencyPosition || 'left';
    var dec     = (IF.currencyDecimals != null) ? parseInt(IF.currencyDecimals, 10) : 2;
    var el, countEl, totalEl, drawer, drawerOpen = false, built = false;

    function money(n){ var v=(parseFloat(n)||0).toFixed(dec); return pos==='right' ? v+sym : sym+v; }
    function esc(s){ return String(s==null?'':s).replace(/[&<>"]/g, function(c){ return {'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[c]; }); }

    function injectStyles(){
        if (document.getElementById('instinctor-sticky-cart-css')) return;
        var css = '.instinctor-sticky-cart{position:fixed;right:20px;bottom:20px;z-index:99990;display:none;align-items:center;gap:10px;'
            + 'background:#1d2327;color:#fff;border:none;border-radius:999px;padding:12px 20px 12px 16px;cursor:pointer;'
            + 'font:600 14px/1 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;box-shadow:0 6px 24px rgba(0,0,0,.28);'
            + 'opacity:0;transform:translateY(12px);transition:opacity .35s ease-in-out,transform .35s ease-in-out}'
            + '.instinctor-sticky-cart.on{display:inline-flex;opacity:1;transform:translateY(0)}'
            + '.instinctor-sticky-cart:hover{background:#000}'
            + '.instinctor-sticky-cart.iscart-top{top:18px;bottom:auto;padding:10px 14px;gap:7px}'   
            + '.instinctor-sticky-cart.iscart-top span:not(.iscart-count){display:none}'            
            + '.instinctor-sticky-cart svg{display:block;flex:0 0 auto}'
            + '.instinctor-sticky-cart .iscart-count{background:#fff;color:#1d2327;border-radius:999px;min-width:20px;height:20px;'
            + 'display:inline-flex;align-items:center;justify-content:center;font-size:12px;font-weight:700;padding:0 6px}'
            + '.instinctor-sticky-cart .iscart-total{font-variant-numeric:tabular-nums}'
            
            + '.iscart-drawer{position:fixed;right:20px;bottom:78px;z-index:99991;width:330px;max-width:calc(100vw - 40px);max-height:62vh;overflow:auto;'
            + 'background:#1d2327;color:#fff;border-radius:14px;padding:6px 16px 16px;box-shadow:0 14px 44px rgba(0,0,0,.42);display:none;'
            + 'font:500 14px/1.3 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}'
            + '.iscart-drawer.on{display:block}'
            + '.iscart-drawer.iscart-top{top:68px;bottom:auto;right:12px}'   
            + '.iscart-drawer h4{margin:12px 4px 4px;font-size:12px;font-weight:700;letter-spacing:.05em;text-transform:uppercase;opacity:.6}'
            + '.iscart-row{display:flex;align-items:center;gap:11px;padding:11px 0;border-bottom:1px solid rgba(255,255,255,.1)}'
            + '.iscart-row:last-of-type{border-bottom:none}'
            + '.iscart-thumb{width:46px;height:46px;border-radius:9px;object-fit:cover;background:#000;flex:0 0 auto}'
            + '.iscart-info{flex:1 1 auto;min-width:0}'
            + '.iscart-nm{font-weight:600;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
            + '.iscart-sub{font-size:12px;opacity:.55;margin-top:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}'
            + '.iscart-lp{font-variant-numeric:tabular-nums;font-weight:600;flex:0 0 auto;margin-left:2px}'
            + '.iscart-rm{flex:0 0 auto;display:inline-flex;align-items:center;justify-content:center;width:26px;height:26px;border:none;background:transparent;color:#fff;opacity:.45;cursor:pointer;border-radius:7px;transition:opacity .2s ease-in-out,background .2s ease-in-out}'
            + '.iscart-rm:hover{opacity:1;background:rgba(255,255,255,.12)}'
            + '.iscart-foot{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-top:15px}'
            + '.iscart-grand{font-size:13px;opacity:.65}.iscart-grand b{font-size:17px;color:#fff;margin-left:7px;font-variant-numeric:tabular-nums}'
            + '.iscart-checkout{flex:0 0 auto;border:none;background:#fff;color:#1d2327;border-radius:999px;padding:11px 22px;font:700 14px/1 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;cursor:pointer;transition:transform .15s ease-in-out,background .2s ease-in-out}'
            + '.iscart-checkout:hover{transform:translateY(-1px);background:#f1e4d2}'

            
            
            + '@media (max-width:759px){.instinctor-sticky-cart{right:12px;bottom:12px;left:12px;justify-content:center}'
            + '.instinctor-sticky-cart.iscart-top{top:auto;bottom:16px;left:auto;right:12px;width:auto}'
            + '.iscart-drawer,.iscart-drawer.iscart-top{left:12px;right:12px;top:auto;bottom:12px;width:auto;max-width:none;max-height:72vh}}';
        var s=document.createElement('style'); s.id='instinctor-sticky-cart-css'; s.textContent=css; document.head.appendChild(s);
    }

    function build(){
        if (built) return; built = true;
        injectStyles();
        el = document.createElement('button');
        el.type='button'; el.className='instinctor-sticky-cart'; el.setAttribute('aria-label','View your order');
        el.innerHTML = '<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round" aria-hidden="true"><circle cx="8" cy="21" r="1"/><circle cx="19" cy="21" r="1"/><path d="M2.05 2.05h2l2.66 12.42a2 2 0 0 0 2 1.58h9.78a2 2 0 0 0 1.95-1.57l1.65-7.43H5.12"/></svg><span>View order</span><span class="iscart-count">0</span><span class="iscart-total"></span>';
        countEl = el.querySelector('.iscart-count');
        totalEl = el.querySelector('.iscart-total');
        el.addEventListener('click', function(e){ e.stopPropagation(); toggleDrawer(); });
        document.body.appendChild(el);
        
        drawer = document.createElement('div');
        drawer.className = 'iscart-drawer';
        drawer.addEventListener('click', function(e){
            e.stopPropagation();   
            var rm = e.target.closest('.iscart-rm');
            if (rm){ removeItem(rm.getAttribute('data-key')); return; }
            if (e.target.closest('.iscart-checkout')){ window.location.href = cartUrl; }
        });
        document.body.appendChild(drawer);
        document.addEventListener('click', function(){ closeDrawer(); });   
    }

    function openDrawer(){
        if (!drawer || !el) return;
        renderDrawer();
        if (drawerOpen) return;
        drawer.classList.toggle('iscart-top', el.classList.contains('iscart-top'));   
        drawer.classList.add('on');
        drawerOpen = true;
    }
    function closeDrawer(){ if (drawer){ drawer.classList.remove('on'); drawerOpen = false; } }
    function toggleDrawer(){ drawerOpen ? closeDrawer() : openDrawer(); }

    function renderDrawer(){
        if (!drawer) return;
        var c = _lastCart, items = (c && c.items) ? c.items : {};
        var keys = Object.keys(items);
        if (!keys.length){ closeDrawer(); return; }
        var total = (c.totals && c.totals.total != null) ? c.totals.total : null;
        var rmIcon = '<svg width="15" height="15" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2.4" stroke-linecap="round"><path d="M18 6 6 18"/><path d="m6 6 12 12"/></svg>';
        var html = '<h4>Your order</h4>';
        keys.forEach(function(k){
            var it = items[k];
            var line = (parseFloat(it.price)||0) * (it.quantity||1);
            var sub = [];
            if (it.meta && it.meta.size) sub.push(it.meta.size);
            if ((it.quantity||1) > 1) sub.push('×' + it.quantity);
            html += '<div class="iscart-row">'
                + (it.image ? '<img class="iscart-thumb" src="'+esc(it.image)+'" alt="">' : '<span class="iscart-thumb"></span>')
                + '<div class="iscart-info"><div class="iscart-nm">'+esc(it.name||'Item')+'</div>'
                + (sub.length ? '<div class="iscart-sub">'+esc(sub.join(' · '))+'</div>' : '')
                + '</div>'
                + '<span class="iscart-lp">'+money(line)+'</span>'
                + '<button type="button" class="iscart-rm" data-key="'+esc(k)+'" aria-label="Remove item">'+rmIcon+'</button>'
                + '</div>';
        });
        html += '<div class="iscart-foot"><span class="iscart-grand">Total<b>'+(total!=null?money(total):'')+'</b></span>'
            + '<button type="button" class="iscart-checkout">Checkout</button></div>';
        drawer.innerHTML = html;
    }

    function removeItem(key){
        if (!key) return;
        fetch(apiBase + 'cart/remove', {
            method: 'POST',
            headers: { 'Content-Type':'application/json', 'X-WP-Nonce': IF.nonce || '' },
            body: JSON.stringify({ item_key: key })
        }).then(function(r){ return r.json(); }).then(function(d){
            update(d && (d.cart || d.data || d));   
            if (window.jQuery) window.jQuery(document).trigger('instinctor:added_to_cart', [_lastCart]);  
        }).catch(function(){});
    }

    

    
    var _lastCart = null;
    function suppressSticky(){
        if (window.parent !== window) return true;   
        var screensEls = document.querySelectorAll('.impulse-screen');
        var act = document.querySelector('.impulse-screen-active') || screensEls[0];
        if (!act) return false;
        if (act.querySelector('a[href$="#quote"]')) return true;           
        if (screensEls.length && act === screensEls[0]) return true;       

        

        
        
        var isPizzaPage = /^\/pizza(\/|$)/i.test(location.pathname);
        if (!isPizzaPage && document.querySelector('.impulse-configurator')) {
            if (!act.querySelector('.impulse-configurator')) return true;
        }
        return false;
    }
    function update(cart){
        if (cart) _lastCart = cart;
        var c = _lastCart, count=0, total=null;
        if (c && c.items) Object.keys(c.items).forEach(function(k){ count += c.items[k].quantity || 0; });
        if (c && c.totals && c.totals.total != null) total = c.totals.total;
        if (count > 0 && !suppressSticky()){
            build();
            var actNow = document.querySelector('.impulse-screen-active');
            el.classList.toggle('iscart-top', !!(actNow && actNow.querySelector('.impulse-configurator'))); 
            countEl.textContent = count;
            totalEl.textContent = (total != null) ? money(total) : '';
            requestAnimationFrame(function(){ el.classList.add('on'); });
            if (drawerOpen){ drawer.classList.toggle('iscart-top', el.classList.contains('iscart-top')); renderDrawer(); }
        } else if (el){
            el.classList.remove('on');
            closeDrawer();   
        }
    }

    function fetchCart(){
        fetch(apiBase + 'cart', { headers: { 'Content-Type':'application/json' } })
            .then(function(r){ return r.json(); })
            .then(function(j){ update(j && (j.data || j.cart || j)); })
            .catch(function(){});
    }

    $(document).ready(function(){
        
        if (!document.querySelector('.impulse-configurator, .instinctor-add-to-cart-btn, [data-product-id]')) return;
        fetchCart();
        $(document).on('instinctor:added_to_cart', function(e, cart){ update(cart); });
        document.addEventListener('instinctor:cart:updated', function(e){ update(e.detail && (e.detail.cart || e.detail)); });
        document.addEventListener('impulse-screen-changed', function(){ update(); });   
    });
})(jQuery);

(function(){
    function placeSmoke(){
        var mobile = window.matchMedia && window.matchMedia('(max-width:759px)').matches;
        document.querySelectorAll('.impulse-smoke-layer').forEach(function(layer){
            if (layer.dataset.origStyle == null) layer.dataset.origStyle = layer.getAttribute('style') || '';
            if (!mobile){ layer.setAttribute('style', layer.dataset.origStyle); return; }
            var section = layer.closest('.impulse-section'); if (!section) return;
            var btns = section.querySelectorAll('.impulse-button, .impulse-button-wrap a, a.impulse-button, button');
            var target = null;
            btns.forEach(function(b){ if (/\btry\b/i.test(b.textContent || '')) target = b; });
            if (!target && btns.length) target = btns[0];
            if (!target) return;
            var sr = section.getBoundingClientRect(), br = target.getBoundingClientRect();
            if (!sr.height || !sr.width) return;
            var wm = layer.dataset.origStyle.match(/width:\s*([\d.]+)%/);
            var widthPct = wm ? parseFloat(wm[1]) : 38;
            var bottomPct = (sr.bottom - (br.top + br.height / 2)) / sr.height * 100;   
            var cxPct = ((br.left + br.width / 2) - sr.left) / sr.width * 100;
            layer.setAttribute('style', layer.dataset.origStyle);   
            layer.style.bottom = bottomPct.toFixed(1) + '%';
            layer.style.left = (cxPct - widthPct / 2).toFixed(1) + '%';
        });
    }
    if (document.readyState !== 'loading') placeSmoke(); else document.addEventListener('DOMContentLoaded', placeSmoke);
    window.addEventListener('resize', placeSmoke);
    document.addEventListener('impulse-screen-changed', placeSmoke);
    setTimeout(placeSmoke, 700);   
})();

(function(){
    var IF = window.instinctorFrontend || {};
    var apiBase = IF.apiUrl || '/api/instinctor/v1/';
    var nonce = IF.nonce || '';
    var X = '<svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2" stroke-linecap="round" stroke-linejoin="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>';
    var overlay = null, cssInjected = false;

    function injectCss(){
        if (cssInjected) return; cssInjected = true;
        var css =
            '.iq-overlay{position:fixed;inset:0;z-index:100000;display:none;align-items:center;justify-content:center;background:rgba(18,18,20,.55);padding:20px;opacity:0;transition:opacity .25s ease-in-out}'
          + '.iq-overlay.on{display:flex;opacity:1}'
          + '.iq-card{position:relative;width:100%;max-width:420px;background:#fff;border-radius:16px;padding:28px 24px 24px;box-shadow:0 20px 60px rgba(0,0,0,.35);transform:translateY(14px);transition:transform .25s ease-in-out;font:400 15px/1.5 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif;color:#1d2327;box-sizing:border-box}'
          + '.iq-overlay.on .iq-card{transform:translateY(0)}'
          + '.iq-card h2{margin:0 0 5px;font-size:21px;font-weight:700}'
          + '.iq-sub{margin:0 0 18px;font-size:14px;color:#555}'
          + '.iq-field{display:block;width:100%;height:44px;padding:0 14px;margin:0 0 10px;border:1px solid #e0e0e0;border-radius:9px;font-size:15px;color:#1d2327;background:#fff;box-sizing:border-box;font-family:inherit;transition:border-color .15s ease-in-out}'
          + 'textarea.iq-field{height:78px;padding:11px 14px;resize:vertical}'
          + '.iq-field:focus{outline:none;border-color:#999}'
          + '.iq-hp{position:absolute;left:-9999px;width:1px;height:1px;opacity:0}'
          + '.iq-submit{width:100%;height:48px;margin-top:6px;border:none;border-radius:999px;background:#1d2327;color:#fff;font-size:16px;font-weight:700;cursor:pointer;transition:background .15s ease-in-out}'
          + '.iq-submit:hover{background:#000}.iq-submit[disabled]{opacity:.6;cursor:default}'
          + '.iq-close{position:absolute;top:13px;right:14px;width:32px;height:32px;border:none;background:none;color:#999;cursor:pointer;display:flex;align-items:center;justify-content:center}'
          + '.iq-close:hover{color:#1d2327}'
          + '.iq-note{font-size:12px;color:#999;text-align:center;margin:10px 0 0}'
          + '.iq-done{text-align:center;padding:18px 0 8px}'
          + '.iq-bar{position:fixed;top:0;left:0;right:0;z-index:99995;display:none;align-items:center;justify-content:center;gap:14px;padding:8px 16px;background:rgba(29,35,39,.86);backdrop-filter:blur(8px);-webkit-backdrop-filter:blur(8px);color:#fff;font:600 13px/1.3 system-ui,-apple-system,"Segoe UI",Roboto,sans-serif}'
          + '.iq-bar.on{display:flex}'
          + '.iq-bar-txt{opacity:.92}'
          + '.iq-bar-cta{flex:0 0 auto;border:1px solid rgba(255,255,255,.5);border-radius:999px;padding:5px 14px;color:#fff;text-decoration:none;font-weight:700;white-space:nowrap;transition:background .15s ease-in-out,border-color .15s ease-in-out}'
          + '.iq-bar-cta:hover{background:#fff;color:#1d2327;border-color:#fff}'
          + '@media(max-width:620px){.iq-bar{font-size:11px;gap:10px;padding:7px 12px}.iq-bar-long{display:none}}'
          + '@media(min-width:621px){.iq-bar-short{display:none}}';
        var s = document.createElement('style'); s.id = 'instinctor-quote-css'; s.textContent = css; document.head.appendChild(s);
    }

    function build(){
        if (overlay) return;
        injectCss();
        overlay = document.createElement('div'); overlay.className = 'iq-overlay';
        overlay.innerHTML =
            '<div class="iq-card" role="dialog" aria-modal="true" aria-label="Request your page">'
          + '<button type="button" class="iq-close" aria-label="Close">' + X + '</button>'
          + '<div class="iq-body">'
          + '<h2>Put this on your website</h2>'
          + '<p class="iq-sub">Tell us about your pizzeria and we&rsquo;ll set up your own build-your-pizza ordering page. No obligation.</p>'
          + '<form class="iq-form" novalidate>'
          + '<input class="iq-field" name="name" placeholder="Your name" autocomplete="name">'
          + '<input class="iq-field" name="restaurant" placeholder="Restaurant name" autocomplete="organization">'
          + '<input class="iq-field" name="phone" placeholder="Phone" autocomplete="tel" inputmode="tel">'
          + '<input class="iq-field" name="email" placeholder="Email (optional)" autocomplete="email" inputmode="email">'
          + '<textarea class="iq-field" name="message" placeholder="Anything we should know (optional)"></textarea>'
          + '<input class="iq-hp" name="company_url" tabindex="-1" autocomplete="off" aria-hidden="true">'
          + '<button type="submit" class="iq-submit">Request your page</button>'
          + '<p class="iq-note">We&rsquo;ll reply within a day.</p>'
          + '</form></div></div>';
        document.body.appendChild(overlay);
        overlay.addEventListener('click', function(e){ if (e.target === overlay) closeForm(); });
        overlay.querySelector('.iq-close').addEventListener('click', closeForm);
        overlay.querySelector('.iq-form').addEventListener('submit', submitForm);
    }

    function openForm(){ build(); requestAnimationFrame(function(){ overlay.classList.add('on'); var f = overlay.querySelector('input[name="name"]'); if (f) f.focus(); }); }
    function closeForm(){ if (overlay) overlay.classList.remove('on'); }

    async function submitForm(e){
        e.preventDefault();
        var form = e.target, btn = form.querySelector('.iq-submit');
        var data = { name: form.name.value, restaurant: form.restaurant.value, phone: form.phone.value, email: form.email.value, message: form.message.value, company_url: form.company_url.value, source: location.href };
        if (!data.name.trim() || (!data.phone.trim() && !data.email.trim())) {
            btn.textContent = 'Add your name and a phone or email'; setTimeout(function(){ btn.textContent = 'Request your page'; }, 2400); return;
        }
        btn.disabled = true; var orig = btn.textContent; btn.textContent = 'Sending...';
        try {
            var r = await fetch(apiBase + 'demo-lead', { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-WP-Nonce': nonce }, body: JSON.stringify(data) });
            var j = await r.json();
            if (j && j.success) {
                overlay.querySelector('.iq-body').innerHTML = '<div class="iq-done"><h2>Thank you</h2><p class="iq-sub">We got your details and will reach out shortly.</p></div>';
            } else { btn.disabled = false; btn.textContent = (j && j.error) ? j.error : 'Something went wrong, try again'; setTimeout(function(){ btn.textContent = orig; }, 2600); }
        } catch (_e) { btn.disabled = false; btn.textContent = 'Network error, try again'; setTimeout(function(){ btn.textContent = orig; }, 2600); }
    }

    document.addEventListener('click', function(e){
        var t = e.target.closest('a[href$="#quote"], [data-quote]');
        if (t) { e.preventDefault(); openForm(); }
    });
    document.addEventListener('keydown', function(e){ if (e.key === 'Escape') closeForm(); });

    

    

    

    

    document.addEventListener('click', function(e){
        var t = e.target && e.target.closest && e.target.closest('a[href="#chat-open"], button[data-link="#chat-open"]');
        if (!t) return;

        

        

        if (t.tagName === 'BUTTON') {
            e.preventDefault();
            if (window.InstinctorChat && typeof window.InstinctorChat.ghostTrigger === 'function') {
                try { window.InstinctorChat.ghostTrigger(); } catch(_e){}
            }
        }

        

        
        (function attractAttention(){
            if (!document.getElementById('iq-chat-attn-css')) {
                var st = document.createElement('style');
                st.id = 'iq-chat-attn-css';
                st.textContent =
                    '@keyframes iq-chat-attn {' +
                    '  0%   { transform: scale(1);    box-shadow: 0 0 0 0 rgba(255,255,255,0.0); }' +
                    '  20%  { transform: scale(1.06); box-shadow: 0 0 32px 10px rgba(255,255,255,0.55); }' +
                    '  60%  { transform: scale(1.02); box-shadow: 0 0 20px 6px  rgba(255,255,255,0.30); }' +
                    '  100% { transform: scale(1);    box-shadow: 0 0 0 0 rgba(255,255,255,0.0); }' +
                    '}' +
                    '.iq-chat-attn-on { animation: iq-chat-attn 1.6s ease-in-out; transform-origin: bottom right; }';
                document.head.appendChild(st);
            }

            setTimeout(function(){
                var target = document.querySelector('.instinctor-chat-panel, .instinctor-chat-window, .instinctor-chat-expanded')
                          || document.getElementById('instinctor-chat-bar');
                if (!target) return;
                target.classList.remove('iq-chat-attn-on');
                
                void target.offsetWidth;
                target.classList.add('iq-chat-attn-on');
                setTimeout(function(){ target.classList.remove('iq-chat-attn-on'); }, 1800);
            }, 200);
        })();
    });

    

    
    
    var isInstinctorHost = /(^|\.)instinctor\.com$/i.test(location.hostname);
    var isPizzaPath      = /^\/pizza(\/|$)/i.test(location.pathname);
    function mountBar(){
        if (!isInstinctorHost || !isPizzaPath || !document.querySelector('.impulse-configurator')) return;
        if (document.querySelector('.iq-bar')) return;
        injectCss();
        var bar = document.createElement('div'); bar.className = 'iq-bar';
        bar.innerHTML = '<span class="iq-bar-txt iq-bar-long">Live demo: a build-your-pizza ordering page for your restaurant&rsquo;s website</span>'
                      + '<span class="iq-bar-txt iq-bar-short">Demo for your restaurant&rsquo;s site</span>'
                      + '<a class="iq-bar-cta" href="#quote">Put this on my site</a>';
        document.body.appendChild(bar);
        updateBar();
    }
    function updateBar(){
        var bar = document.querySelector('.iq-bar'); if (!bar) return;
        var act = document.querySelector('.impulse-screen-active');
        
        if (act && act.querySelector('.impulse-configurator')) bar.classList.remove('on');
        else bar.classList.add('on');
    }
    if (document.readyState !== 'loading') mountBar(); else document.addEventListener('DOMContentLoaded', mountBar);
    document.addEventListener('impulse-screen-changed', updateBar);
    setTimeout(mountBar, 800);
})();
