/**
 * GT BOGO Engine — Deal Reveal UI
 * Reads pending trigger from session (localized via gtBogoDealReveal),
 * renders the appropriate UI (toast/modal/sticky/drawer),
 * tracks impressions and acceptance via AJAX.
 *
 * @since 3.18.5
 */
( function() {
    'use strict';

    var cfg = window.gtBogoDealReveal || {};
    if ( ! cfg.pendingDeal ) return;

    var deal;
    try { deal = JSON.parse( cfg.pendingDeal ); } catch(e) { return; }
    if ( ! deal || ! deal.display_type ) return;

    var backdrop = null;
    var panel    = null;
    var shown    = false;

    // ── Respect reduced motion ──────────────────────────────────────────────
    var prefersReduced = window.matchMedia &&
        window.matchMedia( '(prefers-reduced-motion: reduce)' ).matches;

    // ── Build UI ────────────────────────────────────────────────────────────
    function buildPanel() {
        // Backdrop (for modal only)
        if ( deal.display_type === 'modal' ) {
            backdrop = document.createElement( 'div' );
            backdrop.className = 'gtbogo-reveal-backdrop';
            backdrop.addEventListener( 'click', dismiss );
            document.body.appendChild( backdrop );
        }

        panel = document.createElement( 'div' );
        panel.className = 'gtbogo-reveal-panel gtbogo-reveal-' + deal.display_type;
        panel.setAttribute( 'role', 'dialog' );
        panel.setAttribute( 'aria-modal', 'true' );
        panel.setAttribute( 'aria-label', deal.copy && deal.copy.headline ? deal.copy.headline : 'Special offer' );

        // Dismiss button
        var dismissBtn = document.createElement( 'button' );
        dismissBtn.className = 'gtbogo-reveal-dismiss';
        dismissBtn.setAttribute( 'aria-label', 'Dismiss offer' );
        dismissBtn.textContent = '\u00D7'; // × close symbol via textContent (XSS-safe)
        dismissBtn.addEventListener( 'click', dismiss );
        panel.appendChild( dismissBtn );

        // Headline
        if ( deal.copy && deal.copy.headline ) {
            var h = document.createElement( 'p' );
            h.className = 'gtbogo-reveal-headline';
            h.textContent = deal.copy.headline;
            panel.appendChild( h );
        }

        // Subtext
        if ( deal.copy && deal.copy.subtext ) {
            var sub = document.createElement( 'p' );
            sub.className = 'gtbogo-reveal-sub';
            sub.textContent = deal.copy.subtext;
            panel.appendChild( sub );
        }

        // CTA
        var ctaText = ( deal.copy && deal.copy.cta ) ? deal.copy.cta : 'Claim Offer';
        var cta = document.createElement( 'button' );
        cta.className = 'gtbogo-reveal-cta';
        cta.textContent = ctaText;
        cta.addEventListener( 'click', accept );
        panel.appendChild( cta );

        // Tier label (escalation tier)
        if ( deal.discount_tier && deal.discount_tier > 1 ) {
            var tier = document.createElement( 'p' );
            tier.className = 'gtbogo-reveal-tier';
            tier.textContent = 'Offer upgrades automatically if not redeemed';
            panel.appendChild( tier );
        }

        document.body.appendChild( panel );
    }

    // ── Show ────────────────────────────────────────────────────────────────
    function show() {
        if ( shown ) return;
        shown = true;
        buildPanel();

        // Trigger transition on next frame
        requestAnimationFrame( function() {
            requestAnimationFrame( function() {
                if ( backdrop ) backdrop.classList.add( 'is-visible' );
                panel.classList.add( 'is-visible' );
            } );
        } );

        trackImpression();

        // Auto-dismiss toasts after 8 seconds
        if ( deal.display_type === 'toast' ) {
            setTimeout( dismiss, 8000 );
        }

        // Countdown timer if deal has expiry
        if ( deal.expires_seconds && deal.expires_seconds > 0 ) {
            startCountdown( deal.expires_seconds );
        }
    }

    // ── Dismiss ─────────────────────────────────────────────────────────────
    function dismiss() {
        if ( ! panel ) return;
        panel.classList.remove( 'is-visible' );
        if ( backdrop ) backdrop.classList.remove( 'is-visible' );

        var delay = prefersReduced ? 0 : 380;
        setTimeout( function() {
            if ( panel && panel.parentNode ) panel.parentNode.removeChild( panel );
            if ( backdrop && backdrop.parentNode ) backdrop.parentNode.removeChild( backdrop );
            clearPendingDeal();
        }, delay );

        trackRejection();
    }

    // ── Accept ──────────────────────────────────────────────────────────────
    function accept() {
        trackAcceptance();
        clearPendingDeal();

        // Navigate to cart to apply deal
        var cartUrl = cfg.cartUrl || '/cart/';
        window.location.href = cartUrl + ( cartUrl.indexOf('?') > -1 ? '&' : '?' ) + 'gtbogo_claim=1&rule_id=' + encodeURIComponent( deal.rule_id || 0 );
    }

    // ── AJAX helpers ────────────────────────────────────────────────────────
    function ajax( action, data ) {
        var body = new FormData();
        body.append( 'action', action );
        body.append( 'nonce', cfg.nonce || '' );
        body.append( 'rule_id', deal.rule_id || 0 );
        body.append( 'trigger', deal.trigger || '' );
        if ( data ) {
            Object.keys( data ).forEach( function(k) { body.append( k, data[k] ); } );
        }
        if ( navigator.sendBeacon && action !== 'gtbogo_track_deal_acceptance' ) {
            navigator.sendBeacon( cfg.ajaxUrl, body );
        } else {
            fetch( cfg.ajaxUrl, { method: 'POST', body: body, credentials: 'same-origin' } )
                .catch( function() {} );
        }
    }

    function trackImpression() {
        ajax( 'gtbogo_track_deal_impression', { display_type: deal.display_type } );
    }

    function trackAcceptance() {
        ajax( 'gtbogo_track_deal_acceptance', { accepted: 1 } );
    }

    function trackRejection() {
        ajax( 'gtbogo_track_deal_rejection', { rejected: 1 } );
    }

    function clearPendingDeal() {
        ajax( 'gtbogo_clear_pending_deal', {} );
    }

    // ── Escalation tick ─────────────────────────────────────────────
    // Polls every 30s; updates copy + shows escalation badge on tier change
    function startEscalationTick() {
        if ( ! cfg.escalationEnabled ) return;
        var lastDiscount = deal.discount || '';
        setInterval( function() {
            if ( ! shown || ! panel ) return;
            var url = cfg.ajaxUrl
                + '?action=gtbogo_get_next_tier'
                + '&nonce=' + encodeURIComponent( cfg.nonce || '' )
                + '&rule_id=' + encodeURIComponent( deal.rule_id || 0 )
                + '&archetype=' + encodeURIComponent( deal.archetype || 'universal' )
                + '&product_id=' + encodeURIComponent( deal.product_id || 0 );
            fetch( url )
                .then( function(r) { return r.json(); } )
                .then( function(data) {
                    if ( ! data || ! data.success || ! data.data ) return;
                    var newDiscount = String( data.data.discount || '' );
                    if ( ! newDiscount || newDiscount === lastDiscount ) return;
                    lastDiscount  = newDiscount;
                    deal.discount = newDiscount;
                    var h = panel.querySelector( '.gtbogo-reveal-headline' );
                    if ( h && data.data.headline ) {
                        h.style.transition = 'opacity 300ms ease';
                        h.style.opacity = '0';
                        setTimeout( function() { h.textContent = data.data.headline; h.style.opacity = '1'; }, 300 );
                    }
                    if ( ! panel.querySelector( '.gtbogo-reveal-escalated' ) ) {
                        var badge = document.createElement( 'p' );
                        badge.className = 'gtbogo-reveal-tier gtbogo-reveal-escalated';
                        badge.textContent = 'Offer upgraded automatically.';
                        var cta = panel.querySelector( '.gtbogo-reveal-cta' );
                        if ( cta ) panel.insertBefore( badge, cta );
                    }
                } )
                .catch( function() {} );
        }, 30000 );
    }

    // ── Entry point ─────────────────────────────────────────────────────────
    // Slight delay so page settles before showing deal
    var delay = deal.display_type === 'toast' ? 1200 : 800;
    setTimeout( show, delay );
    startEscalationTick();

    // Keyboard: Escape dismisses
    document.addEventListener( 'keydown', function(e) {
        if ( e.key === 'Escape' && shown ) dismiss();
    } );

}() );
