/**
 * 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;
    }

    // -------------------------------------------------------------------------
    // 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
    // -------------------------------------------------------------------------

    var abVariant = cfg.abVariant || '';

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

    var analyticsTracked = { impression: false, conversion: false };

    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, barId ) {
        if ( ! cfg.analyticsEnabled || ! cfg.analyticsNonce ) return;
        if ( analyticsTracked[ type ] ) return;

        var sessionKey = type === 'impression' ? 'wl_fsb_imp_' + barId : 'wl_fsb_conv_' + barId;
        if ( sessionGet( sessionKey ) === '1' ) {
            analyticsTracked[ type ] = true;
            return;
        }

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

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

    // -------------------------------------------------------------------------
    // Countdown Timer (per-bar)
    // -------------------------------------------------------------------------

    function startCountdown( bar ) {
        var countdownEl = bar.querySelector( '.wl-fsb-countdown' );
        if ( ! cfg.countdownEnabled || ! cfg.countdownEnd || ! countdownEl ) {
            return;
        }

        var template = cfg.countdownMsg || 'Offer ends in {timer}!';
        var timer = null;
        var end   = parseInt( cfg.countdownEnd, 10 );

        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 tick() {
            var remaining = end - Date.now();
            if ( remaining <= 0 ) {
                countdownEl.style.display = 'none';
                clearInterval( timer );
                return;
            }
            var timerStr = '<span class="wl-fsb-timer">' + formatCountdown( remaining ) + '</span>';
            countdownEl.innerHTML = template.replace( '{timer}', timerStr );
            countdownEl.style.display = '';
        }

        tick();
        timer = 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 || '';
                    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
    // -------------------------------------------------------------------------

    document.addEventListener( 'wl_fsb_cart_changed', function () {
        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 );
                        if ( total >= parseFloat( cfg.threshold ) ) {
                            // Conversion: fire for every visible bar
                            var allBars = document.querySelectorAll( '.wl-fsb-wrap' );
                            for ( var i = 0; i < allBars.length; i++ ) {
                                if ( ! allBars[ i ].classList.contains( 'wl-fsb-hidden' ) ) {
                                    var bid = allBars[ i ].dataset.barId || cfg.barId || 'default';
                                    trackEvent( 'conversion', bid );
                                }
                            }
                        }
                    }
                } catch ( e ) { /* silent */ }
            }
        };
        xhr.send( 'action=woolentor_fsb_cart_total&nonce=' + encodeURIComponent( cfg.nonce ) );
    } );

    // -------------------------------------------------------------------------
    // Observe bar visibility for impression tracking (per-bar)
    // -------------------------------------------------------------------------

    function watchBarVisibility( bar ) {
        var barId = bar.dataset.barId || cfg.barId || 'default';

        if ( typeof IntersectionObserver === 'undefined' ) {
            trackEvent( 'impression', barId );
            return;
        }

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

        observer.observe( bar );
    }

    // -------------------------------------------------------------------------
    // Initial conversion check (per-bar)
    // -------------------------------------------------------------------------

    function initialConversionCheck( bar ) {
        var cartTotal = parseFloat( cfg.cartTotal ) || 0;
        var barId     = bar.dataset.barId || cfg.barId || 'default';
        if ( cartTotal >= parseFloat( cfg.threshold ) && ! bar.classList.contains( 'wl-fsb-hidden' ) ) {
            trackEvent( 'conversion', barId );
        }
        updateDrawerBars( cartTotal );
    }

    // -------------------------------------------------------------------------
    // Additional bar — apply skin class and color overrides (per-bar)
    // -------------------------------------------------------------------------

    function applyBarOverride( bar ) {
        if ( cfg.barSkin !== undefined ) {
            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;
        }
    }

    // -------------------------------------------------------------------------
    // Per-bar init
    // -------------------------------------------------------------------------

    function initBar( bar ) {
        applyBarOverride( bar );
        startCountdown( bar );
        watchBarVisibility( bar );
        initialConversionCheck( bar );
    }

    // -------------------------------------------------------------------------
    // Bootstrap all bars
    // -------------------------------------------------------------------------

    function initAllBars() {
        var bars = document.querySelectorAll( '.wl-fsb-wrap' );
        for ( var i = 0; i < bars.length; i++ ) {
            initBar( bars[ i ] );
        }
    }

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

    // -------------------------------------------------------------------------
    // Elementor scoped handler
    // -------------------------------------------------------------------------

    var WoolentorFreeShippingBarProHandler = function ( $scope, $ ) {
        var bar = null;
        if( $scope?.detail?.uniqid && $scope?.detail?.uniqid.length !== 0 ) {
            var el = jQuery('.woolentorblock-'+$scope.detail.uniqid);
            bar = el.find( '.wl-fsb-wrap' )[0];
        }else{
            bar = $scope.find( '.wl-fsb-wrap' )[ 0 ];
        };
        if ( ! bar ) return;
        if ( ! cfg || ! cfg.threshold || parseFloat( cfg.threshold ) <= 0 ) return;
        initBar( bar );
    };

    jQuery( window ).on( 'elementor/frontend/init', function () {
        elementorFrontend.hooks.addAction( 'frontend/element_ready/woolentor_free_shipping_bar.default', WoolentorFreeShippingBarProHandler );
    } );

    // Gutenberg Editor mode
    document.addEventListener( "wooLentorFreeShippingBar", function (event) { WoolentorFreeShippingBarProHandler(event) }, false );

} )();
