<?php
if(!isset($_GET["epg_refresh"])) $_GET["epg_refresh"]="1";
session_start();
date_default_timezone_set("America/Santiago");

$dns  = $_SESSION["dns"]  ?? "http://puntoz.live:2082";
$user = $_SESSION["user"] ?? "admintoc";
$pass = $_SESSION["pass"] ?? "pyk12345";

function api_xtream($dns,$user,$pass,$action,$extra=""){
    $url = rtrim($dns,"/")."/player_api.php?username=".urlencode($user)."&password=".urlencode($pass)."&action=".$action.$extra;
    $json = @file_get_contents($url);
    $data = json_decode($json,true);
    return is_array($data) ? $data : [];
}


function epg_titles($dns,$user,$pass,$sid){
    if(!$sid) return ["No information","No information","","","",""];

    $e = api_xtream($dns,$user,$pass,"get_short_epg","&stream_id=".$sid."&limit=6");
    $list = $e["epg_listings"] ?? $e["epg_list"] ?? [];

    if(!$list || !is_array($list)) return ["No information","No information","","","",""];

    $nowTs = time();
    $actual = $list[0] ?? [];
    $siguiente = $list[1] ?? [];

    foreach($list as $i=>$it){
        $st = intval($it["start_timestamp"] ?? 0);
        $en = intval($it["stop_timestamp"] ?? $it["end_timestamp"] ?? 0);

        if($st > 0 && $en > $st && $nowTs >= $st && $nowTs < $en){
            $actual = $it;
            $siguiente = $list[$i+1] ?? [];
            break;
        }
    }

    $decode = function($v){
        $v = trim((string)$v);
        if($v === "") return "No information";

        $d = base64_decode($v,true);
        if($d !== false && trim($d) !== "") return trim($d);

        return $v;
    };

    $nowTitle = $decode($actual["title"] ?? "No information");
    $nextTitle = $decode($siguiente["title"] ?? "No information");

    $nowStart = (string)intval($actual["start_timestamp"] ?? 0);
    $nowEnd = (string)intval($actual["stop_timestamp"] ?? $actual["end_timestamp"] ?? 0);

    $nextStart = (string)intval($siguiente["start_timestamp"] ?? 0);
    $nextEnd = (string)intval($siguiente["stop_timestamp"] ?? $siguiente["end_timestamp"] ?? 0);

    $thirdTitle = $decode($list[2]["title"] ?? "No information");
$fourthTitle = $decode($list[3]["title"] ?? "No information");
return [$nowTitle,$nextTitle,$nowStart,$nowEnd,$nextStart,$nextEnd,$thirdTitle,$fourthTitle];
}


function epg_grid_titles($dns,$user,$pass,$sid){
    $r = epg_titles($dns,$user,$pass,$sid);
    return [
        $r[0] ?? "No information",
        $r[1] ?? "No information",
        $r[6] ?? "No information",
        $r[7] ?? "No information"
    ];
}


function epg_programs_36h($dns,$user,$pass,$sid){
    if(!$sid) return [];
    $e = api_xtream($dns,$user,$pass,"get_short_epg","&stream_id=".$sid."&limit=160");
    $list = $e["epg_listings"] ?? $e["epg_list"] ?? [];
    if(!$list || !is_array($list)) return [];

    $decode = function($v){
        $v = trim((string)$v);
        if($v === "") return "Sin información";
        $d = base64_decode($v,true);
        if($d !== false && trim($d)!=="") return trim($d);
        return $v;
    };

    $now = time();
    $max = $now + 36*3600;
    $out = [];

    foreach($list as $it){
        $st = intval($it["start_timestamp"] ?? 0);
        $en = intval($it["stop_timestamp"] ?? $it["end_timestamp"] ?? 0);
        if($st<=0 || $en<=$st) continue;
        if($en<$now || $st>$max) continue;
        $out[] = [
            "title"=>$decode($it["title"] ?? "Sin información"),
            "start"=>$st,
            "end"=>$en
        ];
    }
    return $out;
}

