/home/rcfmro/.trash/script.js.2
/* RCFM v5 — main script
   - uses STREAM_URL exactly as provided
   - polls status-json.xsl for current title and listeners (Icecast)
   - visitors via api/visitors.php
   - chat via api/chat.php (POST)
*/

const STREAM_URL = "https://radio.rcfm.ro/autodj";
const STATUS_URL = "https://radio.rcfm.ro/status-json.xsl";

const playBtn = document.getElementById('playBtn');
const nowTitle = document.getElementById('nowTitle');
const eqSim = document.getElementById('eqSim');
const visualizer = document.getElementById('visualizer');
const bars = visualizer ? visualizer.querySelectorAll('.bar') : [];
const volumeRange = document.getElementById('volumeRange');
const muteBtn = document.getElementById('muteBtn');
const listenersEl = document.getElementById('listeners');
const visitorsEl = document.getElementById('visitors');
const logoRotor = document.getElementById('logoRotor');
const loader = document.getElementById('loader');
const themeSelect = document.getElementById('themeSelect');
const djOn = document.getElementById('djOn');
const yearEl = document.getElementById('year');

yearEl.textContent = new Date().getFullYear();

let audio = null;
let playing = false;
let visualizerInterval = null;

// helper: start loader fade
window.addEventListener('load', ()=> {
  setTimeout(()=> {
    if(loader) loader.style.display='none';
  }, 600);
});

// create audio element when needed
function createAudio(){
  if(audio) return;
  audio = new Audio();
  audio.src = STREAM_URL;
  audio.crossOrigin = "anonymous";
  audio.preload = 'none';
  audio.volume = volumeRange.value / 100;
  audio.addEventListener('playing', onPlaying);
  audio.addEventListener('pause', onPause);
  audio.addEventListener('error', (e)=> {
    nowTitle.textContent = 'Stream unavailable';
    console.warn('Audio error', e);
  });
}

// start/stop
function startPlay(){
  createAudio();
  if(!audio) return;
  const p = audio.play();
  if(p && p.catch) p.catch(err=> {
    nowTitle.textContent = 'Apăsați din nou pentru a porni';
    console.warn('Play blocked', err);
  });
}
function stopPlay(){
  if(!audio) return;
  audio.pause();
  try{ audio.src = ''; }catch(e){}
  audio = null;
  playing=false;
  playBtn.classList.remove('playing');
  stopVisualizer();
  logoRotor && (logoRotor.style.transform = '');
}

// events
playBtn.addEventListener('click', ()=>{
  if(!playing) startPlay(); else stopPlay();
});
volumeRange.addEventListener('input', (e)=>{
  const v = Number(e.target.value)/100;
  if(audio) audio.volume = v;
  muteBtn.textContent = v===0 ? '🔈' : '🔊';
});
muteBtn.addEventListener('click', ()=>{
  if(!audio){ volumeRange.value=0; muteBtn.textContent='🔈'; return; }
  audio.muted = !audio.muted;
  muteBtn.textContent = audio.muted ? '🔈' : '🔊';
});

// playing callbacks
function onPlaying(){
  playing=true;
  playBtn.classList.add('playing');
  startVisualizer();
  startLogoRotor();
}
function onPause(){
  playing=false;
  playBtn.classList.remove('playing');
  stopVisualizer();
  stopLogoRotor();
}

// visualizer simulation (not FFT): responsive and dynamic
function startVisualizer(){
  if(visualizerInterval) return;
  visualizerInterval = setInterval(()=>{
    bars.forEach((b,i)=>{
      const base = [30,45,60,42,34][i] || 40;
      const variance = Math.random()*base;
      b.style.height = (variance + base*0.4) + '%';
    });
    // animate eq
    if(eqSim){
      eqSim.querySelectorAll('span').forEach((s, idx)=>{
        s.style.height = (Math.random() * (20 + idx*8) + 10) + 'px';
      });
    }
  }, 220);
}
function stopVisualizer(){
  if(visualizerInterval) { clearInterval(visualizerInterval); visualizerInterval=null; }
  bars.forEach((b)=> b.style.height = '20%');
  if(eqSim) eqSim.querySelectorAll('span').forEach(s=>s.style.height='10px');
}

