(function(){
    'use strict';

    var data=window.NexoraRouletteData||{};
    var segments=Array.isArray(data.segments)?data.segments:[];
    var resultData=data.result||null;
    var svgMount=document.getElementById('nxrWheelSvgMount');
    var wheelCanvas=document.getElementById('nxrWheelCanvas');
    var pointer=document.getElementById('nxrWheelPointer');
    var coreOverlay=document.getElementById('nxrWheelCoreOverlay');
    var form=document.getElementById('nxrSpinForm');
    var spinButton=document.getElementById('nxrSpinButton');
    var resultBox=document.getElementById('nxrResult');
    var flash=document.getElementById('nxrFlash');
    var soundToggle=document.getElementById('nxrSoundToggle');
    var premiumReveal=document.getElementById('nxrPremiumReveal');
    var revealClose=document.getElementById('nxrRevealClose');
    var revealContinue=document.getElementById('nxrRevealContinue');
    var revealIcon=document.getElementById('nxrRevealIcon');
    var spinButtonLabel=document.getElementById('nxrSpinButtonLabel');
    var spinButtonSub=document.getElementById('nxrSpinButtonSub');

    var NS='http://www.w3.org/2000/svg';
    var REDUCED_MOTION=window.matchMedia&&window.matchMedia('(prefers-reduced-motion: reduce)').matches;
    var state={
        processing:false,
        spinning:false,
        currentRotation:0,
        spinCount:0,
        segmentNodes:{},
        segmentGroups:{},
        spinTimer:null,
        tickFrame:null,
        pointerAnimation:null,
        audioContext:null,
        audioMuted:false,
        audioUsable:true
    };

    function createNode(tag,attrs){
        var node=document.createElementNS(NS,tag);
        if(attrs){Object.keys(attrs).forEach(function(key){node.setAttribute(key,attrs[key]);});}
        return node;
    }

    function clamp(value,min,max){return Math.max(min,Math.min(max,value));}

    function formatNumber(value){
        try{return new Intl.NumberFormat().format(parseInt(value,10)||0);}catch(e){return String(parseInt(value,10)||0);}
    }

    function shadeHex(hex,percent){
        hex=String(hex||'#101722').replace('#','');
        if(hex.length!==6)return '#101722';
        var n=parseInt(hex,16),amt=Math.round(2.55*percent);
        var r=clamp((n>>16)+amt,0,255),g=clamp((n>>8&255)+amt,0,255),b=clamp((n&255)+amt,0,255);
        return '#'+(0x1000000+r*0x10000+g*0x100+b).toString(16).slice(1);
    }

    function mixHex(a,b,ratio){
        a=String(a||'#101722').replace('#','');
        b=String(b||'#080b11').replace('#','');
        ratio=clamp(ratio,0,1);
        if(a.length!==6||b.length!==6)return '#101722';
        var na=parseInt(a,16),nb=parseInt(b,16);
        var ar=na>>16,ag=na>>8&255,ab=na&255,br=nb>>16,bg=nb>>8&255,bb=nb&255;
        var r=Math.round(ar+(br-ar)*ratio),g=Math.round(ag+(bg-ag)*ratio),bl=Math.round(ab+(bb-ab)*ratio);
        return '#'+(0x1000000+r*0x10000+g*0x100+bl).toString(16).slice(1);
    }

    function getRarityColors(rarity){
        var map={
            common:{stroke:'#667589',fillA:'#202934',fillB:'#121923'},
            uncommon:{stroke:'#2f9d68',fillA:'#1a3127',fillB:'#101c17'},
            rare:{stroke:'#367edb',fillA:'#16304d',fillB:'#101b2b'},
            epic:{stroke:'#8756d3',fillA:'#2d2046',fillB:'#191226'},
            legendary:{stroke:'#d8aa48',fillA:'#3b2b12',fillB:'#20170b'}
        };
        return map[rarity]||map.common;
    }

    function getHarmonicColors(index){
        var panel=data.panelColor||'#101722';
        var bg=data.backgroundColor||'#080B11';
        var accent=data.accentColor||'#D7A94A';
        var secondary=data.secondaryColor||'#7747C7';
        var even=index%2===0;
        var tertiary=index%4===2;
        var fillA=even?mixHex(panel,accent,.08):mixHex(panel,secondary,.08);
        var fillB=even?mixHex(bg,panel,.42):mixHex(bg,panel,.56);
        if(tertiary)fillA=mixHex(panel,secondary,.13);
        return {stroke:even?mixHex(accent,'#ffffff',.08):mixHex(secondary,'#ffffff',.04),fillA:fillA,fillB:fillB};
    }

    function polarToCartesian(cx,cy,radius,angleDeg){
        var radians=(angleDeg-90)*Math.PI/180;
        return{x:cx+radius*Math.cos(radians),y:cy+radius*Math.sin(radians)};
    }

    function describeSegment(cx,cy,outerRadius,innerRadius,startAngle,endAngle){
        var startOuter=polarToCartesian(cx,cy,outerRadius,endAngle);
        var endOuter=polarToCartesian(cx,cy,outerRadius,startAngle);
        var startInner=polarToCartesian(cx,cy,innerRadius,startAngle);
        var endInner=polarToCartesian(cx,cy,innerRadius,endAngle);
        var largeArc=endAngle-startAngle<=180?0:1;
        return ['M',startOuter.x,startOuter.y,'A',outerRadius,outerRadius,0,largeArc,0,endOuter.x,endOuter.y,'L',startInner.x,startInner.y,'A',innerRadius,innerRadius,0,largeArc,1,endInner.x,endInner.y,'Z'].join(' ');
    }

    function createVectorIcon(segment){
        var g=createNode('g',{class:'nxr-wheel-vector-icon nxr-icon-'+(segment.icon_type||'manual')});
        g.appendChild(createNode('circle',{cx:'0',cy:'0',r:'22',class:'nxr-wheel-icon-shell'}));
        var type=segment.icon_type||'manual';
        if(type==='credits'){
            g.appendChild(createNode('circle',{cx:'0',cy:'0',r:'13',class:'nxr-icon-credit-ring'}));
            g.appendChild(createNode('path',{d:'M -7 -2 L -2 -7 L 7 -7 M -7 2 L -2 7 L 7 7',class:'nxr-icon-credit-mark'}));
        }else if(type==='spin'){
            g.appendChild(createNode('path',{d:'M -12 2 A 14 14 0 1 1 7 12',class:'nxr-icon-spin-arc'}));
            g.appendChild(createNode('path',{d:'M 6 7 L 13 12 L 6 16 Z',class:'nxr-icon-spin-arrow'}));
        }else{
            g.appendChild(createNode('path',{d:'M 0 -14 L 13 0 L 0 14 L -13 0 Z',class:'nxr-icon-manual-diamond'}));
            g.appendChild(createNode('circle',{cx:'0',cy:'0',r:'3.2',class:'nxr-icon-manual-core'}));
        }
        return g;
    }

    function createSegmentIcon(segment,mid,radius){
        if(data.showSegmentIcons===false)return null;
        var point=polarToCartesian(320,320,radius,mid);
        var wrapper=createNode('g',{class:'nxr-wheel-icon-group','data-prize-id':segment.id});
        wrapper.setAttribute('transform','translate('+point.x+' '+point.y+')');
        if(segment.icon_url){
            wrapper.appendChild(createNode('circle',{cx:'0',cy:'0',r:'25',class:'nxr-wheel-icon-shell'}));
            var image=createNode('image',{x:'-22',y:'-22',width:'44',height:'44',preserveAspectRatio:'xMidYMid meet',class:'nxr-wheel-item-icon'});
            image.setAttributeNS('http://www.w3.org/1999/xlink','href',segment.icon_url);
            image.setAttribute('href',segment.icon_url);
            wrapper.appendChild(image);
        }else{
            wrapper.appendChild(createVectorIcon(segment));
        }
        return wrapper;
    }

    function buildWheel(){
        if(!svgMount)return;
        svgMount.innerHTML='';
        state.segmentNodes={};
        state.segmentGroups={};
        if(!segments.length)return;

        var svg=createNode('svg',{viewBox:'0 0 640 640',class:'nxr-wheel-svg',role:'img','aria-label':'Ruleta Nexora'});
        var defs=createNode('defs');
        var shadow=createNode('filter',{id:'nxrWheelShadow',x:'-30%',y:'-30%',width:'160%',height:'160%'});
        shadow.appendChild(createNode('feDropShadow',{dx:'0',dy:'10',stdDeviation:'13','flood-color':'#000000','flood-opacity':'.42'}));
        defs.appendChild(shadow);

        var sheen=createNode('radialGradient',{id:'nxrWheelSheen',cx:'38%',cy:'28%',r:'72%'});
        sheen.appendChild(createNode('stop',{offset:'0%','stop-color':'#ffffff','stop-opacity':'.08'}));
        sheen.appendChild(createNode('stop',{offset:'42%','stop-color':'#ffffff','stop-opacity':'.01'}));
        sheen.appendChild(createNode('stop',{offset:'100%','stop-color':'#000000','stop-opacity':'.18'}));
        defs.appendChild(sheen);

        segments.forEach(function(segment,index){
            var colors=data.segmentPalette==='rarity'?getRarityColors(segment.rarity):getHarmonicColors(index);
            var grad=createNode('linearGradient',{id:'nxrSegGrad'+segment.id,x1:'12%',y1:'0%',x2:'88%',y2:'100%'});
            grad.appendChild(createNode('stop',{offset:'0%','stop-color':colors.fillA}));
            grad.appendChild(createNode('stop',{offset:'100%','stop-color':colors.fillB}));
            defs.appendChild(grad);
            var glow=createNode('filter',{id:'nxrWinnerGlow'+segment.id,x:'-50%',y:'-50%',width:'200%',height:'200%'});
            glow.appendChild(createNode('feDropShadow',{dx:'0',dy:'0',stdDeviation:'9','flood-color':colors.stroke,'flood-opacity':'.68'}));
            defs.appendChild(glow);
        });
        svg.appendChild(defs);

        var staticRing=createNode('g',{class:'nxr-wheel-static-detail'});
        for(var tick=0;tick<72;tick+=1){
            var angle=tick*5;
            var r1=tick%3===0?286:290;
            var r2=296;
            var p1=polarToCartesian(320,320,r1,angle),p2=polarToCartesian(320,320,r2,angle);
            staticRing.appendChild(createNode('line',{x1:p1.x,y1:p1.y,x2:p2.x,y2:p2.y,class:tick%3===0?'nxr-wheel-tick is-major':'nxr-wheel-tick'}));
        }
        svg.appendChild(staticRing);

        var wheelGroup=createNode('g',{class:'nxr-wheel-rotation-group',filter:'url(#nxrWheelShadow)'});
        var outerRadius=274,innerRadius=118;
        var labelRadius=data.showSegmentIcons===false?206:224;
        var iconRadius=188;
        var gap=Math.max(1,parseInt(data.segmentGap||3,10));

        segments.forEach(function(segment,index){
            var colors=data.segmentPalette==='rarity'?getRarityColors(segment.rarity):getHarmonicColors(index);
            var start=parseFloat(segment.start||0),end=parseFloat(segment.end||0),mid=parseFloat(segment.mid||0);
            var group=createNode('g',{class:'nxr-wheel-segment-group rarity-'+(segment.rarity||'common'),'data-prize-id':segment.id});
            var title=createNode('title');
            title.textContent=(segment.name||'')+(segment.probability!==undefined?' · '+Number(segment.probability).toFixed(2)+'%':'');
            group.appendChild(title);

            var path=createNode('path',{
                d:describeSegment(320,320,outerRadius,innerRadius,start,end),
                class:'nxr-wheel-segment',
                fill:'url(#nxrSegGrad'+segment.id+')',
                stroke:colors.stroke,
                'stroke-width':String(gap),
                'stroke-linejoin':'round',
                'data-prize-id':segment.id
            });
            group.appendChild(path);

            group.appendChild(createNode('path',{
                d:describeSegment(320,320,outerRadius-6,innerRadius+6,start,end),
                fill:'url(#nxrWheelSheen)',
                class:'nxr-wheel-segment-sheen'
            }));

            var rarityPoint=polarToCartesian(320,320,outerRadius-19,mid);
            var rarity=getRarityColors(segment.rarity);
            group.appendChild(createNode('circle',{cx:rarityPoint.x,cy:rarityPoint.y,r:'5.2',fill:rarity.stroke,class:'nxr-wheel-rarity-marker'}));

            var icon=createSegmentIcon(segment,mid,iconRadius);
            if(icon)group.appendChild(icon);

            if(data.showSegmentLabels!==false){
                var labelPoint=polarToCartesian(320,320,labelRadius,mid);
                var normalized=((mid%360)+360)%360;
                var flip=normalized>90&&normalized<270;
                var rotation=flip?mid+180:mid;
                var label=createNode('g',{class:'nxr-wheel-label-group'});
                label.setAttribute('transform','translate('+labelPoint.x+' '+labelPoint.y+') rotate('+rotation+')');
                var bgWidth=segments.length>=12?82:(segments.length>=9?98:112);
                label.appendChild(createNode('rect',{x:String(-bgWidth/2),y:'-14',rx:'11',ry:'11',width:String(bgWidth),height:'27',class:'nxr-wheel-label-bg'}));
                var text=createNode('text',{x:'0',y:'4','text-anchor':'middle',class:'nxr-wheel-label-text'});
                text.textContent=segment.short_name||segment.name||'';
                label.appendChild(text);
                group.appendChild(label);
            }

            wheelGroup.appendChild(group);
            state.segmentNodes[String(segment.id)]=path;
            state.segmentGroups[String(segment.id)]=group;
        });

        wheelGroup.appendChild(createNode('circle',{cx:'320',cy:'320',r:'280',class:'nxr-wheel-rim-outer'}));
        wheelGroup.appendChild(createNode('circle',{cx:'320',cy:'320',r:'268',class:'nxr-wheel-rim-innerline'}));
        wheelGroup.appendChild(createNode('circle',{cx:'320',cy:'320',r:'112',class:'nxr-wheel-center-hole'}));
        svg.appendChild(wheelGroup);
        svgMount.appendChild(svg);
    }

    function getSegment(prizeId){
        prizeId=parseInt(prizeId,10);
        for(var i=0;i<segments.length;i+=1){if(parseInt(segments[i].id,10)===prizeId)return segments[i];}
        return null;
    }

    function clearWinnerState(){
        Object.keys(state.segmentNodes).forEach(function(id){
            state.segmentNodes[id].classList.remove('is-winner','is-dimmed');
            state.segmentNodes[id].removeAttribute('filter');
            if(state.segmentGroups[id])state.segmentGroups[id].classList.remove('is-winner-group');
        });
    }

    function setWinner(prizeId){
        var winnerId=String(prizeId||'');
        Object.keys(state.segmentNodes).forEach(function(id){
            var node=state.segmentNodes[id];
            if(id===winnerId){
                node.classList.add('is-winner');
                node.classList.remove('is-dimmed');
                if(state.segmentGroups[id])state.segmentGroups[id].classList.add('is-winner-group');
                if(data.winnerGlow!==false)node.setAttribute('filter','url(#nxrWinnerGlow'+id+')');
            }else if(data.dimNonWinners!==false){
                node.classList.add('is-dimmed');
            }
        });
    }

    function randomInt(min,max){
        min=Math.ceil(min);max=Math.floor(max);
        if(max<min)max=min;
        if(window.crypto&&window.crypto.getRandomValues){
            var arr=new Uint32Array(1);window.crypto.getRandomValues(arr);
            return min+(arr[0]%(max-min+1));
        }
        return Math.floor(Math.random()*(max-min+1))+min;
    }

    function getComputedRotation(){
        if(!wheelCanvas)return 0;
        var transform=window.getComputedStyle(wheelCanvas).transform;
        if(!transform||transform==='none')return 0;
        try{
            var matrix=new DOMMatrixReadOnly(transform);
            var angle=Math.atan2(matrix.b,matrix.a)*180/Math.PI;
            return (angle+360)%360;
        }catch(e){
            var values=transform.match(/matrix\(([^)]+)\)/);
            if(!values)return 0;
            var parts=values[1].split(',').map(parseFloat);
            var fallback=Math.atan2(parts[1],parts[0])*180/Math.PI;
            return (fallback+360)%360;
        }
    }

    function triggerPointerTick(strength){
        if(!pointer)return;
        strength=clamp(strength||.6,.3,1);
        if(pointer.animate){
            if(state.pointerAnimation&&state.pointerAnimation.cancel)state.pointerAnimation.cancel();
            state.pointerAnimation=pointer.animate([
                {transform:'translateX(-50%) rotate(0deg)',offset:0},
                {transform:'translateX(-50%) rotate('+(3+strength*5)+'deg)',offset:.36},
                {transform:'translateX(-50%) rotate('+(strength*-1.5)+'deg)',offset:.68},
                {transform:'translateX(-50%) rotate(0deg)',offset:1}
            ],{duration:110+Math.round(strength*70),easing:'cubic-bezier(.2,.8,.2,1)'});
        }else{
            pointer.classList.remove('is-tick');
            void pointer.offsetWidth;
            pointer.classList.add('is-tick');
        }
        if(data.segmentTicks!==false)playTick(strength);
    }

    function startTickTracker(duration){
        if(state.tickFrame)cancelAnimationFrame(state.tickFrame);
        if(!segments.length)return;
        var sectorAngle=parseFloat(segments[0].angle||0);
        if(!(sectorAngle>0))return;
        var previous=getComputedRotation();
        var accumulated=0;
        var started=performance.now();

        function frame(now){
            if(!state.spinning)return;
            var current=getComputedRotation();
            var delta=current-previous;
            if(delta<-180)delta+=360;
            if(delta>180)delta-=360;
            if(delta>0)accumulated+=delta;
            previous=current;
            while(accumulated>=sectorAngle){
                accumulated-=sectorAngle;
                var progress=clamp((now-started)/Math.max(1,duration),0,1);
                triggerPointerTick(.42+progress*.58);
            }
            state.tickFrame=requestAnimationFrame(frame);
        }
        state.tickFrame=requestAnimationFrame(frame);
    }

    function stopTickTracker(){
        if(state.tickFrame){cancelAnimationFrame(state.tickFrame);state.tickFrame=null;}
    }

    function loadMutePreference(){
        if(data.soundEnabled===false){state.audioMuted=true;return;}
        try{state.audioMuted=window.localStorage.getItem('nexoraRouletteMuted')==='1';}catch(e){state.audioMuted=false;}
        syncSoundButton();
    }

    function syncSoundButton(){
        if(!soundToggle)return;
        soundToggle.classList.toggle('is-muted',state.audioMuted);
        soundToggle.setAttribute('aria-pressed',state.audioMuted?'true':'false');
        var label=soundToggle.querySelector('b');
        if(label)label.textContent=state.audioMuted?'SILENCIO':'SONIDO';
    }

    function ensureAudio(){
        if(data.soundEnabled===false||state.audioMuted||!state.audioUsable)return null;
        var AudioContext=window.AudioContext||window.webkitAudioContext;
        if(!AudioContext){state.audioUsable=false;return null;}
        try{
            if(!state.audioContext)state.audioContext=new AudioContext();
            if(state.audioContext.state==='suspended'){
                var resume=state.audioContext.resume();
                if(resume&&resume.catch)resume.catch(function(){});
            }
            return state.audioContext;
        }catch(e){state.audioUsable=false;return null;}
    }

    function tone(freq,duration,volume,type,delay){
        var ctx=ensureAudio();
        if(!ctx)return;
        var now=ctx.currentTime+(delay||0);
        try{
            var osc=ctx.createOscillator();
            var gain=ctx.createGain();
            osc.type=type||'sine';
            osc.frequency.setValueAtTime(freq,now);
            gain.gain.setValueAtTime(Math.max(.0001,volume),now);
            gain.gain.exponentialRampToValueAtTime(.0001,now+duration);
            osc.connect(gain);gain.connect(ctx.destination);
            osc.start(now);osc.stop(now+duration+.03);
        }catch(e){}
    }

    function playTick(strength){
        if(data.segmentTicks===false)return;
        var baseVolume=(parseInt(data.soundVolume||36,10)/100)*.055;
        tone(760+Math.round(strength*420),.045,baseVolume*(.55+strength*.45),'triangle',0);
    }

    function playSpinStart(){
        var volume=(parseInt(data.soundVolume||36,10)/100)*.06;
        var ctx=ensureAudio();
        if(!ctx)return;
        try{
            var osc=ctx.createOscillator(),gain=ctx.createGain();
            var now=ctx.currentTime;
            osc.type='sine';
            osc.frequency.setValueAtTime(92,now);
            osc.frequency.exponentialRampToValueAtTime(238,now+.42);
            gain.gain.setValueAtTime(.0001,now);
            gain.gain.exponentialRampToValueAtTime(Math.max(.0002,volume),now+.06);
            gain.gain.exponentialRampToValueAtTime(.0001,now+.48);
            osc.connect(gain);gain.connect(ctx.destination);osc.start(now);osc.stop(now+.52);
        }catch(e){}
    }

    function playRarityStinger(rarity){
        if(data.rarityStinger===false)return;
        var master=(parseInt(data.soundVolume||36,10)/100)*.085;
        var notes={
            common:[440],
            uncommon:[440,554],
            rare:[392,587,784],
            epic:[330,494,659,988],
            legendary:[294,440,587,880,1175]
        }[rarity]||[440];
        notes.forEach(function(freq,index){tone(freq,.26+index*.035,master*(1-index*.08),index<2?'triangle':'sine',index*.075);});
    }

    function renderRevealIcon(){
        if(!revealIcon||!resultData||!resultData.prize)return;
        var prize=resultData.prize;
        revealIcon.innerHTML='';
        revealIcon.className='nxr-reveal-icon nxr-reveal-icon--'+(prize.icon_type||'manual');
        if(prize.icon_url){
            var img=document.createElement('img');
            img.src=prize.icon_url;
            img.alt=prize.name||'Premio';
            img.decoding='async';
            revealIcon.appendChild(img);
            return;
        }
        var mark=document.createElement('span');
        mark.className='nxr-reveal-icon-mark';
        if(prize.icon_type==='credits')mark.textContent='C';
        else if(prize.icon_type==='spin')mark.textContent='↻';
        else mark.textContent='NXR';
        revealIcon.appendChild(mark);
    }

    function revealResult(){
        if(resultBox){
            resultBox.classList.remove('is-pending-reveal');
            resultBox.classList.add('is-visible','is-revealing');
            resultBox.setAttribute('aria-hidden','false');
            setTimeout(function(){resultBox.classList.remove('is-revealing');},700);
        }
        if(data.premiumReveal!==false&&premiumReveal){
            renderRevealIcon();
            premiumReveal.classList.add('is-visible');
            premiumReveal.setAttribute('aria-hidden','false');
            var card=premiumReveal.querySelector('.nxr-reveal-card');
            if(card)card.focus&&card.focus();
        }
    }

    function closeReveal(){
        if(!premiumReveal)return;
        premiumReveal.classList.remove('is-visible');
        premiumReveal.setAttribute('aria-hidden','true');
        if(spinButton)spinButton.focus();
    }

    function animateToPrize(prizeId,onDone){
        var segment=getSegment(prizeId);
        if(!segment||!wheelCanvas){if(typeof onDone==='function')onDone();return;}
        clearWinnerState();
        state.spinning=true;
        state.spinCount+=1;

        var mid=parseFloat(segment.mid||0);
        var minTurns=Math.max(5,parseInt(data.turnsMin||7,10));
        var maxTurns=Math.max(minTurns,parseInt(data.turnsMax||10,10));
        var extraTurns=randomInt(minTurns,maxTurns);
        var normalizedCurrent=((state.currentRotation%360)+360)%360;
        var targetNormalized=(360-mid)%360;
        var delta=targetNormalized-normalizedCurrent;
        if(delta<0)delta+=360;
        var targetRotation=state.currentRotation+(extraTurns*360)+delta;
        var duration=Math.max(3500,parseInt(data.spinDurationMs||5200,10));

        if(REDUCED_MOTION){duration=900;targetRotation=state.currentRotation+360+delta;}

        wheelCanvas.style.transitionDuration=duration+'ms';
        wheelCanvas.classList.add('is-spinning');
        if(pointer){pointer.classList.remove('is-impact');}
        if(coreOverlay)coreOverlay.classList.add('is-running');
        state.currentRotation=targetRotation;
        playSpinStart();
        if(!REDUCED_MOTION)startTickTracker(duration);
        requestAnimationFrame(function(){requestAnimationFrame(function(){wheelCanvas.style.transform='rotate('+targetRotation+'deg)';});});

        clearTimeout(state.spinTimer);
        state.spinTimer=setTimeout(function(){
            stopTickTracker();
            wheelCanvas.classList.remove('is-spinning');
            state.spinning=false;
            setWinner(prizeId);
            if(pointer&&data.pointerBounce!==false){
                pointer.classList.add('is-impact');
                setTimeout(function(){pointer.classList.remove('is-impact');},760);
            }
            if(coreOverlay){
                coreOverlay.classList.remove('is-running');
                if(data.landingPulse!==false){coreOverlay.classList.add('is-landing');setTimeout(function(){coreOverlay.classList.remove('is-landing');},950);}
            }
            playRarityStinger(segment.rarity||'common');
            if(typeof onDone==='function')onDone(segment);
        },duration+90);
    }

    function hideFlash(){if(!flash)return;flash.hidden=true;flash.className='nxr-flash';flash.textContent='';}

    function setButtonState(mode){
        if(!spinButton)return;
        if(mode==='validating'){
            spinButton.disabled=true;spinButton.classList.add('is-loading');
            if(spinButtonLabel)spinButtonLabel.textContent='VALIDANDO GIRO';
            if(spinButtonSub)spinButtonSub.textContent='Confirmando saldo y premio en servidor';
            return;
        }
        if(mode==='spinning'){
            spinButton.disabled=true;spinButton.classList.add('is-loading');
            if(spinButtonLabel)spinButtonLabel.textContent='GIRANDO';
            if(spinButtonSub)spinButtonSub.textContent='Resultado confirmado · movimiento en curso';
            return;
        }
        spinButton.classList.remove('is-loading');
        spinButton.disabled=!data.canSpin;
        if(spinButtonLabel)spinButtonLabel.textContent=(parseInt(data.freeSpins||0,10)>0)?'USAR GIRO DISPONIBLE':(data.spinCtaLabel||'GIRAR');
        if(spinButtonSub)spinButtonSub.textContent=(parseInt(data.freeSpins||0,10)>0)?'No consume saldo':formatNumber(data.spinCost||0)+' '+(data.walletLabel||'Moneda');
    }

    function submitSpin(event){
        if(state.processing||state.spinning||!form){event.preventDefault();return;}
        state.processing=true;
        hideFlash();
        var actionInput=form.querySelector('input[name="roulette_action"]');
        if(!actionInput){
            actionInput=document.createElement('input');
            actionInput.type='hidden';actionInput.name='roulette_action';form.appendChild(actionInput);
        }
        actionInput.value='spin';
        setButtonState('validating');
        tone(320,.085,(parseInt(data.soundVolume||36,10)/100)*.045,'triangle',0);
        try{window.sessionStorage.setItem('nexoraRouletteSpinPending','1');}catch(e){}
        // Native WebEngine POST is intentional. The returned page contains the
        // server-confirmed prize and only then starts the visual spin.
    }

    function bindSoundToggle(){
        if(!soundToggle)return;
        soundToggle.addEventListener('click',function(){
            state.audioMuted=!state.audioMuted;
            try{window.localStorage.setItem('nexoraRouletteMuted',state.audioMuted?'1':'0');}catch(e){}
            syncSoundButton();
            if(!state.audioMuted){ensureAudio();tone(660,.09,(parseInt(data.soundVolume||36,10)/100)*.05,'sine',0);}
        });
    }

    buildWheel();
    loadMutePreference();
    bindSoundToggle();
    if(form)form.addEventListener('submit',submitSpin);
    if(revealClose)revealClose.addEventListener('click',closeReveal);
    if(revealContinue)revealContinue.addEventListener('click',closeReveal);
    if(premiumReveal){
        premiumReveal.addEventListener('click',function(event){if(event.target&&event.target.classList.contains('nxr-reveal-backdrop'))closeReveal();});
        document.addEventListener('keydown',function(event){if(event.key==='Escape'&&premiumReveal.classList.contains('is-visible'))closeReveal();});
    }

    if(parseInt(data.resultPrizeId||0,10)>0){
        setButtonState('spinning');
        setTimeout(function(){
            animateToPrize(parseInt(data.resultPrizeId,10),function(){
                var delay=Math.max(200,parseInt(data.revealDelayMs||420,10));
                setTimeout(function(){revealResult();setButtonState('idle');state.processing=false;},REDUCED_MOTION?80:delay);
            });
        },140);
    }else{
        if(resultBox)resultBox.setAttribute('aria-hidden','false');
        setButtonState('idle');
    }
})();
