const player = document.getElementById('mergedPlayer');
const statusDot = document.getElementById('statusDot');
const statusText = document.getElementById('statusText');
const liveBadge = document.getElementById('liveBadge');
const nowPlaying = document.getElementById('nowPlaying');

const retryDelay = 0;

let streams = [];   // now loaded from database

let currentIndex = 0;
let currentStream = '';
let hlsInstance = null;
let checkInterval = null;
let skipPromo = false;

/* ---------------- STATUS UI ---------------- */

function updateStatus(streamObj,state='playing'){

nowPlaying.textContent=`Now Playing: ${streamObj.name}`;

if(state==='playing'){
statusText.textContent=`Status: ${streamObj.type}`;
statusDot.className="dot green";
}else{
statusText.textContent=`Reconnecting: ${streamObj.name}...`;
statusDot.className="dot orange";
}

if(streamObj.type==='HLS'||streamObj.type==='Icecast'){
liveBadge.style.display=(state==='playing')?'inline-block':'none';
liveBadge.textContent=`LIVE - ${streamObj.name}`;
}else{
liveBadge.style.display='none';
}

}

/* ---------------- STOP OTHER PLAYERS ---------------- */

function stopOtherPlayers(except){

document.querySelectorAll("audio").forEach(aud=>{
if(aud!==except){
aud.pause();
aud.currentTime=0;
}
});

}

/* ---------------- PLAY NEXT STREAM ---------------- */

function playNext(){

if(streams.length===0) return;

if(currentIndex>=streams.length) currentIndex=0;

let stream=streams[currentIndex];

let loopCounter=0;

while((!stream.enabled||(skipPromo&&stream.type==='MP3')) && loopCounter<streams.length){

currentIndex++;

if(currentIndex>=streams.length) currentIndex=0;

stream=streams[currentIndex];

loopCounter++;

}

currentStream=stream.type;

if(stream.type==='MP3') playMP3(stream);
else if(stream.type==='HLS') playHLS(stream);
else if(stream.type==='Icecast') playIcecast(stream);

}

/* ---------------- MP3 ---------------- */

function playMP3(streamObj){

currentStream='MP3';

updateStatus(streamObj);

stopOtherPlayers(player);

player.src=streamObj.url+"?t="+Date.now();

player.play().catch(()=>{});

player.onended=()=>{
currentIndex++;
playNext();
};

player.onerror=()=>{
currentIndex++;
playNext();
};

}

/* ---------------- HLS ---------------- */

function playHLS(streamObj){

currentStream='HLS';

updateStatus(streamObj);

stopOtherPlayers(player);

if(hlsInstance) hlsInstance.destroy();

hlsInstance=new Hls();

hlsInstance.loadSource(streamObj.url+"?t="+Date.now());

hlsInstance.attachMedia(player);

hlsInstance.on(Hls.Events.MANIFEST_PARSED,()=>player.play().catch(()=>{}));

hlsInstance.on(Hls.Events.ERROR,(event,data)=>{

if(data.fatal){

if(data.type===Hls.ErrorTypes.NETWORK_ERROR){
setTimeout(()=>playHLS(streamObj),retryDelay);
}

else if(data.type===Hls.ErrorTypes.MEDIA_ERROR){
hlsInstance.recoverMediaError();
}

else{
hlsInstance.destroy();
currentIndex = streams.findIndex(s=>s.type==='Icecast');
playNext();
player.play().catch(()=>{});
}

}

});

/* stall check */

if(checkInterval) clearInterval(checkInterval);

let stallCounter=0;

checkInterval=setInterval(()=>{

if(player.readyState<3){

stallCounter++;

if(stallCounter>=2){

hlsInstance.destroy();

currentIndex=streams.findIndex(s=>s.type==='Icecast');

playNext();

player.play().catch(()=>{});

clearInterval(checkInterval);

}

}else{
stallCounter=0;
}

},2000);

}

/* ---------------- ICECAST ---------------- */

function playIcecast(streamObj){

currentStream='Icecast';

updateStatus(streamObj);

stopOtherPlayers(player);

player.src=streamObj.url+"?t="+Date.now();

player.play().catch(()=>{});

/* stall check */

if(checkInterval) clearInterval(checkInterval);

let stallCounter=0;

checkInterval=setInterval(()=>{

if(player.readyState<3){

stallCounter++;

if(stallCounter>=2){

currentIndex=streams.findIndex(s=>s.type==='HLS');

playNext();

player.play().catch(()=>{});

clearInterval(checkInterval);

}

}else{
stallCounter=0;
}

},2000);

player.onerror=()=>{

currentIndex=streams.findIndex(s=>s.type==='HLS');

playNext();

player.play().catch(()=>{});

clearInterval(checkInterval);

};

}

/* ---------------- ENABLE / DISABLE ---------------- */

function enableStream(type){

const stream=streams.find(s=>s.type===type);

if(stream) stream.enabled=true;

}

function disableStream(type){

const stream=streams.find(s=>s.type===type);

if(stream) stream.enabled=false;

if(currentStream===type){
currentIndex++;
playNext();
}

}

/* ---------------- SKIP PROMO ---------------- */

function skipPromoOnce(skip=true){

skipPromo=skip;

if(skip && currentStream==='MP3'){
currentIndex++;
playNext();
}

}

/* ---------------- PAUSE HANDLER ---------------- */

player.addEventListener('pause',()=>{

updateStatus(streams[currentIndex],"retrying");

setTimeout(()=>{ playNext(); },retryDelay);

});

/* ---------------- SECURITY ---------------- */

document.addEventListener('keydown',function(e){

if(e.ctrlKey && ['s','S','u','U'].includes(e.key) || e.key==='F12'){
e.preventDefault();
}

});

document.addEventListener('selectstart',function(e){

if(!e.target.closest('audio')) e.preventDefault();

});

/* ---------------- CROSS TAB SYNC ---------------- */

const tabId=Math.random().toString(36).substr(2,9);

function claimActivePlayer(){
localStorage.setItem("radio_activeTab",tabId);
}

player.addEventListener("play",()=>{ claimActivePlayer(); });

window.addEventListener("storage",(e)=>{

if(e.key==="radio_activeTab"){

const activeTab=e.newValue;

if(activeTab!==tabId){

if(!player.paused){
player.pause();
player.currentTime=0;
}

}

}

});

/* ---------------- LOAD STREAMS FROM DATABASE ---------------- */

fetch("get_streams.php")

.then(res=>res.json())

.then(data=>{

streams=data;

playNext();

});