// logo rotor
let rotorInterval = null;
function startLogoRotor(){
  if(!logoRotor) return;
  let deg = 0;
  rotorInterval = setInterval(()=>{
    deg = (deg + 0.6) % 360;
    logoRotor.style.transform = `rotate(${deg}deg)`;
    logoRotor.style.opacity = 0.98;
  }, 20);
}
function stopLogoRotor(){ if(rotorInterval){ clearInterval(rotorInterval); rotorInterval=null; logoRotor.style.transform=''; } }

// fetch now playing + listeners
async function fetchStatus(){
  try{
    const r = await fetch(STATUS_URL, {cache:'no-store'});
    if(!r.ok) throw new Error('status '+r.status);
    const j = await r.json();
    let src = j.icestats && j.icestats.source ? j.icestats.source : null;
    if(Array.isArray(src)) src = src[0];
    const title = src && src.title ? src.title : 'Live';
    nowTitle.textContent = title;
    // listeners (icecast)
    const lis = src && (src.listeners || src.listener) ? (src.listeners || src.listener) : (j.icestats && j.icestats.listeners ? j.icestats.listeners : null);
    if(lis !== null && lis !== undefined) listenersEl.textContent = `Ascultători: ${lis}`;
    else listenersEl.textContent = `Ascultători: —`;
    return {title, listeners: lis};
  }catch(err){
    console.warn('status fetch failed', err);
    nowTitle.textContent = 'Loading…';
    listenersEl.textContent = `Ascultători: —`;
    return null;
  }
}

// visitors via API (server-side increments)
async function fetchVisitors(){
  try{
    const r = await fetch('api/visitors.php?op=get', {cache:'no-store'});
    if(!r.ok) throw new Error('vis '+r.status);
    const j = await r.json();
    visitorsEl.textContent = `Vizitatori: ${j.online || 0}`;
  }catch(e){ console.warn('visitors fetch', e); visitorsEl.textContent='Vizitatori: —' }
}

// polling
fetchStatus(); setInterval(fetchStatus, 5000);
fetchVisitors(); setInterval(fetchVisitors, 8000);

// theme change
themeSelect.addEventListener('change', (e)=> {
  document.documentElement.setAttribute('data-theme', e.target.value);
});

// DJ ON -> visually show ON AIR
djOn.addEventListener('change', ()=> {
  if(djOn.checked){
    // show ON AIR LED
    if(!document.querySelector('.onair')){
      const on = document.createElement('div');
      on.className='onair';
      on.innerHTML = '<span class="dot"></span><strong>ON AIR</strong>';
      document.body.appendChild(on);
    }
  } else {
    const ex = document.querySelector('.onair'); if(ex) ex.remove();
  }
});

// share helpers
function getShareText(){
  const title = nowTitle.textContent || 'RCFM';
  return encodeURIComponent(`${title} — Ascultă acum RCFM: https://rcfm.ro`);
}
document.getElementById('shareWhatsApp').addEventListener('click', ()=> {
  window.open(`https://wa.me/?text=${getShareText()}`, '_blank');
});
document.getElementById('shareTelegram').addEventListener('click', ()=> {
  window.open(`https://t.me/share/url?url=https://rcfm.ro&text=${getShareText()}`, '_blank');
});
document.getElementById('shareX').addEventListener('click', ()=> {
  window.open(`https://twitter.com/intent/tweet?text=${getShareText()}`, '_blank');
});

// visitors increment on load (server-side)
fetch('api/visitors.php?op=hit', {method:'GET'}).catch(()=>{});

// simple chat shortcut (link opens chat.html)
document.querySelectorAll('.chat-link').forEach(a=>a.href='chat.html');

// Anti-devtools (best-effort)
window.addEventListener('contextmenu', e=>e.preventDefault(), {capture:true});
window.addEventListener('keydown', function(e){ if(e.key==='F12'||(e.ctrlKey&&e.shiftKey&&(e.key==='I'||e.key==='J'||e.key==='C'))||(e.ctrlKey&&e.key==='U')) { e.preventDefault(); alert('Accesul la instrumente dezvoltator este restricționat.'); } }, {capture:true});
(function detectDevTools(){
  let last = window.outerWidth - window.innerWidth;
  setInterval(()=>{ const diff = window.outerWidth - window.innerWidth; if(Math.abs(diff-last)>160){ try{ stopPlay(); nowTitle.textContent='DevTools detectat — reîncarcă pagina'; document.body.style.transition='background .2s'; document.body.style.background='linear-gradient(180deg,#23001e,#37004b)'; setTimeout(()=>document.body.style.background=''); }catch(e){} } last = diff; }, 1500);
})();