/**
 * GT BOGO Engine — Frontend Cart Intelligence
 * Event-driven — fires instantly on quantity change.
 * No polling. Zero server load between interactions.
 */
(function($) {
    'use strict';

    var isBlocks = (typeof gtBogoCart !== 'undefined' && gtBogoCart.isBlocks === '1');

    // ── Classic cart recalc ───────────────────────────────────────────────────
    function triggerClassicRecalc() {
        if ($('.woocommerce-cart-form').length) {
            $('[name="update_cart"]').prop('disabled', false).trigger('click');
        } else {
            $(document.body).trigger('wc_fragment_refresh');
        }
    }

    // ── Blocks cart recalc ────────────────────────────────────────────────────
    function triggerBlocksRecalc() {
        if (typeof wp !== 'undefined' && wp.data) {
            try {
                wp.data.dispatch('wc/store/cart').invalidateResolutionForStoreSelector('getCartData');
            } catch(e) {}
        }
    }

    // ── Classic cart: fire instantly on qty change ────────────────────────────
    $(document).on('change', 'input.qty', function() {
        triggerClassicRecalc();
    });

    // ── Blocks cart: fire instantly on stepper click ──────────────────────────
    function attachBlocksQtyWatcher() {
        document.querySelectorAll(
            '.wc-block-cart-item__quantity button, .wc-block-components-quantity-stepper button'
        ).forEach(function(btn) {
            if (btn.dataset.gtAttached) return;
            btn.dataset.gtAttached = '1';
            btn.addEventListener('click', function() {
                // Small delay to let Blocks state update first
                setTimeout(triggerBlocksRecalc, 300);
            });
        });
    }

    // ── Animate BOGO discount line when it appears ────────────────────────────
    $(document.body).on('updated_cart_totals wc_fragments_loaded wc_fragments_refreshed', function() {
        $('.cart-discount, .wc-block-components-totals-discount, tr.fee').each(function() {
            var text = $(this).text().toLowerCase();
            if (text.indexOf('bogo') !== -1 || text.indexOf('discount') !== -1) {
                $(this).css('opacity', 0).animate({opacity: 1}, 300);
            }
        });
    });

    // ── System 6: Price Sensitivity signals ──────────────────────────────────

    // ── System 6: Price Sensitivity Detection — signal recording ─────────────
    // Records behavioral signals to WC session via AJAX.
    // Server-side class-gt-bogo-price-sensitivity.php processes and applies bonus.
    function recordSensitivity(signal) {
        if (typeof gtBogoCart === 'undefined' || !gtBogoCart.ajaxUrl) return;
        fetch(gtBogoCart.ajaxUrl, {
            method: 'POST',
            headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
            body: 'action=gt_bogo_record_sensitivity&nonce=' + encodeURIComponent(gtBogoCart.nonce) + '&signal=' + signal
        }).catch(function() {});
    }

    // Signal: item removed from Blocks cart
    document.addEventListener('click', function(e) {
        var btn = e.target.closest('.wc-block-cart-item__remove-link, .wc-block-components-cart-line-items-button-remove');
        if (btn) recordSensitivity('remove');
    });

    // Signal: item removed from classic cart
    $(document).on('click', '.remove', function() {
        recordSensitivity('remove');
    });

    // Idle detection handled by standalone IIFE (idle_5min/idle_10min signals)
    // Duplicate interval-based implementation removed — D5 fix

    // ── Init ─────────────────────────────────────────────────────────────────
    $(function() {
        if (isBlocks) attachBlocksQtyWatcher();
    });

    // Re-attach after Blocks re-renders DOM
    new MutationObserver(function() {
        if (isBlocks) attachBlocksQtyWatcher();
    }).observe(document.body, { childList: true, subtree: true });

})(jQuery);

// ── Scroll depth + return visit sensitivity signals ───────────────────────────
(function() {
    if (typeof gtBogoCart === 'undefined' || !gtBogoCart.ajaxUrl) return;

    var scrollTotalsCount = 0;
    var idleTimer = null;
    var idleFired5 = false;
    var idleFired10 = false;
    var checkoutVisited = sessionStorage.getItem('gtbogo_checkout_visited') === '1';

    function sendSignal(type) {
        fetch(gtBogoCart.ajaxUrl, {
            method: 'POST',
            headers: {'Content-Type': 'application/x-www-form-urlencoded'},
            body: new URLSearchParams({
                action: 'gt_bogo_record_sensitivity',
                nonce: gtBogoCart.nonce,
                signal: type
            })
        });
    }

    // Track if customer came from checkout back to cart
    if (checkoutVisited) {
        sendSignal('checkout_return');
        sessionStorage.removeItem('gtbogo_checkout_visited');
    }

    // Scroll depth — detect scrolling to totals section
    function onScroll() {
        var totals = document.querySelector('.wc-block-cart__totals, .cart_totals, .wc-block-components-totals-wrapper');
        if (!totals) return;
        var rect = totals.getBoundingClientRect();
        if (rect.top < window.innerHeight) {
            scrollTotalsCount++;
            if (scrollTotalsCount === 3) {
                sendSignal('scroll_totals');
            }
        }
    }

    // Idle detection
    function resetIdle() {
        clearTimeout(idleTimer);
        idleTimer = setTimeout(function() {
            if (!idleFired5) {
                idleFired5 = true;
                sendSignal('idle_5min');
                idleTimer = setTimeout(function() {
                    if (!idleFired10) {
                        idleFired10 = true;
                        sendSignal('idle_10min');
                    }
                }, 5 * 60 * 1000);
            }
        }, 5 * 60 * 1000);
    }

    // Quantity decrease detection
    document.addEventListener('change', function(e) {
        var input = e.target;
        if (input && input.type === 'number') {
            var prev = parseInt(input.dataset.prevVal || input.defaultValue || 1);
            var curr = parseInt(input.value);
            if (curr < prev) sendSignal('qty_decrease');
            input.dataset.prevVal = curr;
        }
    });

    // Attach listeners
    window.addEventListener('scroll', onScroll, {passive: true});
    ['mousemove','keydown','touchstart','click'].forEach(function(ev) {
        document.addEventListener(ev, resetIdle, {passive: true});
    });
    resetIdle();
})();
