<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Ofertas Farmácia (1-4-1)</title>
<link href="https://fonts.googleapis.com/css2?family=Roboto:wght@400;700;900&family=Montserrat:wght@700&display=swap" rel="stylesheet">
<style type="text/css">
    /* --- RESET & GERAL --- */
    * { margin: 0; padding: 0; box-sizing: border-box; }
    
    body, html {
        width: 100%; height: 100%;
        background-color: #f0f8ff; /* AliceBlue - Fundo muito leve e clean */
        font-family: 'Roboto', 'Arial', sans-serif;
        overflow: hidden;
    }

    /* --- TOPO --- */
    #topo {
        width: 100%; height: 15vh; 
        /* Gradiente Azul Farmácia (Estilo Drogasil/Raia) */
        background: linear-gradient(135deg, #0d47a1 0%, #1976d2 100%);
        border-bottom: 0.8vh solid #00bcd4; /* Linha Ciano/Verde Água */
        text-align: center;
        position: absolute; top: 0; left: 0; z-index: 100;
        box-shadow: 0 0.5vh 2vh rgba(0,0,0,0.2);
        display: flex; align-items: center; justify-content: center;
    }
    #topo h1 {
        font-family: 'Montserrat', sans-serif;
        font-weight: 700;
        font-size: 7vh; 
        color: #ffffff; 
        text-transform: uppercase; margin: 0;
        letter-spacing: 0.3vw;
        text-shadow: 0 0.2vh 0.5vh rgba(0,0,0,0.3);
    }
    
    /* Ícone de Cruz (Opcional, feito com CSS) */
    .cross-icon {
        color: #00bcd4; margin-right: 2vw; font-size: 6vh; font-weight: bold;
    }

    /* --- ÁREA PRINCIPAL --- */
    #main-container {
        position: absolute; top: 15vh; left: 0; width: 100%; height: 85vh;
        padding: 2vh 1.5vw;
        display: flex; 
        gap: 1.5vw;
    }

    .col-lateral { width: 25%; height: 100%; }
    
    /* Grid Central 2x2 */
    .col-central { 
        width: 50%; height: 100%; 
        display: grid;
        grid-template-columns: 1fr 1fr;
        grid-template-rows: 1fr 1fr;
        gap: 2vh;
    }

    /* --- CARD LATERAL (Destaque Maior) --- */
    .card-lateral {
        width: 100%; height: 100%;
        background: white;
        border-radius: 2vh;
        box-shadow: 0 1vh 3vh rgba(13, 71, 161, 0.15); /* Sombra azulada suave */
        border: 0.3vh solid #bbdefb; /* Borda azul bem clara */
        position: relative;
        display: flex; flex-direction: column; 
        justify-content: space-between; overflow: hidden;
        animation: fadeIn 0.8s ease;
    }
    
    .lat-tag {
        position: absolute; top: 0; right: 0; 
        background: #00bcd4; color: #fff; /* Ciano com texto branco */
        padding: 0.8vh 2vw; font-weight: 900; font-size: 2.2vh;
        border-bottom-left-radius: 2vh;
        z-index: 20; letter-spacing: 1px;
    }

    .lat-img {
        width: 100%; flex-grow: 1; 
        display: flex; align-items: center; justify-content: center;
        padding: 2vh; z-index: 10; min-height: 0;
        background: radial-gradient(circle, #fff 40%, #e3f2fd 100%); /* Aura azulada atrás do produto */
    }
    .lat-img img { 
        max-height: 90%; max-width: 90%; 
        object-fit: contain; filter: drop-shadow(0 2vh 2vh rgba(0,0,0,0.1));
    }
    
    .lat-info {
        width: 100%; height: 35%;
        background: #fff;
        border-top: 1px solid #e3f2fd;
        display: flex; flex-direction: column; justify-content: center; align-items: center;
        padding: 1vh;
    }

    .lat-nome {
        width: 100%; text-align: center; color: #0d47a1; /* Azul Escuro */
        font-weight: 700; font-size: 3vh; 
        line-height: 1.2; text-transform: uppercase;
        margin-bottom: 1vh;
        display: -webkit-box; -webkit-line-clamp: 2; -webkit-box-orient: vertical; overflow: hidden;
    }

    .lat-preco-box {
        display: flex; align-items: flex-start; justify-content: center; line-height: 1;
        color: #0d47a1;
    }
    
    .lat-rs { font-size: 3vh; font-weight: bold; margin-top: 1vh; margin-right: 0.5vw; color: #0288d1; }
    .lat-valor { font-family: 'Roboto', sans-serif; font-size: 8vh; font-weight: 900; letter-spacing: -2px; }
    .lat-un { font-size: 2vh; font-weight: 600; color: #78909c; align-self: flex-end; margin-bottom: 1.5vh; margin-left: 0.5vw;}


    /* --- CARD CENTRAL (Menor) --- */
    .card-central {
        width: 100%; height: 100%;
        background: white;
        border-radius: 2vh; 
        box-shadow: 0 0.5vh 1.5vh rgba(0,0,0,0.05);
        border: 1px solid #e1f5fe;
        display: flex; flex-direction: column; overflow: hidden;
        animation: fadeIn 0.8s ease;
    }

    .cen-img {
        width: 100%; height: 60%; 
        display: flex; align-items: center; justify-content: center;
        padding: 1vh;
    }
    .cen-img img { 
        max-height: 90%; max-width: 90%; 
        object-fit: contain;
    }

    .cen-info {
        width: 100%; height: 40%;
        padding: 0 1vh;
        display: flex; flex-direction: column; justify-content: center; align-items: center;
        background: #fbfdff; border-top: 1px solid #f0f0f0;
    }

    .cen-nome {
        width: 100%; text-align: center; color: #455a64; /* Cinza azulado */
        font-weight: 700; font-size: 2.2vh; 
        line-height: 1.1; text-transform: uppercase;
        margin-bottom: 0.5vh;
        white-space: nowrap; overflow: hidden; text-overflow: ellipsis;
    }

    .cen-preco-box {
        display: flex; align-items: center; justify-content: center;
        color: #0277bd; /* Azul Médio */
    }
    .cen-valor { font-family: 'Roboto', sans-serif; font-size: 5vh; font-weight: 900; letter-spacing: -1px; }
    .cen-rs { font-size: 2vh; font-weight: bold; margin-right: 0.3vw; vertical-align: top; }
    .cen-un { font-size: 1.5vh; color: #90a4ae; font-weight: 600; align-self: flex-end; margin-bottom: 1vh; margin-left: 0.3vw;}

    #status-dot { position: fixed; bottom: 5px; right: 5px; width: 12px; height: 12px; border-radius: 50%; background: #ccc; z-index: 9999; border: 2px solid white; transition: background 0.3s; }
    @keyframes fadeIn { from { opacity: 0; transform: translateY(2vh); } to { opacity: 1; transform: translateY(0); } }
</style>
</head>
<body>

    <div id="topo">
        <span class="cross-icon">+</span>
        <h1>Ofertas da Semana</h1>
    </div>

    <div id="main-container">
        <div class="col-lateral" id="col-esquerda"></div>
        <div class="col-central" id="col-centro"></div>
        <div class="col-lateral" id="col-direita"></div>
    </div>

    <div id="status-dot" title="Status Conexão"></div>

    <script type="text/javascript">
        var API_URL = 'https://mgaplay.com.br/ofertas/destaque-mercado.php'; 
        var placeholder = 'https://cdn-icons-png.flaticon.com/512/883/883407.png'; // Ícone genérico de remédio/produto
        
        var TEMPO_TROCA = 8000; 
        var ITENS_POR_PAGINA = 6;
        var TEMPO_ATUALIZACAO = 30000; 
        
        var listaGlobal = [];
        var indiceGlobal = 0;
        var loopAtivo = false;

        function setStatus(cor) { document.getElementById('status-dot').style.background = cor; }

        function formatarMoeda(valor) {
            if (!valor) return "0,00";
            let v = String(valor).replace(',', '.');
            let floatV = parseFloat(v);
            if (isNaN(floatV)) return valor; 
            return floatV.toFixed(2).replace('.', ',');
        }

        // --- Cache Offline ---
        function salvarCache(dados) { try { localStorage.setItem('mga_141_pharma', JSON.stringify(dados)); } catch (e) { } }
        function carregarCache() {
            try {
                var c = localStorage.getItem('mga_141_pharma');
                if (c) {
                    var d = JSON.parse(c);
                    if (d.length > 0) { listaGlobal = d; setStatus('#2196f3'); if(!loopAtivo) iniciarLoops(); return true; }
                }
            } catch (e) { }
            return false;
        }

        function buscarDados() {
            var urlParams = new URLSearchParams(window.location.search);
            var uid = urlParams.get('uid') || urlParams.get('loja') || 1;

            var xhr = new XMLHttpRequest();
            var url = API_URL + '?uid=' + uid + '&t=' + new Date().getTime();
            xhr.open("GET", url, true);
            xhr.timeout = 5000; 

            xhr.onreadystatechange = function() {
                if (xhr.readyState == 4) {
                    if (xhr.status == 200) {
                        try {
                            var dados = JSON.parse(xhr.responseText);
                            if (!Array.isArray(dados)) dados = [dados];
                            
                            if (dados.length > 0) {
                                listaGlobal = dados;
                                salvarCache(dados);
                                setStatus('#4caf50'); // Verde
                                if(!loopAtivo) iniciarLoops();
                            } else { if(listaGlobal.length === 0) carregarCache(); }
                        } catch (e) { if(listaGlobal.length === 0) carregarCache(); }
                    } else { 
                        setStatus('#f44336'); // Vermelho
                        if(listaGlobal.length === 0) carregarCache(); 
                    }
                }
            };
            xhr.send();
        }

        function getHtmlLateral(item) {
            if(!item) return '<div class="card-lateral" style="opacity:0"></div>';
            var img = (item.imagem && item.imagem.length > 5) ? item.imagem : placeholder;
            return `
            <div class="card-lateral">
                <div class="lat-tag">OFERTA</div>
                <div class="lat-img"><img src="${img}" onerror="this.src='${placeholder}'"></div>
                <div class="lat-info">
                    <div class="lat-nome">${item.produto}</div>
                    <div class="lat-preco-box">
                        <span class="lat-rs">R$</span>
                        <span class="lat-valor">${formatarMoeda(item.preco)}</span>
                        <span class="lat-un">/${item.unidade || 'un'}</span>
                    </div>
                </div>
            </div>`;
        }

        function getHtmlCentral(item) {
            if(!item) return '<div class="card-central" style="opacity:0"></div>';
            var img = (item.imagem && item.imagem.length > 5) ? item.imagem : placeholder;
            return `
            <div class="card-central">
                <div class="cen-img"><img src="${img}" onerror="this.src='${placeholder}'"></div>
                <div class="cen-info">
                    <div class="cen-nome">${item.produto}</div>
                    <div class="cen-preco-box">
                        <span class="cen-rs">R$</span>
                        <span class="cen-valor">${formatarMoeda(item.preco)}</span>
                        <span class="cen-un">/${item.unidade || 'un'}</span>
                    </div>
                </div>
            </div>`;
        }

        function renderizar() {
            var colEsq = document.getElementById('col-esquerda');
            var colCen = document.getElementById('col-centro');
            var colDir = document.getElementById('col-direita');
            
            if (!colEsq) return;

            colEsq.innerHTML = ''; colCen.innerHTML = ''; colDir.innerHTML = '';
            
            if (listaGlobal.length === 0) return;

            for (var i = 0; i < ITENS_POR_PAGINA; i++) {
                var index = (indiceGlobal + i) % listaGlobal.length;
                var item = listaGlobal[index];
                
                if (i === 0) colEsq.innerHTML = getHtmlLateral(item);
                else if (i >= 1 && i <= 4) colCen.innerHTML += getHtmlCentral(item);
                else if (i === 5) colDir.innerHTML = getHtmlLateral(item);
            }
            indiceGlobal += ITENS_POR_PAGINA;
        }

        function iniciarLoops() {
            loopAtivo = true;
            renderizar();
            setInterval(renderizar, TEMPO_TROCA);
        }

        window.onload = function() {
            carregarCache();
            buscarDados();
            setInterval(buscarDados, TEMPO_ATUALIZACAO);
        };
    </script>
</body>
</html>