<?php require 'config.php'; ?>
<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>TV Player - Completo</title>
    <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@400;700;900&display=swap" rel="stylesheet">
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
    <style>
        body, html { margin: 0; background: #050510; font-family: 'Montserrat', sans-serif; overflow: hidden; height: 100vh; width: 100vw; }
        
        /* CAMADA 0: IMAGEM FUNDO */
        #bgLayer { 
            position: fixed; top: 0; left: 0; width: 100%; height: 100%; 
            background-size: cover; background-position: center center; background-repeat: no-repeat;
            transition: opacity 1s, transform 15s ease-in-out; transform: scale(1.0); z-index: 0;
        }
        .zoom-in { transform: scale(1.03) !important; }

        /* CAMADA 1: VÍDEO PLAYER */
        #videoLayer {
            position: fixed; top: 0; left: 0; width: 100%; height: 100%;
            object-fit: cover; z-index: 1; display: none; background: black;
        }

        /* CAMADA 2: DEGRADÊ E TEXTOS */
        .gradient { position: absolute; bottom: 0; width: 100%; height: 80%; background: linear-gradient(to top, rgba(0, 25, 80, 0.95) 0%, transparent 100%); z-index: 2; transition: opacity 0.5s; }
        
        #infoBox { position: absolute; bottom: 8%; left: 5%; width: 90%; color: white; z-index: 5; opacity: 0; transform: translateY(40px); transition: all 1s; }
        #infoBox.show { opacity: 1; transform: translateY(0); }
        
        h1 { font-size: 7vw; line-height: 0.9; color: #ffcc00; font-weight: 900; text-shadow: 5px 5px 0 rgba(0,0,0,0.6); margin: 0 0 1vh 0; }
        p { font-size: 3.5vw; font-weight: 800; text-shadow: 2px 2px 5px rgba(0,0,0,0.8); margin: 0; }
        
        /* --- TICKER / AVISOS (VOLTOU!) --- */
        #tickerContainer {
            position: absolute; top: 0; left: 0; width: 100%; height: 12vh;
            background: #c0392b; z-index: 100; display: flex; align-items: center; justify-content: center;
            box-shadow: 0 5px 20px rgba(0,0,0,0.5);
            transform: translateY(-100%); transition: transform 0.5s ease-in-out, background-color 1s ease;
        }
        #tickerContainer.ativo { transform: translateY(0); }
        
        #tickerText { 
            font-size: 8vh; font-weight: 900; color: #fff; text-transform: uppercase; 
            text-align: center; width: 90%; opacity: 0; transform: translateY(20px);
            transition: opacity 0.5s, transform 0.5s;
        }
        #tickerText.visivel { opacity: 1; transform: translateY(0); }

        /* ELEMENTOS AUXILIARES */
        #relogioBox { position: absolute; top: 40px; left: 40px; z-index: 20; transition: top 0.5s; }
        .relogio-down { top: 15vh !important; }
        
        #logo { position: absolute; top: 40px; right: 40px; width: 12vw; z-index: 10; transition: top 0.5s; }
        .logo-down { top: 15vh !important; }
        
        #hora { font-size: 5vw; font-weight: 900; color: #ffcc00; line-height: 0.9; }
        #data { font-size: 1.8vw; font-weight: 700; color: #fff; text-transform: uppercase; margin-left: 5px; }

        #chartWrapper { position: absolute; top: 50%; left: 50%; transform: translate(-50%, -60%); width: 80%; height: 60%; background: rgba(10, 20, 40, 0.95); border-radius: 20px; display: none; z-index: 4; }
        #chartWrapper.show { display: block; }

        .hide-overlay { opacity: 0 !important; }
    </style>
</head>
<body>

    <div id="tickerContainer">
        <div id="tickerText">...</div>
    </div>

    <video id="videoLayer" muted playsinline></video>

    <div id="relogioBox"><div id="hora">00:00</div><div id="data">---</div></div>
    <img id="logo" src="uploads/logo_padrao.png" onerror="this.style.display='none'">
    
    <div id="bgLayer"></div>
    <div class="gradient" id="gradiente"></div>
    <div id="chartWrapper"><canvas id="tvChart"></canvas></div>

    <div id="infoBox">
        <h1 id="tit"></h1>
        <p id="txt"></p>
    </div>

