/**
 * GT BOGO Engine — Loyalty Progress Bar (Enterprise)
 *
 * Features:
 *   - VIP milestone progress bar with step dots and animated fill
 *   - Cadence insight: "You typically shop every N days"
 *   - Days since last order display
 *   - VIP benefits expandable tooltip
 *   - Stage-aware copy (new / returning / loyal / at-risk)
 *   - Next milestone description
 *   - ARIA progressbar with live region updates
 *   - CSS token system — zero hardcoded values
 *   - Reduced motion compliant
 *   - Fires on cart, account, and order-received pages
 *
 * @since 3.18.6
 */
( function() {
    'use strict';

    var cfg = window.gtBogoLoyalty || {};
    if ( cfg.orderCount === undefined && cfg.orderCount !== 0 ) return;

    var orderCount  = parseInt( cfg.orderCount,   10 ) || 0;
    var threshold   = parseInt( cfg.vipThreshold, 10 ) || 4;
    var remaining   = parseInt( cfg.remaining,    10 ) || Math.max( 0, threshold - orderCount );
    var stage       = cfg.stage       || 'new';
    var isVip       = cfg.isVip === '1';
    var daysSince   = parseInt( cfg.daysSinceLast, 10 ) || 0;
    var avgCadence  = parseInt( cfg.avgCadence,    10 ) || 0;
    var benefits    = Array.isArray( cfg.vipBenefits ) ? cfg.vipBenefits : [];
    var i18n        = cfg.i18n || {};
    var stageCopy   = cfg.stageCopy   || '';
    var nextMile    = cfg.nextMilestone || '';

    if ( isVip ) return; // Already VIP — no bar needed

    var pct = Math.min( 100, Math.round( ( orderCount / threshold ) * 100 ) );

    // ── Build the bar ────────────────────────────────────────────────────────
    function buildBar() {
        var wrap = document.createElement( 'div' );
        wrap.className = 'gtbogo-loyalty-progress';
        wrap.setAttribute( 'role', 'region' );
        wrap.setAttribute( 'aria-label', i18n.vip_title || 'VIP Membership Progress' );

        // Stage copy / greeting
        if ( stageCopy ) {
            var greet = document.createElement( 'p' );
            greet.className = 'gtbogo-loyalty-progress__stage';
            greet.textContent = stageCopy;
            wrap.appendChild( greet );
        }

        // Main progress label
        var label = document.createElement( 'p' );
        label.className = 'gtbogo-loyalty-progress__label';
        label.setAttribute( 'aria-live', 'polite' );

        if ( remaining === 0 ) {
            label.textContent = i18n.vip_unlocked || 'You have reached VIP status.';
        } else if ( remaining === 1 ) {
            label.textContent = i18n.one_away || 'One more order unlocks your VIP membership.';
        } else {
            var tmpl = i18n.n_away || '{n} more orders until VIP.';
            label.textContent = tmpl.replace( '{n}', String( remaining ) );
        }
        wrap.appendChild( label );

        // Progress track
        var track = document.createElement( 'div' );
        track.className = 'gtbogo-loyalty-progress__track';
        track.setAttribute( 'role', 'progressbar' );
        track.setAttribute( 'aria-valuenow', String( pct ) );
        track.setAttribute( 'aria-valuemin', '0' );
        track.setAttribute( 'aria-valuemax', '100' );

        var fill = document.createElement( 'div' );
        fill.className = 'gtbogo-loyalty-progress__fill';
        fill.style.width = '0%';
        track.appendChild( fill );
        wrap.appendChild( track );

        // Step dots
        var steps = document.createElement( 'div' );
        steps.className = 'gtbogo-loyalty-progress__steps';
        steps.setAttribute( 'aria-hidden', 'true' );
        for ( var i = 1; i <= threshold; i++ ) {
            var dot = document.createElement( 'span' );
            var isDone = i <= orderCount;
            var isNext = i === orderCount + 1;
            dot.className = 'gtbogo-loyalty-progress__step' +
                ( isDone ? ' is-done' : '' ) +
                ( isNext ? ' is-next' : '' );
            dot.setAttribute( 'title', isDone ? 'Completed' : ( isNext ? 'Your next milestone' : 'Locked' ) );
            steps.appendChild( dot );
        }
        wrap.appendChild( steps );

        // Step labels
        var stepLabels = document.createElement( 'div' );
        stepLabels.className = 'gtbogo-loyalty-progress__step-labels';
        stepLabels.setAttribute( 'aria-hidden', 'true' );
        for ( var j = 1; j <= threshold; j++ ) {
            var sl = document.createElement( 'span' );
            sl.className = 'gtbogo-loyalty-progress__step-label';
            sl.textContent = j === threshold ? 'VIP' : String( j );
            stepLabels.appendChild( sl );
        }
        wrap.appendChild( stepLabels );

        // Cadence insight
        if ( avgCadence > 0 && i18n.cadence ) {
            var cadenceEl = document.createElement( 'p' );
            cadenceEl.className = 'gtbogo-loyalty-progress__cadence';
            cadenceEl.textContent = i18n.cadence;
            wrap.appendChild( cadenceEl );
        } else if ( daysSince > 0 && avgCadence > 0 ) {
            var daysEl = document.createElement( 'p' );
            daysEl.className = 'gtbogo-loyalty-progress__cadence';
            daysEl.textContent = 'It has been ' + daysSince + ' day(s) since your last order.';
            wrap.appendChild( daysEl );
        }

        // Next milestone
        if ( nextMile ) {
            var mileEl = document.createElement( 'p' );
            mileEl.className = 'gtbogo-loyalty-progress__milestone';
            mileEl.textContent = nextMile;
            wrap.appendChild( mileEl );
        }

        // VIP benefits expandable section
        if ( benefits.length > 0 ) {
            var benefitsWrap = document.createElement( 'div' );
            benefitsWrap.className = 'gtbogo-loyalty-progress__benefits';

            var benefitsToggle = document.createElement( 'button' );
            benefitsToggle.className = 'gtbogo-loyalty-progress__benefits-toggle';
            benefitsToggle.textContent = ( i18n.benefits || 'VIP includes:' ) + ' ▸';
            benefitsToggle.setAttribute( 'aria-expanded', 'false' );

            var benefitsList = document.createElement( 'ul' );
            benefitsList.className = 'gtbogo-loyalty-progress__benefits-list';
            benefitsList.style.display = 'none';
            benefits.forEach( function( b ) {
                var li = document.createElement( 'li' );
                li.textContent = b;
                benefitsList.appendChild( li );
            } );

            benefitsToggle.addEventListener( 'click', function() {
                var expanded = benefitsList.style.display !== 'none';
                benefitsList.style.display = expanded ? 'none' : 'block';
                benefitsToggle.textContent = ( i18n.benefits || 'VIP includes:' ) + ( expanded ? ' ▸' : ' ▾' );
                benefitsToggle.setAttribute( 'aria-expanded', expanded ? 'false' : 'true' );
            } );

            benefitsWrap.appendChild( benefitsToggle );
            benefitsWrap.appendChild( benefitsList );
            wrap.appendChild( benefitsWrap );
        }

        return { wrap: wrap, fill: fill };
    }

    // ── Inject ───────────────────────────────────────────────────────────────
    function inject() {
        var targets = [
            '.woocommerce-cart-form',
            '.cart-collaterals',
            '.woocommerce-MyAccount-content',
            '.woocommerce-order-received',
            '.wc-block-cart',
            '.entry-content form.woocommerce-cart-form',
        ];
        var anchor = null;
        for ( var i = 0; i < targets.length; i++ ) {
            anchor = document.querySelector( targets[i] );
            if ( anchor ) break;
        }
        if ( ! anchor ) return;

        var built = buildBar();
        anchor.parentNode.insertBefore( built.wrap, anchor );

        // Animate fill
        requestAnimationFrame( function() {
            requestAnimationFrame( function() {
                built.fill.style.transition = 'width 700ms cubic-bezier(0.4,0,0.2,1)';
                built.fill.style.width = pct + '%';
            } );
        } );
    }

    // ── Inline styles (CSS token system) ────────────────────────────────────
    function injectStyles() {
        if ( document.getElementById( 'gtbogo-loyalty-progress-styles' ) ) return;
        var s = document.createElement( 'style' );
        s.id = 'gtbogo-loyalty-progress-styles';
        s.textContent = [
            '.gtbogo-loyalty-progress{margin:0 0 var(--gtbogo-sp-gap,20px);font-family:inherit}',
            '.gtbogo-loyalty-progress__stage{font-size:var(--gtbogo-sp-fs-base,0.8em);color:var(--gtbogo-sp-accent,inherit);opacity:0.9;margin:0 0 4px;font-weight:var(--gtbogo-sp-fw-ui,600);letter-spacing:var(--gtbogo-sp-tracking,0.03em)}',
            '.gtbogo-loyalty-progress__label{font-size:var(--gtbogo-sp-fs-base,0.87em);opacity:var(--gtbogo-sp-opacity-secondary,0.72);margin:0 0 var(--gtbogo-sp-gap,8px);line-height:var(--gtbogo-sp-lh-ui,1.5)}',
            '.gtbogo-loyalty-progress__track{height:var(--gtbogo-sp-bar-h,6px);background:var(--gtbogo-sp-accent-tint,rgba(0,0,0,0.08));border-radius:var(--gtbogo-sp-radius,4px);overflow:hidden;margin-bottom:var(--gtbogo-sp-gap,8px)}',
            '.gtbogo-loyalty-progress__fill{height:100%;border-radius:inherit;background:var(--gtbogo-sp-accent,currentColor);width:0%}',
            '.gtbogo-loyalty-progress__steps{display:flex;justify-content:space-between;margin-bottom:4px}',
            '.gtbogo-loyalty-progress__step{width:var(--gtbogo-sp-touch-target,10px);height:var(--gtbogo-sp-touch-target,10px);max-width:10px;max-height:10px;border-radius:50%;background:var(--gtbogo-sp-accent-tint,rgba(0,0,0,0.1));border:var(--gtbogo-sp-border-w,1px) solid var(--gtbogo-sp-accent-border,currentColor);transition:background var(--gtbogo-sp-duration-subtle,300ms) ease;cursor:default}',
            '.gtbogo-loyalty-progress__step.is-done{background:var(--gtbogo-sp-accent,currentColor)}',
            '.gtbogo-loyalty-progress__step.is-next{box-shadow:0 0 0 2px var(--gtbogo-sp-accent,currentColor);animation:gtbogo-lp-pulse 2s ease infinite}',
            '.gtbogo-loyalty-progress__step-labels{display:flex;justify-content:space-between;margin-bottom:var(--gtbogo-sp-gap,8px)}',
            '.gtbogo-loyalty-progress__step-label{font-size:0.65em;opacity:0.55;text-align:center}',
            '.gtbogo-loyalty-progress__cadence{font-size:var(--gtbogo-sp-fs-base,0.78em);opacity:var(--gtbogo-sp-opacity-secondary,0.6);margin:var(--gtbogo-sp-gap,4px) 0 0;font-style:italic;line-height:1.4}',
            '.gtbogo-loyalty-progress__milestone{font-size:var(--gtbogo-sp-fs-base,0.82em);font-weight:var(--gtbogo-sp-fw-ui,600);color:var(--gtbogo-sp-accent,inherit);margin:var(--gtbogo-sp-gap,6px) 0 0}',
            '.gtbogo-loyalty-progress__benefits{margin-top:var(--gtbogo-sp-gap,10px)}',
            '.gtbogo-loyalty-progress__benefits-toggle{background:none;border:none;font-size:var(--gtbogo-sp-fs-base,0.8em);color:var(--gtbogo-sp-accent,inherit);cursor:pointer;padding:0;font-family:inherit;opacity:0.8;text-decoration:underline}',
            '.gtbogo-loyalty-progress__benefits-toggle:hover{opacity:1}',
            '.gtbogo-loyalty-progress__benefits-list{margin:var(--gtbogo-sp-gap,6px) 0 0;padding:0 0 0 var(--gtbogo-sp-gap,16px);font-size:var(--gtbogo-sp-fs-base,0.8em);opacity:var(--gtbogo-sp-opacity-secondary,0.72);line-height:1.8}',
            '@keyframes gtbogo-lp-pulse{0%,100%{box-shadow:0 0 0 2px var(--gtbogo-sp-accent,currentColor)}50%{box-shadow:0 0 0 4px rgba(0,0,0,0)}}',
            '@media(prefers-reduced-motion:reduce){.gtbogo-loyalty-progress__fill{transition:none!important}.gtbogo-loyalty-progress__step.is-next{animation:none!important}}',
        ].join('');
        document.head.appendChild( s );
    }

    // ── Init ─────────────────────────────────────────────────────────────────
    if ( document.readyState === 'loading' ) {
        document.addEventListener( 'DOMContentLoaded', function() { injectStyles(); inject(); } );
    } else {
        injectStyles(); inject();
    }

}() );
