<?php
/**
 * index.php (PHP 8.2) - PWA Player
 * Requiere: ../concha.php (define $nombresitio, $d_color_titulo, $ip_stream, etc.)
 */

declare(strict_types=1);

// Producción: ocultar errores en pantalla (dejá logs activos en el servidor)
@ini_set('display_errors', '0');
error_reporting(E_ALL);

require_once __DIR__ . '/../concha.php';

// Helpers
function h(string $s): string {
    return htmlspecialchars($s, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8');
}

function safe_color(?string $c, string $fallback = '#111111'): string {
    $c = trim((string)$c);
    if ($c === '') return $fallback;

    // Acepta: #RGB, #RRGGBB, #RRGGBBAA
    if (preg_match('/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6}|[0-9a-fA-F]{8})$/', $c)) {
        return $c;
    }

    // Acepta: rgb()/rgba()
    if (preg_match('/^rgba?\(\s*\d{1,3}\s*,\s*\d{1,3}\s*,\s*\d{1,3}(\s*,\s*(0|1|0?\.\d+))?\s*\)$/', $c)) {
        return $c;
    }

    // Acepta: hsl()/hsla()
    if (preg_match('/^hsla?\(\s*\d{1,3}\s*,\s*\d{1,3}%\s*,\s*\d{1,3}%(\s*,\s*(0|1|0?\.\d+))?\s*\)$/', $c)) {
        return $c;
    }

    return $fallback;
}

// Defaults por si algo no viene en concha.php
$nombresitio_safe = h((string)($nombresitio ?? 'Radio'));
$theme_color      = safe_color($d_color_titulo ?? '#111111', '#111111');
$ip_stream_safe   = h((string)($ip_stream ?? ''));

// Headers
header('Content-Type: text/html; charset=UTF-8');
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="UTF-8">
  <title><?= $nombresitio_safe; ?> – Radio</title>
  <meta name="viewport" content="width=device-width, initial-scale=1">

  <!-- PWA -->
  <link rel="manifest" href="manifest.php">
  <meta name="theme-color" content="<?= h($theme_color); ?>">
  <link rel="apple-touch-icon" href="icon-192.png">
  <link rel="icon" href="icon-192.png">

  <!-- Estilos y fuentes -->
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <link href="https://fonts.googleapis.com/css2?family=Poppins:wght@300;700&display=swap" rel="stylesheet">

  <style>
    body{
      background: <?= h($theme_color); ?>;
      color:#fff;
      font-family:'Poppins',sans-serif;
      height:100vh;
      margin:0;
      display:flex;
      flex-direction:column;
      justify-content:center;
      align-items:center;
      text-align:center;
    }

    h1{
      font-size:1.8rem;
      margin-bottom:2rem;
    }

    #playBtn{
      width:110px;
      height:110px;
      border-radius:50%;
      border:4px solid #fff;
      color:#fff;
      background:transparent;
      display:flex;
      justify-content:center;
      align-items:center;
      transition:all .3s;
      padding:0;
      cursor:pointer;
    }

    #playBtn:hover{
      background:#fff;
      color:<?= h($theme_color); ?>;
    }

    #playBtn svg{
      width:42px;
      height:42px;
      fill:currentColor;
      display:block;
    }

    #offlineMsg{
      display:none;
      margin-top:1.5rem;
      font-size:1rem;
      color:#fff;
    }

    .modal-icon{
      width:20px;
      height:20px;
      fill:currentColor;
      vertical-align:middle;
      display:inline-block;
    }

    .inline-icon{
      width:18px;
      height:18px;
      fill:currentColor;
      vertical-align:-3px;
      display:inline-block;
    }
  </style>
