let create= (x)=> document.createElement(x),
select= (x,y=document)=> y.querySelector(x),
selectAll= (x,y=document)=> y.querySelectorAll(x);


let allfew= select("p.show.hide");
let prevGenre= select("span.left");
let nextGenre= select("span.right");
let pause= select("p.play.pause");
let timer= select(".block4");
let audio= select("audio");
let proxy= "https://cors.bitwize.com.lb/";
let offline= "../resources/kdradiosorry.mp3";
offline= new URL(offline, document.baseURI);
let mediaSession= ("mediaSession" in navigator);
let ignoreHS= false;

let genre= Object.keys(blocklist);
let index= 0;
//let hidden= (blocklist[genre[index]]!=[]);
let hidden= true;

//let localhidden= {};

//____________________________________________________________ BLOCK 1




let isSr= select("p.in");
let isBw= select("p.sr");



if(isSr){
isSr.onclick=()=> location= "bollywood.html";
}

if(isBw){
isBw.onclick=()=> location= "index.html";
}




checkHash();
createStations(list[index]);
select("p.genre").style.visibility= (list.length>1) ? "visible" : "hidden";
	










/*
function hmm(){
let interval= setInterval(()=>{
if(audio.currentTime>0){
mediaControl(audio.title);
showControls();
clearInterval(interval);	
}	
},1000);	
}
*/











/*_______________________________________________________________________
														EVENT BINDING
_______________________________________________________________________*/


//Switching genres using location hash
window.onhashchange=()=>{
checkHash();
createStations(list[index]);
};




//Skip to previous genre
select("span.left").onclick=()=>{
index= (index<=0) ? list.length-1 : index-1;
createStations(list[index]);
};

//Skip to next genre
select("span.right").onclick=()=>{
index= (index<list.length-1) ? index+1 : 0;
createStations(list[index]);

}; 



//Play or pause radio
pause.onclick= function(){
if(audio.currentSrc==offline) return;
if(audio.currentTime<1) return;

if(audio.paused){
audio.play();
this.innerHTML= "PAUSE";
}
else{
audio.pause();
this.innerHTML= "PLAY";
}

};


//Update info when audio's playing
audio.ontimeupdate= function(){
let time= formatTime(this.currentTime*1000);
if(this.currentTime<1){
updatePage("clicked",time);
}
else{
if(!this.paused){
let klass= (this.currentSrc==offline) ? "offline" : "playing";
updatePage(klass,time);
}
else{
updatePage("paused",time);
}
}

select("textarea").value= audio.outerHTML;

//console.log(time);
};





//Skip to next/prev stations
select("p.prev").onclick=()=> ignoreHS ? 
skipVisibleStations("left") : skipAllStations("left");
select("p.next").onclick=()=> ignoreHS ? 
skipVisibleStations("right") : skipAllStations("right");




/*_______________________________________________________________________
													MAIN FUNCTION
_______________________________________________________________________*/
function createStations(obj){
select(".block2").innerHTML= "";	

Object.keys(obj).forEach((i,x)=>{
let p= create("p");
p.className= "station flexcenter";
p.dataset.hidden= "false";
p.innerHTML= checkProtocol(i,obj[i]);
select(".block2").append(p);	

p.onclick=()=>{
focusOnStation(p);
timer.innerHTML= `loading ${obj[i]}`;
audio.title= p.innerHTML;
//audio.dataset.url= checkProtocol(i,false);
audio.dataset.url= i;
audio.innerHTML= `<source src="${checkProtocol(i,false)}">
<source src="${offline}">`;
audio.load();
audio.play();
mediaControl(p.innerHTML);
};
});


select("span.middle").innerHTML=location.hash= genre[index];

if(currentStation()){
currentStation().className= "station flexcenter";
currentStation().classList.add(audio.className);
//mediaControl(currentStation().textContent);
}


hideStations();
}












//HELPER FUNCTIONS 🌛

//PROXY HTTP URLS WHEN SSL ENABLED-------------------------------------
function checkProtocol(url,name){
if(location.protocol!="https:") return name ? name : url; 
if(url.startsWith("https:")) return name ? name : url;
return name ? `!${name}` : `${proxy}${url}`;
}


