<?php
session_start();

// ====================================================================
// PROXY DE IMAGEM NATIVO (MÁGICA PARA O BANNER NÃO DAR ERRO AO BAIXAR)
// ====================================================================
if (isset($_GET['proxy_url'])) {
    $url = urldecode($_GET['proxy_url']);
    if (strpos($url, 'http') === 0) {
        $img = @file_get_contents($url);
        if ($img) {
            header("Content-Type: image/jpeg");
            header("Access-Control-Allow-Origin: *");
            echo $img;
            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'];

// ABRINDO AS DUAS CONEXÕES PARA A SIDEBAR FUNCIONAR
$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) {}

// ====================================================================
// CORREÇÃO: DESCOBRINDO SE É ADMIN OU REVENDA PARA O SIDEBAR NÃO BUGAR
// ====================================================================
$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 - <?php echo htmlspecialchars($nome_painel); ?></title>
    
    <!-- Bibliotecas Necessárias para o Gerador -->
    <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>
        /* Estilos base do seu painel */
        :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; }
        
        /* USANDO O SEU SIDEBAR.PHP */
        .sidebar { width: 260px; background-color: var(--bg-sidebar); display: flex; flex-direction: column; transition: 0.3s; border-right: 1px solid var(--border-color); z-index: 1001; 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); }
        .user-info { padding: 20px; text-align: center; border-bottom: 1px solid var(--border-color); }
        .menu-list { list-style: none; padding: 0; margin: 0; overflow-y: auto; flex: 1; padding-bottom: 20px;}
        .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: 14px; 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-category { padding: 20px 20px 5px; font-size: 11px; font-weight: bold; color: var(--text-muted); text-transform: uppercase;}
        
        /* ==================================================================== */
        /* FORÇA A COR AZUL NO ADMINISTRADOR E VERDE NO SALDO */
        /* ==================================================================== */
        .user-info > div:nth-child(2), .user-info .badge { background: rgba(0, 123, 255, 0.2) !important; color: var(--accent) !important; padding: 4px 10px !important; border-radius: 4px !important; font-size: 11px !important; text-transform: uppercase !important; font-weight: bold !important; margin-top: 5px !important; margin-bottom: 5px !important; display: inline-block !important; }
        .user-info > div:nth-child(3), .user-info .credits-badge, .user-info i.fa-coins { color: var(--success) !important; font-weight: bold !important; font-size: 13px !important; display: inline-block !important; }
        .user-info > div:nth-child(3) { margin-top: 8px !important; display: block !important; }

        /* ==================================================================== */
        /* FORÇA OS ÍCONES DA SIDEBAR A FICAREM AZUIS */
        /* ==================================================================== */
        .sidebar i, .sidebar span[class*="icon"], .sidebar .fas, .sidebar .fab { color: var(--accent) !important; }
        .menu-item i:first-child { margin-right: 12px; width: 20px; text-align: center; color: var(--accent) !important; }
        .menu-item:hover, .menu-item.active { background-color: #2c3138 !important; color: white !important; border-left-color: var(--accent) !important; }
        .sidebar .active, .sidebar .menu-item.active, .sidebar li.active > a { border-left-color: var(--accent) !important; color: white !important; background: #24282d !important; }
        .sidebar a:hover, .sidebar .menu-item:hover { border-left-color: var(--accent) !important; color: white !important; background: #2c3138 !important; }


        /* ==================================================================== */
        /* FORÇA O BOTÃO DE SAIR A FICAR UM BLOCO VERMELHO NO FUNDO DA SIDEBAR */
        /* ==================================================================== */
        .sidebar a[href*="logout"], 
        .sidebar a[href*="sair"],
        .logout-btn {
            background-color: #dc3545 !important; /* Vermelho padrão Bootstrap */
            color: #ffffff !important; /* Letra branca */
            display: flex !important;
            justify-content: center !important; /* Centraliza o texto */
            align-items: center !important;
            padding: 15px !important; /* Altura do botão */
            border-left: none !important; /* Remove a bordinha lateral azul */
            font-weight: bold !important;
            font-size: 16px !important;
            text-decoration: none !important;
            margin-top: auto !important; /* MÁGICA: Empurra o botão pro fundo da barra */
            border-radius: 0 !important; /* Deixa quadrado de ponta a ponta */
            width: 100% !important;
            box-sizing: border-box !important;
        }
        
        .sidebar a[href*="logout"] i, 
        .sidebar a[href*="sair"] i,
        .logout-btn i {
            color: #ffffff !important; /* Ícone branco */
            margin-right: 8px !important;
        }

        .sidebar a[href*="logout"]:hover,
        .sidebar a[href*="sair"]:hover,
        .logout-btn:hover {
            background-color: #c82333 !important; /* Vermelho mais escuro no hover */
            color: #ffffff !important;
            border-left: none !important;
        }

        /* ÁREA PRINCIPAL */
        .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; }
        .sidebar-overlay { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.7); z-index: 1000; }
        .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; }

        /* Estilos do Gerador (Adaptados para tema dark) */
        .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; }
        
        .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; }
        .layout-btn { transition:all .2s; }
        
        .result-card { cursor:pointer; border-radius:10px; overflow:hidden; border:2px solid transparent; transition:all .2s; background:#1a1a2e; }
        .result-card:hover { border-color:#0d6efd; transform:translateY(-3px); box-shadow:0 8px 20px rgba(13,110,253,.25); }
        .result-card img { width:100%;height:210px;object-fit:cover;display:block; }
        .result-card-info { padding:8px 10px; }
        .result-card-title { font-size:.8rem;font-weight:700;color:#fff;margin-bottom:2px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis; }
        .result-card-year { font-size:.72rem;color:#6c757d; }

        @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-image" style="color:var(--accent);"></i> Gerador de Banners</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">
            
            <!-- ── BUSCA TMDB ──────────────────────────────────────── -->
            <div class="card shadow mb-4">
                <div class="card-header" style="background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;">
                    <h5 class="mb-0 fs-6"><i class="bi bi-search me-2"></i>Buscar no TMDB</h5>
                </div>
                <div class="card-body">
                    <div class="row g-3 align-items-end">
                        <div class="col-md-5">
                            <label class="form-label fw-semibold">Título</label>
                            <input type="text" class="form-control" id="searchInput" placeholder="Ex: Oppenheimer, Breaking Bad..." onkeyup="debounceSearch()">
                        </div>
                        <div class="col-md-3">
                            <label class="form-label fw-semibold">Tipo</label>
                            <select class="form-select" id="searchType" onchange="limparResultados()">
                                <option value="movie">🎬 Filmes</option>
                                <option value="tv">📺 Séries</option>
                            </select>
                        </div>
                        <div class="col-md-2">
                            <label class="form-label fw-semibold">Idioma</label>
                            <select class="form-select" id="searchLang">
                                <option value="pt-BR">🇧🇷 Português</option>
                                <option value="en-US">🇺🇸 Inglês</option>
                            </select>
                        </div>
                        <div class="col-md-2 d-flex gap-2">
                            <button class="btn btn-primary w-100" onclick="buscar()"><i class="bi bi-search me-1"></i>Buscar</button>
                            <button class="btn btn-outline-light" onclick="popularizarBusca()" title="Populares"><i class="bi bi-star"></i></button>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── RESULTADOS ─────────────────────────────────────── -->
            <div id="resultadosWrap" style="display:none;" class="mb-4">
                <div class="card shadow">
                    <div class="card-header bg-dark text-white d-flex justify-content-between align-items-center">
                        <h6 class="mb-0 fs-6"><i class="bi bi-grid me-2"></i>Resultados</h6>
                        <button class="btn btn-sm btn-outline-light" onclick="limparResultados()"><i class="bi bi-x me-1"></i>Fechar</button>
                    </div>
                    <div class="card-body p-3">
                        <div id="resultadosGrid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(160px,1fr));gap:16px;"></div>
                        <div id="loadingMsg" class="text-center py-4 text-muted" style="display:none;">
                            <div class="spinner-border spinner-border-sm me-2"></div>Buscando...
                        </div>
                        <div id="emptyMsg" class="text-center py-4 text-muted" style="display:none;">
                            <i class="bi bi-inbox" style="font-size:2rem;"></i><p class="mt-2 mb-0">Nenhum resultado encontrado</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- ── LAYOUT PRINCIPAL ───────────────────────────────── -->
            <div class="row">
                <!-- COLUNA ESQUERDA -->
                <div class="col-lg-4 mb-4">
                    <!-- Item Selecionado -->
                    <div class="card shadow mb-4" id="itemSelecionadoCard" style="display:none;">
                        <div class="card-header" style="background:linear-gradient(135deg,#1a1a2e,#16213e);color:#fff;">
                            <h6 class="mb-0 fs-6"><i class="bi bi-check-circle me-2"></i>Item Selecionado</h6>
                        </div>
                        <div class="card-body p-3">
                            <div class="d-flex gap-3">
                                <img id="thumbSelecionado" src="" alt="" style="width:60px;height:90px;object-fit:cover;border-radius:6px;flex-shrink:0;border:2px solid #0d6efd;">
                                <div>
                                    <div class="fw-bold text-white" id="nomeSelecionado"></div>
                                    <small class="text-muted" id="anoSelecionado"></small><br>
                                    <span class="badge bg-primary mt-1" id="tipoSelecionado"></span>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Personalização -->
                    <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>Personalização</h6>
                        </div>
                        <div class="card-body">
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Título (editável)</label>
                                <input type="text" class="form-control" id="customTitulo" placeholder="Título do banner" oninput="atualizar()">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Tagline / Subtítulo</label>
                                <input type="text" class="form-control" id="customTagline" placeholder="Ex: Uma história épica..." oninput="atualizar()">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Disponível em</label>
                                <input type="text" class="form-control" id="customPlataforma" placeholder="Ex: Disponível no ZenPlay" value="Disponível no <?php echo htmlspecialchars($nome_painel); ?>" oninput="atualizar()">
                            </div>
                            <div class="row g-2 mb-3">
                                <div class="col-6">
                                    <label class="form-label fw-semibold">Nota</label>
                                    <input type="text" class="form-control" id="customNota" placeholder="Ex: 8.5" oninput="atualizar()">
                                </div>
                                <div class="col-6">
                                    <label class="form-label fw-semibold">Ano</label>
                                    <input type="text" class="form-control" id="customAno" placeholder="Ex: 2024" oninput="atualizar()">
                                </div>
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Gêneros</label>
                                <input type="text" class="form-control" id="customGeneros" placeholder="Ex: Ação • Ficção Científica" oninput="atualizar()">
                            </div>
                            <div class="mb-3">
                                <label class="form-label fw-semibold">Nome do Serviço</label>
                                <input type="text" class="form-control" id="customMarca" value="<?php echo htmlspecialchars($nome_painel); ?>" oninput="atualizar()">
                            </div>
                        </div>
                    </div>

                    <!-- Layout -->
                    <div class="card shadow mb-4">
                        <div class="card-header bg-dark text-white">
                            <h6 class="mb-0 fs-6"><i class="bi bi-layout-text-sidebar me-2"></i>Layout & Tema</h6>
                        </div>
                        <div class="card-body">
                            <label class="form-label fw-semibold">Layout do Banner</label>
                            <div class="d-flex gap-2 mb-3">
                                <button class="btn btn-sm btn-primary layout-btn active" data-layout="0" onclick="setLayout(0,this)"><i class="bi bi-layout-text-sidebar-reverse me-1"></i>Pôster + Info</button>
                                <button class="btn btn-sm btn-outline-secondary layout-btn" data-layout="1" onclick="setLayout(1,this)"><i class="bi bi-card-text me-1"></i>Só Texto</button>
                                <button class="btn btn-sm btn-outline-secondary layout-btn" data-layout="2" onclick="setLayout(2,this)"><i class="bi bi-image me-1"></i>Full Fundo</button>
                            </div>

                            <label class="form-label fw-semibold">Tema de Cores</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,#1a0a2e,#2d1b69);color:#fff;border:2px solid transparent;">🟣 Roxo</button>
                                <button class="btn btn-sm tema-btn" data-tema="2" style="background:linear-gradient(135deg,#1a0a0a,#4a0000);color:#fff;border:2px solid transparent;">🔴 Vermelho</button>
                                <button class="btn btn-sm tema-btn" data-tema="3" style="background:linear-gradient(135deg,#0a1a2a,#0a2a4a);color:#fff;border:2px solid transparent;">🔵 Azul</button>
                                <button class="btn btn-sm tema-btn" data-tema="4" style="background:linear-gradient(135deg,#1a1200,#3a2800);color:#fff;border:2px solid transparent;">🟡 Gold</button>
                                <button class="btn btn-sm tema-btn" data-tema="5" style="background:linear-gradient(135deg,#0d1b0d,#1b4332);color:#fff;border:2px solid transparent;">🟢 Verde</button>
                            </div>

                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="toggleSinopse" checked onchange="atualizar()">
                                <label class="form-check-label fw-semibold" style="color:var(--text-main);" for="toggleSinopse">Mostrar sinopse</label>
                            </div>
                            <div class="form-check form-switch mb-2">
                                <input class="form-check-input" type="checkbox" id="toggleNota" checked onchange="atualizar()">
                                <label class="form-check-label fw-semibold" style="color:var(--text-main);" for="toggleNota">Mostrar nota</label>
                            </div>
                            <div class="form-check form-switch">
                                <input class="form-check-input" type="checkbox" id="toggleNovo" onchange="atualizar()">
                                <label class="form-check-label fw-semibold" style="color:var(--text-main);" for="toggleNovo">Badge "NOVO"</label>
                            </div>
                        </div>
                    </div>

                    <!-- Export -->
                    <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 Banner</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 (Alta Qualidade)</button>
                            <button class="btn btn-outline-light 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>

                <!-- COLUNA DIREITA (PREVIEW) -->
                <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 do Banner</h6>
                            <span class="badge bg-secondary">900 × 480px</span>
                        </div>
                        <div class="card-body p-3" style="background:#0a0a14; border-radius:0 0 .375rem .375rem;">
                            <div id="previewScaler" style="overflow:hidden;border-radius:12px;">
                                
                                <!-- BANNER REAL (A base de renderização do html2canvas) -->
                                <div id="bannerCard" style="width:900px;height:480px;position:relative;overflow:hidden;border-radius:12px;font-family:'Segoe UI',Tahoma,Geneva,Verdana,sans-serif;">
                                    <div id="bannerBg" style="position:absolute;inset:0;z-index:0;"></div>
                                    <div id="bannerPosterBg" style="position:absolute;inset:0;z-index:1;display:none;background-size:cover;background-position:center;filter:brightness(.35) blur(2px);"></div>
                                    <div id="bannerOverlay" style="position:absolute;inset:0;z-index:2;display:none;"></div>
                                    <div style="position:absolute;inset:0;z-index:3;opacity:.2;background-image:url('data:image/svg+xml,%3Csvg viewBox=\'0 0 200 200\' xmlns=\'http://www.w3.org/2000/svg\'%3E%3Cfilter id=\'n\'%3E%3CfeTurbulence type=\'fractalNoise\' baseFrequency=\'0.9\' numOctaves=\'4\' stitchTiles=\'stitch\'/%3E%3C/filter%3E%3Crect width=\'100%25\' height=\'100%25\' filter=\'url(%23n)\' opacity=\'0.05\'/%3E%3C/svg%3E');background-size:200px 200px;pointer-events:none;"></div>
                                    
                                    <!-- LAYOUT 0 e 2: Poster + Info -->
                                    <div id="layoutPosterInfo" style="position:absolute;inset:0;z-index:4;display:flex;padding:36px;">
                                        <div id="wrapPoster" style="flex-shrink:0;margin-right:32px;">
                                            <div id="bannerPosterFrame" style="width:200px;height:300px;border-radius:12px;overflow:hidden;box-shadow:0 12px 32px rgba(0,0,0,.5);border:3px solid rgba(255,255,255,.15);position:relative;">
                                                <img id="bannerPosterImg" src="" alt="" style="width:100%;height:100%;object-fit:cover;">
                                                <div id="bannerPosterPlaceholder" style="width:100%;height:100%;background:rgba(255,255,255,.06);display:flex;flex-direction:column;align-items:center;justify-content:center;color:rgba(255,255,255,.3);">
                                                    <span style="font-size:36px;">🎬</span>
                                                    <span style="font-size:11px;margin-top:8px;letter-spacing:1px;">SEM PÔSTER</span>
                                                </div>
                                            </div>
                                        </div>
                                        <div style="flex:1;display:flex;flex-direction:column;justify-content:center;gap:12px;overflow:hidden;">
                                            <div style="display:flex;gap:8px;align-items:center;">
                                                <span id="bTipoBadge" style="padding:3px 10px;border-radius:4px;font-size:10px;font-weight:800;letter-spacing:1px;text-transform:uppercase;"></span>
                                                <span id="bNovoBadge" style="padding:3px 10px;border-radius:4px;font-size:10px;font-weight:800;letter-spacing:1px;background:#ff4444;color:#fff;display:none;">NOVO</span>
                                            </div>
                                            <div id="bTitulo" style="font-size:32px;font-weight:900;color:#fff;line-height:1.1;text-shadow:0 2px 12px rgba(0,0,0,.5);word-break:break-word;"></div>
                                            <div id="bTagline" style="font-size:14px;font-style:italic;opacity:.6;color:#fff;margin-top:-6px;"></div>
                                            <div style="display:flex;gap:12px;align-items:center;flex-wrap:wrap;">
                                                <div id="bNotaWrap" style="display:flex;align-items:center;gap:5px;">
                                                    <span style="color:#ffd700;font-size:14px;">★</span>
                                                    <span id="bNota" style="font-weight:800;font-size:15px;color:#ffd700;"></span>
                                                </div>
                                                <span id="bAno" style="font-size:13px;opacity:.65;color:#fff;"></span>
                                                <span id="bGeneros" style="font-size:12px;opacity:.5;color:#fff;"></span>
                                            </div>
                                            <div id="bSinopse" style="font-size:13px;line-height:1.6;color:rgba(255,255,255,.75);max-height:90px;overflow:hidden;position:relative;"></div>
                                            <div id="bPlataforma" style="margin-top:4px;">
                                                <span id="bPlataformaText" style="font-size:13px;font-weight:700;padding:6px 16px;border-radius:6px;color:#fff;display:inline-block;"></span>
                                            </div>
                                        </div>
                                    </div>
                                    
                                    <!-- LAYOUT 1: Só Texto -->
                                    <div id="layoutTexto" style="position:absolute;inset:0;z-index:4;display:none;padding:48px 60px;flex-direction:column;justify-content:center;gap:14px;">
                                        <div style="display:flex;gap:8px;align-items:center;">
                                            <span id="bTipoBadge2" style="padding:3px 10px;border-radius:4px;font-size:10px;font-weight:800;letter-spacing:1px;text-transform:uppercase;"></span>
                                            <span id="bNovoBadge2" style="padding:3px 10px;border-radius:4px;font-size:10px;font-weight:800;letter-spacing:1px;background:#ff4444;color:#fff;display:none;">NOVO</span>
                                        </div>
                                        <div id="bTitulo2" style="font-size:42px;font-weight:900;color:#fff;line-height:1.1;text-shadow:0 2px 12px rgba(0,0,0,.5);"></div>
                                        <div id="bTagline2" style="font-size:16px;font-style:italic;opacity:.6;color:#fff;"></div>
                                        <div style="display:flex;gap:14px;align-items:center;flex-wrap:wrap;">
                                            <div id="bNotaWrap2" style="display:flex;align-items:center;gap:5px;">
                                                <span style="color:#ffd700;">★</span>
                                                <span id="bNota2" style="font-weight:800;font-size:15px;color:#ffd700;"></span>
                                            </div>
                                            <span id="bAno2" style="font-size:13px;opacity:.65;color:#fff;"></span>
                                            <span id="bGeneros2" style="font-size:12px;opacity:.5;color:#fff;"></span>
                                        </div>
                                        <div id="bSinopse2" style="font-size:14px;line-height:1.65;color:rgba(255,255,255,.72);max-height:100px;overflow:hidden;"></div>
                                        <div id="bPlataforma2" style="margin-top:4px;">
                                            <span id="bPlataformaText2" style="font-size:13px;font-weight:700;padding:6px 16px;border-radius:6px;color:#fff;display:inline-block;"></span>
                                        </div>
                                    </div>
                                    
                                    <!-- Rodapé -->
                                    <div style="position:absolute;bottom:0;left:0;right:0;z-index:5;padding:14px 36px;display:flex;align-items:center;justify-content:space-between;border-top:1px solid rgba(255,255,255,.07);background:rgba(0,0,0,.25);">
                                        <span id="bMarca" style="font-size:10px;font-weight:700;letter-spacing:2px;text-transform:uppercase;opacity:.35;color:#fff;"></span>
                                        <span id="bRodapeTipo" style="font-size:10px;opacity:.3;color:#fff;letter-spacing:1px;text-transform:uppercase;"></span>
                                    </div>
                                </div>
                            </div>
                            <!-- Instrução -->
                            <div class="text-center mt-3">
                                <small class="text-muted"><i class="bi bi-info-circle me-1"></i>Busque um título acima ou preencha manualmente os campos à esquerda</small>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            
        </div>
        <?php include 'rodape.php'; ?>
    </div>

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

        const TMDB_KEY  = '10ae08a41683f157a3e774d7ca62ee4f';
        const TMDB_BASE = 'https://api.themoviedb.org/3';
        const IMG_BASE  = 'https://image.tmdb.org/t/p/w500';
        const IMG_ORIG  = 'https://image.tmdb.org/t/p/original';

        const temas = [
            { bg:'linear-gradient(135deg,#1a1a2e 0%,#16213e 60%,#0f3460 100%)', accent:'#4d9fff', pill:'rgba(13,110,253,.35)', overlay:'linear-gradient(to right,rgba(10,10,30,.98) 0%,rgba(10,10,30,.7) 60%,rgba(10,10,30,.1) 100%)' },
            { bg:'linear-gradient(135deg,#1a0a2e 0%,#2d1b69 60%,#4a1080 100%)', accent:'#bf94ff', pill:'rgba(111,66,193,.35)', overlay:'linear-gradient(to right,rgba(20,5,40,.98) 0%,rgba(20,5,40,.7) 60%,rgba(20,5,40,.1) 100%)' },
            { bg:'linear-gradient(135deg,#1a0a0a 0%,#4a0000 60%,#7a0000 100%)', accent:'#ff6b6b', pill:'rgba(220,53,69,.35)',  overlay:'linear-gradient(to right,rgba(30,5,5,.98) 0%,rgba(30,5,5,.7) 60%,rgba(30,5,5,.1) 100%)' },
            { bg:'linear-gradient(135deg,#0a1a2a 0%,#0a2a4a 60%,#0a3a6a 100%)', accent:'#87ceeb', pill:'rgba(13,202,240,.3)',  overlay:'linear-gradient(to right,rgba(5,15,30,.98) 0%,rgba(5,15,30,.7) 60%,rgba(5,15,30,.1) 100%)' },
            { bg:'linear-gradient(135deg,#1a1200 0%,#3a2800 60%,#5a3e00 100%)', accent:'#ffd700', pill:'rgba(255,193,7,.3)',   overlay:'linear-gradient(to right,rgba(20,14,0,.98) 0%,rgba(20,14,0,.7) 60%,rgba(20,14,0,.1) 100%)' },
            { bg:'linear-gradient(135deg,#0d1b0d 0%,#1b4332 60%,#2d6a4f 100%)', accent:'#52b788', pill:'rgba(25,135,84,.35)', overlay:'linear-gradient(to right,rgba(5,20,10,.98) 0%,rgba(5,20,10,.7) 60%,rgba(5,20,10,.1) 100%)' },
        ];

        let temaAtual  = 0; let layoutAtual= 0; let itemAtual  = null; let searchTimer;

        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);
                atualizar();
            });
        });

        function setLayout(idx, btn) {
            layoutAtual = idx;
            document.querySelectorAll('.layout-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');
            atualizar();
        }

        function debounceSearch() {
            clearTimeout(searchTimer);
            searchTimer = setTimeout(() => { if (document.getElementById('searchInput').value.trim().length >= 2) buscar(); }, 500);
        }

        function limparResultados() {
            document.getElementById('resultadosWrap').style.display = 'none';
            document.getElementById('resultadosGrid').innerHTML = '';
        }

        async function popularizarBusca() {
            document.getElementById('searchInput').value = '';
            await buscar(true);
        }

        async function buscar(popular = false) {
            const q = document.getElementById('searchInput').value.trim();
            const tipo = document.getElementById('searchType').value;
            const lang = document.getElementById('searchLang').value;
            const wrap = document.getElementById('resultadosWrap');
            const grid = document.getElementById('resultadosGrid');
            const load = document.getElementById('loadingMsg');
            const empty= document.getElementById('emptyMsg');

            wrap.style.display = 'block'; grid.innerHTML = ''; load.style.display = 'block'; empty.style.display= 'none';

            try {
                let url = (popular || !q) ? `${TMDB_BASE}/${tipo}/popular?api_key=${TMDB_KEY}&language=${lang}&page=1` : `${TMDB_BASE}/search/${tipo}?api_key=${TMDB_KEY}&query=${encodeURIComponent(q)}&language=${lang}`;
                const res = await fetch(url); const data = await res.json();
                load.style.display = 'none';

                const items = data.results || [];
                if (items.length === 0) { empty.style.display = 'block'; return; }

                grid.innerHTML = items.slice(0, 18).map(item => {
                    const titulo = item.title || item.name || '—';
                    const ano = (item.release_date || item.first_air_date || '').split('-')[0] || '';
                    const poster = item.poster_path ? IMG_BASE + item.poster_path : '';
                    return `
                        <div class="result-card" onclick="selecionarItem(${item.id})">
                            ${poster ? `<img src="${poster}" alt="${titulo}">` : `<div style="width:100%;height:210px;background:#1a1a2e;display:flex;align-items:center;justify-content:center;font-size:32px;">🎬</div>`}
                            <div class="result-card-info">
                                <div class="result-card-title" title="${titulo}">${titulo}</div>
                                <div class="result-card-year">${ano ? '📅 ' + ano : ''} ⭐ ${item.vote_average ? item.vote_average.toFixed(1) : '—'}</div>
                            </div>
                        </div>`;
                }).join('');
            } catch(e) { load.style.display = 'none'; empty.style.display= 'block'; }
        }

        // --- A MÁGICA DO PROXY NATIVO OCORRE AQUI ---
        async function urlParaBase64(url) {
            if (!url) return '';
            try {
                const proxyUrl = '?proxy_url=' + encodeURIComponent(url);
                const res = await fetch(proxyUrl);
                if (!res.ok) return url;
                const blob = await res.blob();
                return new Promise((resolve) => {
                    const reader = new FileReader();
                    reader.onloadend = () => resolve(reader.result);
                    reader.readAsDataURL(blob);
                });
            } catch(e) { return url; }
        }

        async function selecionarItem(id) {
            const tipo = document.getElementById('searchType').value;
            const lang = document.getElementById('searchLang').value;
            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>Carregando imagens do servidor...';

            try {
                const res = await fetch(`${TMDB_BASE}/${tipo}/${id}?api_key=${TMDB_KEY}&language=${lang}`);
                const data = await res.json();
                itemAtual = { ...data, _tipo: tipo };
                
                const titulo = data.title || data.name || '';
                const ano = (data.release_date || data.first_air_date || '').split('-')[0] || '';
                const nota = data.vote_average ? data.vote_average.toFixed(1) : '';
                const gen = (data.genres || []).map(g => g.name).join(' • ');
                const sinops = data.overview || '';
                const posterUrlTmdb = data.poster_path ? IMG_BASE + data.poster_path : '';
                const backdropUrlTmdb = data.backdrop_path ? IMG_ORIG + data.backdrop_path : '';

                // Converte as imagens para Base64 usando o proxy interno
                const [posterB64, backdropB64] = await Promise.all([ urlParaBase64(posterUrlTmdb), urlParaBase64(backdropUrlTmdb) ]);

                document.getElementById('customTitulo').value = titulo;
                document.getElementById('customTagline').value = data.tagline || '';
                document.getElementById('customNota').value = nota;
                document.getElementById('customAno').value = ano;
                document.getElementById('customGeneros').value = gen;

                document.getElementById('itemSelecionadoCard').style.display = 'block';
                document.getElementById('nomeSelecionado').textContent = titulo;
                document.getElementById('anoSelecionado').textContent = ano;
                document.getElementById('tipoSelecionado').textContent = tipo === 'movie' ? '🎬 Filme' : '📺 Série';
                if (posterB64) document.getElementById('thumbSelecionado').src = posterB64;

                window._sinopseAtual = sinops; window._posterUrl = posterB64; window._backdropUrl = backdropB64;

                statusDiv.style.display = 'none'; limparResultados(); atualizar();
            } catch(e) { statusDiv.className = 'alert alert-danger py-2'; statusDiv.innerHTML = 'Erro ao carregar: ' + e.message; }
        }

        function atualizar() {
            const titulo = document.getElementById('customTitulo').value || 'Título';
            const tagline = document.getElementById('customTagline').value || '';
            const nota = document.getElementById('customNota').value || '';
            const ano = document.getElementById('customAno').value || '';
            const generos = document.getElementById('customGeneros').value || '';
            const plataforma = document.getElementById('customPlataforma').value || 'Disponível';
            const marca = document.getElementById('customMarca').value || 'Sua Marca';
            const sinopse = window._sinopseAtual || '';
            const posterUrl = window._posterUrl || '';
            const backdropUrl = window._backdropUrl || '';
            const tipo = itemAtual ? (itemAtual._tipo === 'movie' ? 'FILME' : 'SÉRIE') : 'FILME';
            
            const showSinopse = document.getElementById('toggleSinopse').checked;
            const showNota = document.getElementById('toggleNota').checked;
            const showNovo = document.getElementById('toggleNovo').checked;
            const tema = temas[temaAtual];

            document.getElementById('bannerBg').style.background = tema.bg;
            const posterBgEl = document.getElementById('bannerPosterBg');
            const overlayEl = document.getElementById('bannerOverlay');

            if (layoutAtual === 2 && backdropUrl) {
                posterBgEl.style.backgroundImage = `url('${backdropUrl}')`; posterBgEl.style.display = 'block';
                overlayEl.style.display = 'block'; overlayEl.style.background= tema.overlay;
                document.getElementById('bannerBg').style.background = '#000';
            } else if (layoutAtual === 2 && posterUrl) {
                posterBgEl.style.backgroundImage = `url('${posterUrl}')`; posterBgEl.style.display = 'block';
                overlayEl.style.display = 'block'; overlayEl.style.background= tema.overlay;
                document.getElementById('bannerBg').style.background = '#000';
            } else {
                posterBgEl.style.display = 'none'; overlayEl.style.display = 'none';
                document.getElementById('bannerBg').style.background = tema.bg;
            }

            const l0 = document.getElementById('layoutPosterInfo'); const l1 = document.getElementById('layoutTexto');
            if (layoutAtual === 1) { l0.style.display = 'none'; l1.style.display = 'flex'; } else { l0.style.display = 'flex'; l1.style.display = 'none'; }

            const pImg = document.getElementById('bannerPosterImg'); const pPH = document.getElementById('bannerPosterPlaceholder'); const wPoster = document.getElementById('wrapPoster');
            if (layoutAtual === 2) { wPoster.style.display = 'none'; } else {
                wPoster.style.display = 'block';
                if (posterUrl) { pImg.src = posterUrl; pImg.style.display = 'block'; pPH.style.display = 'none'; } else { pImg.style.display = 'none'; pPH.style.display = 'flex'; }
            }

            const tipoCor = tipo === 'SÉRIE' ? tema.accent : '#dc3545';
            setEl('bTipoBadge', `background:${tipoCor}22;color:${tipoCor};border:1px solid ${tipoCor}55;`);
            setEl('bTipoBadge2', `background:${tipoCor}22;color:${tipoCor};border:1px solid ${tipoCor}55;`);
            document.getElementById('bTipoBadge').textContent = tipo; document.getElementById('bTipoBadge2').textContent = tipo;

            showEl('bNovoBadge', showNovo); showEl('bNovoBadge2', showNovo);
            document.getElementById('bTitulo').textContent = titulo; document.getElementById('bTitulo2').textContent = titulo;
            document.getElementById('bTagline').textContent = tagline; document.getElementById('bTagline2').textContent = tagline;
            showEl('bTagline', !!tagline); showEl('bTagline2', !!tagline);
            
            document.getElementById('bNota').textContent = nota; document.getElementById('bNota2').textContent = nota;
            showEl('bNotaWrap', showNota && !!nota); showEl('bNotaWrap2', showNota && !!nota);
            
            document.getElementById('bAno').textContent = ano; document.getElementById('bAno2').textContent = ano;
            document.getElementById('bGeneros').textContent = generos; document.getElementById('bGeneros2').textContent = generos;
            
            const sinTrunc = sinopse.length > 220 ? sinopse.substring(0, 220) + '…' : sinopse;
            document.getElementById('bSinopse').textContent = showSinopse ? sinTrunc : '';
            document.getElementById('bSinopse2').textContent = showSinopse ? sinopse.substring(0, 280) + (sinopse.length > 280 ? '…' : '') : '';
            
            document.getElementById('bPlataformaText').textContent = plataforma; document.getElementById('bPlataformaText2').textContent = plataforma;
            document.getElementById('bPlataformaText').style.background = tema.pill; document.getElementById('bPlataformaText2').style.background = tema.pill;
            document.getElementById('bPlataformaText').style.border = `1px solid ${tema.accent}44`; document.getElementById('bPlataformaText2').style.border = `1px solid ${tema.accent}44`;
            document.getElementById('bPlataformaText').style.color = tema.accent; document.getElementById('bPlataformaText2').style.color = tema.accent;
            
            document.getElementById('bMarca').textContent = marca.toUpperCase(); document.getElementById('bRodapeTipo').textContent = tipo;
            escalarPreview();
        }

        function setEl(id, style) { const el = document.getElementById(id); if (el) el.style.cssText += ';' + style; }
        function showEl(id, show) { const el = document.getElementById(id); if (el) el.style.display = show ? (el.tagName === 'DIV' ? 'flex' : 'inline-block') : 'none'; }

        function escalarPreview() {
            const scaler = document.getElementById('previewScaler'); const banner = document.getElementById('bannerCard');
            const maxW = scaler.parentElement.clientWidth - 2; const scale = Math.min(1, maxW / 900);
            banner.style.transform = `scale(${scale})`; banner.style.transformOrigin = 'top left';
            scaler.style.height = Math.round(480 * scale) + 'px'; scaler.style.width = Math.round(900 * scale) + 'px';
        }

        // =========================================================================================
        // MÁGICA DE RENDERIZAÇÃO PARA O CELULAR (Corrige o bug da sinopse sumir na tela estreita)
        // =========================================================================================
        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>Gerando imagem...';

            const banner = document.getElementById('bannerCard');
            const previewScaler = document.getElementById('previewScaler');
            
            // 1. Salvar as configurações atuais para devolver depois
            const transformOriginal = banner.style.transform;
            const overflowOriginal = previewScaler.style.overflow;
            
            // 2. Tirar o banner do quadro apertado do celular e forçar tamanho de PC invisível
            banner.style.transform = 'scale(1)';
            banner.style.position = 'fixed';
            banner.style.top = '0';
            banner.style.left = '0';
            banner.style.zIndex = '-9999';
            document.body.appendChild(banner);

            try {
                const canvas = await html2canvas(banner, { 
                    scale: 2, 
                    useCORS: true, 
                    allowTaint: false, 
                    backgroundColor: null, 
                    logging: false, 
                    width: 900, 
                    height: 480
                });
                
                // 3. Devolver o banner imediatamente para a caixinha dele
                previewScaler.appendChild(banner);
                banner.style.position = 'relative';
                banner.style.top = 'auto';
                banner.style.left = 'auto';
                banner.style.zIndex = 'auto';
                banner.style.transform = transformOriginal;
                previewScaler.style.overflow = overflowOriginal;
                
                // 4. Salvar e Baixar a Imagem
                const titulo = document.getElementById('customTitulo').value || 'banner';
                const nome = `banner_${titulo}`.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', .95); link.click();
                
                statusDiv.className = 'alert alert-success py-2'; statusDiv.innerHTML = '<i class="bi bi-check-circle me-2"></i>Banner exportado com sucesso!';
                setTimeout(() => statusDiv.style.display = 'none', 4000);
            } catch(e) {
                // Em caso de erro, devolvemos tudo ao normal para não bugar a tela
                previewScaler.appendChild(banner);
                banner.style.position = 'relative';
                banner.style.top = 'auto';
                banner.style.left = 'auto';
                banner.style.zIndex = 'auto';
                banner.style.transform = transformOriginal;
                
                statusDiv.className = 'alert alert-danger py-2'; statusDiv.innerHTML = 'Erro: ' + e.message;
            }
        }

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