function pz_hora36($ts){
    return $ts>0 ? date("H:i",$ts) : "";
}

$cats = api_xtream($dns,$user,$pass,"get_live_categories");
$cat  = $_GET["cat"] ?? "";
$stream = $_GET["stream"] ?? "";

if(!$cat && count($cats)){
    $cat = $cats[0]["category_id"] ?? "";
}

$channels = api_xtream($dns,$user,$pass,"get_live_streams", $cat ? "&category_id=".urlencode($cat) : "");

$selected = null;
foreach($channels as $c){
    if((string)($c["stream_id"] ?? "") === (string)$stream){
        $selected = $c;
        break;
    }
}
if(!$selected && count($channels)){
    $selected = $channels[0];
    $stream = $selected["stream_id"] ?? "";
}

$keepEpg = isset($_GET["epg_refresh"]) ? "&epg_refresh=".urlencode($_GET["epg_refresh"]) : "";

$playUrl = $selected ? rtrim($dns,"/")."/live/".$user."/".$pass."/".$selected["stream_id"].".m3u8" : "";

$epgNow = "Sin información";
$epgNext = "Sin información";

if($selected){
    $epg = api_xtream(
        $dns,
        $user,
        $pass,
        "get_short_epg",
        "&stream_id=".$selected["stream_id"]."&limit=2"
    );

    if(!empty($epg["epg_listings"][0]["title"])){
        $epgNow = base64_decode($epg["epg_listings"][0]["title"]);
    }

    if(!empty($epg["epg_listings"][1]["title"])){
        $epgNext = base64_decode($epg["epg_listings"][1]["title"]);
    }
}