//FORMAT STATIONS----------------------------------------------------
function focusOnStation(station){
allStations().forEach(i=>{
i.dataset.clicked= false;	
i.className= "station flexcenter";
});
//station.dataset.clicked= true;
station.classList.add("clicked");
}



//CHECK WINDOW HASH----------------------------------------------------
function checkHash(){
if(location.hash){
for(let i=0; i<genre.length; i++){
	if(location.hash.includes(genre[i])){
	index= i;
	break;
	}
}
}
}



/*
function restoreHideButton(){
localhidden= localStorage["localhidden"];
if(localhidden){
localhidden= JSON.parse(localhidden,null,1);
hidden= localhidden[genre[index]]||hidden;
}

//localhidden[genre[index]]= hidden;
//localStorage["localhidden"]= JSON.stringify(localhidden);
if(hidden) select(".show.hide").click();
select("textarea").value= hidden;
}
*/



//UPDATE TIMER & STATION INFO--------------------------------------------
function updatePage(klass,time){

switch(klass){
case "playing" : 
pause.innerHTML= "PAUSE";
//pause.style.pointerEvents= "auto";
document.title= `${audio.title} - KD Radio`;
timer.innerHTML= `Listening to ${audio.title} for ${time}`;
break;
case "paused" : 
pause.innerHTML= "PLAY";
//pause.style.pointerEvents= "auto";
document.title= `${audio.title} [Paused] - KD Radio`;
timer.innerHTML= `${audio.title} paused after ${time}`;
break;
case "offline" :
pause.innerHTML= "•&nbsp;•&nbsp;•";
//pause.style.pointerEvents= "none";
document.title= `${audio.title} [Offline] - KD Radio`;
timer.innerHTML= `${audio.title} is offline`;
break;
default:
pause.innerHTML= "•&nbsp;•&nbsp;•";
//pause.style.pointerEvents= "none";
document.title= `Loading ${audio.title}...`;
timer.innerHTML= `Loading ${audio.title}....`;
}


audio.className= klass;
if(currentStation()){
currentStation().className= "station flexcenter";
currentStation().classList.add(audio.className);
}

}



//FIND CURRENT STATION--------------------------------------------------
function currentStation(){
let urls= Object.keys(list[index]);
for(let i=0; i<allStations().length; i++){
if(audio.dataset.url==urls[i]){
return allStations()[i];
}
}
return false;
}




//FORMAT TIME--------------------------------------------------------------
function formatTime(time){
let hms= new Date(time).toISOString().substr(11,8).split(":");
let h= +hms[0], m= +hms[1], s= +hms[2];

let H= h;
let M= m;

switch(h){
case 0: H= ""; break;
case 1: H= "1 hour, "; break;
default:H= `${h} hours, `;
}

switch(m){
case 0: M= ""; break;
case 1: M= "1 min. & "; break;
default:M= `${m} min. & `;
}

return `${H}${M}${s} sec.`;

}




//MEDIASESSION------------------------------------------------------------
function mediaControl(station){
if(!mediaSession) return;
navigator.mediaSession.setActionHandler('previoustrack',()=>{
ignoreHS ? skipAllStations("left") : skipVisibleStations("left");
});

navigator.mediaSession.setActionHandler('nexttrack',()=>{
ignoreHS ? skipAllStations("right") : skipVisibleStations("right");
});

navigator.mediaSession.metadata= new MediaMetadata({
title: station,
artist: "Kawiesh's Radio Collection",
album: `@ ${location.hostname} !`,
artwork: getArtwork([96,128,192,256,384,512])
});

}


//MEDIASESSION ARTWORK----------------------------------------------------
function getArtwork(sizes){
let arr= [];
sizes.forEach(i=>{
let obj= {};
obj.sizes= `${i}x${i}`;
obj.type= `image/png`;
obj.src= `../resources/artwork/background-${i}x${i}.png`;
arr.push(obj);
});

return arr;
}



//SKIP ALL STATIONS-------------------------------------------------------
function skipAllStations(direction){
if(audio.title=="") return;

if(currentStation()){

if(direction=="left"){
let last= select("p.station:last-child");
let prev= currentStation().previousElementSibling;
if(prev) prev.click(); else last.click();
}
else{
let first= select("p.station:first-child");
let next= currentStation().nextElementSibling;
if(next) next.click(); else first.click();
}

}
else{

stationGone();
skipAllStations(direction);
}	
	
}



