<?php
session_start();

if (!isset($_SESSION['user_logged'])) {
    header('Location: index.php');
    exit;
}
$username = $_SESSION['username'];
$password = $_SESSION['password'];
$server_url = rtrim($_SESSION['server_url'], '/');

function getAPI($action, $params = []) {
    global $username, $password, $server_url;
    $params['username'] = $username;
    $params['password'] = $password;
    $params['action'] = $action;
    $url = $server_url . "/player_api.php?" . http_build_query($params);

    $ch = curl_init($url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36');
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 10);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);

    $response = curl_exec($ch);
    $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    curl_close($ch);
    
    if ($response && $http_code == 200) {
        return json_decode($response, true);
    }
    
    return [];
}

$categories = getAPI('get_live_categories');

$category_id = $_GET['category_id'] ?? '';
$channels = [];

if (!empty($category_id)) {
    $channels = getAPI('get_live_streams', ['category_id' => $category_id]);
} elseif (!empty($categories)) {
    $category_id = $categories[0]['category_id'];
    $channels = getAPI('get_live_streams', ['category_id' => $category_id]);
}

$total_channels = count($channels);
?>
<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <title>TV en Vivo - JTECH TV</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no, viewport-fit=cover">
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css" rel="stylesheet">
    <link href="https://vjs.zencdn.net/7.20.3/video-js.css" rel="stylesheet" />
    <script src="https://vjs.zencdn.net/7.20.3/video.min.js"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
            -webkit-tap-highlight-color: transparent;
        }

        body {
            background: #0f171e;
            color: #fff;
            font-family: 'Segoe UI', -apple-system, BlinkMacSystemFont, sans-serif;
            overflow: hidden;
            height: 100vh;
            width: 100vw;
            position: fixed;
            top: 0;
            left: 0;
        }

        .app-container {
            display: flex;
            height: 100vh;
            width: 100%;
            overflow: hidden;
            padding-top: 70px;
        }

        .channels-sidebar {
            width: 320px;
            background: linear-gradient(135deg, #0a0f14 0%, #0f171e 100%);
            border-right: 1px solid rgba(255, 255, 255, 0.08);
            display: flex;
            flex-direction: column;
            z-index: 90;
            height: calc(100vh - 70px);
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
            transition: transform 0.3s ease;
        }

        .quick-categories-bar {
            position: fixed;
            top: 70px;
            left: 0;
            right: 0;
            background: rgba(15, 23, 30, 0.95);
            backdrop-filter: blur(10px);
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            z-index: 85;
            overflow-x: auto;
            overflow-y: hidden;
            white-space: nowrap;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: thin;
            display: none;
            padding: 8px 12px;
            gap: 8px;
        }
        
        .quick-categories-bar::-webkit-scrollbar {
            height: 3px;
        }
        
        .quick-categories-bar .quick-cat-item {
            display: inline-flex;
            align-items: center;
            gap: 6px;
            padding: 6px 14px;
            background: rgba(255, 255, 255, 0.1);
            border-radius: 20px;
            font-size: 0.75rem;
            cursor: pointer;
            transition: all 0.2s;
            margin-right: 8px;
            white-space: nowrap;
        }
        
        .quick-categories-bar .quick-cat-item.active {
            background: #E50914;
        }
        
        .quick-categories-bar .quick-cat-item:active {
            transform: scale(0.95);
        }

        .sidebar-header {
            padding: 20px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            background: rgba(0, 0, 0, 0.3);
            flex-shrink: 0;
        }

        .sidebar-header h2 {
            font-size: 1.3rem;
            font-weight: 600;
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .sidebar-header h2 i {
            color: #E50914;
            font-size: 1.5rem;
        }

        .total-channels {
            font-size: 0.75rem;
            color: rgba(255, 255, 255, 0.5);
            margin-top: 8px;
        }

        .sidebar-search {
            padding: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            flex-shrink: 0;
        }

        .search-input-wrapper {
            position: relative;
        }

        .search-input-wrapper i {
            position: absolute;
            left: 12px;
            top: 50%;
            transform: translateY(-50%);
            color: rgba(255, 255, 255, 0.5);
        }

        .search-input-wrapper input {
            width: 100%;
            padding: 12px 12px 12px 38px;
            background: rgba(0, 0, 0, 0.5);
            border: 1px solid rgba(255, 255, 255, 0.15);
            border-radius: 8px;
            color: white;
            font-size: 0.9rem;
        }

        .search-input-wrapper input:focus {
            outline: none;
            border-color: #E50914;
        }

        .categories-section {
            padding: 15px;
            border-bottom: 1px solid rgba(255, 255, 255, 0.08);
            flex-shrink: 0;
        }

        .section-title {
            font-size: 0.7rem;
            text-transform: uppercase;
            letter-spacing: 1.5px;
            color: rgba(255, 255, 255, 0.5);
            margin-bottom: 12px;
            font-weight: 600;
        }

        .categories-list-sidebar {
            display: flex;
            flex-direction: column;
            gap: 5px;
            max-height: 200px;
            overflow-y: auto;
            -webkit-overflow-scrolling: touch;
        }

        .category-item-sidebar {
            display: flex;
            align-items: center;
            justify-content: space-between;
            padding: 12px 12px;
            cursor: pointer;
            transition: all 0.3s;
            border-radius: 8px;
            font-size: 0.85rem;
            -webkit-tap-highlight-color: transparent;
        }

        .category-item-sidebar:active {
            background: rgba(229, 9, 20, 0.3);
            transform: scale(0.98);
        }

        .category-item-sidebar.active {
            background: rgba(229, 9, 20, 0.25);
            border-left: 3px solid #E50914;
        }

        .category-left {
            display: flex;
            align-items: center;
            gap: 10px;
        }

        .category-dot {
            width: 6px;
            height: 6px;
            background: #E50914;
            border-radius: 50%;
        }

        .channels-section {
            flex: 1;
            display: flex;
            flex-direction: column;
            overflow: hidden;
            min-height: 0;
        }

        .channels-list-sidebar {
            flex: 1;
            overflow-y: auto;
            padding: 10px;
            -webkit-overflow-scrolling: touch;
        }

        .channel-item-sidebar {
            display: flex;
            align-items: center;
            gap: 12px;
            padding: 12px 12px;
            cursor: pointer;
            transition: all 0.3s;
            border-radius: 8px;
            margin-bottom: 4px;
            -webkit-tap-highlight-color: transparent;
        }

        .channel-item-sidebar:active {
            background: rgba(229, 9, 20, 0.3);
            transform: scale(0.98);
        }

        .channel-number-sidebar {
            color: #E50914;
            font-size: 0.7rem;
            font-weight: 700;
            min-width: 30px;
        }

        .channel-icon-sidebar {
            width: 35px;
            height: 25px;
            object-fit: contain;
            border-radius: 4px;
        }

        .channel-name-sidebar {
            flex: 1;
            font-size: 0.85rem;
            font-weight: 500;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }

        .player-area {
            flex: 1;
            position: relative;
            background: #000;
        }

        .video-js {
            width: 100% !important;
            height: 100% !important;
            background: #000 !important;
        }

        .video-js .vjs-big-play-button {
            display: none !important;
        }

        .video-js .vjs-control-bar {
            background: linear-gradient(to top, rgba(0,0,0,0.9), rgba(0,0,0,0.6)) !important;
            backdrop-filter: blur(10px);
        }

        /* Botón pantalla completa - MÁS SUBIDO */
        .custom-fullscreen-btn {
            position: absolute;
            bottom: 140px;
            right: 20px;
            background: rgba(0, 0, 0, 0.85);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.3rem;
            backdrop-filter: blur(10px);
            z-index: 200;
            display: flex;
            align-items: center;
            justify-content: center;
            -webkit-tap-highlight-color: transparent;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
        }
        
        .custom-fullscreen-btn:active {
            background: #E50914;
            transform: scale(1.1);
        }

        .channel-banner {
            position: absolute;
            bottom: 30px;
            left: 30px;
            right: 100px;
            background: linear-gradient(90deg, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0.6) 50%, transparent 100%);
            padding: 20px 25px;
            border-radius: 12px;
            z-index: 100;
            opacity: 0;
            transition: opacity 0.3s ease;
            pointer-events: none;
        }

        .channel-banner.show {
            opacity: 1;
        }

        .banner-content {
            display: flex;
            align-items: center;
            gap: 20px;
        }

        .channel-logo-banner {
            width: 60px;
            height: 45px;
            object-fit: contain;
            border-radius: 8px;
            background: rgba(255, 255, 255, 0.1);
            padding: 5px;
        }

        .channel-name-banner {
            font-size: 1.5rem;
            font-weight: 700;
            margin-bottom: 5px;
        }

        .current-program-banner {
            font-size: 0.9rem;
            color: rgba(255, 255, 255, 0.8);
        }

        .live-indicator-banner {
            background: #E50914;
            padding: 6px 14px;
            border-radius: 20px;
            font-size: 0.7rem;
            font-weight: 700;
            display: flex;
            align-items: center;
            gap: 6px;
        }

        .live-dot {
            width: 8px;
            height: 8px;
            background: white;
            border-radius: 50%;
            animation: pulse 1.5s infinite;
        }

        @keyframes pulse {
            0%, 100% { opacity: 1; }
            50% { opacity: 0.4; }
        }

        .floating-controls {
            position: absolute;
            bottom: 30px;
            right: 30px;
            display: flex;
            gap: 12px;
            z-index: 200;
            opacity: 0;
            transition: opacity 0.3s ease;
        }

        .floating-controls.show {
            opacity: 1;
        }

        .float-btn {
            background: rgba(0, 0, 0, 0.8);
            border: 1px solid rgba(255, 255, 255, 0.2);
            color: white;
            width: 45px;
            height: 45px;
            border-radius: 50%;
            cursor: pointer;
            transition: all 0.3s;
            font-size: 1.1rem;
            -webkit-tap-highlight-color: transparent;
        }

        .float-btn:active {
            background: #E50914;
            transform: scale(1.1);
        }

        .tv-placeholder {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
            color: rgba(255, 255, 255, 0.5);
        }

        .tv-placeholder i {
            font-size: 4rem;
            margin-bottom: 20px;
            color: #E50914;
            opacity: 0.5;
        }

        .tv-placeholder h2 {
            font-size: 1.8rem;
            margin-bottom: 10px;
        }

        .loading-state {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            text-align: center;
        }

        .loading-spinner {
            width: 50px;
            height: 50px;
            border: 3px solid rgba(229, 9, 20, 0.3);
            border-top: 3px solid #E50914;
            border-radius: 50%;
            animation: spin 1s linear infinite;
            margin: 0 auto 20px;
        }

        @keyframes spin {
            0% { transform: rotate(0deg); }
            100% { transform: rotate(360deg); }
        }

        .epg-overlay {
            position: fixed;
            top: 0;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0, 0, 0, 0.97);
            backdrop-filter: blur(20px);
            z-index: 1000;
            display: flex;
            flex-direction: column;
        }

        .epg-overlay.hidden {
            display: none;
        }

        .epg-header {
            padding: 20px 30px;
            background: linear-gradient(135deg, #000, rgba(0,0,0,0.8));
            border-bottom: 1px solid rgba(255, 255, 255, 0.1);
            display: flex;
            justify-content: space-between;
            align-items: center;
        }

        .epg-title {
            font-size: 1.2rem;
            font-weight: 600;
            color: #E50914;
        }

        .close-epg {
            background: rgba(255, 255, 255, 0.1);
            border: none;
            color: white;
            width: 40px;
            height: 40px;
            border-radius: 50%;
            cursor: pointer;
        }

        .close-epg:hover {
            background: #E50914;
        }

        .epg-content {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
        }

        .player-area:fullscreen,
        .player-area:-webkit-full-screen {
            width: 100vw !important;
            height: 100vh !important;
            position: fixed !important;
            top: 0 !important;
            left: 0 !important;
            z-index: 9999 !important;
            background: #000 !important;
        }
        
        .player-area:fullscreen .floating-controls,
        .player-area:-webkit-full-screen .floating-controls,
        .player-area:fullscreen .custom-fullscreen-btn,
        .player-area:-webkit-full-screen .custom-fullscreen-btn,
        .player-area:fullscreen .channel-banner,
        .player-area:-webkit-full-screen .channel-banner {
            display: none !important;
        }

        .show-categories-btn {
            position: fixed;
            bottom: 140px;
            left: 20px;
            z-index: 150;
            background: rgba(0,0,0,0.85);
            backdrop-filter: blur(10px);
            border: 1px solid rgba(255,255,255,0.2);
            color: white;
            width: 55px;
            height: 55px;
            border-radius: 50%;
            cursor: pointer;
            font-size: 1.3rem;
            -webkit-tap-highlight-color: transparent;
            box-shadow: 0 2px 10px rgba(0,0,0,0.3);
            display: none;
            align-items: center;
            justify-content: center;
        }
        
        .show-categories-btn:active {
            background: #E50914;
            transform: scale(0.95);
        }

        .sidebar-overlay {
            position: fixed;
            top: 70px;
            left: 0;
            right: 0;
            bottom: 0;
            background: rgba(0,0,0,0.6);
            z-index: 85;
            display: none;
        }
        
        .sidebar-overlay.active {
            display: block;
        }

        @media (max-width: 768px) {
            .app-container {
                padding-top: 60px;
            }
            
            .channels-sidebar {
                position: fixed;
                left: 0;
                top: 60px;
                bottom: 0;
                width: 85%;
                max-width: 280px;
                transform: translateX(-100%);
                z-index: 200;
                height: calc(100vh - 60px);
                box-shadow: 2px 0 10px rgba(0,0,0,0.5);
            }
            
            .channels-sidebar.open {
                transform: translateX(0);
            }
            
            .show-categories-btn {
                display: flex;
                bottom: 140px;
            }
            
            .custom-fullscreen-btn {
                bottom: 140px;
                right: 20px;
                width: 55px;
                height: 55px;
                font-size: 1.3rem;
            }
            
            .channel-banner {
                right: 100px;
                left: 15px;
                padding: 10px 12px;
                bottom: 15px;
            }
            
            .channel-name-banner {
                font-size: 0.9rem;
            }
            
            .current-program-banner {
                font-size: 0.65rem;
            }
            
            .live-indicator-banner {
                padding: 3px 8px;
                font-size: 0.55rem;
            }
            
            .category-item-sidebar,
            .channel-item-sidebar {
                padding: 14px 12px;
            }
        }
        
        @media (orientation: landscape) and (max-width: 768px) {
            .channels-sidebar {
                display: none;
            }
            
            .show-categories-btn {
                display: flex;
                bottom: 15px;
                left: 15px;
                width: 45px;
                height: 45px;
            }
            
            .quick-categories-bar {
                display: flex;
                top: 60px;
            }
            
            .app-container {
                padding-top: 110px;
            }
            
            .player-area {
                width: 100%;
            }
            
            .custom-fullscreen-btn {
                bottom: 15px;
                right: 80px;
                width: 45px;
                height: 45px;
                font-size: 1.1rem;
            }
            
            .channel-banner {
                right: 150px;
                left: 70px;
                bottom: 15px;
                padding: 8px 12px;
            }
            
            .channel-name-banner {
                font-size: 0.85rem;
            }
        }
        
        @media (min-width: 769px) {
            .show-categories-btn {
                display: none;
            }
        }

        ::-webkit-scrollbar {
            width: 6px;
        }
        ::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
        }
        ::-webkit-scrollbar-thumb {
            background: #E50914;
            border-radius: 4px;
        }
    </style>
