<?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_int = getConexaoInterna();
    if (!empty($slug)) {
        $stmt = $pdo_int->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) {}

$modo_ativo = 'interno';
try {
    $modo_ativo = $pdo_int->query("SELECT modo_ativo FROM configuracoes LIMIT 1")->fetchColumn() ?: 'interno';
} catch (Exception $e) {}

$tabela_clientes = ($modo_ativo === 'xui') ? '`lines`' : '`users`';

// =========================================================================
// 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 $tabela_clientes 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'] ?? '';

// TELA DE LOGIN
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; }

// =========================================================================
// 3. CAPTURA DE STREAM HOST FALLBACK
// =========================================================================
$pdo_ext = getConexaoAtiva();
$protocolo = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on') ? "https://" : "http://";
$streamHost = $protocolo . $_SERVER['HTTP_HOST']; 
$dns_encontrado = false;

try {
    $stmtLb = $pdo_ext->query("SELECT ip_servidor, porta FROM servidores_lb WHERE status = 1 ORDER BY id DESC LIMIT 1");
    $lbAtivo = $stmtLb->fetch(PDO::FETCH_ASSOC);
    if ($lbAtivo && !empty($lbAtivo['ip_servidor'])) {
        $porta_lb = (isset($lbAtivo['porta']) && $lbAtivo['porta'] != 80 && $lbAtivo['porta'] != '') ? ":" . $lbAtivo['porta'] : "";
        $dns_val = trim($lbAtivo['ip_servidor']) . $porta_lb;
        if (strpos($dns_val, 'http') !== 0) $dns_val = "http://" . $dns_val;
        $streamHost = rtrim($dns_val, '/');
        $dns_encontrado = true;
    }
} catch(Exception $e){}

if (!$dns_encontrado) {
    try {
        $tabela_servidores = ($modo_ativo === 'xui') ? 'servers' : 'streaming_servers';
        $stmtDns = $pdo_ext->query("SELECT * FROM $tabela_servidores ORDER BY id ASC LIMIT 1");
        $serverInfo = $stmtDns->fetch(PDO::FETCH_ASSOC);
        if ($serverInfo) {
            $dns_val = (isset($serverInfo['domain_name']) && !empty(trim($serverInfo['domain_name']))) ? trim($serverInfo['domain_name']) : trim($serverInfo['server_ip']);
            if (!empty($dns_val)) {
                if (strpos($dns_val, 'http') !== 0) $dns_val = "http://" . $dns_val;
                $streamHost = rtrim($dns_val, '/');
            }
        }
    } catch(Exception $e){}
}

// =========================================================================
// 4. PROXY DA API LOCAL
// =========================================================================
if (isset($_GET['proxy_api'])) {
    session_write_close();
    while (ob_get_level()) { ob_end_clean(); } 

    $caminho_base = str_replace(['/webplayer/index.php', '/webplayer/'], '', $_SERVER['SCRIPT_NAME']);
    $local_api_url = $protocolo . $_SERVER['HTTP_HOST'] . $caminho_base . "/player_api.php";
    
    $req_url = $local_api_url . "?username=" . urlencode($user) . "&password=" . urlencode($pass);
    foreach ($_GET as $k => $v) {
        if (!in_array($k, ['proxy_api', 'user', 'pass', 'id', '_t'])) {
            $req_url .= "&" . $k . "=" . urlencode($v);
        }
    }

    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, $req_url);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
    echo curl_exec($ch);
    curl_close($ch);
    exit;
}

