<?php

//<----------------------------------------------------------->
//<-------------------COPIA AI BRUXÃO------------------------->
//<-------------CONTATO: https://t.me/eonbry------------------>
//<-------------DEVELOPER: EMANUEL NASCIMENTO----------------->
//<----------------------------------------------------------->

?>


<!DOCTYPE html>
<html>
<head>
    <title>Slideshow de Anúncios</title>
    <style>
        body {
            margin: 0;
            padding: 0;
            overflow: hidden;
        }
        
        #slideshow-container {
            position: relative;
            width: 100vw;
            height: 100vh;
            overflow: hidden;
        }
        
        .slide {
            position: absolute;
            top: 0;
            left: 0;
            width: 100%;
            height: 100%;
            opacity: 0;
            transition: opacity 1s ease-in-out;
            object-fit: cover;
        }
        
        .slide.active {
            opacity: 1;
            z-index: 1;
        }
        
        .slide img, .slide video {
            width: 100%;
            height: 100%;
            object-fit: cover;
        }
        
        /* Loading discreto */
        .loading {
            position: absolute;
            top: 50%;
            left: 50%;
            transform: translate(-50%, -50%);
            color: white;
            font-family: Arial, sans-serif;
            z-index: 100;
            background: rgba(0, 0, 0, 0.7);
            padding: 15px 25px;
            border-radius: 10px;
            font-size: 14px;
        }
    </style>
</head>
<body>
    <div id="slideshow-container">
        <div id="slideshow"></div>
        <div class="loading" id="loading">Carregando anúncios...</div>
    </div>

