<?php
if (session_status() === PHP_SESSION_NONE) {
    session_start();
}
session_write_close();
require_once __DIR__ . '/includes/stream_lib.php';

$pageTitle = "Radio Galaxy FX • Popout Player";
$pageClass = 'page-player-popout';
include __DIR__ . '/includes/header.php';

$playerUrls = smurf_get_player_urls();
$listenUrl = trim((string)($playerUrls['raw'] ?? ''));
$audioUrl = '/stream-proxy.php';
$m3uUrl = $listenUrl !== '' ? preg_replace('~(?:/stream)?$~', '/stream.m3u', $listenUrl) : '';
$xspfUrl = $listenUrl !== '' ? preg_replace('~(?:/stream)?$~', '/stream.xspf', $listenUrl) : '';
?>
<main class="content-area">
  <div class="content-wrapper">
    <section class="content-card popout-player-card">
      <div class="player-pop-layout">
        <div class="player-pop-copy">
          <div class="player-pop-kicker">
            <img src="/img/nav-icons/player.png" alt="" style="width:22px;height:22px;object-fit:contain;">
            Dedicated Popout Stream
          </div>

          <h1 class="player-pop-title">Radio Galaxy FX</h1>
          <p class="player-pop-subtitle">
            Your beautiful little player window for the station. Same country heart, same jukebox soul,
            and the same live now playing feed as the home page.
          </p>

          <div class="player-nowplaying">
            <div class="player-nowplaying-label">Now Playing</div>
            <div id="popup-nowplaying-wrap"><?php include __DIR__ . '/data/nowplaying.php'; ?></div>
            <div class="player-meta-row">
              <span class="player-meta-chip">📻 Live stream ready</span>
              <span class="player-meta-chip">🎵 Auto refresh every 30 sec</span>
            </div>
          </div>

          <div class="player-glow-line"></div>

          <div class="player-audio-shell">
            <audio controls preload="none" playsinline>
              <source src="<?= htmlspecialchars($audioUrl, ENT_QUOTES, 'UTF-8') ?>" type="audio/mpeg">
              Your browser does not support the audio element.
            </audio>
          </div>

          <div class="player-action-row">
            <?php if ($listenUrl !== ''): ?>
              <a class="button play-btn" href="<?= htmlspecialchars($listenUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Open Stream Link</a>
            <?php endif; ?>
            <?php if ($m3uUrl !== ''): ?>
              <a class="button" href="<?= htmlspecialchars($m3uUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Open External Source</a>
            <?php endif; ?>
            <?php if ($xspfUrl !== ''): ?>
              <a class="button" href="<?= htmlspecialchars($xspfUrl, ENT_QUOTES, 'UTF-8') ?>" target="_blank" rel="noopener">Open External Source 2</a>
            <?php endif; ?>
          </div>
        </div>

        <div class="player-pop-visual" style="background-image:linear-gradient(rgba(8,10,26,.72), rgba(8,10,26,.78)), url('/img/logo.png');background-size:cover;background-position:center;border-radius:24px;padding:24px;">
          <div class="player-orb" aria-hidden="true">
            <div class="player-orb-center">🎧</div>
          </div>
          <div class="eq-wrap" aria-hidden="true">
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
            <span class="eq-bar"></span>
          </div>
          <div class="center-text" style="margin-top:10px;">
            <img src="/img/logo.png" alt="Radio Galaxy FX artwork" style="width:min(100%,340px);border-radius:20px;border:1px solid rgba(255,214,135,.22);box-shadow:0 16px 30px rgba(0,0,0,.35);display:block;margin:0 auto;">
          </div>
        </div>
      </div>
    </section>
  </div>
</main>

<script>
async function refreshPopupNowPlaying() {
  try {
    const res = await fetch('/data/nowplaying.php?ts=' + Date.now(), { cache: 'no-store' });
    if (!res.ok) throw new Error('Failed to load now playing');
    const html = await res.text();
    const wrap = document.getElementById('popup-nowplaying-wrap');
    if (wrap && html.trim() !== '') {
      wrap.innerHTML = html;
    }
  } catch (err) {
    console.error(err);
  }
}

refreshPopupNowPlaying();
setInterval(refreshPopupNowPlaying, 30000);
</script>

<script>
(function(){
 const audio=document.querySelector('audio');
 if(!audio)return;
 let retryDelay=3000, timer=null, last=Date.now();
 function reconnect(){
   clearTimeout(timer);
   timer=setTimeout(()=>{
     const src=audio.getAttribute('src').split('?')[0];
     audio.src=src+'?t='+Date.now();
     audio.load();
     audio.play().catch(()=>{});
   },retryDelay);
   retryDelay=Math.min(retryDelay+2000,15000);
 }
 audio.addEventListener('playing',()=>{retryDelay=3000;last=Date.now();});
 audio.addEventListener('timeupdate',()=>{last=Date.now();});
 audio.addEventListener('error',reconnect);
 audio.addEventListener('stalled',reconnect);
 setInterval(()=>{
   if(!audio.paused && Date.now()-last>20000) reconnect();
 },5000);
})();
</script>

</body>
</html>
