/**
 * GT BOGO Engine — Intent Beacon v1.0
 *
 * Lightweight behavioral signal tracker. Tracks purchase intent signals
 * and sends them to the PHP Intent Engine via AJAX.
 *
 * Design principles:
 *  - No cookies, no localStorage, no PII collection
 *  - Session-scoped only — data lives in WC session server-side
 *  - Debounced AJAX — max 1 request per beacon interval (default 30s)
 *  - Gracefully degrades if AJAX fails
 *  - < 4KB minified
 *
 * Signal types tracked:
 *  dwell_time_60s      Product page open > 60 seconds
 *  dwell_time_120s     Product page open > 120 seconds
 *  price_hover_3s      Mouse over price element > 3 seconds
 *  variant_change      Changed size/color/attribute
 *  variant_change_3plus Changed variant 3+ times
 *  scroll_depth_80     Scrolled > 80% of product page
 *  gallery_depth_3     Clicked through 3+ product images
 *  review_scroll_30s   Spent > 30s reading reviews section
 *  shipping_page_visit Viewed shipping/returns page
 *  exit_prediction     Mouse moving toward address bar / navigation
 *  comparison_browse   (Set server-side from page sequence)
 *
 * @package GT_BOGO_Engine
 * @since   3.19.0
 */
( function() {
    'use strict';

    if ( typeof gtBogoIntent === 'undefined' ) return;

    var cfg        = gtBogoIntent;
    var signals    = [];
    var flushTimer = null;
    var sent       = {};

    /* ─────────────────────────────────────────────────────────────
     * SIGNAL QUEUE
     * ───────────────────────────────────────────────────────────── */

    /**
     * Add a signal to the queue. Deduplicates within the flush window.
     *
     * @param {string} type      Signal type key
     * @param {number} value     Signal strength 0–1
     * @param {number} productId Product ID (0 if not product page)
     */
    function addSignal( type, value, productId ) {
        var key = type + '_' + ( productId || cfg.productId || 0 );
        if ( sent[ key ] ) return; // Already sent this signal type for this product

        // Deduplicate within current batch
        for ( var i = 0; i < signals.length; i++ ) {
            if ( signals[ i ].type === type ) return;
        }

        signals.push( {
            type:       type,
            value:      Math.min( 1, Math.max( 0, value || 1 ) ),
            product_id: productId || cfg.productId || 0
        } );

        scheduleFlush();
    }

    /* ─────────────────────────────────────────────────────────────
     * AJAX FLUSH
     * ───────────────────────────────────────────────────────────── */

    function scheduleFlush() {
        if ( flushTimer ) return;
        flushTimer = setTimeout( flush, 2000 ); // Batch within 2s
    }

    function flush() {
        flushTimer = null;
        if ( ! signals.length ) return;

        var batch = signals.slice();
        signals   = [];

        var page = cfg.isCart ? 'cart'
                 : cfg.isProduct ? 'product'
                 : 'other';

        var body = new FormData();
        body.append( 'action',      cfg.action );
        body.append( 'nonce',       cfg.nonce );
        body.append( 'page_type',   page );
        body.append( 'product_id',  cfg.productId || 0 );

        for ( var i = 0; i < batch.length; i++ ) {
            body.append( 'signals[' + i + '][type]',       batch[ i ].type );
            body.append( 'signals[' + i + '][value]',      batch[ i ].value );
            body.append( 'signals[' + i + '][product_id]', batch[ i ].product_id );
        }

        var xhr = new XMLHttpRequest();
        xhr.open( 'POST', cfg.ajaxUrl, true );
        xhr.onreadystatechange = function() {
            if ( xhr.readyState !== 4 ) return;
            if ( xhr.status !== 200 ) return;

            try {
                var response = JSON.parse( xhr.responseText );
                if ( response.success && response.data ) {
                    handleResponse( response.data );
                }
            } catch ( e ) { /* silent fail */ }
        };
        xhr.send( body );

        // Mark signals as sent
        for ( var j = 0; j < batch.length; j++ ) {
            sent[ batch[ j ].type + '_' + batch[ j ].product_id ] = true;
        }
    }

    /**
     * Handle server response — if trigger returned, show deal reveal.
     */
    function handleResponse( data ) {
        if ( data.trigger && data.trigger.display_type ) {
            showDealReveal( data.trigger );
        }
        // Emit custom event for other scripts to listen to
        if ( window.CustomEvent ) {
            window.dispatchEvent( new CustomEvent( 'gtBogoIntentUpdate', {
                detail: { score: data.score, hot: data.hot, trigger: data.trigger }
            } ) );
        }
    }

    /* ─────────────────────────────────────────────────────────────
     * DEAL REVEAL DISPLAY
     * ───────────────────────────────────────────────────────────── */

    /**
     * Show the deal reveal UI based on trigger payload from server.
     * The actual deal content (discount, product) comes from server.
     * This function only handles display.
     */
    function showDealReveal( trigger ) {
        if ( ! trigger || ! trigger.copy || ! trigger.deal ) return;

        // Check if Superpower system will handle this (preferred)
        if ( window.gtBogoSuperpowers && window.gtBogoSuperpowers.showTrigger ) {
            window.gtBogoSuperpowers.showTrigger( trigger );
            return;
        }

        // Fallback: lightweight native reveal
        var displayType = trigger.display_type || 'toast';
        var copy        = trigger.copy;
        var deal        = trigger.deal;

        var el = document.createElement( 'div' );
        el.id        = 'gtbogo-intent-reveal';
        el.className = 'gtbogo-reveal gtbogo-reveal--' + displayType;
        el.setAttribute( 'role', 'dialog' );
        el.setAttribute( 'aria-modal', 'false' );
        el.setAttribute( 'aria-live', 'polite' );

        el.innerHTML =
            '<div class="gtbogo-reveal__inner">' +
                '<button class="gtbogo-reveal__close" aria-label="Close">&times;</button>' +
                '<div class="gtbogo-reveal__badge">' + escHtml( deal.label || '' ) + '</div>' +
                '<h3 class="gtbogo-reveal__headline">' + escHtml( copy.headline || '' ) + '</h3>' +
                '<p class="gtbogo-reveal__body">' + escHtml( copy.body || '' ) + '</p>' +
                '<button class="gtbogo-reveal__cta button" data-action="claim">' + escHtml( copy.cta || 'View deal' ) + '</button>' +
            '</div>';

        // Position based on display type
        var style = el.style;
        style.position   = displayType === 'modal' ? 'fixed' : 'fixed';
        style.zIndex     = '999999';
        style.bottom     = displayType === 'sticky_bar' ? '0'    : '24px';
        style.right      = displayType === 'toast'      ? '24px' : 'auto';
        style.left       = displayType === 'modal'      ? '50%'  : ( displayType === 'sticky_bar' ? '0' : 'auto' );
        style.transform  = displayType === 'modal'      ? 'translateX(-50%) translateY(-50%)' : 'none';
        style.top        = displayType === 'modal'      ? '50%'  : 'auto';

        document.body.appendChild( el );

        // Animate in
        requestAnimationFrame( function() {
            el.style.opacity   = '0';
            el.style.transform = ( style.transform || '' ) + ' translateY(8px)';
            requestAnimationFrame( function() {
                el.style.transition = 'opacity 0.25s ease, transform 0.25s ease';
                el.style.opacity    = '1';
                el.style.transform  = ( displayType === 'modal' ? 'translateX(-50%) translateY(-50%)' : '' );
            } );
        } );

        // Auto-dismiss
        var dismissMs = ( trigger.auto_dismiss || 12 ) * 1000;
        var dismissTimer = setTimeout( function() { dismissReveal( el ); }, dismissMs );

        // Close button
        var closeBtn = el.querySelector( '.gtbogo-reveal__close' );
        if ( closeBtn ) {
            closeBtn.addEventListener( 'click', function() {
                clearTimeout( dismissTimer );
                dismissReveal( el );
            } );
        }

        // CTA button
        var ctaBtn = el.querySelector( '.gtbogo-reveal__cta' );
        if ( ctaBtn ) {
            ctaBtn.addEventListener( 'click', function() {
                clearTimeout( dismissTimer );
                dismissReveal( el );
                // Trigger deal application via AJAX
                if ( window.location.href.indexOf( 'cart' ) === -1 ) {
                    window.location.href = '/?add-to-cart=' + ( trigger.product_id || 0 ) + '&gtbogo_trigger=' + trigger.trigger;
                }
            } );
        }
    }

    function dismissReveal( el ) {
        if ( ! el || ! el.parentNode ) return;
        el.style.opacity   = '0';
        el.style.transform = 'translateY(8px)';
        setTimeout( function() {
            if ( el.parentNode ) el.parentNode.removeChild( el );
        }, 300 );
    }

    function escHtml( str ) {
        var d = document.createElement( 'div' );
        d.appendChild( document.createTextNode( str ) );
        return d.innerHTML;
    }

    /* ─────────────────────────────────────────────────────────────
     * DWELL TIME TRACKING
     * ───────────────────────────────────────────────────────────── */

    if ( cfg.isProduct ) {
        var dwellStart    = Date.now();
        var dwell60Sent   = false;
        var dwell120Sent  = false;

        var dwellInterval = setInterval( function() {
            var elapsed = ( Date.now() - dwellStart ) / 1000;
            if ( ! dwell60Sent && elapsed >= cfg.thresholds.dwell_60 ) {
                addSignal( 'dwell_time_60s', 1.0 );
                dwell60Sent = true;
            }
            if ( ! dwell120Sent && elapsed >= cfg.thresholds.dwell_120 ) {
                addSignal( 'dwell_time_120s', 1.0 );
                dwell120Sent = true;
                clearInterval( dwellInterval );
            }
        }, 5000 );

        window.addEventListener( 'beforeunload', function() {
            clearInterval( dwellInterval );
        } );
    }

    /* ─────────────────────────────────────────────────────────────
     * PRICE ELEMENT HOVER
     * ───────────────────────────────────────────────────────────── */

    var priceHoverStart = 0;
    var priceHoverTimer = null;

    function onPriceEnter() {
        priceHoverStart = Date.now();
        priceHoverTimer = setTimeout( function() {
            addSignal( 'price_hover_3s', 1.0 );
        }, cfg.thresholds.hover_3s );
    }

    function onPriceLeave() {
        if ( priceHoverTimer ) {
            clearTimeout( priceHoverTimer );
            priceHoverTimer = null;
        }
    }

    var priceSelectors = [
        '.price', '.woocommerce-Price-amount', '.product-price',
        'ins .amount', '.price .amount', '[data-product-price]'
    ];
    priceSelectors.forEach( function( sel ) {
        document.querySelectorAll( sel ).forEach( function( el ) {
            el.addEventListener( 'mouseenter', onPriceEnter );
            el.addEventListener( 'mouseleave', onPriceLeave );
        } );
    } );

    /* ─────────────────────────────────────────────────────────────
     * VARIANT / ATTRIBUTE CHANGES
     * ───────────────────────────────────────────────────────────── */

    var variantChangeCount = 0;

    function onVariantChange() {
        variantChangeCount++;
        addSignal( 'variant_change', Math.min( 1.0, variantChangeCount * 0.3 ) );
        if ( variantChangeCount >= 3 ) {
            addSignal( 'variant_change_3plus', 1.0 );
        }
    }

    document.querySelectorAll(
        'select[name^="attribute_"], input[name^="attribute_"], .variation-selector'
    ).forEach( function( el ) {
        el.addEventListener( 'change', onVariantChange );
    } );

    /* ─────────────────────────────────────────────────────────────
     * SCROLL DEPTH
     * ───────────────────────────────────────────────────────────── */

    if ( cfg.isProduct ) {
        var scroll80Sent = false;

        window.addEventListener( 'scroll', function() {
            if ( scroll80Sent ) return;
            var scrolled = window.scrollY + window.innerHeight;
            var total    = document.documentElement.scrollHeight;
            if ( scrolled / total >= 0.80 ) {
                addSignal( 'scroll_depth_80', 1.0 );
                scroll80Sent = true;
            }
        }, { passive: true } );
    }

    /* ─────────────────────────────────────────────────────────────
     * IMAGE GALLERY DEPTH
     * ───────────────────────────────────────────────────────────── */

    var galleryClickCount = 0;
    var gallery3Sent      = false;

    function onGalleryClick() {
        galleryClickCount++;
        if ( ! gallery3Sent && galleryClickCount >= 3 ) {
            addSignal( 'gallery_depth_3', 1.0 );
            gallery3Sent = true;
        }
    }

    document.querySelectorAll(
        '.woocommerce-product-gallery__image, .flex-control-thumbs li, .product-gallery-image, [data-thumb]'
    ).forEach( function( el ) {
        el.addEventListener( 'click', onGalleryClick );
    } );

    /* ─────────────────────────────────────────────────────────────
     * REVIEW SECTION DWELL
     * ───────────────────────────────────────────────────────────── */

    var reviewSection = document.querySelector( '#reviews, #tab-reviews, .woocommerce-Reviews, [data-tab="reviews"]' );
    if ( reviewSection ) {
        var reviewEnterTs    = 0;
        var review30sSent    = false;
        var reviewObserver   = new IntersectionObserver( function( entries ) {
            entries.forEach( function( entry ) {
                if ( entry.isIntersecting && ! review30sSent ) {
                    reviewEnterTs = Date.now();
                    var reviewTimer = setTimeout( function() {
                        addSignal( 'review_scroll_30s', 1.0 );
                        review30sSent = true;
                    }, cfg.thresholds.review_30s );
                    reviewSection._reviewTimer = reviewTimer;
                } else if ( ! entry.isIntersecting && reviewSection._reviewTimer ) {
                    clearTimeout( reviewSection._reviewTimer );
                }
            } );
        }, { threshold: 0.3 } );
        reviewObserver.observe( reviewSection );
    }

    /* ─────────────────────────────────────────────────────────────
     * EXIT PREDICTION
     * ───────────────────────────────────────────────────────────── */

    var exitPredictSent = false;
    var navHeight       = 80;

    document.addEventListener( 'mousemove', function( e ) {
        if ( exitPredictSent ) return;
        if ( e.clientY <= navHeight && e.clientY > 0 ) {
            // Mouse near top of viewport = moving toward address bar or back button
            addSignal( 'exit_prediction', 1.0 );
            exitPredictSent = true;
        }
    } );

    /* ─────────────────────────────────────────────────────────────
     * PERIODIC FLUSH
     * ───────────────────────────────────────────────────────────── */

    // Periodic heartbeat even without new signals (for score recomputation)
    setInterval( function() {
        if ( signals.length > 0 ) flush();
    }, cfg.beaconInterval || 30000 );

    // Flush on page unload
    window.addEventListener( 'beforeunload', function() {
        if ( signals.length > 0 ) flush();
    } );

} )();