//SKIP VISIBLE STATIONS ONLY----------------------------------------------
function skipVisibleStations(direction){
if(audio.title=="") return;
	
if(currentStation()){
let visibleStations= [...allStations()].filter(i=> i.dataset.hidden=="false");

let first= visibleStations[0];
let last= visibleStations[visibleStations.length-1];

if(direction=="left"){
let prev= currentStation().previousElementSibling;
if(!prev) prev= last;
while(prev.dataset.hidden=="true"){
prev= prev.previousElementSibling;
}

prev.click();

}
else{
let next= currentStation().nextElementSibling;
if(!next) next= first;
while(next.dataset.hidden=="true"){
next= next.nextElementSibling;
}
next.click();
}

}
else{
stationGone();
skipStations(direction);
}	
	
}


//RESTORE STATION WHEN GENRE IS CHANGED-----------------------------------
function stationGone(){
for(let i=0; i<list.length; i++){

let a= Object.keys(list[i]);
for(let j=0; j<a.length; j++){
	if(audio.dataset.url==a[j]){
	index= i;
	createStations(list[index]);
	return;
	}
}
	
}
}



/*
© Kawiesh  ❣️❣️❣️🤗🤗❣️❣️❣️❣️❣️❣️
*/


let overlay= select("section.block6");
overlay.innerHTML= `
<div class="modal minimized">

<div class="customlist flexcenter" data-nosnippet title="select stations to hide">
<select class="customlist" multiple></select>
<button class="customlist">HIDE</button>
</div>
<button data-mode="hide">HIDE ALL STATIONS</button>
<button data-mode="show">SHOW ALL STATIONS</button>


<p class="customlist">Updated after your mom</p>

<div class="sleep flexcenter" data-nosnippet title="close tab after x minutes">
<input class="sleep" type="number">
<button class="sleep">SLEEP</button>
</div>



<p class="skip flexcenter" data-ignore="no">
<input type="checkbox">
ignore hidden stations during skipping:
</p>

<p class="updated">Updated after your mom</p>
<p class="close flexcenter">x</span>



</div>`;















//Choose how skipping stations work
select(".skip input").checked= ignoreHS;
select(".skip input").oninput= function(){
if(this.checked){
ignoreHS= true;
this.parentNode.dataset.ignore= "yes";
}
else{
ignoreHS= false;
this.parentNode.dataset.ignore= "no";
}
};



let modal= select("div.modal");

//Open modal
select("p.settings").onclick=()=>{
newDropdownOptions();
restoreSelectedStations();
overlay.classList.remove("transparent");
modal.classList.remove("minimized");
};


//Close modal
select("p.close").onclick=()=>{
modal.classList.add("minimized");
overlay.classList.add("transparent");
};


//Open about page
select(".about").onclick=()=>{
window.open("about","_blank");
}



let dropdown= select("select.customlist");
let message= select("p.customlist");

dropdown.onchange=()=>{
message.innerHTML= "Click on hide to confirm your selection";
};


//Create fresh dropdown
function newDropdownOptions(){
dropdown.innerHTML= message.innerHTML= dropdown.value= "";
Object.keys(list[index]).forEach(i=>{
let option= create("option");
option.innerHTML= list[index][i];
dropdown.append(option);
});
}

//Initial setup on page load
newDropdownOptions();


let localblocklist= {};

let hide= select("button.customlist");

hide.onclick= function(){
message.innerHTML= `
${selectedStations().length} stations hidden!`;
localblocklist[genre[index]]= selectedStations();
localStorage["localblocklist"]= JSON.stringify(localblocklist);
hideStations();
}; //allfew.innerHTML= "ALL"


//collapsed.click() lol to maintain state❤️



//Check selected stations
function selectedStations(){
return [...dropdown.selectedOptions].map(i=> i.index);
}


function restoreSelectedStations(){
let amount= 0;
let options= selectAll("option");
allStations().forEach((i,x)=>{
if(i.dataset.hidden=="true"){
options[x].selected= true;
amount++;
}
});
message.innerHTML= `${amount} stations hidden!`;
}


