  font-weight:900!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($topStartTs ?? 0);
              $endTs = intval($topEndTs ?? 0);
              $nextStartTs = intval($topNextStartTs ?? 0);
              $nextEndTs = intval($topNextEndTs ?? 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 id="epgBarFillLive" class="epgBarFill" style="width:<?=$progress?>%"></div></div>
                <span id="epgRemainLive"><?=$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): ?>
                <?php for($i=0;$i<18;$i++):
                    $left = $i * 120 * $pxPerMin;
                    $width = 120 * $pxPerMin;
                    $st = $rowStart + ($i * 120 * 60);
                    $en = $st + (120 * 60);
                ?>
                    <div class="prog36 noinfo" style="left:<?=$left?>px;width:<?=$width?>px">
                        <b>Programación en Actualización</b>
                        <small><?=pz_hora36($st)?> - <?=pz_hora36($en)?></small>
                    </div>
                <?php endfor; ?>
            <?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;
    }