</head>
<body>
    <?php include 'header.php'; ?>
    
    <div class="app-container">
        <div class="quick-categories-bar" id="quickCategoriesBar">
            <?php foreach($categories as $cat): ?>
                <div class="quick-cat-item <?= ($cat['category_id'] == $category_id) ? 'active' : '' ?>" 
                     onclick="selectCategory('<?= $cat['category_id'] ?>')">
                    <i class="fas fa-circle" style="font-size: 6px;"></i>
                    <?= htmlspecialchars($cat['category_name']) ?>
                </div>
            <?php endforeach; ?>
        </div>
        
        <button class="show-categories-btn" id="showCategoriesBtn" onclick="toggleSidebar()">
            <i class="fas fa-list"></i>
        </button>
        
        <div class="sidebar-overlay" id="sidebarOverlay" onclick="closeSidebar()"></div>
        
        <div class="channels-sidebar" id="channelsSidebar">
            <div class="sidebar-header">
                <h2>
                    <i class="fas fa-tv"></i>
                    Canales TV
                </h2>
                <div class="total-channels">
                    <i class="fas fa-broadcast-tower"></i> Total: <?= $total_channels ?> canales
                </div>
            </div>
            
            <div class="sidebar-search">
                <div class="search-input-wrapper">
                    <i class="fas fa-search"></i>
                    <input type="text" id="searchChannels" placeholder="Buscar canal..." autocomplete="off">
                </div>
            </div>
            
            <div class="categories-section">
                <div class="section-title">
                    <i class="fas fa-th-large"></i> CATEGORÍAS
                </div>
                <div class="categories-list-sidebar" id="categoriesListSidebar">
                    <?php foreach($categories as $cat): ?>
                        <div class="category-item-sidebar <?= ($cat['category_id'] == $category_id) ? 'active' : '' ?>" 
                             data-category-id="<?= $cat['category_id'] ?>"
                             onclick="selectCategoryKeepSidebar('<?= $cat['category_id'] ?>')">
                            <div class="category-left">
                                <div class="category-dot"></div>
                                <span><?= htmlspecialchars($cat['category_name']) ?></span>
                            </div>
                        </div>
                    <?php endforeach; ?>
                </div>
            </div>
            
            <div class="channels-section">
                <div class="section-title" style="padding: 0 15px;">
                    <i class="fas fa-list"></i> CANALES
                </div>
                <div class="channels-list-sidebar" id="channelsListSidebar">
                    <?php if (!empty($channels)): ?>
                        <?php foreach($channels as $index => $channel): ?>
                            <div class="channel-item-sidebar" 
                                 data-channel-name="<?= strtolower(htmlspecialchars($channel['name'])) ?>"
                                 onclick="playChannel(<?= $channel['stream_id'] ?>, <?= $index + 1 ?>, '<?= htmlspecialchars(addslashes($channel['name'])) ?>', '<?= htmlspecialchars($channel['stream_icon'] ?? '') ?>')">
                                <div class="channel-number-sidebar"><?= $index + 1 ?></div>
                                <?php if (!empty($channel['stream_icon'])): ?>
                                    <img src="<?= htmlspecialchars($channel['stream_icon']) ?>" class="channel-icon-sidebar" onerror="this.style.display='none';">
                                <?php endif; ?>
                                <div class="channel-name-sidebar"><?= htmlspecialchars($channel['name']) ?></div>
                            </div>
                        <?php endforeach; ?>
                    <?php else: ?>
                        <div style="text-align: center; padding: 40px; color: rgba(255,255,255,0.5);">
                            <i class="fas fa-tower-broadcast"></i><br>
                            No hay canales en esta categoría
                        </div>
                    <?php endif; ?>
                </div>
            </div>
        </div>
        
        <div class="player-area" id="playerArea">
            <div class="tv-placeholder" id="tvPlaceholder">
                <i class="fas fa-tv"></i>
                <h2>TV en Vivo</h2>
                <p>Selecciona un canal de la lista</p>
                <p style="font-size: 0.8rem; margin-top: 10px;">
                    <i class="fas fa-arrow-left"></i> <i class="fas fa-arrow-right"></i> Cambiar canal
                </p>
            </div>
        </div>
        
        <div class="channel-banner" id="channelBanner">
            <div class="banner-content">
                <img id="channelLogoImg" class="channel-logo-banner" src="" style="display: none;">
                <div class="channel-info-banner">
                    <div class="channel-name-banner" id="currentChannelName">Canal</div>
                    <div class="current-program-banner" id="currentProgram">--:--</div>
                </div>
                <div class="live-indicator-banner">
                    <div class="live-dot"></div>
                    EN VIVO
                </div>
            </div>
        </div>
        
        <div class="floating-controls" id="floatingControls">
            <button class="float-btn" onclick="openEPG()" title="Guía">
                <i class="fas fa-calendar-alt"></i>
            </button>
        </div>
    </div>
    
    <div class="epg-overlay hidden" id="epgOverlay">
        <div class="epg-header">
            <div class="epg-title" id="epgTitle">Guía de Programación</div>
            <button class="close-epg" onclick="closeEPGOverlay()">
                <i class="fas fa-times"></i>
            </button>
        </div>
        <div class="epg-content" id="epgContent"></div>
    </div>

    <script>
        let currentPlayer = null;
        let currentChannelId = null;
        let currentChannelName = null;
        let currentChannelIcon = null;
        let currentChannelIndex = 0;
        let hideTimer;
        let isFullscreen = false;

        document.addEventListener('DOMContentLoaded', function() {
            setupMouseMovement();
            setupKeyboardNavigation();
            setupSearchFilter();
            setupFullscreenListeners();
            checkOrientation();
        });
        
        window.addEventListener('resize', checkOrientation);
        window.addEventListener('orientationchange', function() {
            setTimeout(checkOrientation, 100);
        });
        
        function checkOrientation() {
            const isLandscape = window.innerWidth > window.innerHeight;
            const quickBar = document.getElementById('quickCategoriesBar');
            const sidebar = document.getElementById('channelsSidebar');
            
            if (isLandscape && window.innerWidth <= 768) {
                if (quickBar) quickBar.style.display = 'flex';
                if (sidebar) sidebar.style.display = 'none';
            } else if (window.innerWidth <= 768) {
                if (quickBar) quickBar.style.display = 'none';
                if (sidebar) sidebar.style.display = 'flex';
            } else {
                if (quickBar) quickBar.style.display = 'none';
                if (sidebar) sidebar.style.display = 'flex';
            }
        }
        
        // NUEVA FUNCIÓN: Selecciona categoría SIN cerrar el sidebar
        function selectCategoryKeepSidebar(categoryId) {
            window.location.href = `?category_id=${categoryId}`;
        }
        
        // Función original para compatibilidad (cierra el sidebar)
        function selectCategory(categoryId) {
            window.location.href = `?category_id=${categoryId}`;
        }
        
        function setupFullscreenListeners() {
            document.addEventListener('fullscreenchange', handleFullscreenChange);
            document.addEventListener('webkitfullscreenchange', handleFullscreenChange);
        }
        
        function handleFullscreenChange() {
            isFullscreen = !!(document.fullscreenElement || document.webkitFullscreenElement);
            const fullscreenBtn = document.getElementById('customFullscreenBtn');
            if (fullscreenBtn) {
                if (isFullscreen) {
                    fullscreenBtn.innerHTML = '<i class="fas fa-compress"></i>';
                } else {
                    fullscreenBtn.innerHTML = '<i class="fas fa-expand"></i>';
                }
            }
        }

        function setupSearchFilter() {
            const searchInput = document.getElementById('searchChannels');
            if (!searchInput) return;
            
            searchInput.addEventListener('input', function(e) {
                const query = e.target.value.trim().toLowerCase();
                const channelItems = document.querySelectorAll('#channelsListSidebar .channel-item-sidebar');
                
                channelItems.forEach(item => {
                    const channelName = item.getAttribute('data-channel-name') || '';
                    if (query === '' || channelName.includes(query)) {
                        item.style.display = 'flex';
                    } else {
                        item.style.display = 'none';
                    }
                });
            });
        }

        function setupMouseMovement() {
            document.addEventListener('mousemove', function() {
                if (!currentPlayer) return;
                clearTimeout(hideTimer);
                showFloatingControls();
                showChannelBanner();
                hideTimer = setTimeout(() => {
                    hideFloatingControls();
                    hideChannelBanner();
                }, 3000);
            });
            
            document.addEventListener('touchstart', function() {
                if (!currentPlayer) return;
                showFloatingControls();
                showChannelBanner();
                clearTimeout(hideTimer);
                hideTimer = setTimeout(() => {
                    hideFloatingControls();
                    hideChannelBanner();
                }, 3000);
            });
        }

        function setupKeyboardNavigation() {
            document.addEventListener('keydown', function(e) {
                if (currentPlayer) {
                    switch(e.key) {
                        case 'ArrowLeft':
                            e.preventDefault();
                            previousChannel();
                            break;
                        case 'ArrowRight':
                            e.preventDefault();
                            nextChannel();
                            break;
                        case 'g':
                        case 'G':
                            e.preventDefault();
                            openEPG();
                            break;
                        case 'f':
                        case 'F':
                            e.preventDefault();
                            toggleFullscreen();
                            break;
                    }
                }
            });
        }
        
        function toggleFullscreen() {
            const playerArea = document.getElementById('playerArea');
            
            if (!isFullscreen) {
                if (playerArea.requestFullscreen) {
                    playerArea.requestFullscreen();
                } else if (playerArea.webkitRequestFullscreen) {
                    playerArea.webkitRequestFullscreen();
                }
            } else {
                if (document.exitFullscreen) {
                    document.exitFullscreen();
                } else if (document.webkitExitFullscreen) {
                    document.webkitExitFullscreen();
                }
            }
        }
        
        function closeSidebar() {
            document.getElementById('channelsSidebar').classList.remove('open');
            document.getElementById('sidebarOverlay').classList.remove('active');
        }

        function toggleSidebar() {
            const sidebar = document.getElementById('channelsSidebar');
            const overlay = document.getElementById('sidebarOverlay');
            sidebar.classList.toggle('open');
            overlay.classList.toggle('active');
        }

        function playChannel(channelId, channelNum, channelName, channelIcon) {
            currentChannelId = channelId;
            currentChannelName = channelName;
            currentChannelIcon = channelIcon;
            currentChannelIndex = channelNum - 1;

            if (window.innerWidth <= 768) {
                closeSidebar();
            }

            if (currentPlayer) {
                try { currentPlayer.dispose(); } catch(e) {}
            }

            showLoading(`Cargando ${channelName}...`);

            fetch(`load_player.php?id=${channelId}&t=${Date.now()}`)
                .then(response => response.text())
                .then(html => {
                    document.getElementById('playerArea').innerHTML = html;
                    addCustomElements();
                    updateChannelInfo();
                    setTimeout(() => initializePlayer(channelId), 200);
                })
                .catch(error => showError('Error al cargar el canal'));
        }

        function addCustomElements() {
            const bannerHTML = `
                <div class="channel-banner" id="channelBanner">
                    <div class="banner-content">
                        <img id="channelLogoImg" class="channel-logo-banner" src="" style="display: none;">
                        <div class="channel-info-banner">
                            <div class="channel-name-banner" id="currentChannelName">${currentChannelName}</div>
                            <div class="current-program-banner" id="currentProgram">Cargando...</div>
                        </div>
                        <div class="live-indicator-banner">
                            <div class="live-dot"></div>
                            EN VIVO
                        </div>
                    </div>
                </div>
            `;
            
            const fullscreenHTML = `
                <button class="custom-fullscreen-btn" id="customFullscreenBtn" onclick="toggleFullscreen()" title="Pantalla completa">
                    <i class="fas fa-expand"></i>
                </button>
            `;
            
            document.getElementById('playerArea').insertAdjacentHTML('beforeend', bannerHTML);
            document.getElementById('playerArea').insertAdjacentHTML('beforeend', fullscreenHTML);
            
            // Forzar visibilidad del botón en móvil
            setTimeout(() => {
                const btn = document.getElementById('customFullscreenBtn');
                if (btn) {
                    btn.style.display = 'flex';
                    btn.style.visibility = 'visible';
                    btn.style.opacity = '1';
                }
            }, 100);
        }

        function initializePlayer(channelId) {
            if (typeof videojs === 'undefined') {
                setTimeout(() => initializePlayer(channelId), 100);
                return;
            }

            const playerElement = document.getElementById('player-' + channelId);
            if (!playerElement) return;

            try {
                currentPlayer = videojs(playerElement, {
                    controls: true,
                    autoplay: true,
                    liveui: true,
                    fluid: true
                });
                
                currentPlayer.ready(function() {
                    hideLoading();
                });
                
                currentPlayer.on('error', function() {
                    showError('Error de reproducción');
                });

            } catch(e) { 
                showError('Error al iniciar reproductor'); 
            }
        }

        function updateChannelInfo() {
            document.getElementById('currentChannelName').textContent = currentChannelName;
            if (currentChannelIcon) {
                const img = document.getElementById('channelLogoImg');
                img.src = currentChannelIcon;
                img.style.display = 'block';
            }
            
            fetch(`load_epg.php?id=${currentChannelId}&t=${Date.now()}`)
                .then(response => response.text())
                .then(html => {
                    const parser = new DOMParser();
                    const doc = parser.parseFromString(html, 'text/html');
                    const currentProgram = doc.querySelector('.epg-card.now');
                    if (currentProgram) {
                        const title = currentProgram.querySelector('.epg-title')?.textContent.trim() || 'Programa actual';
                        document.getElementById('currentProgram').textContent = title;
                    } else {
                        document.getElementById('currentProgram').textContent = 'Sin información';
                    }
                })
                .catch(() => {
                    document.getElementById('currentProgram').textContent = 'Sin información';
                });
        }

        function nextChannel() {
            const items = Array.from(document.querySelectorAll('#channelsListSidebar .channel-item-sidebar'))
                .filter(item => item.style.display !== 'none');
            if (items.length === 0) return;
            const nextIndex = (currentChannelIndex + 1) % items.length;
            items[nextIndex].click();
        }

        function previousChannel() {
            const items = Array.from(document.querySelectorAll('#channelsListSidebar .channel-item-sidebar'))
                .filter(item => item.style.display !== 'none');
            if (items.length === 0) return;
            const prevIndex = currentChannelIndex > 0 ? currentChannelIndex - 1 : items.length - 1;
            items[prevIndex].click();
        }

        function openEPG() {
            if (!currentChannelId) {
                alert('Selecciona un canal primero');
                return;
            }
            
            const overlay = document.getElementById('epgOverlay');
            overlay.classList.remove('hidden');
            document.getElementById('epgTitle').innerHTML = `Guía - ${currentChannelName}`;
            document.getElementById('epgContent').innerHTML = '<div class="loading-spinner" style="margin:20px auto;"></div>';
            
            fetch(`load_epg.php?id=${currentChannelId}&t=${Date.now()}`)
                .then(r => r.text())
                .then(html => document.getElementById('epgContent').innerHTML = html)
                .catch(() => document.getElementById('epgContent').innerHTML = '<div style="text-align:center;padding:50px;">Error al cargar EPG</div>');
        }

        function closeEPGOverlay() {
            document.getElementById('epgOverlay').classList.add('hidden');
        }

        function showLoading(msg) {
            document.getElementById('playerArea').innerHTML = `
                <div class="loading-state">
                    <div class="loading-spinner"></div>
                    <div>${msg}</div>
                </div>
            `;
        }

        function hideLoading() {}

        function showError(msg) {
            document.getElementById('playerArea').innerHTML = `
                <div class="tv-placeholder">
                    <i class="fas fa-exclamation-triangle" style="color:#E50914;"></i>
                    <h2>Error</h2>
                    <p>${msg}</p>
                </div>
            `;
        }

        function showFloatingControls() {
            const c = document.getElementById('floatingControls');
            if (c) c.classList.add('show');
        }

        function hideFloatingControls() {
            const c = document.getElementById('floatingControls');
            if (c) c.classList.remove('show');
        }

        function showChannelBanner() {
            const b = document.getElementById('channelBanner');
            if (b) b.classList.add('show');
        }

        function hideChannelBanner() {
            const b = document.getElementById('channelBanner');
            if (b) b.classList.remove('show');
        }

        window.addEventListener('beforeunload', () => {
            if (currentPlayer) try { currentPlayer.dispose(); } catch(e) {}
        });
    </script>
</body>
</html>