<?php
// admin.php - VERSÃO FINAL (LAYOUT CORRIGIDO + SEM ZOOM NO PREVIEW)
date_default_timezone_set('America/Sao_Paulo');
ini_set('upload_max_filesize', '100M');
ini_set('post_max_size', '100M');
set_time_limit(300);

require 'config.php';
require 'ai_generator.php';

// --- 1. AJAX APAGAR ---
if (isset($_POST['acao']) && $_POST['acao'] == 'apagar_arquivos_ajax') {
    header('Content-Type: application/json');
    $arquivos = json_decode($_POST['lista_arquivos']);
    $removidos = 0;
    if (is_array($arquivos)) {
        foreach ($arquivos as $arq) {
            $caminhoCompleto = 'uploads/' . basename($arq);
            if (file_exists($caminhoCompleto)) { unlink($caminhoCompleto); $removidos++; }
        }
    }
    echo json_encode(['sucesso' => true, 'qtd' => $removidos]); exit;
}

// --- 2. AJAX REORDENAR ---
if (isset($_POST['acao']) && $_POST['acao'] == 'reordenar') {
    $ordem = json_decode($_POST['lista_ids']);
    foreach ($ordem as $posicao => $id) {
        $pdo->prepare("UPDATE conteudos SET ordem = ? WHERE id = ?")->execute([$posicao, $id]);
    }
    exit;
}

// --- 3. AÇÕES GET ---
if (isset($_GET['del_conteudo'])) {
    $pdo->query("DELETE FROM conteudos WHERE id = " . (int)$_GET['del_conteudo']);
    header("Location: admin.php"); exit;
}
if (isset($_GET['del_aviso'])) {
    $pdo->query("DELETE FROM avisos WHERE id = " . (int)$_GET['del_aviso']);
    header("Location: admin.php"); exit;
}
if (isset($_GET['toggle_conteudo'])) {
    $pdo->query("UPDATE conteudos SET ativo = NOT ativo WHERE id = " . (int)$_GET['toggle_conteudo']);
    header("Location: admin.php"); exit;
}

// --- 4. SALVAR CONTEÚDO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'salvar_conteudo') {
    $tipo = $_POST['tipo_conteudo'];
    $dados_grafico = null;
    $url_final = '';

    if (!empty($_FILES['arquivo_upload']['name'])) {
        $ext = strtolower(pathinfo($_FILES['arquivo_upload']['name'], PATHINFO_EXTENSION));
        $prefixo = ($tipo == 'video') ? 'vid_' : 'img_';
        $path = 'uploads/' . $prefixo . uniqid() . '.' . $ext;
        if (move_uploaded_file($_FILES['arquivo_upload']['tmp_name'], $path)) $url_final = $path;
    } elseif (!empty($_POST['media_existente'])) {
        $url_final = $_POST['media_existente'];
    } elseif (!empty($_POST['hidden_bg_url'])) {
        $url_final = $_POST['hidden_bg_url'];
    }

    if ($tipo === 'grafico') {
        $dados_grafico = json_encode([
            'labels' => explode(',', $_POST['grafico_labels']),
            'data' => explode(',', $_POST['grafico_dados']),
            'label' => $_POST['grafico_titulo']
        ]);
        $url_final = '';
    }

    $maxOrdem = $pdo->query("SELECT MAX(ordem) FROM conteudos")->fetchColumn();
    $stmt = $pdo->prepare("INSERT INTO conteudos (titulo, texto_conteudo, imagem_url, dados_grafico, tipo_conteudo, formato, ativo, ordem) VALUES (?, ?, ?, ?, ?, ?, 1, ?)");
    $stmt->execute([$_POST['titulo'], $_POST['texto'], $url_final, $dados_grafico, $tipo, $_POST['formato'], $maxOrdem + 1]);
}

// --- 5. SALVAR/EDITAR AVISO ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['acao']) && $_POST['acao'] == 'salvar_aviso') {
    if (!empty($_POST['id_aviso'])) {
        $stmt = $pdo->prepare("UPDATE avisos SET mensagem=?, cor_fundo=?, data_inicio=?, data_fim=? WHERE id=?");
        $stmt->execute([$_POST['aviso_msg'], $_POST['aviso_cor'], $_POST['data_inicio'], $_POST['data_fim'], $_POST['id_aviso']]);
    } else {
        $stmt = $pdo->prepare("INSERT INTO avisos (mensagem, cor_fundo, data_inicio, data_fim, ativo) VALUES (?, ?, ?, ?, 1)");
        $stmt->execute([$_POST['aviso_msg'], $_POST['aviso_cor'], $_POST['data_inicio'], $_POST['data_fim']]);
    }
    header("Location: admin.php"); exit;
}