//hideStations();

//get array
//select stations










let sleeptimer= create("p");
sleeptimer.className= "sleeptimer";
document.body.append(sleeptimer);


//Sleeptimer-------------------------------------------
select("button.sleep").onclick= function(){
let mins= this.previousElementSibling.value;
if(mins>0){
let time= mins*60*1000;
let left= time;
sleeptimer.classList.add("flexcenter");
writeIt(time,left);

/*
setTimeout(()=>{
document.write("closed")
},time);
*/
}
else alert("INVALID TIME");
};



function writeIt(x,y){
if(x>1000){
x= x-1000;
sleeptimer.innerHTML= `Radio will stop playing after ${formatTime(x)}`;
setTimeout(()=>{ writeIt(x,y); },1000);
}
else{
audio.pause();
sleeptimer.innerHTML= `Radio stopped after ${formatTime(y)}`;
document.title= "KD Radio - Stopped";
}
}



//Last updated-----------------------RATE LIMIT >___<

//lastUpdated();


function lastUpdated(){
	
let file= location.href.includes("bollywood") ? "bollywood" : "suriname";	
let url= `https://api.github.com/repos/nostalgickd/nostalgickd.github.io/commits?path=${file}.js`;

fetch(url, {
authorization: "token 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"
}).then(r=> r.json())
.then(d=> {
let date= new Date(d[0].commit.author.date);

let _date= date.toLocaleDateString("en-US",{
//weekday: 'long',
year: 'numeric', 
month: 'short', 
day: 'numeric'
});

let _time= date.toLocaleTimeString("en-US",{
hour: '2-digit', 
minute: '2-digit'
});

//alert(` ${_date} @ ${_time}`);
select("p.updated").innerHTML= `Stations updated on ${_date} @ ${_time}`;

})
.catch(x=> select("p.updated").innerHTML= x.message);

}



/*
function restoreSelectedStations(){
[...selectAll("p.station")].filter((i,x)=>{
if(i.dataset.hidden=="true") return x;
});
}
*/




/*_______________________________________________________________________
													SVG ICONS
_______________________________________________________________________*/
let icons={
	
"loading" : `<!-- By Sam Herbert (@sherb), for everyone. More @ http://goo.gl/7AJzbL -->
<svg width="120" height="30" viewBox="0 0 120 30" xmlns="http://www.w3.org/2000/svg" fill="#fff">
    <circle cx="15" cy="15" r="15">
        <animate attributeName="r" from="15" to="15"
                 begin="0s" dur="0.8s"
                 values="15;9;15" calcMode="linear"
                 repeatCount="indefinite" />
        <animate attributeName="fill-opacity" from="1" to="1"
                 begin="0s" dur="0.8s"
                 values="1;.5;1" calcMode="linear"
                 repeatCount="indefinite" />
    </circle>
    <circle cx="60" cy="15" r="9" fill-opacity="0.3">
        <animate attributeName="r" from="9" to="9"
                 begin="0s" dur="0.8s"
                 values="9;15;9" calcMode="linear"
                 repeatCount="indefinite" />
        <animate attributeName="fill-opacity" from="0.5" to="0.5"
                 begin="0s" dur="0.8s"
                 values=".5;1;.5" calcMode="linear"
                 repeatCount="indefinite" />
    </circle>
    <circle cx="105" cy="15" r="15">
        <animate attributeName="r" from="15" to="15"
                 begin="0s" dur="0.8s"
                 values="15;9;15" calcMode="linear"
                 repeatCount="indefinite" />
        <animate attributeName="fill-opacity" from="1" to="1"
                 begin="0s" dur="0.8s"
                 values="1;.5;1" calcMode="linear"
                 repeatCount="indefinite" />
    </circle>
</svg>`,

	
"suriname" : `<svg viewBox="0 0 640 480"><path fill="#377e3f" d="M.1 0h640v480H.1z"/><path fill="#fff" d="M.1 96h640v288H.1z"/><path fill="#b40a2d" d="M.1 144h640v192H.1z"/><path fill="#ecc81d" d="M320 153.2l56.4 173.6-147.7-107.3h182.6L263.6 326.8z"/>SR</svg>`,


"india" : `<svg viewBox="0 0 640 480"><path fill="#f93" d="M0 0h640v160H0z"/><path fill="#fff" d="M0 160h640v160H0z"/><path fill="#128807" d="M0 320h640v160H0z"/><g transform="matrix(3.2 0 0 3.2 320 240)"><circle r="20" fill="#008"/><circle r="17.5" fill="#fff"/><circle r="3.5" fill="#008"/><g id="d"><g id="c"><g id="b"><g id="a" fill="#008"><circle r=".9" transform="rotate(7.5 -8.8 133.5)"/><path d="M0 17.5L.6 7 0 2l-.6 5L0 17.5z"/></g><use width="100%" height="100%" transform="rotate(15)" xlink:href="#a"/></g><use width="100%" height="100%" transform="rotate(30)" xlink:href="#b"/></g><use width="100%" height="100%" transform="rotate(60)" xlink:href="#c"/></g><use width="100%" height="100%" transform="rotate(120)" xlink:href="#d"/><use width="100%" height="100%" transform="rotate(-120)" xlink:href="#d"/></g>IN</svg>`,
	
	
"left" : `<svg viewBox="0 0 24 24">
<g> <path d="M2 11l7-9v5c11.953 0 13.332 9.678 13 15c-.502-2.685-.735-7-13-7v5l-7-9z"/></g></svg>`,

"right" : `<svg viewBox="0 0 24 24">
<g><path d="M22 11l-7-9v5C3.047 7 1.668 16.678 2 22c.502-2.685.735-7 13-7v5l7-9z"/></g></svg>`,

"cross" : `<svg viewBox="0 0 24 24">
<path d="M15.59 7L12 10.59L8.41 7L7 8.41L10.59 12L7 15.59L8.41 17L12 13.41L15.59 17L17 15.59L13.41 12L17 8.41L15.59 7Z"/></svg>`,

"close"	: `<svg viewBox="0 0 64 64">
<path d="M62 10.6L53.4 2L32 23.4L10.6 2L2 10.6L23.4 32L2 53.4l8.6 8.6L32 40.6L53.4 62l8.6-8.6L40.6 32z"/></svg>`,
};