<script>
    // --- 1. RELÓGIO ---
    function atualizarRelogio() {
        const agora = new Date();
        document.getElementById('hora').innerText = String(agora.getHours()).padStart(2,'0') + ':' + String(agora.getMinutes()).padStart(2,'0');
        document.getElementById('data').innerText = agora.toLocaleDateString('pt-BR', {weekday:'short', day:'numeric', month:'short'}).replace('.','');
    }
    setInterval(atualizarRelogio, 1000); atualizarRelogio();

    // --- 2. AVISOS / TICKER (LÓGICA RESTAURADA) ---
    let listaGlobalAvisos = [];
    let indiceAviso = 0;
    let timerCiclo = null;

    function buscarAvisosNoServidor() {
        fetch('api_avisos.php').then(r => r.json()).then(lista => {
            if (JSON.stringify(lista) !== JSON.stringify(listaGlobalAvisos)) {
                listaGlobalAvisos = lista || [];
                if (!timerCiclo && listaGlobalAvisos.length > 0) {
                    rodarCicloAvisos();
                }
            }
        });
    }

    function rodarCicloAvisos() {
        const tkContainer = document.getElementById('tickerContainer');
        const tkText = document.getElementById('tickerText');

        if (listaGlobalAvisos.length === 0) {
            tkContainer.classList.remove('ativo');
            document.getElementById('relogioBox').classList.remove('relogio-down');
            document.getElementById('logo').classList.remove('logo-down');
            timerCiclo = null;
            return; 
        }

        tkContainer.classList.add('ativo');
        document.getElementById('relogioBox').classList.add('relogio-down');
        document.getElementById('logo').classList.add('logo-down');

        const aviso = listaGlobalAvisos[indiceAviso];
        tkText.classList.remove('visivel'); 

        setTimeout(() => {
            tkText.innerText = aviso.mensagem;
            tkContainer.style.backgroundColor = aviso.cor_fundo;
            tkText.classList.add('visivel'); 
        }, 500);

        indiceAviso++;
        if (indiceAviso >= listaGlobalAvisos.length) indiceAviso = 0;

        timerCiclo = setTimeout(rodarCicloAvisos, 8000); // 8 segundos por aviso
    }
    setInterval(buscarAvisosNoServidor, 10000);
    buscarAvisosNoServidor();


    // --- 3. PLAYER DE CONTEÚDO (VIDEO + IMG) ---
    const formato = "<?= $_GET['formato'] ?? '16:9' ?>";
    let playlist = [], index = 0, chartInstance = null;
    let timerSlide = null;

    async function loadPlaylist() {
        try { playlist = await (await fetch(`api_playlist.php?formato=${formato}`)).json(); } catch(e){}
    }
    
    function play() {
        if(!playlist.length) { loadPlaylist(); return setTimeout(play, 3000); }
        const item = playlist[index];
        
        const bg = document.getElementById('bgLayer');
        const vid = document.getElementById('videoLayer');
        const box = document.getElementById('infoBox');
        const chartDiv = document.getElementById('chartWrapper');
        const grad = document.getElementById('gradiente');

        // Reset
        box.classList.remove('show'); chartDiv.classList.remove('show'); bg.classList.remove('zoom-in');
        vid.style.display = 'none'; vid.pause(); grad.classList.remove('hide-overlay');

        setTimeout(() => {
            if (item.tipo_conteudo === 'video') {
                // VIDEO
                bg.style.display = 'none';
                vid.src = item.imagem_url;
                vid.style.display = 'block';
                
                if(item.titulo) {
                    document.getElementById('tit').innerText = item.titulo;
                    box.classList.add('show');
                } else {
                    grad.classList.add('hide-overlay'); 
                }
                
                vid.play().catch(e => console.log("Autoplay block", e));
                vid.onended = function() { proximoSlide(); };

            } else {
                // IMAGEM / GRÁFICO
                bg.style.display = 'block';
                document.getElementById('tit').innerText = item.titulo;
                document.getElementById('txt').innerText = item.texto_conteudo;

                if (item.tipo_conteudo === 'grafico') {
                    bg.style.backgroundImage = 'none'; bg.style.backgroundColor = '#050510';
                    chartDiv.classList.add('show'); renderChart(item.dados_grafico);
                } else {
                    bg.style.backgroundColor = 'transparent'; 
                    bg.style.backgroundImage = `url('${item.imagem_url}')`;
                }
                
                box.classList.add('show'); 
                setTimeout(()=>bg.classList.add('zoom-in'), 100);
                timerSlide = setTimeout(proximoSlide, 15000); // 15s para imagens
            }
        }, 500);
    }

    function proximoSlide() {
        index++;
        if(index >= playlist.length) { index = 0; loadPlaylist(); }
        play();
    }

    function renderChart(json) {
        if(!json) return;
        const d = JSON.parse(json);
        if(chartInstance) chartInstance.destroy();
        chartInstance = new Chart(document.getElementById('tvChart'), {
            type: 'bar',
            data: { labels: d.labels, datasets: [{ label: d.label, data: d.data, backgroundColor: '#ffcc00', borderColor: '#ffcc00' }] },
            options: { responsive:true, maintainAspectRatio:false, plugins: { legend: { labels: { color: 'white', font: { size: 24 } } } }, scales: { y: { ticks: { color: 'white', font:{size:18} } }, x: { ticks: { color: 'white', font:{size:18} } } } }
        });
    }

    loadPlaylist().then(() => play());
</script>
</body>
</html>