// --- LEITURA ---
$arquivos = array_diff(scandir('uploads'), array('.', '..'));
$galeriaImagens = []; $galeriaVideos = [];
foreach($arquivos as $arq) {
    $ext = strtolower(pathinfo($arq, PATHINFO_EXTENSION)); $c = 'uploads/' . $arq;
    if(in_array($ext, ['jpg', 'jpeg', 'png', 'gif', 'webp'])) $galeriaImagens[] = $c;
    elseif(in_array($ext, ['mp4', 'webm'])) $galeriaVideos[] = $c;
}

$playlist = $pdo->query("SELECT * FROM conteudos ORDER BY ordem ASC")->fetchAll(PDO::FETCH_ASSOC);
$avisosAtivos = $pdo->query("SELECT * FROM avisos WHERE data_fim >= NOW() ORDER BY data_inicio ASC")->fetchAll(PDO::FETCH_ASSOC);
$avisosHistorico = $pdo->query("SELECT * FROM avisos WHERE data_fim < NOW() ORDER BY id DESC LIMIT 20")->fetchAll(PDO::FETCH_ASSOC);
?>

<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0, maximum-scale=1.0, user-scalable=no">
    <title>Painel TV - Ultimate</title>
    
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/html2canvas/1.4.1/html2canvas.min.js"></script>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.14.0/Sortable.min.js"></script>
    <link href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.0.0/css/all.min.css" rel="stylesheet">
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700;900&display=swap" rel="stylesheet">
    
    <style>
        :root { --primary: #ffcc00; --dark: #0f1016; --gray: #1f2235; --text: #eee; }
        * { box-sizing: border-box; -webkit-tap-highlight-color: transparent; }
        body { margin: 0; font-family: 'Segoe UI', sans-serif; background: var(--dark); color: var(--text); display: flex; height: 100vh; overflow: hidden; }
        
        .sidebar { width: 340px; background: #050510; padding: 20px; border-right: 1px solid #222; overflow-y: auto; display: flex; flex-direction: column; gap: 15px; flex-shrink: 0; z-index: 10; }
        .main { flex: 1; padding: 30px; display: flex; flex-direction: column; align-items: center; background: #12121a; overflow-y: auto; }

        /* RESPONSIVIDADE (Mobile Layout) */
        @media (max-width: 900px) {
            body { flex-direction: column; overflow-y: auto; height: auto; }
            .sidebar { width: 100%; height: auto; max-height: 50vh; border-right: none; border-bottom: 2px solid #ffcc00; padding: 10px; order: 1; }
            .main { width: 100%; height: auto; padding: 10px; overflow-x: hidden; order: 2; }
            .play-item { width: 48% !important; } 
        }

        .logo-area { text-align: center; margin-bottom: 20px; color: var(--primary); font-weight: bold; font-size: 1.5rem; text-transform: uppercase; }
        .tabs { display: flex; gap: 5px; margin-bottom: 15px; }
        .tab-btn { flex: 1; padding: 10px; background: var(--gray); border: none; color: #aaa; cursor: pointer; border-radius: 4px; font-size: 0.8rem; transition: 0.3s; white-space: nowrap; }
        .tab-btn.active { background: var(--primary); color: #000; font-weight: bold; }
        .form-section { display: none; animation: fadeIn 0.5s; }
        .form-section.active { display: block; }
        label { display: block; margin-top: 10px; font-size: 0.85rem; color: #889; }
        input, select, textarea { width: 100%; padding: 10px; background: #1a1c29; border: 1px solid #334; color: #fff; border-radius: 4px; margin-top: 5px; }
        .btn-action { width: 100%; padding: 12px; margin-top: 15px; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }
        .btn-ia { background: #5a4fcf; color: white; border:none; cursor:pointer; padding: 10px; border-radius: 4px; }
        .btn-save { background: #27ae60; color: white; }
        .btn-alert { background: #e74c3c; color: white; }
        .btn-cancel { background: #7f8c8d; color: white; display: none; margin-top: 5px; }
        .btn-gallery { background: #e67e22; color: white; padding: 8px; border:none; border-radius: 4px; cursor: pointer; font-size: 0.8rem; width: 100%; margin-top: 5px; }
        .btn-png { background: #2980b9; color: white; margin-top: 20px; width: 100%; padding: 12px; border: none; border-radius: 4px; font-weight: bold; cursor: pointer; }
        .quick-tags { display: flex; gap: 5px; flex-wrap: wrap; margin-bottom: 5px; }
        .tag-btn { flex: 1; min-width: 45%; border: none; padding: 8px; border-radius: 4px; cursor: pointer; font-size: 0.8rem; font-weight: bold; color: white; display: flex; align-items: center; justify-content: center; gap: 5px; }
        .t-nutri { background: #27ae60; } .t-saude { background: #3498db; } .t-gym { background: #c0392b; } .t-yoga { background: #9b59b6; }

        /* PREVIEW CONTAINER (FIXED LAYOUT) */
        .preview-wrapper { width: 100%; display: flex; justify-content: center; margin-bottom: 40px; } /* Margem maior embaixo */
        
        #previewBox { 
            position: relative; 
            background: #000; 
            overflow: hidden; 
            border: 4px solid #1a1c29; 
            font-family: 'Montserrat', sans-serif; 
            box-shadow: 0 0 50px rgba(0,0,0,0.5); 
            /* Importante: Flexibilidade sem JS */
            width: 100%;
            max-width: 720px; /* Max largura desktop */
        }
        
        /* Classes controladas por CSS puro (AspectRatio) */
        .fmt-16-9 { aspect-ratio: 16/9; } 
        .fmt-9-16 { max-width: 360px !important; aspect-ratio: 9/16; }
        
        /* CORREÇÃO DO ZOOM: CONTAIN */
        #bgLayer { 
            position: absolute; top: 0; left: 0; width: 100%; height: 100%; 
            background-size: contain !important; /* Mostra imagem inteira */
            background-position: center center !important; 
            background-repeat: no-repeat !important; 
            z-index: 0; 
        }
        
        .text-layer { position: absolute; bottom: 0; left: 0; width: 100%; padding: 40px; background: linear-gradient(to top, rgba(0, 25, 80, 0.95), transparent); pointer-events: none; box-sizing: border-box; z-index: 2; }
        .text-layer h1 { margin: 0; color: #ffcc00; font-size: 4rem; line-height: 0.9; font-weight: 900; text-transform: uppercase; text-shadow: 3px 3px 0 rgba(0,0,0,0.5); }
        .text-layer p { font-size: 2rem; font-weight: 800; margin-top: 5px; text-shadow: 2px 2px 5px rgba(0,0,0,0.8); }
        
        /* Responsividade do Texto no Preview (Usando vw/clamp se necessário, mas scale funciona melhor no player. Aqui vamos simplificar) */
        @media (max-width: 600px) {
            .text-layer h1 { font-size: 2rem; }
            .text-layer p { font-size: 1rem; }
            .text-layer { padding: 15px; }
        }

        .chart-container { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -55%); width: 85%; height: 55%; background: rgba(10, 20, 40, 0.9); border-radius: 15px; padding: 20px; display: none; z-index: 1; }
        
        .aviso-item { background: #222; padding: 10px; border-radius: 5px; margin-bottom: 5px; display: flex; justify-content: space-between; align-items: center; border-left: 5px solid #555; }
        .aviso-ativo { border-left: 5px solid #27ae60; background: #1b261b; }
        .section-title { font-size: 0.8rem; color: #ffcc00; margin: 15px 0 5px 0; border-bottom: 1px solid #444; padding-bottom: 3px; font-weight:bold; }

        .playlist-container { margin-top: 10px; width: 100%; overflow-y: auto; }
        .playlist-grid { display: flex; flex-wrap: wrap; gap: 10px; padding-bottom: 50px; justify-content: center; }
        
        .play-item { 
            width: 220px; aspect-ratio: 16/9; background: #000; border-radius: 6px; 
            position: relative; overflow: hidden; border: 2px solid #333; cursor: grab; 
            box-shadow: 0 4px 6px rgba(0,0,0,0.3); transition: transform 0.2s; flex-shrink: 0; touch-action: none; 
        }
        .play-item img, .play-item video { width: 100%; height: 100%; object-fit: cover; opacity: 0.7; pointer-events: none; }
        .item-info { position: absolute; bottom: 0; left: 0; width: 100%; background: rgba(0,0,0,0.8); padding: 5px; text-align: center; color: #fff; display: flex; flex-direction: column; justify-content: center; min-height: 40px; }
        .item-tit { color: #ffcc00; font-weight: 800; font-size: 0.8rem; text-transform: uppercase; line-height: 1; margin-bottom: 2px; }
        .item-desc { color: #ddd; font-size: 0.6rem; line-height: 1.1; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .play-actions { position: absolute; top: 2px; right: 2px; z-index: 10; display:flex; gap:2px; }
        .badge { background: rgba(0,0,0,0.6); color: white; padding: 4px; border-radius: 3px; font-size: 10px; cursor: pointer;}

        /* MODAL GALERIA */
        #modalGaleria { display: none; position: fixed; top: 0; left: 0; width: 100%; height: 100%; background: rgba(0,0,0,0.95); z-index: 2000; align-items: center; justify-content: center; }
        .modal-content { background: #1a1c29; width: 90%; height: 90%; border-radius: 10px; padding: 15px; display: flex; flex-direction: column; border: 1px solid #333; }
        .modal-header { display: flex; justify-content: space-between; align-items: center; margin-bottom: 10px; border-bottom: 1px solid #333; padding-bottom: 10px; }
        .modal-body { flex: 1; overflow-y: auto; padding: 10px; }
        .gallery-grid { display: grid; grid-template-columns: repeat(auto-fill, minmax(120px, 1fr)); gap: 10px; }
        .gallery-item { position: relative; border: 2px solid #333; border-radius: 5px; overflow: hidden; cursor: pointer; aspect-ratio: 16/9; background:#000; }
        .gallery-item img, .gallery-item video { width: 100%; height: 100%; object-fit: contain; }
        .check-overlay { position: absolute; top: 5px; left: 5px; width: 20px; height: 20px; border: 2px solid white; border-radius: 50%; background: rgba(0,0,0,0.5); z-index: 10; }
        .gallery-item.selected { border-color: #c0392b; } 
        .gallery-item.selected .check-overlay { background: #c0392b; border-color: #c0392b; }
        #btnApagarMassa { display: none; background: #c0392b; color: white; border: none; padding: 8px 15px; border-radius: 4px; font-weight: bold; cursor: pointer; }
        
        .play-item.sortable-ghost { opacity: 0.4; }
        .play-item.sortable-drag { border: 2px solid #ffcc00; cursor: grabbing; }
    </style>
</head>
<body>

<div class="sidebar">
    <div class="logo-area"><i class="fas fa-tv"></i> GESTOR TV</div>
    
    <div class="tabs">
        <button class="tab-btn active" onclick="switchTab('img')">Img</button>
        <button class="tab-btn" onclick="switchTab('video')">Vídeo</button>
        <button class="tab-btn" onclick="switchTab('chart')">Graf</button>
        <button class="tab-btn" onclick="switchTab('aviso')">Avisos</button>
    </div>

    <div id="formImg" class="form-section active">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="acao" value="salvar_conteudo"> <input type="hidden" name="tipo_conteudo" value="imagem">
            <select name="formato" id="selFormato" onchange="resizePreview()"><option value="16:9">Horizontal</option><option value="9:16">Vertical</option></select>
            <div class="quick-tags" style="margin-top:10px;">
                <button type="button" class="tag-btn t-nutri" onclick="setTema('Nutrição')"><i class="fas fa-apple-alt"></i></button>
                <button type="button" class="tag-btn t-saude" onclick="setTema('Saúde')"><i class="fas fa-heartbeat"></i></button>
                <button type="button" class="tag-btn t-gym" onclick="setTema('Musculação')"><i class="fas fa-dumbbell"></i></button>
                <button type="button" class="tag-btn t-yoga" onclick="setTema('Yoga')"><i class="fas fa-spa"></i></button>
            </div>
            <div style="display:flex; gap:5px; margin-top:5px;">
                <input type="text" id="temaIA" placeholder="Tema IA"> <button type="button" class="btn-ia" onclick="gerarIA()">IA</button>
            </div>
            <label>Título</label><input type="text" name="titulo" id="inpTitulo" value="FOCO" onkeyup="updatePreview()">
            <label>Msg</label><textarea name="texto" id="inpTexto" rows="2" onkeyup="updatePreview()">Sem dor, sem ganho.</textarea>
            <button type="button" class="btn-gallery" onclick="abrirGaleria('img')"><i class="fas fa-images"></i> Galeria</button>
            <div style="margin-top:5px; border-top:1px dashed #333; padding-top:5px;"><label style="margin:0; font-size:0.7rem;">Ou Upload:</label><input type="file" name="arquivo_upload" onchange="previewBg(this)"></div>
            <input type="hidden" name="hidden_bg_url" id="hiddenBgUrl"> <input type="hidden" name="media_existente" id="mediaExistenteImg">
            <button type="submit" class="btn-action btn-save">SALVAR</button>
        </form>
    </div>

    <div id="formVideo" class="form-section">
        <form method="POST" enctype="multipart/form-data">
            <input type="hidden" name="acao" value="salvar_conteudo"> <input type="hidden" name="tipo_conteudo" value="video">
            <select name="formato"><option value="16:9">Horizontal</option><option value="9:16">Vertical</option></select>
            <label>Título</label><input type="text" name="titulo" placeholder="Ex: AULA">
            <button type="button" class="btn-gallery" onclick="abrirGaleria('video')"><i class="fas fa-film"></i> Galeria</button>
            <div style="margin-top:5px; border-top:1px dashed #333; padding-top:5px;"><label style="margin:0; font-size:0.7rem;">Ou Upload:</label><input type="file" name="arquivo_upload" accept="video/mp4"></div>
            <input type="hidden" name="media_existente" id="mediaExistenteVid">
            <button type="submit" class="btn-action btn-save">SALVAR VÍDEO</button>
        </form>
    </div>

    <div id="formChart" class="form-section">
        <form method="POST">
            <input type="hidden" name="acao" value="salvar_conteudo"> <input type="hidden" name="tipo_conteudo" value="grafico"> <input type="hidden" name="formato" value="16:9">
            <input type="text" name="titulo" value="DADOS"> <input type="text" name="texto" value="Números"> <input type="text" name="grafico_titulo" value="Legenda">
            <input type="text" name="grafico_labels" value="A, B, C" onkeyup="renderChartPreview()"> <input type="text" name="grafico_dados" value="10, 20, 30" onkeyup="renderChartPreview()">
            <button type="submit" class="btn-action btn-save">SALVAR GRÁFICO</button>
        </form>
    </div>

    <div id="formAviso" class="form-section">
        <form method="POST" id="formAvisoTag">
            <input type="hidden" name="acao" value="salvar_aviso"> <input type="hidden" name="id_aviso" id="inpIdAviso">
            <label>Mensagem</label><input type="text" name="aviso_msg" id="inpAvisoMsg" placeholder="Msg" required>
            <select name="aviso_cor" id="inpAvisoCor"><option value="#c0392b">🔴 Verm</option><option value="#2980b9">🔵 Azul</option><option value="#f39c12">🟠 Lar</option><option value="#27ae60">🟢 Verde</option></select>
            <label>Início</label><input type="datetime-local" name="data_inicio" id="inpAvisoInicio" value="<?= date('Y-m-d\TH:i') ?>" required>
            <label>Fim</label><input type="datetime-local" name="data_fim" id="inpAvisoFim" value="<?= date('Y-m-d\TH:i', strtotime('+1 day')) ?>" required>
            <button type="submit" class="btn-action btn-alert" id="btnSalvarAviso">AGENDAR</button>
            <button type="button" class="btn-action btn-cancel" id="btnCancelarEdicao" onclick="limparEdicaoAviso()">CANCELAR</button>
        </form>
        <div style="max-height: 200px; overflow-y:auto; margin-top:10px;">
            <div class="section-title">📅 No Ar</div>
            <?php foreach($avisosAtivos as $av): ?>
                <div class="aviso-item aviso-ativo" style="border-color:<?= $av['cor_fundo'] ?>">
                    <div style="font-size:0.7rem;"><strong><?= substr($av['mensagem'],0,20) ?>...</strong><br><span style="color:#27ae60;">Até: <?= date('d/m H:i', strtotime($av['data_fim'])) ?></span></div>
                    <div><button type="button" style="background:none;border:none;color:#f39c12;cursor:pointer;" onclick='editarAviso(<?= json_encode($av) ?>)'><i class="fas fa-pencil-alt"></i></button> <a href="?del_aviso=<?= $av['id'] ?>" onclick="return confirm('Apagar?')" style="color:#c0392b;"><i class="fas fa-times-circle"></i></a></div>
                </div>
            <?php endforeach; ?>
            
            <div class="section-title">📂 Histórico</div>
            <?php foreach($avisosHistorico as $av): ?>
                <div class="aviso-item" style="border-color:<?= $av['cor_fundo'] ?>; opacity:0.7;">
                    <div style="font-size:0.7rem;"><strong><?= substr($av['mensagem'],0,20) ?>...</strong></div>
                    <div><button type="button" style="background:none;border:none;color:#3498db;cursor:pointer;" onclick='editarAviso(<?= json_encode($av) ?>)'><i class="fas fa-redo"></i></button> <a href="?del_aviso=<?= $av['id'] ?>" onclick="return confirm('Apagar permanente?')" style="color:#555;"><i class="fas fa-trash"></i></a></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
    <button class="btn-png" onclick="baixarPNG()"><i class="fas fa-download"></i> PNG</button>
</div>

<div class="main">
    <div class="preview-wrapper">
        <div id="previewBox" class="fmt-16-9">
            <div id="bgLayer"></div>
            <div class="chart-container" id="chartLayer"><canvas id="myChart"></canvas></div>
            <div class="text-layer" id="textLayer"><h1 id="prevTitulo">FOCO</h1><p id="prevTexto">Sem dor, sem ganho.</p></div>
        </div>
    </div>

    <h2 style="color: #ffcc00; margin-top:10px; border-bottom: 2px solid #333; width:100%; font-size:1rem;">
        <i class="fas fa-layer-group"></i> Playlist (Segure p/ mover)
    </h2>
    <div class="playlist-container">
        <div id="listaPlaylist" class="playlist-grid">
            <?php foreach($playlist as $item): ?>
                <div class="play-item <?= $item['ativo']?'active':'' ?>" data-id="<?= $item['id'] ?>">
                    <?php if($item['tipo_conteudo']=='video'): ?><video src="<?= $item['imagem_url'] ?>" muted></video><div style="position:absolute;top:35%;left:40%;font-size:30px;color:white;"><i class="fas fa-play-circle"></i></div>
                    <?php elseif($item['tipo_conteudo']=='grafico'): ?><div style="width:100%;height:100%;background:#333;color:#ffcc00;display:flex;align-items:center;justify-content:center"><i class="fas fa-chart-bar fa-2x"></i></div>
                    <?php else: ?><img src="<?= $item['imagem_url'] ?>"><?php endif; ?>
                    
                    <div class="item-info">
                        <div class="item-tit"><?= htmlspecialchars(substr($item['titulo'], 0, 20)) ?></div>
                        <div class="item-desc"><?= htmlspecialchars(substr($item['texto_conteudo'], 0, 30)) ?>...</div>
                    </div>

                    <div class="play-actions"><a href="?toggle_conteudo=<?= $item['id'] ?>" class="badge"><i class="fas fa-power-off" style="color:<?= $item['ativo']?'#27ae60':'#ccc' ?>"></i></a> <a href="?del_conteudo=<?= $item['id'] ?>" onclick="return confirm('Apagar?')" class="badge"><i class="fas fa-trash"></i></a></div>
                </div>
            <?php endforeach; ?>
        </div>
    </div>
</div>

<div id="modalGaleria">
    <div class="modal-content">
        <div class="modal-header">
            <h3 style="color:#ffcc00; margin:0;">Galeria</h3>
            <div style="display:flex; gap:10px; align-items:center;">
                <button id="btnApagarMassa" onclick="apagarSelecionados()"><i class="fas fa-trash"></i></button>
                <div style="display:flex; gap:5px;"><button class="tab-btn active" id="btnTabImg" onclick="filtroGaleria('img')">Img</button><button class="tab-btn" id="btnTabVid" onclick="filtroGaleria('vid')">Vid</button></div>
                <button onclick="fecharGaleria()" style="background:none; border:none; color:white; font-size:1.5rem; cursor:pointer;">&times;</button>
            </div>
        </div>
        <div class="modal-body">
            <div id="galeria-img" class="gallery-grid">
                <?php foreach($galeriaImagens as $img): ?>
                    <div class="gallery-item" onclick="selecionarItem(this, '<?= $img ?>', 'img')"><img src="<?= $img ?>" loading="lazy"><div class="check-overlay" onclick="event.stopPropagation(); toggleSelecao(this, '<?= $img ?>')"></div></div>
                <?php endforeach; ?>
            </div>
            <div id="galeria-vid" class="gallery-grid" style="display:none;">
                <?php foreach($galeriaVideos as $vid): ?>
                    <div class="gallery-item" onclick="selecionarItem(this, '<?= $vid ?>', 'vid')"><video src="<?= $vid ?>" muted></video><div class="check-overlay" onclick="event.stopPropagation(); toggleSelecao(this, '<?= $vid ?>')"></div></div>
                <?php endforeach; ?>
            </div>
        </div>
    </div>
</div>

<script>
    function editarAviso(aviso) {
        document.getElementById('inpIdAviso').value = aviso.id;
        document.getElementById('inpAvisoMsg').value = aviso.mensagem;
        document.getElementById('inpAvisoCor').value = aviso.cor_fundo;
        document.getElementById('inpAvisoInicio').value = aviso.data_inicio.replace(' ', 'T');
        document.getElementById('inpAvisoFim').value = aviso.data_fim.replace(' ', 'T');
        document.getElementById('btnSalvarAviso').innerText = "SALVAR";
        document.getElementById('btnSalvarAviso').style.background = "#f39c12";
        document.getElementById('btnCancelarEdicao').style.display = "block";
        document.getElementById('formAviso').scrollIntoView({ behavior: 'smooth' });
    }
    function limparEdicaoAviso() {
        document.getElementById('formAvisoTag').reset();
        document.getElementById('inpIdAviso').value = "";
        document.getElementById('btnSalvarAviso').innerText = "AGENDAR";
        document.getElementById('btnSalvarAviso').style.background = "#e74c3c";
        document.getElementById('btnCancelarEdicao').style.display = "none";
        const agora = new Date(); agora.setMinutes(agora.getMinutes() - agora.getTimezoneOffset());
        document.getElementById('inpAvisoInicio').value = agora.toISOString().slice(0,16);
        const amanha = new Date(agora); amanha.setDate(amanha.getDate() + 1);
        document.getElementById('inpAvisoFim').value = amanha.toISOString().slice(0,16);
    }

    // SCROLL FIX
    let selecionadosParaApagar = [];
    function toggleSelecao(bolinha, url) {
        let item = bolinha.parentElement;
        if (selecionadosParaApagar.includes(url)) { selecionadosParaApagar = selecionadosParaApagar.filter(u => u !== url); item.classList.remove('selected'); bolinha.style.background = 'rgba(0,0,0,0.5)'; } 
        else { selecionadosParaApagar.push(url); item.classList.add('selected'); bolinha.style.background = '#c0392b'; }
        let btn = document.getElementById('btnApagarMassa');
        btn.style.display = selecionadosParaApagar.length > 0 ? 'block' : 'none';
        btn.innerHTML = `<i class="fas fa-trash"></i> (${selecionadosParaApagar.length})`;
    }
    function apagarSelecionados() {
        if (!confirm(`Apagar ${selecionadosParaApagar.length} arquivos?`)) return;
        let formData = new FormData(); formData.append('acao', 'apagar_arquivos_ajax'); formData.append('lista_arquivos', JSON.stringify(selecionadosParaApagar));
        fetch('admin.php', { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            if (data.sucesso) { selecionadosParaApagar.forEach(url => { document.querySelectorAll('.gallery-item img, .gallery-item video').forEach(el => { if(el.getAttribute('src') === url) el.parentElement.remove(); }); }); selecionadosParaApagar = []; document.getElementById('btnApagarMassa').style.display = 'none'; }
        });
    }
    let tipoAtualGaleria = 'img';
    function abrirGaleria(tipo) { tipoAtualGaleria = tipo; document.getElementById('modalGaleria').style.display = 'flex'; filtroGaleria(tipo); selecionadosParaApagar = []; document.querySelectorAll('.gallery-item').forEach(el => el.classList.remove('selected')); document.getElementById('btnApagarMassa').style.display = 'none'; }
    function fecharGaleria() { document.getElementById('modalGaleria').style.display = 'none'; }
    function filtroGaleria(tipo) {
        if(tipo === 'img') { document.getElementById('galeria-img').style.display = 'grid'; document.getElementById('galeria-vid').style.display = 'none'; document.getElementById('btnTabImg').classList.add('active'); document.getElementById('btnTabVid').classList.remove('active'); } 
        else { document.getElementById('galeria-img').style.display = 'none'; document.getElementById('galeria-vid').style.display = 'grid'; document.getElementById('btnTabImg').classList.remove('active'); document.getElementById('btnTabVid').classList.add('active'); }
    }
    function selecionarItem(elemento, url, tipo) {
        if (selecionadosParaApagar.length > 0) return;
        if (tipoAtualGaleria === 'img') { document.getElementById('hiddenBgUrl').value = url; document.getElementById('mediaExistenteImg').value = url; document.getElementById('bgLayer').style.backgroundImage = `url('${url}')`; } 
        else { document.getElementById('mediaExistenteVid').value = url; }
        fecharGaleria();
    }
    function switchTab(mode) {
        document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active')); document.querySelectorAll('.form-section').forEach(f => f.classList.remove('active'));
        if(mode === 'aviso') { document.querySelectorAll('.tab-btn')[3].classList.add('active'); document.getElementById('formAviso').classList.add('active'); }
        else if (mode === 'img') { document.querySelectorAll('.tab-btn')[0].classList.add('active'); document.getElementById('formImg').classList.add('active'); document.getElementById('chartLayer').style.display = 'none'; document.getElementById('bgLayer').style.opacity = '1'; }
        else if (mode === 'video') { document.querySelectorAll('.tab-btn')[1].classList.add('active'); document.getElementById('formVideo').classList.add('active'); }
        else { document.querySelectorAll('.tab-btn')[2].classList.add('active'); document.getElementById('formChart').classList.add('active'); document.getElementById('chartLayer').style.display = 'block'; document.getElementById('bgLayer').style.opacity = '0.3'; renderChartPreview(); }
        // Não é mais necessário autoScalePreview com CSS puro
    }
    function setTema(tema) { document.getElementById('temaIA').value = tema; gerarIA(); }
    function gerarIA() {
        const btn = document.querySelector('.btn-ia'); const iconOriginal = btn.innerHTML; btn.innerHTML = '<i class="fas fa-spinner fa-spin"></i>'; 
        const tema = document.getElementById('temaIA').value; const formato = document.getElementById('selFormato').value;
        const formData = new FormData(); formData.append('gerar_ia', 'true'); formData.append('tema', tema); formData.append('formato', formato);
        fetch('ajax_ia.php', { method: 'POST', body: formData }).then(r => r.json()).then(data => {
            if(data.erro) { alert("Erro: " + (data.msg || "Desconhecido")); } else { document.getElementById('inpTitulo').value = data.titulo; document.getElementById('inpTexto').value = data.texto; document.getElementById('hiddenBgUrl').value = data.imagem; document.getElementById('bgLayer').style.backgroundImage = `url('${data.imagem}')`; updatePreview(); }
        }).catch(err => { console.error(err); alert("Erro de rede."); }).finally(() => { btn.innerHTML = iconOriginal; });
    }
    function resizePreview() { const fmt = document.getElementById('selFormato').value; document.getElementById('previewBox').className = (fmt === '16:9') ? 'fmt-16-9' : 'fmt-9-16'; }
    function updatePreview() { document.getElementById('prevTitulo').innerText = document.getElementById('inpTitulo').value; document.getElementById('prevTexto').innerText = document.getElementById('inpTexto').value; }
    function previewBg(input) { let r = new FileReader(); r.onload = (e) => { document.getElementById('bgLayer').style.backgroundImage = `url('${e.target.result}')`; }; if(input.files[0]) r.readAsDataURL(input.files[0]); }
    function renderChartPreview() { const ctx = document.getElementById('myChart').getContext('2d'); const labels = document.getElementsByName('grafico_labels')[0].value.split(','); const data = document.getElementsByName('grafico_dados')[0].value.split(','); if (chartInstance) chartInstance.destroy(); chartInstance = new Chart(ctx, { type: 'bar', data: { labels: labels, datasets: [{ label: document.getElementsByName('grafico_titulo')[0].value, data: data, backgroundColor: 'rgba(255, 204, 0, 0.9)', borderColor: '#ffcc00', borderWidth: 1 }] }, options: { responsive: true, maintainAspectRatio: false, plugins: { legend: { labels: { color: 'white' } } }, scales: { y: { ticks: { color: 'white' }, grid: { color: '#444' } }, x: { ticks: { color: 'white' }, grid: { display: false } } } } }); document.getElementById('prevTitulo').innerText = document.getElementsByName('titulo')[1].value; document.getElementById('prevTexto').innerText = document.getElementsByName('texto')[1].value; }
    function baixarPNG() { html2canvas(document.getElementById('previewBox'), { useCORS: true, scale: 2 }).then(c => { let l = document.createElement('a'); l.download = 'arte_academia.png'; l.href = c.toDataURL(); l.click(); }); }
    
    // SORTABLE COM ATRASO MOBILE
    var el = document.getElementById('listaPlaylist');
    Sortable.create(el, { 
        animation: 150, 
        ghostClass: 'active', 
        delay: 400, 
        delayOnTouchOnly: true, 
        touchStartThreshold: 5,
        onEnd: function (evt) { 
            var novaOrdem = []; 
            document.querySelectorAll('.play-item').forEach(function(item){ novaOrdem.push(item.getAttribute('data-id')); }); 
            var formData = new FormData(); 
            formData.append('acao', 'reordenar'); 
            formData.append('lista_ids', JSON.stringify(novaOrdem)); 
            fetch('admin.php', { method: 'POST', body: formData });
        } 
    });
</script>
</body>
</html>