<?php
/**
 * Temporizador de Uso de la Palabra — Ventana Standalone
 * Sprint 13 — Brújula Virtual / FONDOENERGIA
 * Se abre en ventana nueva desde admin.php
 */
ini_set("session.gc_maxlifetime", 86400);
session_set_cookie_params(86400);
session_save_path("/home/evolucionamos/public_html/mejora/sessions");
session_start();
require_once '../env_loader.php';
require_once '../app/models/conexion.php';
require_once '../app/models/datos.php';

if (empty($_SESSION['adm'])) { header('Location: index.php'); exit; }

try {
    $cfg     = (new \app\models\datos())->obtenerDatos();
    $titulo  = $cfg->titulo   ?? 'Asamblea';
    $entidad = $cfg->app      ?? 'Brújula Virtual';
    $tp      = (int)($cfg->tiempo_palabra ?? 120);
} catch (Exception $e) {
    $titulo  = 'Asamblea';
    $entidad = 'Brújula Virtual';
    $tp      = 120;
}
$minutos  = floor($tp / 60);
$segundos = $tp % 60;
$display  = str_pad($minutos,2,'0',STR_PAD_LEFT).':'.str_pad($segundos,2,'0',STR_PAD_LEFT);
?>
<!DOCTYPE html>
<html lang="es">
<head>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <title>⏱ Temporizador — <?= htmlspecialchars($titulo) ?></title>
  <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet">
  <style>
    * { box-sizing: border-box; margin: 0; padding: 0; }

    body {
      min-height: 100vh;
      background: linear-gradient(135deg, #0d1b2a 0%, #1F4E79 50%, #0d1b2a 100%);
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;
      font-family: 'Segoe UI', system-ui, sans-serif;
      color: #fff;
      overflow: hidden;
    }

    /* Partículas de fondo */
    .particles { position: fixed; top:0; left:0; width:100%; height:100%; pointer-events:none; z-index:0; }
    .particle  {
      position: absolute;
      border-radius: 50%;
      background: rgba(23,193,232,.15);
      animation: float linear infinite;
    }

    @keyframes float {
      0%   { transform: translateY(100vh) scale(0); opacity: 0; }
      10%  { opacity: 1; }
      90%  { opacity: 1; }
      100% { transform: translateY(-10vh) scale(1); opacity: 0; }
    }

    .contenedor { position: relative; z-index: 1; text-align: center; padding: 20px; width:100%; max-width:600px; }

    /* Entidad y título */
    .tag-entidad {
      font-size: .75em;
      letter-spacing: 3px;
      text-transform: uppercase;
      color: #17c1e8;
      margin-bottom: 4px;
      opacity: .9;
    }
    .titulo-evento {
      font-size: clamp(1.4rem, 4vw, 2.2rem);
      font-weight: 800;
      letter-spacing: -0.5px;
      color: #fff;
      margin-bottom: 32px;
      text-shadow: 0 2px 20px rgba(0,0,0,.5);
    }

    /* Reloj */
    .clock-ring {
      width: clamp(240px, 50vw, 320px);
      height: clamp(240px, 50vw, 320px);
      border-radius: 50%;
      border: 6px solid rgba(255,255,255,.15);
      margin: 0 auto 28px;
      display: flex;
      align-items: center;
      justify-content: center;
      position: relative;
      transition: border-color .3s, box-shadow .3s;
    }
    .clock-ring.urgente {
      border-color: #dc3545;
      box-shadow: 0 0 40px rgba(220,53,69,.6), 0 0 80px rgba(220,53,69,.2);
      animation: ring-pulse .7s ease-in-out infinite alternate;
    }
    .clock-ring.tiempo-ok {
      border-color: rgba(23,193,232,.6);
      box-shadow: 0 0 30px rgba(23,193,232,.25);
    }
    @keyframes ring-pulse {
      from { box-shadow: 0 0 20px rgba(220,53,69,.4); }
      to   { box-shadow: 0 0 60px rgba(220,53,69,.8), 0 0 100px rgba(220,53,69,.3); }
    }

    /* SVG progreso */
    .clock-svg {
      position: absolute; top: -6px; left: -6px;
      width: calc(100% + 12px); height: calc(100% + 12px);
      transform: rotate(-90deg);
    }
    .clock-svg circle { fill: none; }
    .progress-track   { stroke: rgba(255,255,255,.08); }
    .progress-arc {
      stroke: #17c1e8;
      stroke-linecap: round;
      transition: stroke-dashoffset .9s linear, stroke .3s;
    }
    .clock-ring.urgente .progress-arc { stroke: #dc3545; }

    .display {
      font-size: clamp(3.5rem, 12vw, 5.5rem);
      font-weight: 900;
      letter-spacing: -2px;
      font-variant-numeric: tabular-nums;
      line-height: 1;
      color: #fff;
      text-shadow: 0 2px 20px rgba(0,0,0,.4);
      transition: color .3s;
    }
    .clock-ring.urgente .display { color: #ff6b6b; }

    /* Alerta tiempo agotado */
    .alerta-tiempo {
      display: none;
      font-size: 1.3rem;
      font-weight: 700;
      color: #ff6b6b;
      margin-bottom: 16px;
      animation: blink 1s ease-in-out infinite alternate;
    }
    @keyframes blink {
      from { opacity: 1; } to { opacity: .4; }
    }

    /* Botones */
    .btns { display: flex; gap: 16px; justify-content: center; flex-wrap: wrap; }
    .btn-iniciar {
      background: linear-gradient(135deg, #17c1e8, #0ca8d0);
      color: #fff; border: none; border-radius: 50px;
      padding: 14px 48px; font-size: 1.1rem; font-weight: 700;
      cursor: pointer; transition: all .2s;
      box-shadow: 0 6px 20px rgba(23,193,232,.4);
    }
    .btn-iniciar:hover { transform: translateY(-2px); box-shadow: 0 10px 28px rgba(23,193,232,.5); }
    .btn-iniciar:disabled { opacity: .5; cursor: not-allowed; transform: none; }
    .btn-detener {
      background: rgba(255,255,255,.1);
      color: #fff; border: 2px solid rgba(255,255,255,.3);
      border-radius: 50px; padding: 14px 36px;
      font-size: 1rem; font-weight: 600; cursor: pointer; transition: all .2s;
    }
    .btn-detener:hover { background: rgba(255,255,255,.2); }

    /* Footer info */
    .footer-info {
      margin-top: 28px;
      font-size: .8rem;
      color: rgba(255,255,255,.4);
      letter-spacing: 1px;
    }
  </style>
</head>
<body>

<!-- Partículas de fondo -->
<div class="particles" id="particles"></div>

<div class="contenedor">
  <div class="tag-entidad"><?= htmlspecialchars($entidad) ?></div>
  <h1 class="titulo-evento"><?= htmlspecialchars($titulo) ?></h1>

  <div class="clock-ring tiempo-ok" id="clock-ring">
    <!-- SVG arco de progreso -->
    <svg class="clock-svg" id="clock-svg" viewBox="0 0 330 330">
      <circle class="progress-track" cx="165" cy="165" r="152" stroke-width="8"/>
      <circle class="progress-arc"   cx="165" cy="165" r="152" stroke-width="8"
              id="progress-arc"
              stroke-dasharray="955"
              stroke-dashoffset="0"/>
    </svg>
    <span class="display" id="display"><?= htmlspecialchars($display) ?></span>
  </div>

  <div class="alerta-tiempo" id="alerta">🔔 ¡TIEMPO AGOTADO!</div>

  <div class="btns">
    <button class="btn-iniciar" id="btn-iniciar" onclick="iniciar()">▶ Iniciar</button>
    <button class="btn-detener" onclick="detener()">■ Detener</button>
  </div>

  <div class="footer-info">Tiempo configurado: <?= $tp ?> segundos</div>
</div>

<script>
// ── Configuración ─────────────────────────────────────────────────────────
const TIEMPO_TOTAL = <?= (int)$tp ?>;
let restantes   = TIEMPO_TOTAL;
let intervalo   = null;
let audioCtx    = null;

function getAudioCtx() {
    if (!audioCtx) {
        audioCtx = new (window.AudioContext || window.webkitAudioContext)();
    }
    return audioCtx;
}

// ── Tick-tock (suave mientras corre, urgente en últimos 10s) ─────────────
function tick(urgente = false) {
    try {
        const ctx  = getAudioCtx();
        const osc  = ctx.createOscillator();
        const gain = ctx.createGain();
        osc.connect(gain);
        gain.connect(ctx.destination);
        osc.type = 'square';
        osc.frequency.value = urgente ? 1200 : 800;
        gain.gain.setValueAtTime(urgente ? 0.08 : 0.03, ctx.currentTime);
        gain.gain.exponentialRampToValueAtTime(0.001, ctx.currentTime + (urgente ? 0.12 : 0.06));
        osc.start(ctx.currentTime);
        osc.stop(ctx.currentTime + 0.15);
    } catch(e) {}
}

// ── Campana final (3 toques fuertes) ──────────────────────────────────────
function campana() {
    try {
        const ctx    = getAudioCtx();
        const toques = [880, 1100, 880];
        const vols   = [0.7, 0.8, 0.9];
        toques.forEach((freq, i) => {
            const osc  = ctx.createOscillator();
            const gain = ctx.createGain();
            osc.connect(gain);
            gain.connect(ctx.destination);
            osc.type = 'sine';
            osc.frequency.value = freq;
            const t = ctx.currentTime + i * 0.55;
            gain.gain.setValueAtTime(0, t);
            gain.gain.linearRampToValueAtTime(vols[i], t + 0.03);
            gain.gain.exponentialRampToValueAtTime(0.001, t + 1.2);
            osc.start(t);
            osc.stop(t + 1.3);
        });
    } catch(e) {}
}

// ── Formatear MM:SS ────────────────────────────────────────────────────────
function fmt(s) {
    const m = Math.floor(s/60).toString().padStart(2,'0');
    const n = (s%60).toString().padStart(2,'0');
    return m + ':' + n;
}

// ── Actualizar arco SVG ────────────────────────────────────────────────────
function actualizarArco() {
    const arc = document.getElementById('progress-arc');
    const pct = restantes / TIEMPO_TOTAL;
    arc.style.strokeDashoffset = (955 * (1 - pct)).toFixed(2);
}

// ── Iniciar ────────────────────────────────────────────────────────────────
function iniciar() {
    if (intervalo) clearInterval(intervalo);
    // Si ya llegó a 0, reiniciar
    if (restantes <= 0) restantes = TIEMPO_TOTAL;

    document.getElementById('alerta').style.display = 'none';
    document.getElementById('btn-iniciar').disabled = true;
    document.getElementById('clock-ring').className = 'clock-ring tiempo-ok';
    document.getElementById('display').textContent  = fmt(restantes);
    actualizarArco();

    // Desbloquear AudioContext con gesto del usuario
    try { getAudioCtx().resume(); } catch(e) {}

    intervalo = setInterval(() => {
        restantes--;
        document.getElementById('display').textContent = fmt(restantes);
        actualizarArco();

        const urgente = restantes <= 10 && restantes > 0;
        if (urgente) {
            document.getElementById('clock-ring').className = 'clock-ring urgente';
            tick(true);
        }

        if (restantes <= 0) {
            clearInterval(intervalo);
            intervalo = null;
            campana();
            document.getElementById('display').textContent       = '¡TIEMPO!';
            document.getElementById('alerta').style.display      = 'block';
            document.getElementById('btn-iniciar').disabled      = false;
            document.getElementById('btn-iniciar').textContent   = '▶ Reiniciar';
            restantes = TIEMPO_TOTAL;
        }
    }, 1000);
}

// ── Detener ────────────────────────────────────────────────────────────────
function detener() {
    if (intervalo) { clearInterval(intervalo); intervalo = null; }
    restantes = TIEMPO_TOTAL;
    document.getElementById('display').textContent      = fmt(TIEMPO_TOTAL);
    document.getElementById('alerta').style.display     = 'none';
    document.getElementById('btn-iniciar').disabled     = false;
    document.getElementById('btn-iniciar').textContent  = '▶ Iniciar';
    document.getElementById('clock-ring').className     = 'clock-ring tiempo-ok';
    actualizarArco();
}

// ── Partículas decorativas ─────────────────────────────────────────────────
(function crearParticulas() {
    const cont = document.getElementById('particles');
    for (let i = 0; i < 18; i++) {
        const p = document.createElement('div');
        p.className = 'particle';
        const sz = Math.random() * 60 + 20;
        p.style.cssText = `
            width:${sz}px; height:${sz}px;
            left:${Math.random()*100}%;
            animation-duration:${Math.random()*20+15}s;
            animation-delay:-${Math.random()*20}s;
        `;
        cont.appendChild(p);
    }
})();
</script>
</body>
</html>