<?php
if (!defined('access') || !access) return;
$musicCfg = loadConfig('music');
if (!is_array($musicCfg) || empty($musicCfg['settings']['enabled'])) return;
$musicSettings = $musicCfg['settings'];
$musicMode = in_array($musicSettings['source_mode'] ?? '', array('local','youtube','hybrid'), true) ? $musicSettings['source_mode'] : 'local';
$musicYoutubeUrl = trim((string)($musicSettings['youtube_url'] ?? ''));
$musicYoutube = array('videoId'=>'','playlistId'=>'');
if ($musicYoutubeUrl !== '') {
    $parts = @parse_url($musicYoutubeUrl); $query = array();
    if (!empty($parts['query'])) parse_str($parts['query'], $query);
    if (!empty($query['list']) && preg_match('/^[a-zA-Z0-9_-]+$/', $query['list'])) $musicYoutube['playlistId'] = $query['list'];
    if (!empty($query['v']) && preg_match('/^[a-zA-Z0-9_-]{6,20}$/', $query['v'])) $musicYoutube['videoId'] = $query['v'];
    $host = strtolower((string)($parts['host'] ?? ''));
    if ($musicYoutube['videoId'] === '' && in_array($host,array('youtu.be','www.youtu.be'),true)) { $candidate=trim((string)($parts['path'] ?? ''),'/'); if(preg_match('/^[a-zA-Z0-9_-]{6,20}$/',$candidate))$musicYoutube['videoId']=$candidate; }
    if ($musicYoutube['videoId'] === '' && preg_match('#/(?:embed|shorts)/([a-zA-Z0-9_-]{6,20})#',(string)($parts['path'] ?? ''),$m)) $musicYoutube['videoId']=$m[1];
}
$musicRealm = class_exists('NexoraRealm') ? NexoraRealm::active() : 'legacy';
$musicTracks = array();
foreach ($musicCfg['tracks'] as $track) {
    if (empty($track['enabled']) || !in_array($track['realm'] ?? 'both', array('both',$musicRealm), true)) continue;
    $src = trim((string)($track['url'] ?? ''));
    if ($src === '' && !empty($track['file'])) $src = __PATH_TEMPLATE__ . 'audio/' . rawurlencode(basename($track['file']));
    if ($src === '') continue;
    $musicTracks[] = array('title'=>(string)($track['title'] ?? 'Pista Nexora'),'artist'=>(string)($track['artist'] ?? ''),'src'=>$src,'order'=>(int)($track['order'] ?? 100));
}
usort($musicTracks, function($a,$b){ return $a['order'] <=> $b['order']; });
$hasYoutube = $musicYoutube['videoId'] !== '' || $musicYoutube['playlistId'] !== '';
/* Evita un reproductor invisible si se pegó YouTube pero quedó seleccionado "local" sin pistas. */
if ($musicMode === 'local' && !$musicTracks && $hasYoutube) $musicMode = 'youtube';
if ($musicMode === 'youtube' && !$hasYoutube) return;
if ($musicMode === 'local' && !$musicTracks) return;
if ($musicMode === 'hybrid' && !$hasYoutube && !$musicTracks) return;
$GLOBALS['nex_music_rendered'] = true;
?>
<aside class="nex-music" data-nex-music data-mode="<?php echo htmlspecialchars($musicMode,ENT_QUOTES,'UTF-8'); ?>" data-volume="<?php echo max(0,min(100,(int)($musicSettings['initial_volume'] ?? 35))); ?>" data-shuffle="<?php echo !empty($musicSettings['shuffle'])?'1':'0'; ?>" data-loop="<?php echo !isset($musicSettings['loop'])||$musicSettings['loop']?'1':'0'; ?>" data-remember="<?php echo !isset($musicSettings['remember_state'])||$musicSettings['remember_state']?'1':'0'; ?>">
    <div class="nex-music__consent" data-music-consent role="dialog" aria-labelledby="nex-music-consent-title" aria-describedby="nex-music-consent-copy">
        <span class="nex-music__consent-sigil" aria-hidden="true">N</span>
        <div class="nex-music__consent-copy"><small>IDENTIDAD SONORA</small><strong id="nex-music-consent-title">¿Activamos la ambientación?</strong><p id="nex-music-consent-copy">Nexora puede acompañar tu recorrido con música. Tú decides el volumen y cuándo detenerla.</p></div>
        <div class="nex-music__consent-actions"><button type="button" class="is-primary" data-music-accept>Activar sonido</button><button type="button" data-music-decline>Ahora no</button></div>
    </div>
    <button class="nex-music__reopen" type="button" data-music-reopen aria-label="Abrir opciones de ambientación">♪</button>
    <div class="nex-music__panel">
        <div class="nex-music__brand"><span class="nex-music__sigil">N</span><span><small><?php echo htmlspecialchars($musicSettings['subtitle'] ?? 'Sonido del ecosistema',ENT_QUOTES,'UTF-8'); ?></small><strong data-music-title><?php echo htmlspecialchars($musicSettings['title'] ?? 'Ambientación Nexora',ENT_QUOTES,'UTF-8'); ?></strong><em data-music-artist></em></span></div>
        <div class="nex-music__controls"><button type="button" data-music-prev aria-label="Anterior">‹</button><button class="is-main" type="button" data-music-play aria-label="Reproducir o pausar">▶</button><button type="button" data-music-next aria-label="Siguiente">›</button><button type="button" data-music-mute aria-label="Silenciar">♪</button><input data-music-volume type="range" min="0" max="100" aria-label="Volumen"><button type="button" data-music-minimize aria-label="Minimizar">—</button></div>
    </div>
    <audio data-music-audio preload="none"></audio>
    <div class="nex-music__youtube" data-music-youtube></div>
    <script type="application/json" data-music-playlist><?php echo json_encode($musicTracks, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); ?></script>
    <script type="application/json" data-music-youtube-config><?php echo json_encode($musicYoutube, JSON_UNESCAPED_SLASHES|JSON_UNESCAPED_UNICODE); ?></script>
</aside>
