/**
 * WooLentor – Free Shipping Bar Pro
 *
 * Extends the free-bar JS (wlFSB) with:
 *  – Countdown timer
 *  – A/B variant message application
 *  – Analytics impression / conversion tracking
 *  – Cart drawer / mini-cart real-time updates
 */
( function () {
    'use strict';

    var cfg = window.wlFSB || {};

    // Only run if the free bar is present and configured
    if ( ! cfg || ! cfg.threshold || parseFloat( cfg.threshold ) <= 0 ) {
        return;
    }

    var bar = document.getElementById( 'wl-free-shipping-bar' );
    if ( ! bar ) return;

    // -------------------------------------------------------------------------
    // Helpers
    // -------------------------------------------------------------------------

    function pad( n ) {
        return String( n ).padStart( 2, '0' );
    }

    function post( action, data, nonce ) {
        var xhr   = new XMLHttpRequest();
        var body  = 'action=' + encodeURIComponent( action ) + '&nonce=' + encodeURIComponent( nonce );
        for ( var k in data ) {
            if ( Object.prototype.hasOwnProperty.call( data, k ) ) {
                body += '&' + encodeURIComponent( k ) + '=' + encodeURIComponent( data[ k ] );
            }
        }
        xhr.open( 'POST', cfg.ajaxUrl, true );
        xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
        xhr.send( body );
    }

    // -------------------------------------------------------------------------
    // A/B Testing – message is already baked into cfg.msgInitial by PHP,
    // but we also record the variant assignment via analytics.
    // -------------------------------------------------------------------------

    var abVariant = cfg.abVariant || '';   // 'a' | 'b' | ''

    // -------------------------------------------------------------------------
    // Analytics – impression / conversion tracking (session-deduplicated)
    // -------------------------------------------------------------------------

    // In-memory guard: prevents duplicate calls within a single page lifetime.
    var analyticsTracked = { impression: false, conversion: false };

    // sessionStorage keys — scoped to the bar ID so multi-bar setups are safe.
    var barId      = cfg.barId || 'default';
    var SK_IMP     = 'wl_fsb_imp_'  + barId;   // impression tracked this session
    var SK_CONV    = 'wl_fsb_conv_' + barId;   // conversion tracked this session

    function sessionGet( key ) {
        try { return sessionStorage.getItem( key ); } catch ( e ) { return null; }
    }
    function sessionSet( key ) {
        try { sessionStorage.setItem( key, '1' ); } catch ( e ) { /* silent */ }
    }

    function trackEvent( type ) {
        if ( ! cfg.analyticsEnabled || ! cfg.analyticsNonce ) return;

        // In-page guard (e.g. cart-change fires conversion multiple times)
        if ( analyticsTracked[ type ] ) return;

        // Session guard: skip if already tracked in this browser tab session.
        // This prevents page refreshes from inflating counts.
        var sessionKey = type === 'impression' ? SK_IMP : SK_CONV;
        if ( sessionGet( sessionKey ) === '1' ) {
            analyticsTracked[ type ] = true; // sync the in-memory flag
            return;
        }

        analyticsTracked[ type ] = true;
        sessionSet( sessionKey );

        post( 'woolentor_fsb_track', {
            event_type : type,
            bar_id     : barId,
            variant    : abVariant,
        }, cfg.analyticsNonce );
    }

    // Track impression once the bar is visible
    function onBarVisible() {
        trackEvent( 'impression' );
    }

    // Track conversion when cart reaches threshold
    function onConversion() {
        trackEvent( 'conversion' );
    }

    // -------------------------------------------------------------------------
    // Countdown Timer
    // -------------------------------------------------------------------------

    var countdownEl   = bar.querySelector( '.wl-fsb-countdown' );
    var countdownTimer = null;

    function formatCountdown( ms ) {
        if ( ms <= 0 ) return '00:00:00';

        var totalSeconds = Math.floor( ms / 1000 );
        var days         = Math.floor( totalSeconds / 86400 );
        var hours        = Math.floor( ( totalSeconds % 86400 ) / 3600 );
        var minutes      = Math.floor( ( totalSeconds % 3600 ) / 60 );
        var seconds      = totalSeconds % 60;

        if ( days > 0 ) {
            return days + 'd ' + pad( hours ) + ':' + pad( minutes ) + ':' + pad( seconds );
        }
        return pad( hours ) + ':' + pad( minutes ) + ':' + pad( seconds );
    }

    function startCountdown() {
        if ( ! cfg.countdownEnabled || ! cfg.countdownEnd || ! countdownEl ) {
            return;
        }

        var template = cfg.countdownMsg || 'Offer ends in {timer}!';

        function tick() {
            var remaining = cfg.countdownEnd - Date.now();

            if ( remaining <= 0 ) {
                countdownEl.style.display = 'none';
                clearInterval( countdownTimer );
                return;
            }

            var timerStr = '<span class="wl-fsb-timer">' + formatCountdown( remaining ) + '</span>';
            countdownEl.innerHTML = template.replace( '{timer}', timerStr );
            countdownEl.style.display = '';
        }

        tick();
        countdownTimer = setInterval( tick, 1000 );
    }

    // -------------------------------------------------------------------------
    // Cart Drawer updates
    // -------------------------------------------------------------------------

    var drawerBars = document.querySelectorAll( '.wl-fsb-drawer-wrap' );

    function updateDrawerBars( cartTotal ) {
        if ( ! drawerBars.length ) return;

        var threshold = parseFloat( cfg.threshold );
        var total     = parseFloat( cartTotal ) || 0;
        var remaining = Math.max( 0, threshold - total );
        var pct       = Math.min( 100, ( total / threshold ) * 100 );

        for ( var i = 0; i < drawerBars.length; i++ ) {
            var drawerBar  = drawerBars[ i ];
            var msgEl      = drawerBar.querySelector( '.wl-fsb-drawer-message' );
            var fillEl     = drawerBar.querySelector( '.wl-fsb-progress-fill' );

            if ( msgEl ) {
                if ( remaining === 0 ) {
                    msgEl.textContent = cfg.msgSuccess || '';
                } else {
                    var template = cfg.msgInitial || '';
                    // Simple price format for drawer (uses free bar's formatPrice if available)
                    var amountStr = remaining.toFixed( 2 );
                    msgEl.textContent = template.replace( '{amount}', ( cfg.currencySymbol || '' ) + amountStr );
                }
            }
            if ( fillEl ) {
                fillEl.style.width = pct.toFixed( 2 ) + '%';
            }
        }
    }

    // -------------------------------------------------------------------------
    // Hook into free bar's cart-change event to update drawer + track conversions
    // -------------------------------------------------------------------------

    document.addEventListener( 'wl_fsb_cart_changed', function () {
        // fetch fresh total (the free module already handles the main bar;
        // we need it here for the drawer and conversion check)
        var xhr = new XMLHttpRequest();
        xhr.open( 'POST', cfg.ajaxUrl, true );
        xhr.setRequestHeader( 'Content-Type', 'application/x-www-form-urlencoded' );
        xhr.onload = function () {
            if ( xhr.status === 200 ) {
                try {
                    var resp = JSON.parse( xhr.responseText );
                    if ( resp.success && resp.data && resp.data.cart_total !== undefined ) {
                        var total = parseFloat( resp.data.cart_total );
                        updateDrawerBars( total );

                        // Conversion: cart total reached or exceeded threshold
                        if ( total >= parseFloat( cfg.threshold ) ) {
                            onConversion();
                        }
                    }
                } catch ( e ) { /* silent */ }
            }
        };
        xhr.send( 'action=woolentor_fsb_cart_total&nonce=' + encodeURIComponent( cfg.nonce ) );
    } );

    // -------------------------------------------------------------------------
    // Observe bar visibility for impression tracking
    // -------------------------------------------------------------------------

    function watchBarVisibility() {
        if ( typeof IntersectionObserver === 'undefined' ) {
            // Fallback: track impression immediately
            onBarVisible();
            return;
        }

        var observer = new IntersectionObserver( function ( entries ) {
            entries.forEach( function ( entry ) {
                if ( entry.isIntersecting ) {
                    onBarVisible();
                    observer.disconnect();
                }
            } );
        }, { threshold: 0.5 } );

        observer.observe( bar );
    }

    // -------------------------------------------------------------------------
    // Initial conversion check (server-provided cart total)
    // -------------------------------------------------------------------------

    function initialConversionCheck() {
        var cartTotal = parseFloat( cfg.cartTotal ) || 0;
        // Only track conversion if bar is actually visible (not dismissed/hidden)
        if ( cartTotal >= parseFloat( cfg.threshold ) && ! bar.classList.contains( 'wl-fsb-hidden' ) ) {
            onConversion();
        }
        updateDrawerBars( cartTotal );
    }

    // -------------------------------------------------------------------------
    // Additional bar — apply skin class and color overrides to the bar DOM
    // -------------------------------------------------------------------------

    function applyBarOverride() {
        if ( cfg.barSkin !== undefined ) {
            // Remove any existing skin class then add the new one
            bar.className = bar.className.replace( /wl-fsb-skin-\S+/g, '' ).trim();
            if ( cfg.barSkin && cfg.barSkin !== 'default' ) {
                bar.classList.add( 'wl-fsb-skin-' + cfg.barSkin );
            }
        }

        if ( cfg.barBgColor ) {
            bar.style.backgroundColor = cfg.barBgColor;
        }

        if ( cfg.barTextColor ) {
            var msgEl = bar.querySelector( '.wl-fsb-message' );
            if ( msgEl ) msgEl.style.color = cfg.barTextColor;
        }

        if ( cfg.barFillColor ) {
            var fillEl = bar.querySelector( '.wl-fsb-progress-fill' );
            if ( fillEl ) fillEl.style.backgroundColor = cfg.barFillColor;
        }
    }

    // -------------------------------------------------------------------------
    // Init
    // -------------------------------------------------------------------------

    function init() {
        applyBarOverride();
        startCountdown();
        watchBarVisibility();
        initialConversionCheck();
    }

    if ( document.readyState === 'loading' ) {
        document.addEventListener( 'DOMContentLoaded', init );
    } else {
        init();
    }

} )();