// =========================================================================
// 5. PROXY DE VÍDEO (DUAS ETAPAS: RESOLUÇÃO + STREAMING LIMPO)
// =========================================================================
if (isset($_GET['proxy_stream'])) {
    header('X-Accel-Buffering: no'); 
    session_write_close(); 

    @set_time_limit(0);
    @ini_set('output_buffering', 'off');
    @ini_set('zlib.output_compression', false);
    while (ob_get_level() > 0) { @ob_end_clean(); } // Limpa qualquer lixo na memória

    $id_stream = intval($_GET['proxy_stream']);
    $type_stream = $_GET['type'] ?? 'movie';
    $ext_stream = preg_replace('/[^a-zA-Z0-9]/', '', $_GET['ext'] ?? 'mp4');
    
    $url_original = "";

    try {
        $stmtSrc = $pdo_ext->prepare("SELECT stream_source FROM streams WHERE id = ? LIMIT 1");
        $stmtSrc->execute([$id_stream]);
        $source = $stmtSrc->fetchColumn();
        
        if (empty($source)) {
            $tabela_ep = ($modo_ativo === 'xui') ? 'streams_episodes' : 'series_episodes';
            $stmtSrcS = $pdo_ext->prepare("SELECT stream_source FROM $tabela_ep WHERE stream_id = ? LIMIT 1");
            $stmtSrcS->execute([$id_stream]);
            $source = $stmtSrcS->fetchColumn();
        }

        if (!empty($source)) {
            $dec = @json_decode($source, true);
            $candidato = is_array($dec) && isset($dec[0]) ? trim($dec[0]) : trim(str_replace(['[', ']', '"', '\\', "'"], '', $source));
            if (strpos($candidato, ',http') !== false) { $parts = explode(',http', $candidato); $candidato = $parts[0]; }
            
            if (strpos($candidato, 'http') !== 0) {
                $url_original = rtrim($streamHost, '/') . '/' . ltrim($candidato, '/');
            } else {
                $url_original = $candidato;
            }
        }
    } catch(Exception $e){}

    if (empty($url_original)) {
        if ($type_stream === 'live') {
            $url_original = $streamHost . "/live/" . $user . "/" . $pass . "/" . $id_stream . ".ts";
        } else {
            $url_original = $streamHost . "/" . $type_stream . "/" . $user . "/" . $pass . "/" . $id_stream . "." . $ext_stream;
        }
    }

    // ETAPA 1: O BATEDOR (Acha o link final da Backblaze)
    $url_final = $url_original;
    if (!empty($url_final) && strpos($url_final, '/play/') !== false) {
        $ch_res = curl_init(str_replace(' ', '%20', $url_final));
        curl_setopt($ch_res, CURLOPT_RETURNTRANSFER, true);
        curl_setopt($ch_res, CURLOPT_HEADER, true);
        curl_setopt($ch_res, CURLOPT_NOBODY, true); // Não baixa o filme, só os cabeçalhos!
        curl_setopt($ch_res, CURLOPT_FOLLOWLOCATION, true);
        curl_setopt($ch_res, CURLOPT_MAXREDIRS, 5);
        curl_setopt($ch_res, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch_res, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36');
        curl_exec($ch_res);
        $url_final = curl_getinfo($ch_res, CURLINFO_EFFECTIVE_URL); // Pega o link real
        curl_close($ch_res);
    }

    // ETAPA 2: O TRANSPORTADOR (Faz o download nativo, sem misturar código)
    header('Access-Control-Allow-Origin: *');
    header('Cache-Control: no-cache, no-store, must-revalidate');
    header('Content-Type: ' . ($type_stream === 'live' || $ext_stream === 'ts' ? 'video/mp2t' : 'video/mp4'));
    
    $ch = curl_init(str_replace(' ', '%20', $url_final));
    
    $headers_req = [];
    if (isset($_SERVER['HTTP_RANGE'])) {
        $headers_req[] = 'Range: ' . $_SERVER['HTTP_RANGE'];
    }
    if (!empty($headers_req)) {
        curl_setopt($ch, CURLOPT_HTTPHEADER, $headers_req);
    }

    // A MÁGICA DE NÃO QUEBRAR O PLAYER: Deixamos o PHP enviar os bytes nativamente!
    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_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) Chrome/120.0.0.0 Safari/537.36');
    curl_setopt($ch, CURLOPT_TIMEOUT, 0);

    // Filtra os cabeçalhos essenciais de tempo/duração para o player do celular
    curl_setopt($ch, CURLOPT_HEADERFUNCTION, function($curl, $header_line) {
        $hl = strtolower(trim($header_line));
        
        if (preg_match('/^http\/(1\.0|1\.1|2|2\.0)\s+(200|206)/i', $hl, $matches)) {
            http_response_code(intval($matches[2]));
        } elseif (strpos($hl, 'content-type:') === 0 || 
                  strpos($hl, 'content-length:') === 0 || 
                  strpos($hl, 'content-range:') === 0 || 
                  strpos($hl, 'accept-ranges:') === 0) {
            header(trim($header_line));
        }
        return strlen($header_line);
    });

    ignore_user_abort(true);
    curl_exec($ch);
    curl_close($ch);
    exit;
}

try {
    $stmt = $pdo_ext->prepare("SELECT id, username, exp_date, enabled FROM $tabela_clientes 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'];
    $vencimento = (empty($res['exp_date']) || $res['exp_date'] == 0) ? 'Ilimitado' : 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>
        :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; }
        
        .search-box { display: flex; align-items: center; background: rgba(0,0,0,0.5); border: 1px solid rgba(255,255,255,0.2); border-radius: 20px; padding: 6px 12px; transition: all 0.3s ease; }
        .search-box input { background: transparent; border: none; color: white; width: 0px; padding: 0; outline: none; transition: all 0.3s ease; font-size: 13px; }
        .search-box.active input { width: 130px; padding-left: 8px; }
        .search-box i { color: var(--accent); cursor: pointer; font-size: 16px; }

        .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 class="search-box" id="searchBox">
            <i class="fas fa-search" onclick="toggleSearch()"></i>
            <input type="text" id="searchInput" placeholder="Pesquisar..." onkeyup="filterItems()">
        </div>
        
        <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 = "?proxy_api=1";

let mpegtsPlayer = null; 
let appCache = {}; 
let globalSearchCache = {}; 
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;
}

