(function(){
  'use strict';
  var root=document.querySelector('[data-nex-music]');if(!root)return;
  var audio=root.querySelector('[data-music-audio]'),playlistNode=root.querySelector('[data-music-playlist]'),ytNode=root.querySelector('[data-music-youtube-config]');
  var tracks=[],ytCfg={};try{tracks=JSON.parse(playlistNode.textContent)||[];}catch(e){}try{ytCfg=JSON.parse(ytNode.textContent)||{};}catch(e){}
  var mode=root.dataset.mode||'local',useYT=(mode==='youtube'||mode==='hybrid')&&!!(ytCfg.videoId||ytCfg.playlistId),player=null,ready=false,ytRequested=false;
  var remember=root.dataset.remember==='1',shuffle=root.dataset.shuffle==='1',loop=root.dataset.loop==='1',key='nexora_music_v3',pendingPlay=false;
  var state={index:0,volume:Number(root.dataset.volume||35),muted:false,consent:'pending',minimized:false};
  if(remember){try{Object.assign(state,JSON.parse(localStorage.getItem(key)||'{}'));}catch(e){}}
  state.index=Math.max(0,Math.min(Math.max(0,tracks.length-1),Number(state.index)||0));state.volume=Math.max(0,Math.min(100,Number(state.volume)||35));
  var play=root.querySelector('[data-music-play]'),title=root.querySelector('[data-music-title]'),artist=root.querySelector('[data-music-artist]'),volume=root.querySelector('[data-music-volume]'),muteBtn=root.querySelector('[data-music-mute]');volume.value=state.volume;
  function save(){if(remember)localStorage.setItem(key,JSON.stringify(state));}
  function playing(on){play.textContent=on?'❚❚':'▶';root.classList.toggle('is-playing',on);}
  function labelYT(){if(!player||!ready)return;var d=player.getVideoData?player.getVideoData():{};if(d&&d.title)title.textContent=d.title;artist.textContent='YouTube · Nexora';}
  function loadLocal(i){if(!tracks.length)return;state.index=(i+tracks.length)%tracks.length;var t=tracks[state.index];audio.src=t.src;title.textContent=t.title;artist.textContent=t.artist||'Nexora';save();}
  function localPlay(){if(!tracks.length)return;audio.volume=state.volume/100;audio.muted=!!state.muted;audio.play().then(function(){playing(true);save();}).catch(function(){playing(false);});}
  function ytPlay(){if(!ready){pendingPlay=true;ensureYT();return;}pendingPlay=false;player.setVolume(state.volume);state.muted?player.mute():player.unMute();player.playVideo();playing(true);save();}
  function start(){state.consent='accepted';root.classList.remove('is-declined','is-prompting');root.classList.add('is-activated');useYT?ytPlay():localPlay();save();}
  function pause(){if(useYT&&ready)player.pauseVideo();else audio.pause();playing(false);save();}
  function step(dir){if(useYT&&ready){dir>0?player.nextVideo():player.previousVideo();setTimeout(labelYT,500);return;}if(!tracks.length)return;var next=shuffle?Math.floor(Math.random()*tracks.length):state.index+dir;loadLocal(next);localPlay();}
  function fallback(){if(mode!=='hybrid'||!tracks.length)return;useYT=false;loadLocal(state.index);if(state.consent==='accepted')localPlay();}
  function buildYT(){
    if(!useYT||player||!window.YT||typeof window.YT.Player!=='function')return;
    player=new YT.Player(root.querySelector('[data-music-youtube]'),{height:'200',width:'356',videoId:ytCfg.playlistId?'':ytCfg.videoId,playerVars:{playsinline:1,controls:0,rel:0,origin:location.origin},events:{onReady:function(){ready=true;player.setVolume(state.volume);if(ytCfg.playlistId)player.cuePlaylist({listType:'playlist',list:ytCfg.playlistId,index:0,startSeconds:0});else if(ytCfg.videoId)player.cueVideoById(ytCfg.videoId);setTimeout(function(){player.setLoop(loop);if(shuffle)player.setShuffle(true);labelYT();if(pendingPlay)ytPlay();},350);},onStateChange:function(e){if(e.data===YT.PlayerState.PLAYING){playing(true);labelYT();}else if(e.data===YT.PlayerState.PAUSED)playing(false);else if(e.data===YT.PlayerState.ENDED){if(loop&&ytCfg.videoId){player.seekTo(0);player.playVideo();}else playing(false);}},onError:fallback,onAutoplayBlocked:function(){state.consent='pending';root.classList.remove('is-activated');root.classList.add('is-prompting');playing(false);save();}}});
  }
  function ensureYT(){
    if(!useYT||player)return;
    if(window.YT&&typeof window.YT.Player==='function'){buildYT();return;}
    if(ytRequested)return;
    ytRequested=true;
    var previous=window.onYouTubeIframeAPIReady;
    window.onYouTubeIframeAPIReady=function(){if(typeof previous==='function'){try{previous();}catch(e){}}buildYT();};
    var s=document.createElement('script');s.src='https://www.youtube.com/iframe_api';s.async=true;s.defer=true;document.head.appendChild(s);
  }
  root.querySelector('[data-music-accept]').addEventListener('click',start);
  root.querySelector('[data-music-decline]').addEventListener('click',function(){state.consent='declined';root.classList.remove('is-prompting','is-activated');root.classList.add('is-declined');pause();save();});
  root.querySelector('[data-music-reopen]').addEventListener('click',function(){root.classList.remove('is-declined','is-activated');root.classList.add('is-prompting');});
  play.addEventListener('click',function(){var paused=useYT?(!ready||!player||player.getPlayerState()!==YT.PlayerState.PLAYING):audio.paused;paused?start():pause();});
  root.querySelector('[data-music-prev]').addEventListener('click',function(){step(-1);});root.querySelector('[data-music-next]').addEventListener('click',function(){step(1);});
  audio.addEventListener('ended',function(){if(loop||state.index<tracks.length-1)step(1);else playing(false);});
  muteBtn.addEventListener('click',function(){state.muted=!state.muted;if(useYT&&ready){state.muted?player.mute():player.unMute();}else audio.muted=state.muted;muteBtn.textContent=state.muted?'×':'♪';save();});
  volume.addEventListener('input',function(){state.volume=Number(this.value);if(useYT&&ready)player.setVolume(state.volume);else audio.volume=state.volume/100;if(state.volume>0)state.muted=false;save();});
  root.querySelector('[data-music-minimize]').addEventListener('click',function(){state.minimized=!state.minimized;root.classList.toggle('is-minimized',state.minimized);save();});
  if(tracks.length)loadLocal(state.index);root.classList.toggle('is-activated',state.consent==='accepted');root.classList.toggle('is-declined',state.consent==='declined');root.classList.toggle('is-prompting',state.consent==='pending');root.classList.toggle('is-minimized',!!state.minimized);muteBtn.textContent=state.muted?'×':'♪';
})();