if(isBw) isBw.innerHTML= icons.suriname;
if(isSr) isSr.innerHTML= icons.india;


prevGenre.innerHTML= icons.left;
nextGenre.innerHTML= icons.right;
select("p.close").innerHTML= icons.close;


//if(hidden) select(".show.hide").click();


select("p.finishing").innerHTML= `${icons.loading}`;

setTimeout(()=>{
select("p.finishing").remove();
},1000);



function allStations(display){
let stations= selectAll("p.station");
switch(display){
case "hide" : stations.forEach(i=> i.dataset.hidden= "true");
break;
case "show" : stations.forEach(i=> i.dataset.hidden= "false");
break;
default: return stations;
}
}


//Show and hide stations
function hideStations(){



let arr= blocklist[genre[index]];
let localblocklist= localStorage["localblocklist"];

if(localblocklist){
localblocklist= JSON.parse(localblocklist,null,1);
arr= localblocklist[genre[index]]||blocklist[genre[index]];
}




//let options= selectAll("option");



let hidden= select(".station[data-hidden='true']") ? true : false;
allStations().forEach(i=> i.dataset.hidden= "false");


if(!hidden){
arr.forEach(i=>{
//options[i].selected= true; 
allStations()[i].dataset.hidden= "true";
});

allfew.innerHTML= "ALL";
}
else{
allfew.innerHTML= "FEW";
}

//restoreSelectedStations();
select("textarea").value= JSON.stringify(localblocklist);
}



allfew.onclick=()=>{


hideStations();

/*

if(!hidden){
hideStations();
}
else all.innerHTML= "FEW";

*/

};



selectAll("button[data-mode]").forEach(i=>{
i.onclick= function(){
let mode= this.dataset.mode;
dropdown.value= "";
if(mode=="hide") selectAll("option").forEach(i=> i.selected= true);
allStations(this.dataset.mode);
message.innerHTML= `
${selectedStations().length} stations hidden!`;
localblocklist[genre[index]]= selectedStations();
localStorage["localblocklist"]= JSON.stringify(localblocklist);
};
});