<script>
    // Configurações
    const CONFIG = {
        checkInterval: 30000,  // Verificar a cada 30 segundos
        slideDuration: 5000,   // Trocar slide a cada 5 segundos
        apiUrl: '../api/ads.php',
        shuffleMode: 'smart',  // 'smart', 'random', ou 'sequential'
        avoidRepetition: true, // Evitar mostrar a mesma imagem seguida
        shuffleAfterCycles: 3   // Reembaralhar após X ciclos completos
    };

    // Estado
    let state = {
        currentUrls: [],
        slideIndex: 0,
        slides: [],
        slideInterval: null,
        checkInterval: null,
        isLoading: false,
        currentOrder: [],      // Ordem atual dos slides
        shownHistory: [],      // Histórico dos últimos mostrados
        cyclesCompleted: 0     // Contador de ciclos completos
    };

    // Elementos
    const slideshow = document.getElementById("slideshow");
    const loadingElement = document.getElementById("loading");

    // Iniciar
    document.addEventListener('DOMContentLoaded', init);

    async function init() {
        await loadSlides();
        startAutoCheck();
    }

    // Buscar URLs
    async function fetchAds() {
        try {
            const url = `${CONFIG.apiUrl}?t=${Date.now()}`;
            const response = await fetch(url);
            
            if (!response.ok) throw new Error(`HTTP ${response.status}`);
            
            const data = await response.json();
            return data.map(obj => obj.AdUrl).filter(url => url && url.trim() !== '');
            
        } catch (error) {
            console.warn('Erro ao buscar anúncios:', error);
            return [];
        }
    }

    // Comparar se mudou
    function hasChanges(newUrls) {
        if (state.currentUrls.length !== newUrls.length) return true;
        
        for (let i = 0; i < newUrls.length; i++) {
            if (state.currentUrls[i] !== newUrls[i]) return true;
        }
        
        return false;
    }

    // Embaralhar array (Fisher-Yates)
    function shuffleArray(array) {
        const shuffled = [...array];
        for (let i = shuffled.length - 1; i > 0; i--) {
            const j = Math.floor(Math.random() * (i + 1));
            [shuffled[i], shuffled[j]] = [shuffled[j], shuffled[i]];
        }
        return shuffled;
    }

    // Gerar ordem inteligente dos slides
    function generateSmartOrder(urls) {
        if (urls.length <= 1) return urls;
        
        let order;
        
        switch(CONFIG.shuffleMode) {
            case 'random':
                // Totalmente aleatório
                order = shuffleArray(urls);
                break;
                
            case 'smart':
                // Embaralha, mas evita repetição do último
                order = shuffleArray(urls);
                
                if (CONFIG.avoidRepetition && state.shownHistory.length > 0) {
                    const lastShown = state.shownHistory[state.shownHistory.length - 1];
                    const lastIndex = order.indexOf(lastShown);
                    
                    // Se o último slide está no início, movê-lo para trás
                    if (lastIndex >= 0 && lastIndex < Math.floor(order.length / 2)) {
                        const [moved] = order.splice(lastIndex, 1);
                        order.push(moved);
                    }
                }
                break;
                
            default:
                // Sequencial (original)
                order = urls;
        }
        
        console.log('Nova ordem gerada:', order.map((_, i) => i));
        return order;
    }

    // Carregar/atualizar slides
    async function loadSlides(initialLoad = true) {
        if (state.isLoading) return;
        
        state.isLoading = true;
        
        try {
            const newUrls = await fetchAds();
            
            // Primeira carga sem anúncios
            if (initialLoad && newUrls.length === 0) {
                loadingElement.textContent = 'Nenhum anúncio disponível';
                state.isLoading = false;
                return;
            }
            
            // Verificar se há mudanças
            if (!initialLoad && !hasChanges(newUrls)) {
                state.isLoading = false;
                return;
            }
            
            // Atualizar estado
            state.currentUrls = newUrls;
            
            // Gerar nova ordem (embaralhar)
            state.currentOrder = generateSmartOrder(newUrls);
            state.shownHistory = [];
            state.cyclesCompleted = 0;
            
            // Esconder loading na primeira carga
            if (initialLoad) {
                loadingElement.style.display = 'none';
            }
            
            // Limpar slides antigos
            clearInterval(state.slideInterval);
            slideshow.innerHTML = '';
            state.slides = [];
            state.slideIndex = 0;
            
            // Criar slides na NOVA ORDEM
            state.currentOrder.forEach((url, index) => {
                createSlide(url, index);
            });
            
            // Iniciar slideshow
            if (state.slides.length > 0) {
                if (state.slides.length === 1) {
                    showSlide(0);
                } else {
                    showSlide(0);
                    startSlideCycle();
                }
            }
            
            console.log(`Slides carregados: ${newUrls.length} | Ordem: ${state.currentOrder.map((_, i) => i)}`);
            
        } catch (error) {
            console.error('Erro ao atualizar slides:', error);
        }
        
        state.isLoading = false;
    }

    // Criar slide
    function createSlide(url, index) {
        const slide = document.createElement("div");
        slide.className = "slide";
        slide.dataset.index = index;
        slide.dataset.originalUrl = url;
        
        const isVideo = /\.(mp4|webm|ogg|mov)$/i.test(url);
        let mediaElement;
        
        if (isVideo) {
            mediaElement = document.createElement("video");
            mediaElement.src = url;
            mediaElement.autoplay = false;
            mediaElement.controls = false;
            mediaElement.muted = true;
            mediaElement.loop = false;
            mediaElement.preload = "auto";
            mediaElement.addEventListener('ended', () => {
                setTimeout(nextSlide, 1000);
            });
        } else {
            mediaElement = document.createElement("img");
            mediaElement.src = url;
            mediaElement.alt = `Anúncio ${index + 1}`;
        }
        
        mediaElement.onerror = () => {
            console.warn('Erro ao carregar:', url);
            if (!isVideo) {
                mediaElement.src = `https://picsum.photos/1920/1080?random=${index}`;
            }
        };
        
        slide.appendChild(mediaElement);
        slideshow.appendChild(slide);
        state.slides.push(slide);
    }

    // Mostrar slide
    function showSlide(index) {
        if (state.slides.length === 0) return;
        
        // Ajustar índice (circular)
        if (index < 0) index = state.slides.length - 1;
        if (index >= state.slides.length) index = 0;
        
        // Registrar no histórico
        const currentUrl = state.slides[index].dataset.originalUrl;
        state.shownHistory.push(currentUrl);
        
        // Manter histórico limitado
        if (state.shownHistory.length > 10) {
            state.shownHistory.shift();
        }
        
        // Verificar se completou um ciclo
        if (index === 0 && state.slideIndex === state.slides.length - 1) {
            state.cyclesCompleted++;
            
            // Reembaralhar após X ciclos completos
            if (CONFIG.shuffleAfterCycles > 0 && 
                state.cyclesCompleted >= CONFIG.shuffleAfterCycles) {
                reshuffleSlides();
            }
        }
        
        // Remover active de todos
        state.slides.forEach(slide => {
            slide.classList.remove('active');
            const video = slide.querySelector('video');
            if (video) video.pause();
        });
        
        // Ativar atual
        const currentSlide = state.slides[index];
        currentSlide.classList.add('active');
        
        // Tocar vídeo se houver
        const video = currentSlide.querySelector('video');
        if (video) {
            video.currentTime = 0;
            video.play().catch(e => null);
        }
        
        state.slideIndex = index;
    }

    // Próximo slide com lógica anti-repetição
    function nextSlide() {
        if (state.slides.length <= 1) return;
        
        let nextIndex = state.slideIndex + 1;
        
        // Se for o último slide, voltar ao início
        if (nextIndex >= state.slides.length) {
            nextIndex = 0;
        }
        
        showSlide(nextIndex);
    }

    // Reembaralhar slides em tempo real
    function reshuffleSlides() {
        if (state.currentUrls.length <= 1) return;
        
        console.log('Reembaralhando slides...');
        
        // Guardar o slide atual
        const currentSlide = state.slides[state.slideIndex];
        const currentUrl = currentSlide?.dataset.originalUrl;
        
        // Gerar nova ordem
        state.currentOrder = generateSmartOrder(state.currentUrls);
        
        // Reordenar slides no DOM
        slideshow.innerHTML = '';
        state.slides = [];
        
        state.currentOrder.forEach((url, index) => {
            createSlide(url, index);
        });
        
        // Encontrar novo índice do slide atual (se ainda existir)
        let newIndex = state.currentOrder.indexOf(currentUrl);
        if (newIndex === -1) newIndex = 0;
        
        state.slideIndex = newIndex;
        state.cyclesCompleted = 0;
        
        // Mostrar slide
        showSlide(newIndex);
        
        console.log('Reembaralhado! Nova ordem:', state.currentOrder.map((_, i) => i));
    }

    // Ciclo automático
    function startSlideCycle() {
        if (state.slides.length <= 1) return;
        
        clearInterval(state.slideInterval);
        
        state.slideInterval = setInterval(() => {
            const currentSlide = state.slides[state.slideIndex];
            const currentVideo = currentSlide.querySelector('video');
            
            // Se for vídeo e não terminou, esperar
            if (currentVideo && !currentVideo.ended) {
                return;
            }
            
            nextSlide();
        }, CONFIG.slideDuration);
    }

    // Verificação automática em background
    function startAutoCheck() {
        state.checkInterval = setInterval(() => {
            loadSlides(false);
        }, CONFIG.checkInterval);
    }

    // Pausar quando aba não estiver visível
    document.addEventListener('visibilitychange', () => {
        if (document.hidden) {
            clearInterval(state.slideInterval);
            clearInterval(state.checkInterval);
            
            const currentVideo = document.querySelector('.slide.active video');
            if (currentVideo) currentVideo.pause();
            
        } else {
            startSlideCycle();
            startAutoCheck();
            
            const currentVideo = document.querySelector('.slide.active video');
            if (currentVideo && !currentVideo.ended) {
                currentVideo.play();
            }
            
            setTimeout(() => loadSlides(false), 1000);
        }
    });

    // Debug: comandos úteis
    window.debugSlides = {
        reload: () => loadSlides(false),
        next: nextSlide,
        reshuffle: reshuffleSlides,
        showState: () => console.log('Estado:', {
            totalSlides: state.slides.length,
            currentOrder: state.currentOrder.map((_, i) => i),
            currentIndex: state.slideIndex,
            shownHistory: state.shownHistory.length,
            cyclesCompleted: state.cyclesCompleted
        }),
        setShuffleMode: (mode) => {
            if (['smart', 'random', 'sequential'].includes(mode)) {
                CONFIG.shuffleMode = mode;
                console.log(`Modo alterado para: ${mode}`);
                reshuffleSlides();
            }
        }
    };
</script>

</body>
</html>