<?php
session_start();
error_reporting(0);
require_once '../config.php';

// =========================================================================
// 1. BUSCA AS CONFIGURAÇÕES WHITE LABEL (CORES E LOGO DA REVENDA)
// =========================================================================
$slug = $_GET['id'] ?? '';
$marca = 'TOP TV';
$logo = '';
$cor_bg = '#121519';
$cor_btn = '#0ea5e9';

try {
    $pdo = getConexaoInterna();
    if (!empty($slug)) {
        $stmt = $pdo->prepare("SELECT nome_marca, logo_url, cor_fundo, cor_botao FROM revenda_players WHERE slug = ? LIMIT 1");
        $stmt->execute([$slug]);
        $playerData = $stmt->fetch(PDO::FETCH_ASSOC);
        if ($playerData) {
            $marca = $playerData['nome_marca'];
            $logo = $playerData['logo_url'];
            $cor_bg = $playerData['cor_fundo'];
            $cor_btn = $playerData['cor_botao'];
        }
    }
} catch (Exception $e) {}

// =========================================================================
// 2. SISTEMA DE LOGIN SEGURO
// =========================================================================
$erro_login = '';
if ($_SERVER['REQUEST_METHOD'] == 'POST' && isset($_POST['acao_login'])) {
    $user_try = trim($_POST['username']);
    $pass_try = trim($_POST['password']);
    
    try {
        $pdo_ext = getConexaoAtiva();
        $stmt_chk = $pdo_ext->prepare("SELECT id, exp_date, enabled FROM users WHERE username = ? AND password = ? LIMIT 1");
        $stmt_chk->execute([$user_try, $pass_try]);
        $res_chk = $stmt_chk->fetch(PDO::FETCH_ASSOC);
        
        if (!$res_chk || $res_chk['enabled'] == 0) {
            $erro_login = "Usuário ou senha inválidos.";
        } else if ($res_chk['exp_date'] != null && $res_chk['exp_date'] != 0 && $res_chk['exp_date'] < time()) {
            $erro_login = "Sua conta está vencida. Contate o suporte.";
        } else {
            $_SESSION['webplayer_user'] = $user_try;
            $_SESSION['webplayer_pass'] = $pass_try;
            header("Location: ?id=" . urlencode($slug));
            exit;
        }
    } catch (Exception $e) {
        $erro_login = "Erro ao conectar com o servidor.";
    }
}

// Logout
if (isset($_GET['action']) && $_GET['action'] == 'logout') {
    session_destroy();
    header("Location: ?id=" . urlencode($slug));
    exit;
}

$user = $_GET['user'] ?? $_SESSION['webplayer_user'] ?? '';
$pass = $_GET['pass'] ?? $_SESSION['webplayer_pass'] ?? '';

