<?php
session_start();

// ====================================================================
// 1. TÚNEL ANTI-BLOQUEIO PARA PUXAR A LISTA DE JOGOS (MÁGICA AQUI)
// ====================================================================
if (isset($_GET['fetch_jogos'])) {
    header('Content-Type: application/json; charset=utf-8');
    header('Access-Control-Allow-Origin: *');
    
    // Tenta os dois links oficiais da Unyserve
    $urls = ['https://api.unyserve.com.br/jogos.php', 'https://api.unyserve.com.br/jogos.json'];
    $response = null;

    foreach ($urls as $url) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_ENCODING, ''); // ISSO AQUI QUEBRA A BARREIRA DO CLOUDFLARE
        curl_setopt($ch, CURLOPT_TIMEOUT, 10);
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36');
        curl_setopt($ch, CURLOPT_HTTPHEADER, [
            'Accept: application/json, text/plain, */*',
            'Referer: https://api.unyserve.com.br/'
        ]);
        
        $res = curl_exec($ch);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200 && $res) {
            $response = $res;
            break; // Achou os jogos! Sai do loop.
        }
    }

    if ($response) {
        echo $response;
    } else {
        echo json_encode(['erro' => true, 'msg' => 'Bloqueado pela origem']);
    }
    exit;
}

// ====================================================================
// 2. PROXY DE IMAGENS (PARA OS ESCUDOS NÃO DAREM ERRO NO BANNER)
// ====================================================================
if (isset($_GET['proxy_url'])) {
    $url = urldecode($_GET['proxy_url']);
    if (strpos($url, 'http') === 0) {
        $ch = curl_init();
        curl_setopt($ch, CURLOPT_URL, $url);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_ENCODING, ''); // Ajuda nas imagens também
        curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36');
        
        $conteudo = curl_exec($ch);
        $content_type = curl_getinfo($ch, CURLINFO_CONTENT_TYPE);
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        curl_close($ch);

        if ($http_code == 200 && $conteudo) {
            header("Access-Control-Allow-Origin: *");
            if (strpos($content_type, 'json') !== false || strpos($url, '.json') !== false) {
                header("Content-Type: application/json");
            } else {
                header("Content-Type: image/png"); 
            }
            echo $conteudo;
            exit;
        }
    }
    http_response_code(404);
    exit;
}

require_once 'config.php';

if (!isset($_SESSION['user_id'])) { header("Location: login.php"); exit; }
$my_id = $_SESSION['user_id'];

$pdo = getConexaoAtiva(); 
$pdo_int = getConexaoInterna();

$nome_painel = 'TOP IPTV';
$cor_primaria = '#007bff';