?>
<!doctype html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=1920,height=1080,initial-scale=1">
<title>Puntoz TV Clean</title>
<style>
*{box-sizing:border-box}
body{margin:0;background:#05080d;color:white;font-family:Arial,Helvetica,sans-serif;overflow:hidden}
.app{width:1920px;height:1080px;display:grid;grid-template-columns:240px 440px 1fr;background:#101820;padding:35px 20px;background:rgba(0,0,0,.45)}
.logo{font-size:34px;font-weight:900;margin:10px 0 55px}
.logo span{color:#9cff37}
.side .nav{font-size:22px;font-weight:800;padding:18px 16px;margin:16px 0;border-radius:12px}
.side .active{background:#042c40;border:1px solid #00cfff;box-shadow:0 0 20px #00cfff55}
.cats{padding:30px 24px;background:rgba(0,0,0,.35);overflow-y:auto;scroll-behavior:smooth}
.cats h1{font-size:42px;margin:0 0 25px}
.cat{display:block;color:white;text-decoration:none;font-size:24px;font-weight:900;padding:16px 18px;border-radius:12px;margin:8px 0}
.cat.active{background:#3d4855}
.main{display:grid;grid-template-rows:250px 52px 1fr}
.top{display:grid;grid-template-columns:430px 1fr;background:#172126}
.videoBox{background:#000;height:250px}
video{width:100%;height:100%;object-fit:contain;background:#000}
.info{padding:30px;position:relative}
.info h2{margin:0 0 12px;font-size:34px}
.info p{margin:5px 0;font-size:17px;color:#ddd}
.timebar{display:grid;grid-template-columns:300px repeat(4,1fr);background:#223039;border-top:1px solid #334;border-bottom:1px solid #334}
.timebar div{padding:17px 18px;font-size:18px;font-weight:900;border-right:1px solid #394852}
.grid{height:778px;overflow-y:auto;background:#142026;scroll-behavior:smooth}
.row{display:grid;grid-template-columns:300px repeat(4,1fr);height:66px;color:white;text-decoration:none;border-bottom:1px solid #25343b;align-items:stretch}
.row.active{background:#087ec0}
.ch{display:flex;align-items:center;gap:14px;padding:8px 18px;font-size:17px;font-weight:900;min-height:66px}
.ch img{width:54px;height:42px;object-fit:contain;display:block;flex:0 0 54px}
.epg{padding:0 14px;color:#9caeb8;font-size:15px;border-left:1px solid #25343b;display:flex;align-items:center;justify-content:center;text-align:center;line-height:1.2;overflow:hidden}
.focus{outline:5px solid #00d9ff!important;box-shadow:0 0 25px #00d9ff!important;z-index:9}
.refreshEpg{outline:none;
position:absolute;top:22px;right:26px;
padding:10px 18px;border:1px solid #00d9ff;
border-radius:14px;background:rgba(0,217,255,.10);
color:white;text-decoration:none;font-weight:900;
box-shadow:0 0 18px #00d9ff55;
}
.refreshEpg:hover{background:rgba(0,217,255,.22)}
.toast{
position:absolute;top:78px;right:30px;
background:rgba(0,217,255,.18);
border:1px solid #00d9ff;color:white;
padding:12px 18px;border-radius:14px;
font-weight:900;box-shadow:0 0 18px #00d9ff77;
animation:fadeToast 2.2s forwards;
}
@keyframes fadeToast{0%{opacity:1}75%{opacity:1}100%{opacity:0}}

.timelineWrap{
display:flex;
gap:12px;
overflow-x:auto;
overflow-y:hidden;
padding:10px 0;
scroll-behavior:smooth;
}

.timelineWrap::-webkit-scrollbar{
height:8px;
}

.timelineWrap::-webkit-scrollbar-thumb{
background:#00d9ff88;
border-radius:20px;
}

.epgBlock{
min-width:240px;
height:74px;
background:#101820;
border:1px solid #00d9ff55;
border-radius:14px;
padding:10px;
flex:none;
color:#fff;
box-shadow:0 0 12px #00d9ff22;
}

.epgHour{
font-size:12px;
font-weight:700;
color:#8fe8ff;
margin-bottom:6px;
}

.epgText{
font-size:14px;
font-weight:700;
line-height:1.2;
}


/* PLAYER_FOCUS_INVISIBLE */
.videoBox.focus{
    outline:none!important;
    box-shadow:none!important;
    border:0!important;
}


.epgDetail{margin-top:6px;color:white;max-width:640px}
.epgDate{font-size:12px;font-weight:800;color:#d9f6ff;margin-bottom:7px;letter-spacing:.3px}
.epgLabelNow{font-size:12px;font-weight:900;color:#ffd900;margin-top:3px}
.epgProgramNow{font-size:16px;font-weight:900;color:white;margin:2px 0 5px 0;line-height:1.08;max-width:620px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.epgTimeSimple{font-size:12px;font-weight:700;color:#d9f6ff;margin-bottom:4px}
.epgBarLine{display:flex;align-items:center;gap:10px;margin:3px 0 8px 0}
.epgBarMini{width:300px;height:7px;border-radius:20px;background:rgba(220,230,235,.38);overflow:hidden}
.epgBarFill{height:100%;border-radius:20px;background:#ffd900}
.epgBarLine span{font-size:12px;font-weight:800;color:white;white-space:nowrap}
.epgLabelNext{font-size:12px;font-weight:900;color:#00d2ff;margin-top:3px}
.epgProgramNext{font-size:14px;font-weight:800;color:white;margin:2px 0;line-height:1.08;max-width:620px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.epgNextTime{font-size:12px;font-weight:700;color:#cdefff}


.timebar36{display:flex;height:46px;background:#0878c8;color:white;font-weight:900;overflow:hidden}
.timeDate{width:330px;min-width:330px;padding:13px 16px;font-size:16px}
.timeScroll{display:flex;min-width:8640px}
.hourCell{width:240px;min-width:240px;padding:13px 0;font-size:15px;border-left:1px solid rgba(255,255,255,.18)}
.grid36Wrap{overflow:hidden;background:rgba(15,20,25,.88)}
.row36{display:flex;height:64px;color:white;text-decoration:none;border-bottom:1px solid rgba(255,255,255,.11)}
.row36.active,.row36.focus,.row36:hover{background:rgba(0,210,255,.35);outline:none}
.ch36{width:330px;min-width:330px;height:64px;display:flex;align-items:center;gap:12px;padding:0 14px;background:rgba(0,38,85,.82);font-size:15px;font-weight:900}
.ch36 img{width:52px;height:40px;object-fit:contain}
.track36{position:relative;height:64px;min-width:8640px;background:rgba(0,62,130,.42)}
.prog36{position:absolute;top:5px;height:54px;border-radius:7px;background:rgba(25,32,40,.92);border:1px solid rgba(0,210,255,.18);padding:7px 10px;overflow:hidden}
.prog36 b{display:block;font-size:14px;line-height:1.05;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
.prog36 small{display:block;font-size:10px;color:#cdefff;margin-top:4px}
.prog36.nowProg{background:rgba(25,32,40,.92)!important;border:2px solid rgba(0,210,255,.95)!important;box-shadow:0 0 14px rgba(0,210,255,.75)!important}
.prog36.noinfo{text-align:center;color:#bdefff;font-weight:800;padding-top:18px}


/* AJUSTE FINAL VISUAL EPG */
.row36 .ch span,
.row .ch span{
  color:#ffffff !important;
  font-size:17px !important;
  font-weight:950 !important;
  text-shadow:0 0 8px rgba(255,255,255,.35);
}

.row36.focus .ch span,
.row36.active .ch span,
.row.focus .ch span,
.row.active .ch span{
  color:#ffd900 !important;
  text-shadow:0 0 10px rgba(255,217,0,.75);
}

.row36.focus,
.row36.active,
.row36:hover{
  background:rgba(0,0,0,.22) !important;
  outline:none !important;
  box-shadow:none !important;
}

/* Programa enfocado: glow estilo Home sin pintar amarillo */
.progBlock.focusProg{
  outline:3px solid rgba(0,210,255,.95) !important;
  box-shadow:0 0 18px rgba(0,210,255,.85) !important;
  border-radius:8px !important;
  z-index:20 !important;
}

/* Evita montajes visuales */
.progBlock{
  overflow:hidden !important;
  box-sizing:border-box !important;
}


/* NUMERO + ACTIVE/FOCUS FINAL */
.ch36{
  gap:12px !important;
}
.ch36 .chanNum{
  width:34px;
  min-width:34px;
  text-align:center;
  color:#ffffff;
  font-size:18px;
  font-weight:950;
}
.ch36 .chanName{
  color:#ffffff;
  font-size:18px !important;
  font-weight:950 !important;
  text-shadow:0 0 8px rgba(255,255,255,.35);
}

/* Canal navegando */
.row36.focus .chanNum,
.row36.focus .chanName{
  color:#ffd900 !important;
  text-shadow:0 0 12px rgba(255,217,0,.85) !important;
}

/* Canal reproduciendo */
.row36.active:not(.focus) .chanNum,
.row36.active:not(.focus) .chanName{
  color:#ffffff !important;
}

/* Símbolo solo para canal reproduciendo */
.row36.active:not(.focus) .chanName::after{
  content:" ▸";
  color:#ffd900 !important;
  text-shadow:0 0 12px rgba(255,217,0,.95) !important;
  font-size:300% !important;
  font-weight:950 !important;
  vertical-align:middle;
  line-height:1;
}

/* Si estoy navegando encima, no mostrar doble símbolo */
.row36.focus .chanName::after{
  content:"" !important;
}

/* No pintar fila completa al navegar */
.row36.focus,
.row36.active,
.row36:hover{
  background:rgba(0,0,0,.18) !important;
  outline:none !important;
  box-shadow:none !important;
}


/* HOME STYLE MENU */
.cat.focus,
.side .navFocus.focus{
    background:rgba(4,44,64,.95)!important;
    border:1px solid #00d9ff!important;
    box-shadow:0 0 20px rgba(0,217,255,.55)!important;
    border-radius:12px!important;
    color:#ffffff!important;
}

.cat.active{
    background:rgba(61,72,85,.65)!important;
}

</style>
</head>
<body>


<div class="app">
    <aside class="side">
        <div class="logo"><span>puntoz</span> TV</div>
        <div class="nav active navFocus">▣ TV EN VIVO</div>
        <div class="nav navFocus">⌂ Inicio</div>
        <div class="nav navFocus">🎬 Movies</div>
        <div class="nav navFocus">▤ TV Shows</div>
        <div class="nav navFocus">⚙ Settings</div>
    </aside>

    <section class="cats">
        <h1>All playlists</h1>
        <a class="cat navFocus <?=$cat===''?'active':''?>" href="tv_clean.php">All channels</a>
        <?php foreach($cats as $c): ?>
        <a class="cat navFocus <?=((string)$cat===(string)$c["category_id"])?'active':''?>" href="tv_clean.php?cat=<?=urlencode($c["category_id"])?><?=$keepEpg?>">
            <?=htmlspecialchars($c["category_name"] ?? "Sin nombre")?>
        </a>
        <?php endforeach; ?>
    </section>

    <main class="main">
        <section class="top">
            <div class="videoBox navFocus" tabindex="0">
                <?php if($playUrl): ?>
                <video id="mainVideo" class="navFocus" tabindex="0" autoplay playsinline src="<?=htmlspecialchars($playUrl)?>"></video>
                <?php endif; ?>
            </div>
            <div class="info"><a class="refreshEpg navFocus" href="<?=htmlspecialchars($_SERVER["PHP_SELF"])?>?<?=htmlspecialchars(http_build_query(array_merge($_GET, ["epg_refresh"=>time()])))?>">↻ Actualizar EPG</a>
<?php if(isset($_GET["epg_refresh"])): ?><div class="toast">Guía actualizada OK</div><?php endif; ?>
            <?php
              $nowTitle = $epg[0] ?? $epgNow ?? "No information";
              $nextTitle = $epg[1] ?? $epgNext ?? "No information";
              $startTs = intval($epg[2] ?? 0);
              $endTs = intval($epg[3] ?? 0);
              $nextStartTs = intval($epg[4] ?? 0);
              $nextEndTs = intval($epg[5] ?? 0);
              $nowTs = time();

              $progress = 0;
              $remainMin = 0;
              if ($startTs > 0 && $endTs > $startTs) {
                  $progress = max(0, min(100, intval((($nowTs - $startTs) / ($endTs - $startTs)) * 100)));
                  $remainMin = max(0, intval(ceil(($endTs - $nowTs) / 60)));
              }

              if (!function_exists("pz_hora_epg")) {
                function pz_hora_epg($ts) {
                    return $ts > 0 ? date("H:i", $ts) : "";
                }
              }

              $dias = ["domingo","lunes","martes","miércoles","jueves","viernes","sábado"];
              $meses = ["","ene","feb","mar","abr","may","jun","jul","ago","sep","oct","nov","dic"];
              $fechaBonita = strtoupper($dias[intval(date("w"))]) . " " . date("d") . " " . strtoupper($meses[intval(date("n"))]) . " · " . date("H:i");
            ?>

            <h2 id="channelTitle"><?=htmlspecialchars($selected["name"] ?? "Sin canal")?></h2>
            <div class="epgDetail">
              <div class="epgDate"><?=$fechaBonita?></div>

              <div class="epgLabelNow">AHORA</div>
              <div class="epgProgramNow"><?=htmlspecialchars($nowTitle)?></div>
              <?php if ($startTs > 0 && $endTs > 0): ?>
              <div class="epgTimeSimple"><?=pz_hora_epg($startTs)?> - <?=pz_hora_epg($endTs)?></div>
              <?php endif; ?>
              <div class="epgBarLine">
                <div class="epgBarMini"><div class="epgBarFill" style="width:<?=$progress?>%"></div></div>
                <span><?=$remainMin?> min</span>
              </div>

              <div class="epgLabelNext">SIGUE</div>
              <div class="epgProgramNext"><?=htmlspecialchars($nextTitle)?></div>
              <div class="epgNextTime"><?=pz_hora_epg($nextStartTs)?> - <?=pz_hora_epg($nextEndTs)?></div>
            </div>
            </div>
        </section>

        
<section class="timebar36">
    <div class="timeDate"><?=date("D, d M, H:i")?></div>
    <div class="timeScroll" id="timeScroll">
        <?php for($h=0;$h<=36;$h++): ?>
            <div class="hourCell"><?=date("H:i", time()+($h*3600))?></div>
        <?php endfor; ?>
    </div>
</section>

<section class="grid36Wrap" id="grid36Wrap">
    <?php foreach($channels as $idx=>$c):
        $is=((string)$stream===(string)$c["stream_id"]);
        $programs = epg_programs_36h($dns,$user,$pass,$c["stream_id"]);
        $rowStart = time();
        $pxPerMin = 4;
    ?>
    <a class="row row36 navFocus <?=$is?'active':''?>"
       data-play="<?=htmlspecialchars(trim($dns,"/")."/live/".$user."/".$pass."/".$c["stream_id"].".m3u8")?>"
       data-name="<?=htmlspecialchars($c["name"] ?? "Canal")?>"
       data-logo="<?=htmlspecialchars($c["stream_icon"] ?? "")?>"
       data-now="<?=htmlspecialchars($epgNow ?? "No information")?>"
       data-next="<?=htmlspecialchars($epgNext ?? "No information")?>"
       href="tv_clean.php?cat=<?=urlencode($cat)?>&stream=<?=urlencode($c["stream_id"])?><?=$keepEpg?>">
        <div class="ch ch36">
            <span class="chanNum"><?=intval($idx)+1?></span>
            <?php if(!empty($c["stream_icon"])): ?><img src="<?=htmlspecialchars($c["stream_icon"])?>"><?php endif; ?>
            <span class="chanName"><?=htmlspecialchars($c["name"] ?? "Canal")?></span>
        </div>
        <div class="track36">
            <?php if(!$programs): ?>
                <div class="prog36 noinfo" style="left:0px;width:8640px">Sin información</div>
            <?php else: foreach($programs as $pr):
                $left=max(0,intval((($pr["start"]-$rowStart)/60)*$pxPerMin));
                $width=max(90,intval((($pr["end"]-$pr["start"])/60)*$pxPerMin));
                $nowProg=(time()>=$pr["start"] && time()<$pr["end"]);
            ?>
                <div class="prog36 <?=$nowProg?'nowProg':''?>" style="left:<?=$left?>px;width:<?=$width?>px">
                    <b><?=htmlspecialchars($pr["title"])?></b>
                    <small><?=pz_hora36($pr["start"])?> - <?=pz_hora36($pr["end"])?></small>
                </div>
            <?php endforeach; endif; ?>
        </div>
    </a>
    <?php endforeach; ?>
</section>

    </main>
</div>

<script>
let zone = 2;
let idx = [0,0,0,0,0];

function groups(){
    return [
        Array.from(document.querySelectorAll('.side .navFocus')),
        Array.from(document.querySelectorAll('.cats .cat')),
        Array.from(document.querySelectorAll('.row36')),
        Array.from(document.querySelectorAll('.videoBox')),
        Array.from(document.querySelectorAll('.refreshEpg'))
    ].map(a=>a.filter(e=>e && e.offsetParent !== null));
}

function setFocus(){
    const g = groups();
    g.flat().forEach(e=>e.classList.remove('focus'));

    if(!g[zone] || !g[zone].length) return;

    idx[zone] = Math.max(0, Math.min(idx[zone], g[zone].length - 1));

    const el = g[zone][idx[zone]];
    if(!el) return;

    el.classList.add('focus');
    el.setAttribute('tabindex','0');
    el.focus({preventScroll:true});
    el.scrollIntoView({block:'nearest', inline:'nearest'});
}

function enterItem(){
    const g = groups();
    const el = g[zone] && g[zone][idx[zone]];
    if(!el) return;

    if(zone === 3){
        const v=document.getElementById('mainVideo');
        if(v){
            v.muted=false;
            v.volume=1.0;
            if(v.requestFullscreen) v.requestFullscreen();
            else if(v.webkitRequestFullscreen) v.webkitRequestFullscreen();
        }
        return;
    }

    if(el.classList.contains('row') && typeof quickPlay === 'function'){
        quickPlay(el);
        return;
    }

    if(el.href){
        window.location.href = el.href;
        return;
    }

    el.click();
}

document.addEventListener('keydown',function(e){
    const k = e.key;

    if(k === 'ArrowLeft'){
        e.preventDefault();
        if(zone === 2){
            const gw=document.getElementById('grid36Wrap');
            const tw=document.getElementById('timeScroll');
            if(gw && gw.scrollLeft > 0){ gw.scrollLeft = Math.max(0, gw.scrollLeft - 420); if(tw) tw.style.transform='translateX(-'+gw.scrollLeft+'px)'; return; }
        }
        if(zone === 4){ zone = 3; setFocus(); return; }
        zone = Math.max(0, zone - 1);
        setFocus();
        return;
    }

    if(k === 'ArrowRight'){
        e.preventDefault();
        if(zone === 2){
            const gw=document.getElementById('grid36Wrap');
            const tw=document.getElementById('timeScroll');
            if(gw){ gw.scrollLeft += 420; if(tw) tw.style.transform='translateX(-'+gw.scrollLeft+'px)'; }
            return;
        }
        if(zone === 3){ zone = 4; setFocus(); return; }
        zone = Math.min(4, zone + 1);
        setFocus();
        return;
    }

    if(k === 'ArrowUp'){
        e.preventDefault();
        if(zone === 2){
            if(idx[zone] <= 0){
                zone = 3;
                setFocus();
                return;
            }
            idx[zone]--;
            setFocus();
            return;
        }
        idx[zone]--;
        setFocus();
        return;
    }

    if(k === 'ArrowDown'){
        e.preventDefault();
        if(zone === 3 || zone === 4){ zone = 2; setFocus(); return; }
        idx[zone]++;
        setFocus();
        return;
    }

    if(k === 'Enter'){
        e.preventDefault();
        enterItem();
        return;
    }
}, true);

setTimeout(setFocus, 500);
</script>

<script>
function quickPlay(row){
    const video=document.getElementById('mainVideo');
    const title=document.getElementById('channelTitle');
    if(!row || !video) return false;

    const url=row.getAttribute('data-play');
    const name=row.getAttribute('data-name') || 'Canal';

    if(!url) return false;

    document.querySelectorAll('.row').forEach(r=>r.classList.remove('active'));
    row.classList.add('active');

    if(title) title.textContent=name;

/* FOCO_PLAYER_AUTOMATICO_FINAL */
setTimeout(function(){
    document.querySelectorAll('.focus').forEach(function(x){x.classList.remove('focus');});
    var box=document.querySelector('.videoBox');
    if(box){
        box.classList.add('focus');
        box.setAttribute('tabindex','0');
        box.focus();
    }
},250);

    video.muted = false;
    video.volume = 1.0;
    if(video.src !== url){
        video.src = url;
    }
    video.play().catch(()=>{});

    return true;
}

document.addEventListener('click',function(e){
    const row=e.target.closest('.row');
    if(row){
        e.preventDefault();
        quickPlay(row);
    }
},true);
</script>

<script>
document.addEventListener('DOMContentLoaded',function(){
    const v=document.getElementById('mainVideo');
    if(v){
        v.muted=false;
        v.volume=1.0;
        v.addEventListener('dblclick',function(){
            if(v.requestFullscreen) v.requestFullscreen();
            else if(v.webkitRequestFullscreen) v.webkitRequestFullscreen();
        });
    }
});
</script>

<script>
let lastRow = null;
let lastTime = 0;

function abrirFullscreenActual(){
    const v=document.getElementById('mainVideo');
    const focused=document.querySelector('.focus.row');
    const active=document.querySelector('.row.active');

    let url = "";

    if(focused && focused.getAttribute('data-play')) url = focused.getAttribute('data-play');
    else if(active && active.getAttribute('data-play')) url = active.getAttribute('data-play');
    else if(v && v.currentSrc) url = v.currentSrc;
    else if(v && v.src) url = v.src;

    if(!url) return;

    if(window.PuntozAndroid && PuntozAndroid.abrirFullscreen){
        PuntozAndroid.abrirFullscreen(url);
        return;
    }

    if(v.requestFullscreen) v.requestFullscreen();
    else if(v.webkitRequestFullscreen) v.webkitRequestFullscreen();
}

document.addEventListener('keydown',function(e){
    if(e.key !== 'Enter') return;

    const el=document.querySelector('.focus');

    if(el && el.classList.contains('videoBox')){
        e.preventDefault();
        abrirFullscreenActual();
        return;
    }

    if(el && el.classList.contains('row')){
        const now=Date.now();

        if(lastRow === el && (now-lastTime) < 700){
            e.preventDefault();
            if(typeof quickPlay === 'function') quickPlay(el);
            setTimeout(abrirFullscreenActual,250);
            return;
        }

        lastRow = el;
        lastTime = now;
    }
},true);

document.addEventListener('dblclick',function(e){
    const row=e.target.closest('.row');
    if(row){
        if(typeof quickPlay === 'function') quickPlay(row);
        setTimeout(abrirFullscreenActual,250);
    }
},true);
</script>




<script>
/* GLOW PROGRAMA SEGUN CANAL SELECCIONADO */
(function(){
  function syncProgGlow(){
    document.querySelectorAll('.progBlock.focusProg').forEach(function(x){
      x.classList.remove('focusProg');
    });

    var row = document.querySelector('.row36.focus, .row36.active, .row.focus, .row.active');
    if(!row) return;

    var allRows = Array.from(document.querySelectorAll('.row36, .row'));
    var idx = allRows.indexOf(row);
    if(idx < 0) return;

    var blocks = document.querySelectorAll('.grid36 .progBlock, .progBlock');
    var candidates = [];

    blocks.forEach(function(b){
      var top = parseInt((b.style.top || '0').replace('px','')) || 0;
      candidates.push({el:b, top:top});
    });

    candidates.sort(function(a,b){ return a.top - b.top; });

    var rowTop = row.offsetTop || (idx * 64);
    var best = null;
    var bestDiff = 999999;

    candidates.forEach(function(o){
      var d = Math.abs(o.top - rowTop);
      if(d < bestDiff){
        bestDiff = d;
        best = o.el;
      }
    });

    if(best) best.classList.add('focusProg');
  }

  document.addEventListener('keydown', function(){
    setTimeout(syncProgGlow, 80);
  }, true);

  document.addEventListener('click', function(){
    setTimeout(syncProgGlow, 80);
  }, true);

  setTimeout(syncProgGlow, 800);
})();
</script>

</body>
</html>