// =========================================================================
// 3. TELA DE LOGIN (Se não estiver logado, mostra isso e PARA o script)
// =========================================================================
if (empty($user) || empty($pass)) {
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Login - <?php echo htmlspecialchars($marca); ?></title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <style>
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: <?php echo $cor_bg; ?>; color: white; display: flex; justify-content: center; align-items: center; height: 100vh; }
        .login-box { background: rgba(0, 0, 0, 0.4); padding: 40px 30px; border-radius: 15px; width: 100%; max-width: 350px; text-align: center; box-shadow: 0 10px 30px rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.05); backdrop-filter: blur(10px); }
        .login-logo { max-width: 200px; max-height: 80px; margin-bottom: 25px; object-fit: contain; }
        .login-title { font-size: 24px; font-weight: bold; margin-bottom: 25px; color: <?php echo $cor_btn; ?>; }
        .input-group { margin-bottom: 20px; text-align: left; position: relative; }
        .input-group i { position: absolute; left: 15px; top: 15px; color: #888; }
        .input-group input { width: 100%; padding: 15px 15px 15px 45px; background: rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.1); color: white; border-radius: 8px; box-sizing: border-box; font-size: 15px; outline: none; transition: 0.3s; }
        .input-group input:focus { border-color: <?php echo $cor_btn; ?>; }
        .btn-login { background: <?php echo $cor_btn; ?>; color: white; border: none; padding: 15px; width: 100%; border-radius: 8px; font-size: 16px; font-weight: bold; cursor: pointer; transition: 0.3s; margin-top: 10px; }
        .btn-login:hover { filter: brightness(1.2); box-shadow: 0 0 15px <?php echo $cor_btn; ?>80; }
        .error-msg { background: rgba(220,53,69,0.2); color: #ff4d4d; padding: 10px; border-radius: 6px; margin-bottom: 20px; font-size: 13px; border: 1px solid #ff4d4d; }
    </style>
</head>
<body>
    <div class="login-box">
        <?php if(!empty($logo)): ?>
            <img src="<?php echo htmlspecialchars($logo); ?>" alt="Logo" class="login-logo">
        <?php else: ?>
            <div class="login-title"><?php echo htmlspecialchars($marca); ?></div>
        <?php endif; ?>
        
        <?php if(!empty($erro_login)): ?>
            <div class="error-msg"><i class="fas fa-exclamation-triangle"></i> <?php echo $erro_login; ?></div>
        <?php endif; ?>

        <form method="POST">
            <input type="hidden" name="acao_login" value="1">
            <div class="input-group">
                <i class="fas fa-user"></i>
                <input type="text" name="username" placeholder="Seu Usuário" required autocomplete="off">
            </div>
            <div class="input-group">
                <i class="fas fa-lock"></i>
                <input type="password" name="password" placeholder="Sua Senha" required>
            </div>
            <button type="submit" class="btn-login">ENTRAR</button>
        </form>
    </div>
</body>
</html>
<?php
    exit; // FIM DO SCRIPT DE LOGIN
}

// =========================================================================
// 4. O PLAYER (Só carrega se passou pelo login)
// =========================================================================

$dominio = $_SERVER['HTTP_HOST'];
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$streamHost = $protocolo . $dominio;
$apiUrl = $streamHost . "/player_api.php?username=$user&password=$pass";

// Sistema de Proxy para Canais Ao Vivo
if (isset($_GET['proxy_canal'])) {
    session_write_close(); 
    while (ob_get_level()) { ob_end_clean(); } 

    $id_canal = intval($_GET['proxy_canal']);
    $url_canal = $streamHost . "/" . $user . "/" . $pass . "/" . $id_canal;

    header('Content-Type: video/mp2t');
    header('Access-Control-Allow-Origin: *');
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $url_canal);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, false); 
    curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    curl_setopt($ch, CURLOPT_TIMEOUT, 0);
    curl_exec($ch);
    curl_close($ch);
    exit;
}

try {
    $pdo_ext = getConexaoAtiva();
    $stmt = $pdo_ext->prepare("SELECT id, username, exp_date, enabled FROM users WHERE username = ? AND password = ? LIMIT 1");
    $stmt->execute([$user, $pass]);
    $res = $stmt->fetch(PDO::FETCH_ASSOC);
    
    if (!$res || $res['enabled'] == 0) { die("Usuário inválido ou bloqueado."); }
    
    $nome_cliente = $res['username'];
    if (empty($res['exp_date']) || $res['exp_date'] == 0 || $res['exp_date'] == 'null') {
        $vencimento = 'Ilimitado';
    } else {
        $vencimento = date('d/m/Y', intval($res['exp_date']));
    }
} catch (Exception $e) { 
    die("Erro de conexão com o banco de dados."); 
}
?>

