<!DOCTYPE html>
<html lang="pt-br">
<head>
    <meta charset="UTF-8">
    <title>TV Digital Pro</title>
    <meta http-equiv="refresh" content="3600">
    <link href="https://fonts.googleapis.com/css2?family=Bebas+Neue&family=Montserrat:wght@400;700;900&family=Orbitron:wght@700&family=Oswald:wght@700&family=Pacifico&family=Playfair+Display:wght@700&family=Poppins:wght@400;800&display=swap" rel="stylesheet">
    <style>
        body { margin: 0; overflow: hidden; background: radial-gradient(circle at center, #ffffff 0%, #dcdcdc 100%); cursor: none; font-family: 'Montserrat', sans-serif; }
        #app { width: 100vw; height: 100vh; display: flex; opacity: 0; transition: opacity 0.5s ease-in-out; background-size: cover; background-position: center; position: relative; }
        
        /* Layouts */
        .layout-landscape { flex-direction: row; }
        .layout-landscape .sidebar { width: 40%; height: 100%; }
        .layout-landscape .visual { width: 60%; height: 100%; }
        
        .layout-portrait { flex-direction: column-reverse; }
        .layout-portrait .sidebar { width: 100%; height: 45%; text-align: center; padding: 2vw; }
        .layout-portrait .visual { width: 100%; height: 55%; }

        .sidebar { z-index: 2; display: flex; flex-direction: column; justify-content: center; padding: 4vw; box-sizing: border-box; transition: 0.3s; }
        .visual { position: relative; overflow: hidden; width: 100%; height: 100%; }

        /* Estilos Padrão */
        .prod-title { line-height: 1; margin: 0 0 20px 0; text-shadow: 2px 2px 4px rgba(0,0,0,0.2); }
        .tag-oferta { display: inline-block; padding: 10px 30px; border-radius: 5px; font-weight: bold; margin-bottom: 20px; text-transform: uppercase; font-size: 1.5rem; }
        
        /* Preço Container */
        .price-container { display: inline-flex; align-items: baseline; justify-content: center; line-height: 1; }
        .currency { font-size: 0.4em; vertical-align: super; margin-right: 10px; font-weight: 400; opacity: 0.9; }
        .amount { font-size: 1em; font-weight: 900; letter-spacing: -2px; }
        .unit { font-size: 0.3em; margin-left: 10px; font-weight: 600; text-transform: uppercase; opacity: 0.8; }

        .img-produto { position: absolute; max-width: 85%; max-height: 85%; filter: drop-shadow(0 20px 40px rgba(0,0,0,0.4)); transition: 0.5s; opacity: 1; }
        .logo-area { position: absolute; display: flex; align-items: center; justify-content: center; z-index: 10; }
        .extra-text { position: absolute; font-weight: bold; white-space: nowrap; z-index: 5; text-shadow: 2px 2px 4px rgba(0,0,0,0.5); }
        .modo-multiply { mix-blend-mode: multiply; filter: contrast(1.1); }

        /* === TEMPLATES === */
        /* Clássico */
        .tpl-classico .sidebar { background: linear-gradient(135deg, #d32f2f 0%, #b71c1c 100%); color: white; clip-path: polygon(0 0, 100% 0, 90% 100%, 0% 100%); }
        .layout-portrait.tpl-classico .sidebar { clip-path: polygon(0 10%, 100% 0, 100% 100%, 0% 100%); }
        .tpl-classico .tag-oferta { background: #ffeb3b; color: #d32f2f; }
        .tpl-classico .prod-title { font-weight: 900; font-size: 5rem; text-transform: uppercase; }
        .tpl-classico .price-container { font-weight: 900; font-size: 7.5rem; background: rgba(0,0,0,0.2); padding: 10px 40px; border-radius: 20px; }

        /* Premium */
        .tpl-premium .sidebar { background: #111; color: #d4af37; border-right: 5px solid #d4af37; font-family: 'Playfair Display', serif; }
        .layout-portrait.tpl-premium .sidebar { border-right: none; border-top: 5px solid #d4af37; }
        .tpl-premium .tag-oferta { background: #d4af37; color: #000; letter-spacing: 5px; }
        .tpl-premium .prod-title { font-size: 5rem; font-style: italic; }
        .tpl-premium .price-container { font-size: 7.5rem; color: #fff; text-shadow: 0 0 20px #d4af37; }

        /* Fresh */
        .tpl-fresh .sidebar { background: linear-gradient(to bottom, #4caf50, #2e7d32); color: white; border-radius: 0 100px 100px 0; margin-right: -50px; }
        .layout-portrait.tpl-fresh .sidebar { border-radius: 80px 80px 0 0; margin-right: 0; margin-top: -50px; }
        .tpl-fresh .tag-oferta { background: white; color: #2e7d32; border-radius: 50px; }
        .tpl-fresh .prod-title { font-weight: 700; font-size: 5rem; }
        .tpl-fresh .price-container { font-weight: 800; font-size: 7.5rem; color: #a5d6a7; }

        /* Impacto */
        .tpl-impacto .sidebar { background: #ffeb3b; color: #d32f2f; font-family: 'Oswald', sans-serif; }
        .tpl-impacto .tag-oferta { background: #d32f2f; color: #fff; transform: skew(-10deg); }
        .tpl-impacto .prod-title { font-size: 6rem; line-height: 0.9; text-transform: uppercase; transform: skew(-5deg); }
        .tpl-impacto .price-container { font-size: 9rem; color: #000; font-weight: 900; letter-spacing: -5px; }

        /* Black Friday */
        .tpl-blackfriday .sidebar { background: #111; color: yellow; border-right: 10px solid yellow; font-family: 'Montserrat', sans-serif; }
        .layout-portrait.tpl-blackfriday .sidebar { border-right: none; border-top: 10px solid yellow; }
        .tpl-blackfriday .tag-oferta { background: red; color: white; font-weight:900; letter-spacing: 2px; transform: skew(-10deg); box-shadow: 5px 5px 0px rgba(255,255,255,0.2); }
        .tpl-blackfriday .prod-title { font-weight: 900; font-size: 5rem; text-transform: uppercase; color: white; }
        .tpl-blackfriday .price-container { font-family: 'Bebas Neue', sans-serif; font-size: 9rem; color: yellow; line-height: 0.9; text-shadow: 4px 4px 0px red; }

        /* Padaria */
        .tpl-padaria .sidebar { background: #5d4037; color: #fbe9e7; border-radius: 0 60px 60px 0; margin-right: -40px; font-family: 'Poppins', sans-serif; }
        .layout-portrait.tpl-padaria .sidebar { border-radius: 60px 60px 0 0; margin-right: 0; margin-top: -40px; }
        .tpl-padaria .tag-oferta { background: #d7ccc8; color: #3e2723; font-family: 'Pacifico', cursive; padding: 10px 40px; text-transform: none; font-size: 2rem; }
        .tpl-padaria .prod-title { font-weight: 600; font-size: 4.5rem; }
        .tpl-padaria .price-container { font-weight: 800; font-size: 7.5rem; background: #fff; color: #5d4037; padding: 5px 40px; border-radius: 50px; box-shadow: 0 10px 30px rgba(0,0,0,0.3); }

        /* Cyber */
        .tpl-cyber .sidebar { background: linear-gradient(180deg, #240b36 0%, #c31432 100%); color: white; border-right: 2px solid #00f2ff; font-family: 'Orbitron', sans-serif; }
        .layout-portrait.tpl-cyber .sidebar { border-right: none; border-top: 2px solid #00f2ff; }
        .tpl-cyber .tag-oferta { background: transparent; border: 2px solid #00f2ff; color: #00f2ff; box-shadow: 0 0 20px #00f2ff; text-shadow: 0 0 10px #00f2ff; }
        .tpl-cyber .prod-title { font-size: 4.5rem; text-transform: uppercase; letter-spacing: 2px; }
        .tpl-cyber .price-container { font-size: 7.5rem; color: #fff; text-shadow: 0 0 30px #c31432, 2px 2px 0px #00f2ff; }

        /* Açougue */
        .tpl-acougue .sidebar { background: radial-gradient(circle, #8a0000 0%, #300000 100%); color: white; border-right: 5px dashed rgba(255,255,255,0.3); font-family: 'Oswald', sans-serif; }
        .layout-portrait.tpl-acougue .sidebar { border-right: none; border-top: 5px dashed rgba(255,255,255,0.3); }
        .tpl-acougue .tag-oferta { background: #fff; color: #8a0000; }
        .tpl-acougue .prod-title { font-size: 6rem; text-transform: uppercase; }
        .tpl-acougue .price-container { font-size: 9rem; color: #ffca28; font-weight: 900; text-shadow: 3px 3px 15px rgba(0,0,0,0.8); }

        /* Varejo Azul */
        .tpl-varejo-azul .sidebar { background: #0277bd; color: white; font-family: 'Montserrat', sans-serif; }
        .tpl-varejo-azul .tag-oferta { background: #ffeb3b; color: #01579b; border-radius: 50px; padding: 10px 40px; box-shadow: 0 5px 0 #fbc02d; }
        .tpl-varejo-azul .prod-title { font-size: 5rem; font-weight: 800; text-transform: uppercase; }
        .tpl-varejo-azul .price-container { font-size: 7.5rem; font-weight: 900; background: yellow; color: #01579b; padding: 0 30px; transform: rotate(-3deg); box-shadow: 5px 5px 20px rgba(0,0,0,0.3); }

        /* Pharma */
        .tpl-pharma .sidebar { background: white; color: #333; border-right: 20px solid #26c6da; font-family: 'Poppins', sans-serif; }
        .layout-portrait.tpl-pharma .sidebar { border-right: none; border-top: 20px solid #26c6da; }
        .tpl-pharma .tag-oferta { background: #26c6da; color: white; border-radius: 5px; font-weight: 400; }
        .tpl-pharma .prod-title { font-size: 4.5rem; font-weight: 400; color: #555; }
        .tpl-pharma .price-container { font-size: 7.5rem; font-weight: 700; color: #0097a7; }

        /* Bebidas */
        .tpl-bebidas .sidebar { background: linear-gradient(45deg, #00c6ff, #0072ff); color: white; font-family: 'Bebas Neue', sans-serif; }
        .tpl-bebidas .tag-oferta { background: rgba(255,255,255,0.2); border: 2px solid white; backdrop-filter: blur(10px); letter-spacing: 2px; }
        .tpl-bebidas .prod-title { font-family: 'Montserrat', sans-serif; font-size: 5rem; font-weight: 900; text-transform: uppercase; font-style: italic; }
        .tpl-bebidas .price-container { font-size: 9rem; text-shadow: 0 5px 15px rgba(0,0,0,0.3); }

        /* Organic */
        .tpl-organic .sidebar { background: #8d6e63; color: white; font-family: 'Montserrat', sans-serif; }
        .tpl-organic .tag-oferta { background: #7cb342; color: white; border-radius: 50% 10% 50% 10%; padding: 15px 30px; }
        .tpl-organic .prod-title { font-size: 5rem; font-weight: 700; }
        .tpl-organic .price-container { font-size: 7.5rem; color: #c5e1a5; font-weight: 900; border-bottom: 5px solid #7cb342; }

        /* AJUSTE PARA MODO VERTICAL (PORTRAIT) */
        .layout-portrait .prod-title { font-size: 3.5rem !important; margin-bottom: 10px; }
        .layout-portrait .price-container { font-size: 6rem !important; }
        .layout-portrait .tag-oferta { font-size: 1.2rem !important; padding: 5px 20px; margin-bottom: 10px; }
        .layout-portrait .currency { font-size: 0.4em !important; }
        .layout-portrait .amount { font-size: 1em !important; }
        .layout-portrait .unit { font-size: 0.3em !important; }

    </style>
</head>
<body>
<div id="loading" style="color:#333; font-size:2em; display:flex; justify-content:center; align-items:center; height:100vh;">
    Carregando Ofertas...
</div>

<div id="app" style="display:none">
    <div id="sidebar" class="sidebar">
        <div class="tag-oferta">OFERTA ESPECIAL</div>
        <h1 class="prod-title" id="elProduto">Produto</h1>
        
        <div id="elPriceContainer" class="price-container">
            <span class="currency">R$</span>
            <span class="amount" id="elPreco">0,00</span>
            <span class="unit" id="elMedida"></span>
        </div>

        <div id="elValidade" style="font-size:1.5rem; margin-top:20px; opacity:0.8"></div>
    </div>
    <div class="visual">
        <div id="elLogo" class="logo-area" style="display:none"><img style="width:100%; height:100%; object-fit:contain"></div>
        <img id="elImg" class="img-produto">
        <div id="elExtra" class="extra-text" style="display:none"></div>
    </div>
</div>

<script>
    const CONFIG = { 
        tempoSlide: 10000, 
        modo: "<?php echo $_GET['modo'] ?? 'landscape'; ?>" 
    };
    
    const app = document.getElementById('app'); 
    let playlist = []; 
    let index = 0;
    let imagesCache = []; // Cache para evitar flicker

    // 1. CARREGA DADOS DO SERVIDOR
    async function atualizarPlaylist() {
        try {
            const r = await fetch(`api.php?modo=${CONFIG.modo}&t=${Date.now()}`);
            const d = await r.json();
            
            if(d.length > 0) { 
                // Se for a primeira vez, inicia o loop
                if(playlist.length === 0) {
                    playlist = d;
                    document.getElementById('loading').style.display='none'; 
                    app.style.display='flex';
                    iniciarLoop();
                } else {
                    // Se já está rodando, atualiza a lista silenciosamente
                    playlist = d;
                }
            } else {
                // Se não tem ofertas, tenta de novo em 10s
                setTimeout(atualizarPlaylist, 10000);
            }
        } catch(e) { 
            console.error("Erro conexão", e);
            setTimeout(atualizarPlaylist, 10000); 
        }
    }

    // 2. FUNÇÃO QUE RODA O VISUAL
    function iniciarLoop() {
        exibirOferta();
    }

    function exibirOferta() {
        // Se a lista estiver vazia, espera dados
        if(playlist.length === 0) return;

        // Reseta índice se chegar ao fim
        if(index >= playlist.length) index = 0;

        const item = playlist[index];
        
        // 1. Aplica Transição (Fade Out)
        app.style.opacity = 0;

        setTimeout(() => {
            // 2. Atualiza Dados (Enquanto está invisível)
            const tpl = item.template_style || 'classico';
            app.className = `layout-${CONFIG.modo} tpl-${tpl}`;

            document.getElementById('elProduto').innerText = item.produto;
            document.getElementById('elPreco').innerText = parseFloat(item.preco).toFixed(2).replace('.',',');
            
            const med = item.medida || '';
            const medDisplay = med ? (med.includes('/') ? med : '/'+med) : ''; 
            document.getElementById('elMedida').innerText = medDisplay;

            const img = document.getElementById('elImg');
            img.src = item.imagem_url;
            if(item.efeito_visual === 'multiply') img.classList.add('modo-multiply'); else img.classList.remove('modo-multiply');
            
            // Posição Imagem
            if(item.img_pos_x && item.img_pos_x !== 'center') { 
                img.style.left=item.img_pos_x; img.style.top=item.img_pos_y; img.style.transform='none'; 
            } else { 
                img.style.left='50%'; img.style.top='50%'; img.style.transform='translate(-50%, -50%)'; 
            }

            // Logo
            const logoDiv = document.getElementById('elLogo');
            if(item.logo_url) {
                logoDiv.querySelector('img').src = item.logo_url; logoDiv.style.display = 'flex';
                const size = (item.logo_tamanho || 100) * 1.5; logoDiv.style.width = size+'px'; logoDiv.style.height = size+'px';
                if(item.logo_pos_x && item.logo_pos_x !== 'default') { 
                    logoDiv.style.left=item.logo_pos_x; logoDiv.style.top=item.logo_pos_y; logoDiv.style.right='auto'; 
                } else { 
                    logoDiv.style.top='40px'; logoDiv.style.right='40px'; logoDiv.style.left=''; 
                }
            } else { logoDiv.style.display='none'; }

            // Texto Extra
            const extDiv = document.getElementById('elExtra');
            if(item.extra_texto) {
                extDiv.innerText = item.extra_texto; extDiv.style.color = item.extra_cor;
                // Escala texto proporcionalmente
                const scale = document.body.offsetWidth / 800; 
                extDiv.style.fontSize = (item.extra_tamanho * scale) + 'px';
                extDiv.style.display = 'block';
                if(item.extra_pos_x && item.extra_pos_x !== 'center') { 
                    extDiv.style.left=item.extra_pos_x; extDiv.style.top=item.extra_pos_y; 
                } else { 
                    extDiv.style.left='50%'; extDiv.style.top='80%'; extDiv.style.transform='translateX(-50%)'; 
                }
            } else { extDiv.style.display='none'; }

            // Fundo
            app.style.background = '';
            if(item.bg_tipo === 'cor') { app.style.background = item.bg_valor; }
            else if(item.bg_tipo === 'imagem') { app.style.background = `url('${item.bg_valor}') center/cover`; }

            // Validade
            const valDiv = document.getElementById('elValidade');
            if(item.data_validade && item.data_validade !== '0000-00-00') { 
                const d = item.data_validade.split('-'); valDiv.innerText=`Válido até ${d[2]}/${d[1]}`; 
            } else { valDiv.innerText=""; }

            // 3. Fade In (Aparece suavemente)
            app.style.opacity = 1;

            // 4. Preload da Próxima Imagem (Evita tela preta/branca na troca)
            precarregarProxima();

            // 5. Agenda próxima troca
            index++;
            setTimeout(exibirOferta, CONFIG.tempoSlide);

        }, 500); // 500ms é o tempo do fade-out no CSS
    }

    function precarregarProxima() {
        let next = index + 1;
        if(next >= playlist.length) next = 0;
        if(playlist[next] && playlist[next].imagem_url) {
            const img = new Image();
            img.src = playlist[next].imagem_url;
            // Opcional: precarregar também o fundo se for imagem
            if(playlist[next].bg_tipo === 'imagem') {
                const bg = new Image();
                bg.src = playlist[next].bg_valor;
            }
        }
    }

    // Inicializa: Carrega dados e configura atualização em background
    atualizarPlaylist();
    // Atualiza a lista do banco a cada 60 segundos sem parar a TV
    setInterval(atualizarPlaylist, 60000);

</script>
</body>
</html>