function normalizar(texto) {
    if (!texto) return '';
    return texto.normalize("NFD").replace(/[\u0300-\u036f]/g, "").toLowerCase();
}

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

function toggleSearch() {
    const box = document.getElementById('searchBox');
    box.classList.toggle('active');
    if(box.classList.contains('active')) {
        document.getElementById('searchInput').focus();
    } else {
        document.getElementById('searchInput').value = '';
        filterItems();
    }
}

function filterItems() {
    const query = normalizar(document.getElementById('searchInput').value);
    const activeScreenEl = document.querySelector('.app-screen.active');
    if(!activeScreenEl) return;
    const type = activeScreenEl.id.replace('screen-', '');
    if (type === 'home') return; 

    const grid = document.getElementById('grid-' + type);
    const headerContent = document.getElementById('header-' + type).innerHTML;
    
    if (headerContent.includes('btn-back-page')) {
        if (query === '') {
            renderItemsChunk(grid, type, true);
        } else {
            const filtered = currentItemsList.filter(item => normalizar(item.name).includes(query));
            renderFiltered(filtered, grid, type);
        }
    } 
    else {
        if (query === '') {
            if(appCache['cat_' + type]) renderCategoryCards(appCache['cat_' + type], grid, type);
        } else {
            if(globalSearchCache[type]) {
                const filtered = globalSearchCache[type].filter(item => normalizar(item.name).includes(query));
                renderFiltered(filtered, grid, type);
            } else {
                grid.innerHTML = '<div style="grid-column:1/-1; text-align:center;">Buscando em todo o acervo...</div>';
                const action = type === 'live' ? 'get_live_streams' : (type === 'movie' ? 'get_vod_streams' : 'get_series');
                fetch(`${apiBase}&action=${action}&_t=` + Date.now())
                .then(res => res.json())
                .then(data => {
                    globalSearchCache[type] = data || [];
                    filterItems(); 
                });
            }
        }
    }
}

function renderFiltered(filteredList, grid, type) {
    grid.innerHTML = '';
    if(filteredList.length === 0) {
        grid.innerHTML = '<div style="grid-column:1/-1; text-align:center;">Nenhum conteúdo encontrado.</div>';
        return;
    }
    filteredList.slice(0, 150).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);
    });
}

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);

    document.getElementById('searchInput').value = '';
    document.getElementById('searchBox').classList.remove('active');

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

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&_t=` + Date.now())
    .then(res => 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(() => { document.getElementById('heroTitle').innerText = "TOP TV PLAYER"; });
}

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}&_t=` + Date.now())
    .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);
    });
}

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);
    document.getElementById('header-' + type).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');

    fetch(`${apiBase}&action=${action}&category_id=${catId}&_t=` + Date.now())
    .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 chunk = currentItemsList.slice(currentRenderIndex, currentRenderIndex + 40);

    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</button>`;
        btnBox.onclick = function() { this.remove(); renderItemsChunk(grid, type, false); };
        grid.appendChild(btnBox);
    }
}

function openSeries(id, name, img) {
    document.getElementById('seriesModal').style.display = 'block';
    const content = document.getElementById('seriesDetailContent');
    content.innerHTML = `<div style="padding:20px;">Carregando Episódios...</div>`;

    fetch(`${apiBase}&action=get_series_info&series_id=${id}&_t=` + Date.now())
    .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"></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');

    let formatExt = ext || (type === 'live' ? 'ts' : 'mp4');
    let proxyUrl = `?proxy_stream=${id}&type=${type}&ext=${formatExt}&_t=` + Date.now();

    if (type === 'live' || formatExt === 'ts') {
        if (mpegts.getFeatureList().mseLivePlayback) {
            mpegtsPlayer = mpegts.createPlayer({ type: 'mpegts', isLive: (type === 'live'), url: proxyUrl });
            mpegtsPlayer.attachMediaElement(videoElement);
            mpegtsPlayer.load();
            mpegtsPlayer.play().catch(e => {});
        } else { videoElement.src = proxyUrl; videoElement.play(); }
    } else { videoElement.src = proxyUrl; videoElement.play(); }
}

function closePlayer() {
    const videoElement = document.getElementById('videoPlayer');
    
    if (mpegtsPlayer) {
        try {
            mpegtsPlayer.pause();
            mpegtsPlayer.unload();
            mpegtsPlayer.detachMediaElement();
            mpegtsPlayer.destroy();
        } catch(e) {}
        mpegtsPlayer = null;
    }
    
    if (videoElement) {
        videoElement.pause();
        videoElement.removeAttribute('src'); 
        videoElement.load(); 
        videoElement.parentNode.removeChild(videoElement); 
    }

    document.getElementById('playerModal').style.display = 'none';
    document.getElementById('videoContainer').innerHTML = '';
}
window.onload = () => { loadHomeData(); };
</script>
</body>
</html>