<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title><?php echo htmlspecialchars($marca); ?> - Web Player</title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <script src="https://cdn.jsdelivr.net/npm/mpegts.js@latest/dist/mpegts.min.js"></script>

    <style>
        /* AS CORES DINÂMICAS SÃO APLICADAS AQUI */
        :root { --bg: <?php echo $cor_bg; ?>; --bg-sec: #111; --accent: <?php echo $cor_btn; ?>; --text: #ffffff; --text-muted: #888888; }
        body { margin: 0; background: var(--bg); color: var(--text); font-family: 'Segoe UI', Roboto, sans-serif; overflow-x: hidden; -webkit-tap-highlight-color: transparent; }
        
        header { position: fixed; top: 0; width: 100%; padding: 15px 20px; display: flex; justify-content: space-between; align-items: center; z-index: 1000; background: linear-gradient(to bottom, rgba(0,0,0,0.9) 0%, rgba(0,0,0,0) 100%); box-sizing: border-box; transition: 0.3s; }
        header.scrolled { background: rgba(5,5,5,0.95); backdrop-filter: blur(10px); border-bottom: 1px solid #222; }
        
        .logo { font-size: 20px; font-weight: 900; color: var(--accent); text-shadow: 0 2px 4px rgba(0,0,0,0.5); display: flex; align-items: center;}
        .logo img { max-height: 30px; object-fit: contain; }
        
        .header-actions { display: flex; gap: 15px; align-items: center; }

        .app-screen { display: none; padding-bottom: 80px; min-height: 100vh; }
        .app-screen.active { display: block; animation: fadeIn 0.3s ease; }
        @keyframes fadeIn { from { opacity: 0; } to { opacity: 1; } }

        .hero-banner { width: 100%; height: 65vh; position: relative; background-size: cover; background-position: top center; display: flex; align-items: flex-end; }
        .hero-overlay { position: absolute; inset: 0; background: linear-gradient(to top, var(--bg) 0%, transparent 70%); }
        .hero-content { position: relative; z-index: 10; padding: 20px; width: 100%; text-align: center; }
        .hero-title { font-size: 32px; font-weight: 900; margin: 0 0 10px 0; text-shadow: 0 2px 10px rgba(0,0,0,0.9); }
        .hero-tags { display: flex; justify-content: center; gap: 10px; font-size: 12px; color: #ccc; margin-bottom: 15px; font-weight: bold; text-shadow: 0 1px 3px black; }
        .hero-buttons { display: flex; justify-content: center; gap: 15px; }
        .btn-play { background: white; color: black; padding: 10px 25px; border-radius: 5px; font-weight: bold; font-size: 16px; border: none; display: flex; align-items: center; gap: 8px; cursor: pointer; transition: 0.2s;}

        .row-section { padding: 10px 0 20px 15px; }
        .row-title { font-size: 16px; font-weight: bold; margin: 0 0 10px 0; padding-right: 15px; }
        .row-container { display: flex; gap: 10px; overflow-x: auto; scroll-behavior: smooth; padding-bottom: 10px; padding-right: 15px; }
        .row-container::-webkit-scrollbar { display: none; }
        .poster-card { flex: 0 0 auto; width: 115px; border-radius: 8px; overflow: hidden; cursor: pointer; position: relative; background: #111; }
        .poster-card img { width: 100%; height: 165px; object-fit: cover; }
        .poster-title { font-size: 10px; text-align: center; padding: 5px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background: #111; position: absolute; bottom: 0; width: 100%; box-sizing: border-box;}

        .bottom-nav { position: fixed; bottom: 0; width: 100%; background: rgba(18, 18, 18, 0.95); backdrop-filter: blur(15px); display: flex; justify-content: space-around; padding: 12px 0 15px 0; border-top: 1px solid #222; z-index: 2000; }
        .nav-item { display: flex; flex-direction: column; align-items: center; gap: 5px; color: var(--text-muted); cursor: pointer; width: 60px; }
        .nav-item i { font-size: 22px; transition: 0.2s; }
        .nav-item span { font-size: 10px; font-weight: 600; }
        .nav-item.active { color: white; }
        .nav-item.active i { transform: translateY(-3px); color: var(--accent); }

        .page-header { padding: 75px 15px 15px; font-size: 22px; font-weight: bold; display: flex; align-items: center; gap: 10px; }
        .btn-back-page { background: rgba(255,255,255,0.1); border: none; color: white; padding: 8px 12px; border-radius: 8px; cursor: pointer; font-size: 14px; font-weight: bold; margin-right: 10px; }
        
        .grid-content { display: grid; grid-template-columns: repeat(auto-fill, minmax(105px, 1fr)); gap: 10px; padding: 0 15px; }
        
        .cat-box { background: rgba(0,0,0,0.3); border-radius: 10px; padding: 20px 10px; text-align: center; border: 1px solid rgba(255,255,255,0.1); cursor: pointer; transition: 0.2s;}
        .cat-box:hover { border-color: var(--accent); }
        .cat-box i { font-size: 28px; color: var(--accent); margin-bottom: 8px; }
        .cat-box span { font-size: 11px; font-weight: bold; text-transform: uppercase; display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap;}

        .grid-item { background: #111; border-radius: 8px; overflow: hidden; cursor: pointer; border: 1px solid #222; position: relative;}
        .grid-item img { width: 100%; height: 150px; object-fit: cover; }
        .grid-item .item-title { padding: 8px; font-size: 10px; text-align: center; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; background: rgba(0,0,0,0.8);}

        .btn-load-more { background: rgba(255,255,255,0.1); color: white; border: 1px solid rgba(255,255,255,0.2); padding: 12px; border-radius: 8px; font-weight: bold; cursor: pointer; width: 100%; display: flex; justify-content: center; align-items: center; gap: 8px; transition: 0.2s;}
        
        #playerModal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: #000; z-index: 3000; }
        .btn-close-player { position: absolute; top: 15px; right: 15px; background: rgba(0,0,0,0.5); color: white; border: 2px solid white; padding: 8px 15px; border-radius: 8px; font-weight: bold; cursor: pointer; z-index: 3001; }

        #seriesModal { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: var(--bg); z-index: 2500; overflow-y: auto; padding-bottom: 50px; }
        .series-header { position: relative; width: 100%; height: 250px; background-size: cover; background-position: top; display: flex; align-items: flex-end; }
        .series-overlay { position: absolute; inset: 0; background: linear-gradient(to top, var(--bg) 0%, transparent 100%); }
        .series-info { position: relative; z-index: 10; padding: 20px; }
        .series-title { font-size: 24px; font-weight: bold; margin: 0; }
        .season-block { padding: 0 20px; margin-top: 15px; }
        .season-title { font-weight: bold; color: var(--accent); margin-bottom: 10px; border-bottom: 1px solid rgba(255,255,255,0.1); padding-bottom: 5px; }
        .episode-row { padding: 12px; background: rgba(0,0,0,0.3); margin-bottom: 8px; border-radius: 8px; display: flex; justify-content: space-between; align-items: center; border: 1px solid rgba(255,255,255,0.1); cursor: pointer; }

        .skeleton { background: rgba(255,255,255,0.05); position: relative; overflow: hidden; border-radius: 8px; border: 1px solid rgba(255,255,255,0.05); }
        .skeleton::after { content: ""; position: absolute; top: 0; left: 0; width: 100%; height: 100%; background: linear-gradient(90deg, transparent, rgba(255,255,255,0.05), transparent); animation: shimmer 1.5s infinite; }
        .skeleton-cat { height: 100px; }
        .skeleton-item { height: 180px; }
        @keyframes shimmer { 0% { transform: translateX(-100%); } 100% { transform: translateX(100%); } }

        @media (max-width: 600px) {
            .grid-content { grid-template-columns: repeat(auto-fill, minmax(105px, 1fr)); }
        }
    </style>
</head>
<body>

<header id="main-header">
    <div class="logo">
        <?php if(!empty($logo)): ?>
            <img src="<?php echo htmlspecialchars($logo); ?>" alt="Logo">
        <?php else: ?>
            <?php echo htmlspecialchars($marca); ?>
        <?php endif; ?>
    </div>
    <div style="text-align:right; display:flex; align-items:center; gap:15px;">
        <div>
            <div style="font-size:12px; font-weight:bold; color: white;"><?php echo htmlspecialchars($nome_cliente); ?></div>
            <div style="font-size:10px; color:#ffc107;">Exp: <?php echo $vencimento; ?></div>
        </div>
        <a href="?id=<?php echo urlencode($slug); ?>&action=logout" style="color:#ff4d4d; font-size:22px; text-decoration:none;"><i class="fas fa-sign-out-alt"></i></a>
    </div>
</header>

<div id="screen-home" class="app-screen active">
    <div class="hero-banner" id="heroBanner" style="background-image: url('https://via.placeholder.com/600x800/111/111');">
        <div class="hero-overlay"></div>
        <div class="hero-content">
            <h1 class="hero-title" id="heroTitle">Sincronizando...</h1>
            <div class="hero-tags" id="heroTags" style="display:none;"><span>LANÇAMENTO</span> • <span style="color:var(--accent);"><?php echo htmlspecialchars($marca); ?></span></div>
            <div class="hero-buttons">
                <button class="btn-play" id="btnPlayHero" style="display:none;"><i class="fas fa-play"></i> Assistir</button>
            </div>
        </div>
    </div>
    <div class="row-section">
        <h3 class="row-title">Adicionados Recentemente</h3>
        <div class="row-container" id="row-recent-movies"></div>
    </div>
</div>

<div id="screen-movie" class="app-screen">
    <div class="page-header" id="header-movie">Filmes</div>
    <div class="grid-content" id="grid-movie"></div>
</div>
<div id="screen-series" class="app-screen">
    <div class="page-header" id="header-series">Séries</div>
    <div class="grid-content" id="grid-series"></div>
</div>
<div id="screen-live" class="app-screen">
    <div class="page-header" id="header-live">TV Ao Vivo</div>
    <div class="grid-content" id="grid-live"></div>
</div>

<nav class="bottom-nav">
    <div class="nav-item active" id="nav-home" onclick="switchScreen('home')">
        <i class="fas fa-home"></i><span>Início</span>
    </div>
    <div class="nav-item" id="nav-movie" onclick="switchScreen('movie')">
        <i class="fas fa-film"></i><span>Filmes</span>
    </div>
    <div class="nav-item" id="nav-series" onclick="switchScreen('series')">
        <i class="fas fa-layer-group"></i><span>Séries</span>
    </div>
    <div class="nav-item" id="nav-live" onclick="switchScreen('live')">
        <i class="fas fa-tv"></i><span>TV Ao Vivo</span>
    </div>
</nav>

<div id="seriesModal">
    <button class="btn-close-player" onclick="document.getElementById('seriesModal').style.display='none'" style="position:fixed; top:15px; right:15px; z-index:2501; border:none; background:rgba(0,0,0,0.6);"><i class="fas fa-arrow-left"></i> VOLTAR</button>
    <div id="seriesDetailContent"></div>
</div>

<div id="playerModal">
    <button class="btn-close-player" onclick="closePlayer()">FECHAR X</button>
    <div id="videoContainer" style="width: 100%; height: 100%; background: #000;"></div>
</div>

<script>
const apiBase = "<?php echo $apiUrl; ?>";
const streamHost = "<?php echo rtrim($streamHost, '/'); ?>";
const user = "<?php echo $user; ?>";
const pass = "<?php echo $pass; ?>";

let mpegtsPlayer = null; 
let appCache = {}; 
let currentItemsList = []; 
let currentRenderIndex = 0; 

function fixImg(url) {
    if (!url) return 'https://via.placeholder.com/150x225/111111/ffffff?text=TOP+TV';
    if (url.startsWith('//')) return 'https:' + url;
    return url;
}

window.addEventListener('scroll', () => {
    const header = document.getElementById('main-header');
    if (window.scrollY > 50) header.classList.add('scrolled');
    else header.classList.remove('scrolled');
});

function switchScreen(screenName) {
    document.querySelectorAll('.app-screen').forEach(el => el.classList.remove('active'));
    document.querySelectorAll('.nav-item').forEach(el => el.classList.remove('active'));
    document.getElementById('screen-' + screenName).classList.add('active');
    document.getElementById('nav-' + screenName).classList.add('active');
    window.scrollTo(0, 0);

    if(screenName !== 'home') {
        const grid = document.getElementById('grid-' + screenName);
        if(grid.innerHTML.trim() === '') { loadCategories(screenName); }
    }
}

function showSkeletons(grid, type) {
    grid.innerHTML = '';
    const qtd = type === 'cat' ? 12 : 15;
    for(let i=0; i<qtd; i++) {
        grid.innerHTML += `<div class="skeleton ${type === 'cat' ? 'skeleton-cat' : 'skeleton-item'}"></div>`;
    }
}

function loadHomeData() {
    const row = document.getElementById('row-recent-movies');
    row.innerHTML = '';
    for(let i=0; i<5; i++) { row.innerHTML += `<div class="skeleton skeleton-item" style="width:115px;"></div>`; }

    fetch(`${apiBase}&action=get_vod_streams`)
    .then(res => {
        if (!res.ok) throw new Error("Erro na API");
        return res.json();
    })
    .then(data => {
        if(!data || data.length === 0) return;
        let recentes = data.reverse().slice(0, 15);
        let destaque = recentes[0];
        
        document.getElementById('heroTitle').innerText = destaque.name;
        document.getElementById('heroTags').style.display = 'flex';
        document.getElementById('btnPlayHero').style.display = 'flex';
        document.getElementById('heroBanner').style.backgroundImage = `url('${fixImg(destaque.stream_icon)}')`;
        document.getElementById('btnPlayHero').onclick = () => playStream('movie', destaque.stream_id, destaque.container_extension);

        let htmlFilmes = '';
        recentes.forEach(filme => {
            htmlFilmes += `
                <div class="poster-card" onclick="playStream('movie', '${filme.stream_id}', '${filme.container_extension}')">
                    <img src="${fixImg(filme.stream_icon)}" loading="lazy">
                    <div class="poster-title">${filme.name}</div>
                </div>
            `;
        });
        row.innerHTML = htmlFilmes;
    })
    .catch(err => {
        document.getElementById('heroTitle').innerText = "Erro ao Carregar";
        row.innerHTML = '<div style="color:#ff4d4d; padding:15px; font-size:12px;">Falha de comunicação. Verifique a API.</div>';
    });
}

function loadCategories(type) {
    const grid = document.getElementById('grid-' + type);
    const header = document.getElementById('header-' + type);
    header.innerHTML = type === 'live' ? 'TV Ao Vivo' : (type === 'movie' ? 'Filmes' : 'Séries');
    
    const cacheKey = 'cat_' + type;
    if(appCache[cacheKey]) {
        renderCategoryCards(appCache[cacheKey], grid, type);
        return;
    }

    showSkeletons(grid, 'cat');

    const action = type === 'live' ? 'get_live_categories' : (type === 'movie' ? 'get_vod_categories' : 'get_series_categories');

    fetch(`${apiBase}&action=${action}`)
    .then(res => res.json())
    .then(data => {
        if(!data || data.length === 0) { grid.innerHTML = '<div style="grid-column:1/-1; text-align:center;">Nada encontrado.</div>'; return; }
        appCache[cacheKey] = data; 
        renderCategoryCards(data, grid, type);
    })
    .catch(() => { grid.innerHTML = '<div style="grid-column:1/-1; text-align:center; color:red;">Erro ao buscar dados.</div>'; });
}

function renderCategoryCards(data, grid, type) {
    grid.innerHTML = '';
    data.forEach(cat => {
        const div = document.createElement('div');
        div.className = 'cat-box';
        div.innerHTML = `<i class="fas fa-folder"></i><span>${cat.category_name}</span>`;
        div.onclick = () => loadItems(cat.category_id, cat.category_name, type);
        grid.appendChild(div);
    });
}

function loadItems(catId, catName, type) {
    const grid = document.getElementById('grid-' + type);
    const header = document.getElementById('header-' + type);
    header.innerHTML = `<button class="btn-back-page" onclick="loadCategories('${type}')"><i class="fas fa-arrow-left"></i></button> ${catName}`;
    
    const cacheKey = 'items_' + type + '_' + catId;

    if(appCache[cacheKey]) {
        currentItemsList = appCache[cacheKey];
        renderItemsChunk(grid, type, true); 
        return;
    }

    showSkeletons(grid, 'item');

    const action = type === 'live' ? 'get_live_streams' : (type === 'movie' ? 'get_vod_streams' : 'get_series');
    actionFinal = type === 'series' ? 'get_series' : action;

    fetch(`${apiBase}&action=${actionFinal}&category_id=${catId}`)
    .then(res => res.json())
    .then(data => {
        if(!data || data.length === 0) { grid.innerHTML = '<div style="grid-column:1/-1; text-align:center;">Pasta vazia.</div>'; return; }
        appCache[cacheKey] = data; 
        currentItemsList = data;
        renderItemsChunk(grid, type, true); 
    });
}

function renderItemsChunk(grid, type, isReset = false) {
    if(isReset) { grid.innerHTML = ''; currentRenderIndex = 0; window.scrollTo(0, 0); }

    let limite = currentRenderIndex + 40;
    let chunk = currentItemsList.slice(currentRenderIndex, limite);

    chunk.forEach(item => {
        const div = document.createElement('div');
        div.className = 'grid-item';
        let imgUrl = fixImg(item.stream_icon || item.cover);
        div.innerHTML = `<img src="${imgUrl}" loading="lazy"><div class="item-title">${item.name}</div>`;
        if(type === 'series') div.onclick = () => openSeries(item.series_id, item.name, imgUrl);
        else div.onclick = () => playStream(type, item.stream_id, item.container_extension);
        grid.appendChild(div);
    });

    currentRenderIndex += 40;

    if(currentRenderIndex < currentItemsList.length) {
        const btnBox = document.createElement('div');
        btnBox.style = "grid-column: 1/-1; padding: 15px 0;";
        btnBox.innerHTML = `<button class="btn-load-more">Mostrar Mais (${currentItemsList.length - currentRenderIndex})</button>`;
        btnBox.onclick = function() { this.remove(); renderItemsChunk(grid, type, false); };
        grid.appendChild(btnBox);
    }
}

function openSeries(id, name, img) {
    const modal = document.getElementById('seriesModal');
    const content = document.getElementById('seriesDetailContent');
    modal.style.display = 'block';
    
    content.innerHTML = `<div class="series-header" style="background:#111;"></div><div style="padding:20px;"><div class="skeleton skeleton-cat" style="margin-bottom:10px;"></div><div class="skeleton skeleton-cat"></div></div>`;

    fetch(`${apiBase}&action=get_series_info&series_id=${id}`)
    .then(res => res.json())
    .then(data => {
        let html = `<div class="series-header" style="background-image: url('${img}');"><div class="series-overlay"></div><div class="series-info"><h2 class="series-title">${name}</h2></div></div>`;
        for (let s in data.episodes) {
            html += `<div class="season-block"><div class="season-title">TEMPORADA ${s}</div>`;
            data.episodes[s].forEach(ep => {
                html += `<div class="episode-row" onclick="playStream('series', '${ep.id}', '${ep.container_extension}')">
                        <span style="font-size:13px;"><b>EP ${ep.episode_num}</b> - ${ep.title}</span>
                        <i class="fas fa-play-circle" style="color:var(--accent);"></i>
                    </div>`;
            });
            html += `</div>`;
        }
        content.innerHTML = html;
    });
}

function playStream(type, id, ext) {
    document.getElementById('playerModal').style.display = 'block';
    const container = document.getElementById('videoContainer');
    
    container.innerHTML = '<video id="videoPlayer" controls playsinline style="width: 100%; height: 100%; outline: none; background: #000;"></video>';
    const videoElement = document.getElementById('videoPlayer');

    if (type === 'live') {
        let proxyUrl = `?proxy_canal=${id}`;
        
        if (mpegts.getFeatureList().mseLivePlayback) {
            mpegtsPlayer = mpegts.createPlayer({
                type: 'mpegts',
                isLive: true,
                url: proxyUrl
            });
            mpegtsPlayer.attachMediaElement(videoElement);
            mpegtsPlayer.load();
            mpegtsPlayer.play().catch(e => console.log("Aguardando play do usuário"));
        } else {
            videoElement.src = proxyUrl;
            videoElement.play();
        }
    } else {
        let url = type === 'movie' 
            ? `${streamHost}/movie/${user}/${pass}/${id}.${ext || 'mp4'}`
            : `${streamHost}/series/${user}/${pass}/${id}.${ext || 'mp4'}`;
            
        videoElement.src = url;
        videoElement.play();
    }
}

function closePlayer() {
    const videoElement = document.getElementById('videoPlayer');
    if (videoElement) {
        videoElement.pause();
        videoElement.src = "";
    }
    if (mpegtsPlayer) {
        mpegtsPlayer.destroy();
        mpegtsPlayer = null;
    }
    document.getElementById('playerModal').style.display = 'none';
    document.getElementById('videoContainer').innerHTML = '';
}

window.onload = () => { loadHomeData(); };
</script>
</body>
</html>