</head>
<body>

  <img src="icon-512.png" alt="Icono del sitio" class="img-fluid mb-3" style="max-width:120px;">
  <h1><?= $nombresitio_safe; ?></h1>

  <button id="playBtn" type="button" aria-label="Reproducir">
    <svg id="playIcon" viewBox="0 0 24 24" aria-hidden="true">
      <path d="M8 5v14l11-7z"></path>
    </svg>
  </button>

  <div id="offlineMsg">Sin conexión</div>

  <audio id="player" preload="none" src="<?= $ip_stream_safe; ?>"></audio>

  <!-- Modal instalación -->
  <div class="modal fade" id="installModal" tabindex="-1" aria-hidden="true">
    <div class="modal-dialog modal-dialog-centered">
      <div class="modal-content bg-dark text-white border-light">
        <div class="modal-header border-0">
          <h5 class="modal-title">
            <svg class="modal-icon me-2" viewBox="0 0 24 24" aria-hidden="true">
              <path d="M5 20h14v-2H5v2zm7-18l-5.5 5.5h3.5V15h4V7.5H17.5L12 2z"></path>
            </svg>
            Instalá la App
          </h5>
          <button type="button" class="btn-close btn-close-white" data-bs-dismiss="modal" aria-label="Cerrar"></button>
        </div>
        <div class="modal-body">
          <p>Agregá esta radio a tu inicio para acceder más fácil.</p>

          <div id="iosTip" class="d-none">
            <p>
              En <strong>iOS</strong> tocá
              <svg class="inline-icon mx-1" viewBox="0 0 24 24" aria-hidden="true">
                <path d="M12 3l4 4h-3v6h-2V7H8l4-4zm-7 9h2v7h10v-7h2v9H5v-9z"></path>
              </svg>
              y luego “Agregar a inicio”.
            </p>
          </div>

          <button id="installBtn" class="btn btn-light w-100 d-none" type="button">Instalar</button>
        </div>
      </div>
    </div>
  </div>

  <!-- Scripts -->
  <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.3/dist/js/bootstrap.bundle.min.js"></script>
  <script>
    // SVGs
    const playSvg = `
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M8 5v14l11-7z"></path>
      </svg>
    `;

    const pauseSvg = `
      <svg viewBox="0 0 24 24" aria-hidden="true">
        <path d="M6 5h4v14H6zm8 0h4v14h-4z"></path>
      </svg>
    `;

    // Service Worker
    if ('serviceWorker' in navigator) {
      navigator.serviceWorker.register('./sw.js').catch(() => {});
    }

    const player = document.getElementById('player');
    const btn = document.getElementById('playBtn');

    function setBtnPlaying(isPlaying) {
      btn.innerHTML = isPlaying ? pauseSvg : playSvg;
      btn.setAttribute('aria-label', isPlaying ? 'Pausar' : 'Reproducir');
    }

    btn.addEventListener('click', async () => {
      if (player.paused) {
        try {
          await player.play();
          setBtnPlaying(true);
        } catch (e) {
          setBtnPlaying(false);
        }
      } else {
        player.pause();
        setBtnPlaying(false);
      }
    });

    // Offline/Online
    const offlineMsg = document.getElementById('offlineMsg');

    function updateOnlineStatus() {
      const online = navigator.onLine;
      offlineMsg.style.display = online ? 'none' : 'block';

      if (!online) {
        player.pause();
        setBtnPlaying(false);
      }
    }

    window.addEventListener('online', updateOnlineStatus);
    window.addEventListener('offline', updateOnlineStatus);
    updateOnlineStatus();

    // Modal instalación
    let deferredPrompt = null;
    const installModalEl = document.getElementById('installModal');
    const installModal = new bootstrap.Modal(installModalEl);
    const installBtn = document.getElementById('installBtn');
    const iosTip = document.getElementById('iosTip');
    const isIOS = /iphone|ipad|ipod/i.test(navigator.userAgent);

    window.addEventListener('load', () => {
      if (isIOS) {
        iosTip.classList.remove('d-none');
        installModal.show();
      }
    });

    window.addEventListener('beforeinstallprompt', (e) => {
      e.preventDefault();
      deferredPrompt = e;
      installBtn.classList.remove('d-none');
      installModal.show();
    });

    installBtn.addEventListener('click', async () => {
      if (!deferredPrompt) return;

      deferredPrompt.prompt();
      const choiceResult = await deferredPrompt.userChoice;

      if (choiceResult.outcome === 'accepted') {
        installModal.hide();
      }

      deferredPrompt = null;
    });

    // Eventos del player
    player.addEventListener('ended', () => setBtnPlaying(false));
    player.addEventListener('pause', () => setBtnPlaying(false));
    player.addEventListener('playing', () => setBtnPlaying(true));

    // Estado inicial
    setBtnPlaying(false);
  </script>
</body>
</html>