try {
    $config_painel = $pdo_int->query("SELECT * FROM painel_config LIMIT 1")->fetch(PDO::FETCH_ASSOC);
    if ($config_painel) {
        $nome_painel = $config_painel['nome_painel'] ?? $nome_painel;
        $cor_primaria = $config_painel['cor_primaria'] ?? $cor_primaria;
    }
} 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_revendedores = ($modo_ativo === 'xui') ? '`users`' : '`reg_users`';
try {
    $stmtRole = $pdo->prepare("SELECT member_group_id, credits FROM $tabela_revendedores WHERE id = ?");
    $stmtRole->execute([$my_id]);
    $userData = $stmtRole->fetch(PDO::FETCH_ASSOC);
    
    $role = ($userData && $userData['member_group_id'] == 1) ? 'admin' : 'reseller';
    $user_credits = $userData ? floatval($userData['credits']) : 0.0;
} catch (Exception $e) {
    $role = 'reseller';
    $user_credits = 0.0;
}
?>
<!DOCTYPE html>
<html lang="pt-BR">
<head>
    <link rel="stylesheet" href="tema.css">
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Gerador de Banners de Futebol - <?php echo htmlspecialchars($nome_painel); ?></title>
    
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet">
    <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap-icons@1.11.1/font/bootstrap-icons.css">
    <script src="https://cdn.jsdelivr.net/npm/html2canvas@1.4.1/dist/html2canvas.min.js"></script>

    <style>
        :root { --bg-dark: #121519; --bg-sidebar: #1e2227; --bg-card: #272c33; --text-main: #d1d5da; --text-muted: #8a94a1; --accent: <?php echo $cor_primaria; ?>; --border-color: #3a4149; --success: #28a745;}
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background-color: var(--bg-dark); color: var(--text-main); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 260px; background-color: var(--bg-sidebar); border-right: 1px solid var(--border-color); display: flex; flex-direction: column; z-index: 1001; transition: 0.3s; flex-shrink: 0; }
        .sidebar-header { padding: 25px 20px; text-align: center; font-size: 22px; font-weight: bold; color: white; border-bottom: 1px solid var(--border-color); }
        .sidebar-logo { width: 100%; max-width: 180px; height: auto; max-height: 60px; object-fit: contain; display: block; margin: 0 auto; }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .user-info .badge { background: rgba(0, 123, 255, 0.2); color: var(--accent); padding: 4px 10px; border-radius: 4px; font-size: 11px; text-transform: uppercase; font-weight: bold; margin-top: 5px; display: inline-block; }
        .credits-badge { display: block; margin-top: 10px; color: var(--success); font-weight: bold; font-size: 13px; }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; }
        .menu-item { padding: 14px 20px; color: var(--text-main); text-decoration: none; display: flex; align-items: center; transition: 0.2s; border-left: 3px solid transparent; font-size: 15px; cursor: pointer; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--text-muted); }
        .menu-item:hover, .menu-item.active { background-color: #2c3138; color: white; border-left-color: var(--accent); }
        .menu-item.active i:first-child { color: var(--accent); }
        .submenu { display: none; background: #16191d; list-style: none; padding: 0; margin: 0; }
        .submenu .menu-item { padding-left: 52px; font-size: 13px; border-left: none; }
        .arrow-icon { margin-left: auto; transition: 0.3s; font-size: 11px; }
        .rotate { transform: rotate(180deg); }
        .menu-category { padding: 20px 20px 8px; font-size: 10px; text-transform: uppercase; color: var(--text-muted); font-weight: bold; letter-spacing: 1px; }
        .logout-btn { padding: 15px; background-color: #dc3545; color: white; text-align: center; text-decoration: none; font-weight: bold; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }

        .main-content { flex: 1; display: flex; flex-direction: column; overflow-y: auto; width: 100%; position: relative; }
        .topbar { display: flex; justify-content: space-between; align-items: center; padding: 15px 25px; background-color: var(--bg-sidebar); border-bottom: 1px solid var(--border-color); gap: 15px;}
        .menu-toggle { display: none; background: none; border: none; color: white; font-size: 22px; cursor: pointer; padding: 5px; }
        .mode-badge { padding: 6px 15px; background: rgba(0, 123, 255, 0.15); color: var(--accent); border-radius: 20px; font-size: 12px; font-weight: bold; border: 1px solid var(--accent); white-space: nowrap; }
        .content-area { padding: 30px; flex: 1; max-width: 1400px; margin: 0 auto; width: 100%; box-sizing: border-box; }

        .card { background-color: var(--bg-card); border: 1px solid var(--border-color); border-radius: 10px; }
        .card-header { border-bottom: 1px solid var(--border-color); }
        .form-control, .form-select { background-color: #121519; border: 1px solid var(--border-color); color: white; }
        .form-control:focus, .form-select:focus { background-color: #121519; color: white; border-color: var(--accent); box-shadow: 0 0 0 0.25rem rgba(13, 110, 253, 0.25); }
        .form-label { color: var(--text-main); font-size: 0.85rem; }

        @keyframes pulse { 0%,100%{opacity:1;transform:scale(1)} 50%{opacity:.35;transform:scale(.7)} }
        .tema-btn { transition:all .2s; } .tema-btn:hover { transform:scale(1.06); } .tema-btn.active { border-color:#fff !important; box-shadow:0 0 0 2px #0d6efd; }
        .fmt-btn { transition:all .2s; font-size:.75rem; }
        
        .jogo-api-item { background: #1a1a2e; color: white; border-color: var(--border-color) !important; cursor: pointer; transition: all .15s;}
        .jogo-api-item.selected { background: rgba(13, 110, 253, 0.2) !important; border-color: var(--accent) !important; }
        .jogo-api-item:hover { box-shadow:0 2px 8px rgba(13,110,253,.15); }
        
        .fundo-item { background: #1a1a2e; border: 2px solid transparent; }
        .fundo-item.active { border-color: var(--accent) !important; background: rgba(13, 110, 253, 0.2) !important; }
        .fundo-item small { color: white; }

        @media (max-width: 768px) {
            .menu-toggle { display: block; }
            .sidebar { position: fixed; left: -260px; height: 100%; box-shadow: 10px 0 20px rgba(0,0,0,0.5); }
            .sidebar.active { left: 0; }
            .sidebar-overlay.active { display: block; }
            .content-area { padding: 15px; }
            .topbar-right { margin-left: auto; }
        }
    </style>
</head>
<body>
    <div class="sidebar-overlay" id="overlay" onclick="toggleMenu()"></div>
    
    <?php include 'sidebar.php'; ?>

    <div class="main-content">
        <header class="topbar">
            <div style="display:flex; align-items:center; gap: 10px;">
                <button class="menu-toggle" onclick="toggleMenu()"><i class="fas fa-bars"></i></button>
                <h2 style="margin:0; font-size: 18px; color:white;"><i class="fas fa-futbol" style="color:var(--accent);"></i> Banners de Futebol</h2>
            </div>
            <div class="topbar-right">
                <span class="mode-badge"><i class="fas fa-database"></i> MODO: <?php echo defined('MODO_SISTEMA') ? strtoupper(MODO_SISTEMA) : strtoupper($modo_ativo); ?></span>
            </div>
        </header>

        <div class="content-area">
            
            <div id="api_warning" class="alert alert-warning" style="display:none; background: rgba(243, 156, 18, 0.1); border: 1px solid #f39c12; color: #f39c12; padding: 15px; border-radius: 5px; margin-bottom: 20px;">
                <i class="fas fa-exclamation-triangle"></i> Não foi possível conectar à API. Exibindo jogos de demonstração salvos. <b>Verifique a comunicação da sua rede.</b>
            </div>

            <div class="row">
                <div class="col-lg-4 mb-4">
                    <div class="card shadow mb-4">
                        <div class="card-header" style="background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;">
                            <h6 class="mb-0 fs-6"><i class="bi bi-lightning-fill me-2 text-warning"></i>Jogos do Dia <span id="badge_count_jogos" class="badge bg-warning text-dark ms-2">0</span></h6>
                        </div>
                        <div id="lista_jogos_container" class="card-body p-2" style="max-height:320px;overflow-y:auto;">
                            <div style="padding:40px; text-align:center; color:#fff;">
                                <i class="fas fa-circle-notch fa-spin fa-2x mb-3" style="color:var(--accent);"></i><br>Buscando jogos ao vivo...
                            </div>
                        </div>
                    </div>

                    <div class="card shadow mb-4">
                        <div class="card-header bg-dark text-white"><h6 class="mb-0 fs-6"><i class="bi bi-sliders me-2"></i>Configurações</h6></div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label fw-semibold" style="font-size:.78rem;">Nome do Serviço</label>
                                <input type="text" class="form-control" id="marca" value="<?php echo htmlspecialchars($nome_painel); ?>" oninput="renderBanner()">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-semibold" style="font-size:.78rem;">Título do Banner</label>
                                <input type="text" class="form-control" id="tituloBanner" value="JOGOS DE HOJE" oninput="renderBanner()">
                            </div>
                            
                            <label class="form-label fw-semibold" style="font-size:.78rem;">Formato</label>
                            <div class="d-flex flex-wrap gap-2 mb-3">
                                <button class="btn btn-sm btn-primary fmt-btn active" data-fmt="horizontal" onclick="setFormato('horizontal',this)" title="720×auto">
                                    <i class="bi bi-aspect-ratio me-1"></i>Horizontal
                                </button>
                                <button class="btn btn-sm btn-outline-secondary fmt-btn" data-fmt="quadrado" onclick="setFormato('quadrado',this)" title="1080×1080">
                                    <i class="bi bi-square me-1"></i>Feed (1:1)
                                </button>
                                <button class="btn btn-sm btn-outline-secondary fmt-btn" data-fmt="stories" onclick="setFormato('stories',this)" title="1080×1920">
                                    <i class="bi bi-phone me-1"></i>Stories
                                </button>
                                <button class="btn btn-sm btn-outline-secondary fmt-btn" data-fmt="whatsapp" onclick="setFormato('whatsapp',this)" title="800×450">
                                    <i class="bi bi-whatsapp me-1"></i>WA Card
                                </button>
                            </div>

                            <label class="form-label fw-semibold" style="font-size:.78rem;">Tema</label>
                            <div class="d-flex flex-wrap gap-2 mb-3">
                                <button class="btn btn-sm tema-btn active" data-tema="0" style="background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;border:2px solid #0d6efd;">⚫ Noite</button>
                                <button class="btn btn-sm tema-btn" data-tema="1" style="background:linear-gradient(135deg,#0d1b0d,#1b4332);color:#fff;border:2px solid transparent;">🟢 Verde</button>
                                <button class="btn btn-sm tema-btn" data-tema="2" style="background:linear-gradient(135deg,#1a0a2e,#2d1b69);color:#fff;border:2px solid transparent;">🟣 Roxo</button>
                                <button class="btn btn-sm tema-btn" data-tema="3" style="background:linear-gradient(135deg,#1a0a0a,#4a0000);color:#fff;border:2px solid transparent;">🔴 Vermelho</button>
                                <button class="btn btn-sm tema-btn" data-tema="4" style="background:linear-gradient(135deg,#0a1a2a,#0a3a6a);color:#fff;border:2px solid transparent;">🔵 Azul</button>
                                <button class="btn btn-sm tema-btn" data-tema="5" style="background:linear-gradient(135deg,#1a1200,#3a2800);color:#fff;border:2px solid transparent;">🟡 Gold</button>
                            </div>

                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="mostrarCanais" checked onchange="renderBanner()">
                                <label class="form-check-label text-white" style="font-size:.82rem;">Mostrar canais</label>
                            </div>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="mostrarCompetição" checked onchange="renderBanner()">
                                <label class="form-check-label text-white" style="font-size:.82rem;">Mostrar competição</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="mostrarEscudos" checked onchange="renderBanner()">
                                <label class="form-check-label text-white" style="font-size:.82rem;">Mostrar escudos</label>
                            </div>
                        </div>
                    </div>

                    <div class="card shadow mb-4">
                        <div class="card-header bg-dark text-white"><h6 class="mb-0 fs-6"><i class="bi bi-image-fill me-2"></i>Fundo do Banner</h6></div>
                        <div class="card-body p-2" style="max-height: 200px; overflow-y: auto;">
                            <div class="fundo-item active mb-2 px-2 py-1 rounded d-flex align-items-center gap-2" style="cursor:pointer;border:2px solid #0d6efd;background:#e8f0fe;" onclick="selecionarFundo(null, this)">
                                <div style="width:48px;height:30px;border-radius:4px;background:linear-gradient(135deg,#1a1a2e,#16213e);flex-shrink:0;"></div>
                                <small class="fw-semibold text-dark">Sem fundo (cor do tema)</small>
                            </div>
                            
                            <?php 
                            $fundos = [
                                "https://media.gettyimages.com/id/1283680954/pt/foto/soccer-field-with-illumination-green-grass-and-clouds.jpg?s=612x612&w=0&k=20&c=Jd2kK9r_62ZkU30jE0K5Q2j_3y0V85a3c940_n_b588=",
                                "https://media.gettyimages.com/id/1324546653/pt/foto/soccer-stadium-at-night.jpg?s=612x612&w=0&k=20&c=t19aY5m-t2P28y50o4g62bX_R76Y-773q00y7f8y83A=",
                                "https://media.gettyimages.com/id/1149959632/pt/foto/soccer-ball-on-green-grass-of-soccer-field-with-copy-space.jpg?s=612x612&w=0&k=20&c=V-y3z5E_Z0bE8s-074Q4R4v_867R2f2X-n2452R_yM0=",
                                "/modules/jogos/imgs/barcelona-futebol-messi.jpg",
                                "/modules/jogos/imgs/borussia-dortmund.jpg",
                                "/modules/jogos/imgs/cbf-futebol-brasil.jpg",
                                "/modules/jogos/imgs/corinthians-football-futebol-sccp.jpg",
                                "/modules/jogos/imgs/corinthians.jpg",
                                "/modules/jogos/imgs/flamengo-arrascaeta.jpg",
                                "/modules/jogos/imgs/flamengo-crf-futebol-torcida.jpg",
                                "/modules/jogos/imgs/fortaleza-ec-futebol.jpg",
                                "/modules/jogos/imgs/gremio-fbpa.jpg",
                                "/modules/jogos/imgs/lewandowski-09-futebol.jpg",
                                "/modules/jogos/imgs/lionel-messi.jpg",
                                "/modules/jogos/imgs/manchester.jpg",
                                "/modules/jogos/imgs/mbappe-psg.jpg",
                                "/modules/jogos/imgs/messi-and-ronaldinho.jpg",
                                "/modules/jogos/imgs/neymar-atleta-barcelonar.jpg",
                                "/modules/jogos/imgs/neymar-best-brazil.jpg",
                                "/modules/jogos/imgs/neymar-jr-brazil.jpg",
                                "/modules/jogos/imgs/neymar-jr.jpg",
                                "/modules/jogos/imgs/palmeiras-futebol.jpg",
                                "/modules/jogos/imgs/palmeiras.jpg",
                                "/modules/jogos/imgs/ronaldinho-barcelona-brazil.jpg",
                                "/modules/jogos/imgs/ronaldinho-barcelona.jpg",
                                "/modules/jogos/imgs/santos-fc-alvinegro.jpg",
                                "/modules/jogos/imgs/santos-fc-santos-futebol.jpg",
                                "/modules/jogos/imgs/spfc-tricolor.jpg",
                                "/modules/jogos/imgs/spfc.jpg",
                                "/modules/jogos/imgs/sport-recifel.jpg",
                                "/modules/jogos/imgs/torcida-flamengo.jpg",
                                "/modules/jogos/imgs/vasco-brasil-futebol.jpg",
                                "/modules/jogos/imgs/vasco-da-gama-compilado-futebol.jpg",
                                "/modules/jogos/imgs/vasco-da-gama.jpg"
                            ];
                            foreach($fundos as $idx => $f): ?>
                            <div class="fundo-item mb-1 px-2 py-1 rounded d-flex align-items-center gap-2" style="cursor:pointer;border:2px solid transparent;transition:all .15s;" onclick="selecionarFundo('<?php echo $f; ?>', this)" onmouseover="this.style.borderColor='#6c757d'" onmouseout="if(!this.classList.contains('active'))this.style.borderColor='transparent'">
                                <img src="<?php echo $f; ?>" style="width:48px;height:30px;border-radius:4px;object-fit:cover;flex-shrink:0;">
                                <small class="text-truncate" style="font-size:.72rem;">Fundo Estádio <?php echo $idx+1; ?></small>
                            </div>
                            <?php endforeach; ?>
                        </div>
                    </div>
                    
                    <div class="card shadow mb-4">
                        <div class="card-header bg-dark text-white"><h6 class="mb-0"><i class="bi bi-badge-ad me-2"></i>Logo da Marca</h6></div>
                        <div class="card-body">
                            <p class="text-light mb-2" style="font-size:.78rem; opacity: 0.9;">PNG transparente recomendado.</p>
                            <div id="logoPreviewArea" class="mb-3 d-flex align-items-center" style="min-height:52px;">
                                <span class="text-light" style="font-size:.8rem; opacity: 0.9;">Carregando...</span>
                            </div>
                            <input type="file" id="logoFileInput" accept="image/png,image/jpeg,image/webp" style="display:none;" onchange="uploadLogo(this)">
                            <button id="btnUploadLogo" class="btn btn-outline-primary w-100" onclick="document.getElementById('logoFileInput').click()">
                                <i class="bi bi-upload me-1"></i>Fazer upload
                            </button>
                            <div class="text-light mt-1" style="font-size:.7rem; opacity: 0.9;">PNG / JPG / WEBP · máx. 2 MB</div>
                        </div>
                    </div>

                    <div class="card shadow">
                        <div class="card-header" style="background:linear-gradient(135deg,#198754,#157347);color:#fff;">
                            <h6 class="mb-0 fs-6"><i class="bi bi-download me-2"></i>Exportar</h6>
                        </div>
                        <div class="card-body">
                            <button class="btn btn-success w-100 mb-2" onclick="baixarBanner('png')"><i class="bi bi-image me-2"></i>Baixar PNG</button>
                            <button class="btn btn-outline-secondary w-100" onclick="baixarBanner('jpeg')"><i class="bi bi-file-image me-2"></i>Baixar JPEG</button>
                            <div id="statusMsg" class="mt-3" style="display:none;"></div>
                        </div>
                    </div>
                </div>

                <div class="col-lg-8 mb-4">
                    <div class="card shadow" style="position:sticky;top:20px;">
                        <div class="card-header bg-dark text-white d-flex align-items-center justify-content-between">
                            <h6 class="mb-0 fs-6"><i class="bi bi-eye me-2"></i>Preview</h6>
                            <span class="badge bg-secondary" id="badgeDimensoes">720px × auto</span>
                        </div>
                        <div class="card-body p-3" style="background:#0f0f1a;border-radius:0 0 .375rem .375rem;">
                            <div id="previewScaler" style="overflow:hidden;border-radius:12px;margin:0 auto;">
                                <div id="bannerCard" style="width:720px;position:relative;font-family:'Segoe UI',Tahoma,sans-serif;"></div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <?php include 'rodape.php'; ?>
    </div>

    <script>
        let TODOS_JOGOS = [];
        let _logoUrl   = null;
        let fundoAtual = null;
        let formatoAtual = 'horizontal';
        let temaAtual    = 0;
        let cacheImagens = {}; 
        let _renderTimeout = null; 
        
        const FORMATOS = {
            horizontal: { w:720,  hAuto:true,  label:'720px × auto',  vertical:false },
            quadrado:   { w:1080, h:1080,      label:'1080 × 1080px', vertical:false },
            stories:    { w:1080, h:1920,      label:'1080 × 1920px', vertical:true  },
            whatsapp:   { w:800,  hAuto:true,  label:'800px × auto',  vertical:false },
        };
        
        const TEMAS = [
            { bg:'linear-gradient(135deg,#0f0c29,#1a1a2e 40%,#16213e 70%,#0f3460)', accent:'#4d9fff', pill:'#0d6efd', sep:'rgba(77,159,255,.3)', header:'rgba(13,110,253,.15)' },
            { bg:'linear-gradient(135deg,#0a1f0a,#1b4332 50%,#2d6a4f)',              accent:'#52b788', pill:'#198754', sep:'rgba(82,183,136,.3)', header:'rgba(25,135,84,.15)' },
            { bg:'linear-gradient(135deg,#12002e,#2d1b69 50%,#4a1080)',              accent:'#bf94ff', pill:'#6f42c1', sep:'rgba(191,148,255,.3)', header:'rgba(111,66,193,.15)' },
            { bg:'linear-gradient(135deg,#1a0000,#4a0000 50%,#7a0000)',              accent:'#ff6b6b', pill:'#dc3545', sep:'rgba(255,107,107,.3)', header:'rgba(220,53,69,.15)' },
            { bg:'linear-gradient(135deg,#00091a,#0a2a4a 50%,#0a3a6a)',              accent:'#87ceeb', pill:'#0dcaf0', sep:'rgba(135,206,235,.3)', header:'rgba(13,202,240,.15)' },
            { bg:'linear-gradient(135deg,#0f0a00,#3a2800 50%,#5a3e00)',              accent:'#ffd700', pill:'#ffc107', sep:'rgba(255,215,0,.3)',   header:'rgba(255,193,7,.15)' }
        ];

        async function initJogosAPI() {
            let fetchedData = null;
            
            try {
                const res = await fetch('?fetch_jogos=1');
                if(res.ok){
                    const json = await res.json();
                    let tempArr = [];
                    
                    if (json.hoje && Array.isArray(json.hoje)) {
                        json.hoje.forEach(j => { j._dia = 'hoje'; tempArr.push(j); });
                    }
                    if (json.amanha && Array.isArray(json.amanha)) {
                        json.amanha.forEach(j => { j._dia = 'amanha'; tempArr.push(j); });
                    }
                    
                    if (tempArr.length > 0) {
                        fetchedData = tempArr;
                    } 
                    else if (Array.isArray(json) && json.length > 0 && json[0].time1) {
                        fetchedData = json;
                    }
                }
            } catch(e) { console.log("Falha no túnel: ", e); }
            
            if (fetchedData) {
                TODOS_JOGOS = fetchedData.map(jogo => {
                    if (!jogo._dia) {
                        jogo._dia = (jogo.data_jogo && String(jogo.data_jogo).toLowerCase().includes('amanh')) ? 'amanha' : 'hoje';
                    }
                    return jogo;
                });
                document.getElementById('api_warning').style.display = 'none';
            } else {
                document.getElementById('api_warning').style.display = 'block';
                TODOS_JOGOS = [
                    {"time1":"Portugal","time2":"Congo DR","competicao":"Copa do Mundo (Backup)","horario":"14:00","canais":[{"nome":"CAZÉ TV"}],"img_time1_url":"https://api.unyserve.com.br/imgs/f6f1f89231e27b2f44849c7215d987ae.png","img_time2_url":"https://api.unyserve.com.br/imgs/1f37f8b75980ceac769755acfc6ab55d.png","_dia":"hoje"},
                    {"time1":"Inglaterra","time2":"Croácia","competicao":"Copa do Mundo (Backup)","horario":"17:00","canais":[{"nome":"GLOBO"},{"nome":"SPORTV"}],"img_time1_url":"https://api.unyserve.com.br/imgs/e44ab723a811b814e7455b329025e524.png","img_time2_url":"https://api.unyserve.com.br/imgs/bd6f528ef6b57a5ddb12456de9056649.png","_dia":"hoje"},
                    {"time1":"República Tcheca","time2":"África do Sul","competicao":"Copa do Mundo (Backup)","horario":"13:00","canais":[{"nome":"CAZÉ TV"}],"img_time1_url":"https://api.unyserve.com.br/imgs/a269901a736af2fdeac74052da957ce1.png","img_time2_url":"https://api.unyserve.com.br/imgs/6859d9ecf64fe55d7eb547a1c80b1b02.png","_dia":"amanha"}
                ];
            }
            
            renderListaEsquerda();
            renderBanner();
            carregarLogo();
        }

        function modoAutomatico() {
            let count = 0;
            document.querySelectorAll('.jogo-api-item').forEach(el => {
                const idx = parseInt(el.dataset.idx);
                const chk = document.getElementById('chk_' + idx);
                let isTop10 = false;
                if (count < 10) {
                    isTop10 = true;
                    count++;
                }
                chk.checked = isTop10;
                el.classList.toggle('selected', isTop10);
                el.style.background = isTop10 ? '#e8f0fe' : '#1a1a2e';
                el.style.borderColor = isTop10 ? '#0d6efd' : 'var(--border-color)';
            });
            renderBanner();
        }

        function modoManual() {
            deselecionarTodos();
        }

        function renderListaEsquerda() {
            const container = document.getElementById('lista_jogos_container');
            document.getElementById('badge_count_jogos').innerText = TODOS_JOGOS.length;
            
            let html = `
            <div class="d-flex gap-2 mb-2 px-1">
                <button class="btn btn-primary btn-sm flex-fill fw-bold" onclick="modoAutomatico()"><i class="bi bi-magic me-1"></i>Automático</button>
                <button class="btn btn-secondary btn-sm flex-fill fw-bold" onclick="modoManual()"><i class="bi bi-hand-index-thumb me-1"></i>Manual</button>
            </div>
            <div class="d-flex gap-1 mb-2 px-1 flex-wrap">
                <button class="btn btn-outline-primary btn-sm" onclick="selecionarTodos()"><i class="bi bi-check-all me-1"></i>Todos</button>
                <button class="btn btn-outline-light btn-sm" onclick="deselecionarTodos()"><i class="bi bi-x me-1"></i>Nenhum</button>
                <button class="btn btn-outline-success btn-sm" onclick="selecionarDia('hoje')">Hoje</button>
                <button class="btn btn-outline-info btn-sm" onclick="selecionarDia('amanha')">Amanhã</button>
            </div>`;
            
            let dia_atual = '';
            TODOS_JOGOS.forEach((jogo, idx) => {
                if(jogo._dia !== dia_atual) {
                    dia_atual = jogo._dia;
                    let labelDia = (dia_atual === 'hoje') ? '⚡ HOJE' : '📅 AMANHÃ';
                    html += `<div class="px-2 py-1 mb-1 mt-2"><small class="fw-bold text-uppercase" style="color:var(--accent);font-size:.68rem;letter-spacing:1px;">${labelDia}</small></div>`;
                }
                
                const proxyImg1 = '?proxy_url=' + encodeURIComponent(jogo.img_time1_url);
                const proxyImg2 = '?proxy_url=' + encodeURIComponent(jogo.img_time2_url);

                let checkPadrao = idx < 10;
                let classeSelecionado = checkPadrao ? 'selected' : '';
                let corFundoItem = checkPadrao ? '#e8f0fe' : '#1a1a2e';
                let corBordaItem = checkPadrao ? '#0d6efd' : 'var(--border-color)';
                let attrCheck = checkPadrao ? 'checked' : '';

                html += `
                <div class="d-flex align-items-center gap-2 px-2 py-1 rounded mb-1 jogo-api-item ${classeSelecionado}" data-idx="${idx}" data-dia="${jogo._dia}" onclick="toggleJogo(this, ${idx})" style="background:${corFundoItem};border:1px solid ${corBordaItem};">
                    <div style="display:flex;align-items:center;gap:4px;flex-shrink:0;">
                        <img src="${proxyImg1}" style="width:24px;height:24px;border-radius:50%;object-fit:cover;background:white;" onerror="this.src='${jogo.img_time1_url}'">
                        <small class="text-muted">×</small>
                        <img src="${proxyImg2}" style="width:24px;height:24px;border-radius:50%;object-fit:cover;background:white;" onerror="this.src='${jogo.img_time2_url}'">
                    </div>
                    <div class="flex-grow-1 min-w-0">
                        <div class="fw-semibold" style="font-size:.8rem;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;color:#000;">
                            ${escHtml(jogo.time1)} × ${escHtml(jogo.time2)}
                        </div>
                        <div style="font-size:.7rem;color:#444;">${escHtml(jogo.competicao)}</div>
                    </div>
                    <div style="flex-shrink:0;text-align:right;">
                        <span class="badge bg-warning text-dark" style="font-size:.65rem;">${jogo.horario}</span>
                        <div class="form-check mt-1 d-flex justify-content-end">
                            <input type="checkbox" class="form-check-input jogo-check" id="chk_${idx}" style="width:16px;height:16px;" ${attrCheck}>
                        </div>
                    </div>
                </div>`;
            });
            
            container.innerHTML = html;
        }

        async function carregarLogo() {
            try {
                const r = await fetch('/api/logo_get.php');
                const d = await r.json();
                if (d.ok && d.url) {
                    _logoUrl = await imgParaBase64(d.url);
                    mostrarLogoPreview(); renderBanner();
                } else {
                    document.getElementById('logoPreviewArea').innerHTML = '<span class="text-light" style="font-size:.8rem; opacity: 0.9;">Nenhum logo definido</span>';
                }
            } catch(e) { document.getElementById('logoPreviewArea').innerHTML = '<span class="text-light" style="font-size:.8rem; opacity: 0.9;">Nenhum logo definido</span>'; }
        }

        async function imgParaBase64(url) {
            try {
                const r = await fetch(url); const blob = await r.blob();
                return new Promise(resolve => { const rd=new FileReader(); rd.onloadend=()=>resolve(rd.result); rd.readAsDataURL(blob); });
            } catch(e) { return url; }
        }

        async function uploadLogo(input) {
            if (!input.files[0]) return;
            const fd = new FormData(); fd.append('logo', input.files[0]);
            const btn = document.getElementById('btnUploadLogo');
            btn.disabled=true; btn.innerHTML='<i class="bi bi-hourglass-split me-1"></i>Enviando...';
            try {
                const r = await fetch('/api/logo_upload.php',{method:'POST',body:fd});
                const d = await r.json();
                if (d.ok) { _logoUrl=await imgParaBase64(d.url); mostrarLogoPreview(); renderBanner(); }
                else alert('Erro: '+d.error);
            } catch(e) { alert('Erro de rede'); }
            btn.disabled=false; btn.innerHTML='<i class="bi bi-upload me-1"></i>Fazer upload'; input.value='';
        }

        function removerLogo() { _logoUrl=null; mostrarLogoPreview(); renderBanner(); }

        function mostrarLogoPreview() {
            document.getElementById('logoPreviewArea').innerHTML = _logoUrl
                ? `<img src="${_logoUrl}" style="max-height:48px;max-width:180px;border-radius:6px;border:1px solid rgba(0,0,0,.12);">
                   <button class="btn btn-sm btn-outline-danger ms-2" onclick="removerLogo()"><i class="bi bi-trash"></i></button>`
                : '<span class="text-light" style="font-size:.8rem; opacity: 0.9;">Nenhum logo definido</span>';
        }

        function setFormato(fmt, btn) {
            formatoAtual = fmt;
            document.querySelectorAll('.fmt-btn').forEach(b=>{b.classList.remove('btn-primary');b.classList.add('btn-outline-secondary');});
            btn.classList.add('btn-primary'); btn.classList.remove('btn-outline-secondary');
            document.getElementById('badgeDimensoes').textContent = FORMATOS[fmt].label;
            renderBanner();
        }

        function toggleMenu() { document.getElementById('sidebar').classList.toggle('active'); document.getElementById('overlay').classList.toggle('active'); }

        function selecionarFundo(url, el) {
            fundoAtual = url;
            document.querySelectorAll('.fundo-item').forEach(f => { f.classList.remove('active'); f.style.borderColor='transparent'; f.style.background='';});
            el.classList.add('active'); el.style.borderColor='#0d6efd'; el.style.background='#e8f0fe';
            renderBanner();
        }

        function toggleJogo(el, idx) {
            const chk=document.getElementById('chk_'+idx); chk.checked=!chk.checked;
            el.classList.toggle('selected',chk.checked);
            el.style.background=chk.checked?'#e8f0fe':'#1a1a2e'; el.style.borderColor=chk.checked?'#0d6efd':'var(--border-color)';
            renderBanner();
        }

        function selecionarTodos() {
            document.querySelectorAll('.jogo-check').forEach((c,i)=>{c.checked=true;const el=document.querySelector(`[data-idx="${i}"]`);if(el){el.classList.add('selected');el.style.background='#e8f0fe';el.style.borderColor='#0d6efd';}});
            renderBanner();
        }
        function deselecionarTodos() {
            document.querySelectorAll('.jogo-check').forEach((c,i)=>{c.checked=false;const el=document.querySelector(`[data-idx="${i}"]`);if(el){el.classList.remove('selected');el.style.background='#1a1a2e';el.style.borderColor='var(--border-color)';}});
            renderBanner();
        }
        function selecionarDia(dia) {
            let limit = 10;
            let count = 0;
            document.querySelectorAll('.jogo-api-item').forEach(el=>{
                const idx=el.dataset.idx; 
                const chk=document.getElementById('chk_'+idx); 
                let match = false;
                if (el.dataset.dia === dia) {
                    if (count < limit) {
                        match = true;
                        count++;
                    }
                }
                chk.checked = match; 
                el.classList.toggle('selected', match);
                el.style.background = match ? '#e8f0fe' : '#1a1a2e'; 
                el.style.borderColor = match ? '#0d6efd' : 'var(--border-color)';
            }); 
            renderBanner();
        }

        document.querySelectorAll('.tema-btn').forEach(btn => {
            btn.addEventListener('click', () => {
                document.querySelectorAll('.tema-btn').forEach(b => { b.classList.remove('active'); b.style.borderColor = 'transparent'; });
                btn.classList.add('active'); btn.style.borderColor = '#fff';
                temaAtual = parseInt(btn.dataset.tema);
                renderBanner();
            });
        });

        async function getBase64ImageProxy(url) {
            if (!url) return '';
            if (cacheImagens[url]) return cacheImagens[url];
            try {
                const proxyUrl = '?proxy_url=' + encodeURIComponent(url);
                const res = await fetch(proxyUrl);
                if (!res.ok) throw new Error('Proxy error');
                const blob = await res.blob();
                return new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onloadend = () => { cacheImagens[url] = reader.result; resolve(reader.result); };
                    reader.readAsDataURL(blob);
                });
            } catch(e) { 
                return url; 
            }
        }

        async function renderBanner() {
            clearTimeout(_renderTimeout);
            return new Promise((resolve) => {
                _renderTimeout = setTimeout(async () => {
                    
                    const tema      = TEMAS[temaAtual];
                    const marca     = document.getElementById('marca').value || 'ZenPlay';
                    const titulo    = document.getElementById('tituloBanner').value || 'JOGOS DE HOJE';
                    const verCanais = document.getElementById('mostrarCanais').checked;
                    const verComp   = document.getElementById('mostrarCompetição').checked;
                    const verEscudo = document.getElementById('mostrarEscudos').checked;
                    const fmt       = FORMATOS[formatoAtual];
                    const isVertical= fmt.vertical;
                    const W         = fmt.w;

                    const selecionados = TODOS_JOGOS.filter((_, i) => document.getElementById('chk_' + i)?.checked);
                    const banner = document.getElementById('bannerCard');

                    banner.style.width  = W + 'px';
                    banner.style.height = (fmt.hAuto || isVertical) ? 'auto' : fmt.h + 'px';

                    const S = isVertical ? 1.9 : (formatoAtual==='quadrado' ? 1.5 : 1);

                    // OTIMIZAÇÃO: Pré-carregar a imagem de fundo em Base64 para evitar bloqueio CORS do html2canvas
                    let bgUrlParaUso = fundoAtual;
                    if (fundoAtual && fundoAtual.startsWith('http')) {
                        if (!cacheImagens[fundoAtual]) {
                            await getBase64ImageProxy(fundoAtual);
                        }
                        bgUrlParaUso = cacheImagens[fundoAtual] || fundoAtual;
                    }

                    const bgStyle     = fundoAtual ? `background:url('${bgUrlParaUso}') center/cover no-repeat;position:relative;` : `background:${tema.bg};`;
                    const overlayHtml = fundoAtual ? `<div style="position:absolute;inset:0;background:rgba(0,0,0,.65);border-radius:12px;z-index:0;"></div>` : '';

                    const logoHeaderHtml = _logoUrl
                        ? `<img src="${_logoUrl}" style="max-height:${Math.round(32*S)}px;max-width:${Math.round(130*S)}px;object-fit:contain;filter:drop-shadow(0 1px 4px rgba(0,0,0,.5));">`
                        : `<span style="font-size:${Math.round(10*S)}px;font-weight:700;letter-spacing:3px;text-transform:uppercase;color:${tema.accent};opacity:.8;">${escHtml(marca)}</span>`;

                    const logoRodapeHtml = _logoUrl
                        ? `<img src="${_logoUrl}" style="max-height:${Math.round(20*S)}px;max-width:${Math.round(100*S)}px;object-fit:contain;opacity:.45;">`
                        : `<span style="font-size:${Math.round(9*S)}px;font-weight:700;letter-spacing:3px;text-transform:uppercase;color:rgba(255,255,255,.25);">${escHtml(marca)}</span>`;

                    const escudoSize = Math.round(48 * S);
                    const timeFontSz = Math.round(15 * S);
                    const horFontSz  = Math.round(13 * S);

                    if (verEscudo) {
                        const promessasFetch = [];
                        for (let idx = 0; idx < selecionados.length; idx++) {
                            const jogo = selecionados[idx];
                            if (jogo.img_time1_url && !cacheImagens[jogo.img_time1_url]) {
                                promessasFetch.push(getBase64ImageProxy(jogo.img_time1_url));
                            }
                            if (jogo.img_time2_url && !cacheImagens[jogo.img_time2_url]) {
                                promessasFetch.push(getBase64ImageProxy(jogo.img_time2_url));
                            }
                        }
                        if (promessasFetch.length > 0) {
                            await Promise.all(promessasFetch);
                        }
                    }

                    let html = `<div style="${bgStyle}padding:0;border-radius:12px;overflow:hidden;border:1px solid ${tema.sep};">
                        ${overlayHtml}
                        <div style="position:relative;z-index:1;">
                        <div style="padding:${Math.round(20*S)}px ${Math.round(28*S)}px ${Math.round(16*S)}px;border-bottom:1px solid ${tema.sep};background:${tema.header};">
                            <div style="display:flex;align-items:center;justify-content:space-between;">
                                <div>
                                    ${logoHeaderHtml}
                                    <div style="font-size:${Math.round(20*S)}px;font-weight:900;color:#fff;letter-spacing:-0.5px;margin-top:${_logoUrl?Math.round(6*S):Math.round(2*S)}px;">
                                        ${escHtml(titulo)}
                                    </div>
                                </div>
                                <div style="display:flex;align-items:center;gap:${Math.round(6*S)}px;font-size:${Math.round(11*S)}px;font-weight:800;color:#ff4444;background:rgba(255,68,68,.12);padding:${Math.round(6*S)}px ${Math.round(12*S)}px;border-radius:${Math.round(20*S)}px;border:1px solid rgba(255,68,68,.3);">
                                    <div style="width:${Math.round(7*S)}px;height:${Math.round(7*S)}px;background:#ff4444;border-radius:50%;animation:pulse 1.2s ease-in-out infinite;"></div>
                                    AO VIVO
                                </div>
                            </div>
                        </div>`;

                    let ultimoDia = null;

                    if (selecionados.length === 0) {
                        html += `<div style="padding:${Math.round(40*S)}px;text-align:center;color:rgba(255,255,255,.3);font-size:${Math.round(14*S)}px;">Nenhum jogo selecionado</div>`;
                    } else {
                        for (let idx = 0; idx < selecionados.length; idx++) {
                            const jogo = selecionados[idx];
                            
                            if (jogo._dia !== ultimoDia) {
                                ultimoDia = jogo._dia;
                                const label = jogo._dia === 'hoje' ? '⚡ HOJE' : '📅 AMANHÃ';
                                html += `<div style="padding:${Math.round(8*S)}px ${Math.round(28*S)}px;background:${tema.header};border-bottom:1px solid ${tema.sep};"><span style="font-size:${Math.round(9*S)}px;font-weight:800;letter-spacing:3px;text-transform:uppercase;color:${tema.accent};">${label}</span></div>`;
                            }

                            const border = (idx === selecionados.length - 1) ? 'none' : `1px solid ${tema.sep}`;
                            const canaisHtml = (verCanais && jogo.canais) ? jogo.canais.map(c => `<span style="display:inline-flex;align-items:center;gap:4px;padding:${Math.round(2*S)}px ${Math.round(8*S)}px;border-radius:4px;font-size:${Math.round(10*S)}px;font-weight:700;color:${tema.accent};background:rgba(255,255,255,.06);border:1px solid ${tema.sep};white-space:nowrap;">📺 ${escHtml(c.nome)}</span>`).join('') : '';
                            
                            let esc1 = `<div style="width:${escudoSize}px;height:${escudoSize}px;border-radius:50%;background:rgba(255,255,255,.1);border:2px solid ${tema.sep};display:flex;align-items:center;justify-content:center;font-size:${Math.round(20*S)}px;">⚽</div>`;
                            let esc2 = esc1;
                            
                            if (verEscudo && jogo.img_time1_url) esc1 = `<img src="${cacheImagens[jogo.img_time1_url] || await getBase64ImageProxy(jogo.img_time1_url)}" style="width:${escudoSize}px;height:${escudoSize}px;border-radius:50%;object-fit:cover;border:2px solid ${tema.sep};background:#fff;" crossorigin="anonymous">`;
                            if (verEscudo && jogo.img_time2_url) esc2 = `<img src="${cacheImagens[jogo.img_time2_url] || await getBase64ImageProxy(jogo.img_time2_url)}" style="width:${escudoSize}px;height:${escudoSize}px;border-radius:50%;object-fit:cover;border:2px solid ${tema.sep};background:#fff;" crossorigin="anonymous">`;

                            const compHtml = (verComp && jogo.competicao) ? `<div style="margin-bottom:${Math.round(8*S)}px;"><span style="font-size:${Math.round(9*S)}px;font-weight:700;letter-spacing:1.5px;text-transform:uppercase;color:${tema.accent};opacity:.7;">${escHtml(jogo.competicao)}</span></div>` : '';

                            html += `
                            <div style="padding:${Math.round(14*S)}px ${Math.round(28*S)}px;border-bottom:${border};">
                                ${compHtml}
                                <div style="display:flex;align-items:center;gap:0;">
                                    <div style="display:flex;align-items:center;gap:${Math.round(10*S)}px;flex:1;min-width:0;">
                                        ${esc1}
                                        <div style="font-size:${timeFontSz}px;font-weight:800;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:0 1px 4px rgba(0,0,0,.5);">${escHtml(jogo.time1)}</div>
                                    </div>
                                    <div style="display:flex;flex-direction:column;align-items:center;gap:${Math.round(2*S)}px;padding:0 ${Math.round(16*S)}px;flex-shrink:0;">
                                        <span style="font-size:${Math.round(11*S)}px;font-weight:900;color:rgba(255,255,255,.4);letter-spacing:1px;">VS</span>
                                        <span style="font-size:${horFontSz}px;font-weight:900;color:#fff;background:${tema.pill};padding:${Math.round(3*S)}px ${Math.round(10*S)}px;border-radius:${Math.round(8*S)}px;font-variant-numeric:tabular-nums;">${escHtml(jogo.horario)}</span>
                                    </div>
                                    <div style="display:flex;align-items:center;gap:${Math.round(10*S)}px;flex:1;min-width:0;flex-direction:row-reverse;text-align:right;">
                                        ${esc2}
                                        <div style="font-size:${timeFontSz}px;font-weight:800;color:#fff;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;text-shadow:0 1px 4px rgba(0,0,0,.5);">${escHtml(jogo.time2)}</div>
                                    </div>
                                </div>
                                ${canaisHtml ? `<div style="display:flex;flex-wrap:wrap;gap:${Math.round(4*S)}px;margin-top:${Math.round(8*S)}px;">${canaisHtml}</div>` : ''}
                            </div>`;
                        }
                    }
                    html += `<div style="padding:${Math.round(10*S)}px ${Math.round(28*S)}px;background:${tema.header};border-top:1px solid ${tema.sep};display:flex;align-items:center;justify-content:space-between;">
                        ${logoRodapeHtml}
                        <span style="font-size:${Math.round(9*S)}px;color:rgba(255,255,255,.2);">Onde assistir ao vivo</span>
                    </div></div></div>`;
                    
                    banner.innerHTML = html;
                    
                    if (!fmt.hAuto && !isVertical) { banner.style.height = fmt.h + 'px'; banner.style.overflow = 'hidden'; }
                    if (isVertical) { banner.style.height = fmt.h + 'px'; banner.style.overflow = 'hidden'; }

                    escalarPreview();
                    resolve();
                    
                }, 50); 
            });
        }

        function escHtml(str) { return String(str || '').replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;').replace(/"/g,'&quot;'); }

        function escalarPreview() {
            const scaler = document.getElementById('previewScaler'); const banner = document.getElementById('bannerCard');
            const fmt    = FORMATOS[formatoAtual];
            const maxW = scaler.parentElement.clientWidth - 2; 
            const maxH   = fmt.vertical ? 620 : 9999;
            const scaleW = maxW / fmt.w;
            const scaleH = fmt.vertical ? maxH / fmt.h : 1;
            const scale  = Math.min(1, scaleW, scaleH);
            
            banner.style.transform = `scale(${scale})`; banner.style.transformOrigin = 'top left';
            scaler.style.width  = Math.round(fmt.w * scale) + 'px';
            const bH = fmt.hAuto ? banner.scrollHeight : fmt.h;
            scaler.style.height = Math.round(bH * scale) + 'px';
        }

        async function baixarBanner(fmt) {
            const statusDiv = document.getElementById('statusMsg');
            statusDiv.style.display = 'block'; statusDiv.className = 'alert alert-info py-2';
            statusDiv.innerHTML = '<i class="bi bi-hourglass-split me-2"></i>Processando imagem...';

            await new Promise(r => setTimeout(r, 100));

            const banner = document.getElementById('bannerCard');
            const fmtCfg = FORMATOS[formatoAtual];
            const bH = fmtCfg.hAuto ? banner.scrollHeight : fmtCfg.h;

            // OTIMIZAÇÃO: Cria um clone invisível para tirar a foto. O preview na tela NUNCA mais fica preto.
            const clone = banner.cloneNode(true);
            clone.style.transform = 'scale(1)'; 
            clone.style.position = 'absolute';
            clone.style.top = '-9999px';
            clone.style.left = '-9999px';
            document.body.appendChild(clone);

            try {
                // OTIMIZAÇÃO: Scale 1.5 deixa 40% mais rápido sem perder qualidade visual pro celular
                const canvas = await html2canvas(clone, { 
                    scale: 1.5, 
                    useCORS: true, 
                    allowTaint: true, 
                    backgroundColor: null, 
                    logging: false, 
                    width: fmtCfg.w, 
                    height: bH 
                });
                
                document.body.removeChild(clone);
                
                const marca = document.getElementById('marca').value || 'banner';
                const nome = `jogos_${formatoAtual}_${marca}`.replace(/[^a-z0-9_]/gi,'_').toLowerCase();
                const link = document.createElement('a'); 
                link.download = `${nome}.${fmt}`;
                link.href = canvas.toDataURL(fmt === 'png' ? 'image/png' : 'image/jpeg', 0.90); 
                link.click();
                
                statusDiv.className = 'alert alert-success py-2'; 
                statusDiv.innerHTML = '<i class="bi bi-check-circle me-2"></i>Banner exportado!';
                setTimeout(() => statusDiv.style.display = 'none', 3000);
            } catch(err) {
                if(document.body.contains(clone)) document.body.removeChild(clone);
                statusDiv.className = 'alert alert-danger py-2'; 
                statusDiv.innerHTML = 'Erro ao exportar. Tente novamente.';
            }
        }

        document.addEventListener('DOMContentLoaded', () => { 
            initJogosAPI(); 
        });
        window.addEventListener('resize', escalarPreview);
    </script>
    <script src="tema.js"></script>
</body>
</html>
