/**
 * VIDEO LOADER UNIVERSAL
 * 
 * Carrega o player Vturb usando configurações do APP_CONFIG.
 * Usa a API oficial da VTurb para delay (displayHiddenElements).
 * 
 * Para trocar a VSL, edite apenas: app-config.js
 */
(function() {
    // Aguarda o DOM estar pronto
    function startLoader() {
        if ('requestIdleCallback' in window) {
            requestIdleCallback(initVideoLoader, { timeout: 2000 });
        } else {
            setTimeout(initVideoLoader, 100);
        }
    }
    
    if (document.readyState === 'loading') {
        document.addEventListener('DOMContentLoaded', startLoader);
    } else {
        startLoader();
    }

    function initVideoLoader() {
        var cfg = window.APP_CONFIG || {};
        var vturb = cfg.vturb || {};
        var delay = cfg.delay || {};
        var timer = cfg.timer || {};
        var checkout = cfg.checkout || {};

        var playerId = vturb.playerId || "";
        var accountId = vturb.accountId || "";
        var delayTime = delay.showProducts || 2190;
        var countdownTime = timer.countdown || 600;

        // Detecta qual página está
        var reportWrapper = document.getElementById("vsl-video-player-wrapper");
        var presellWrapper = document.getElementById("presell-video-wrapper");
        var wrapper = reportWrapper || presellWrapper;
        var pageType = reportWrapper ? "report" : (presellWrapper ? "presell" : null);
        var storagePrefix = pageType === "report" ? "burnslim_report" : "burnslim_presell";

        // Configura links de checkout e timer (report)
        if (pageType === "report") {
            setupCheckoutLinks(checkout);
            initTimer(storagePrefix, countdownTime);
        }

        // Se não tem player configurado, mostra conteudo após delay (fallback)
        if (!playerId || !accountId) {
            console.warn("[VideoLoader] APP_CONFIG.vturb não configurado");
            setTimeout(function() {
                showHiddenContent();
            }, delayTime * 1000);
            return;
        }

        if (!wrapper) return;

        // Insere o player no wrapper
        if (!document.getElementById("vid-" + playerId)) {
            var maxWidth = pageType === "presell" ? "600px" : "900px";
            wrapper.innerHTML = '<vturb-smartplayer id="vid-' + playerId + '" style="display: block; margin: 0 auto; width: 100%; max-width: ' + maxWidth + ';"></vturb-smartplayer>';
        }

        // Carrega o script do Vturb
        if (!document.getElementById("scr-" + playerId)) {
            var script = document.createElement("script");
            script.src = "https://scripts.converteai.net/" + accountId + "/players/" + playerId + "/v4/player.js";
            script.async = true;
            script.defer = true;
            script.id = "scr-" + playerId;
            (document.body || document.head).appendChild(script);
        }

        // Usa a API oficial da VTurb para delay
        var attempts = 0;
        var interval = setInterval(function() {
            var player = document.querySelector("vturb-smartplayer");
            if (player && player.addEventListener) {
                clearInterval(interval);
                
                player.addEventListener("player:ready", function() {
                    // API oficial da VTurb: displayHiddenElements
                    // persist: true = cache (quem já viu não espera de novo)
                    player.displayHiddenElements(delayTime, [".esconder"], {
                        persist: true
                    });
                });
            }
            
            attempts++;
            if (attempts >= 60) {
                clearInterval(interval);
                // Fallback: se player não carregar, mostra conteudo mesmo assim
                setTimeout(function() {
                    showHiddenContent();
                }, delayTime * 1000);
            }
        }, 500);
    }

    function showHiddenContent() {
        var elements = document.querySelectorAll(".esconder");
        elements.forEach(function(el) {
            el.style.display = "block";
            el.classList.remove("esconder");
        });
    }

    function setupCheckoutLinks(checkout) {
    // Apenas define os links base - o script de TID no HTML adiciona os parâmetros de tracking
    var kit1Links = document.querySelectorAll(".checkout-kit1, #checkout-kit1");
    var kit2Links = document.querySelectorAll(".checkout-kit2, #checkout-kit2");
    var kit3Links = document.querySelectorAll(".checkout-kit3, #checkout-kit3");
    
    kit1Links.forEach(function(link) { if (checkout.kit1) link.href = checkout.kit1; });
    kit2Links.forEach(function(link) { if (checkout.kit2) link.href = checkout.kit2; });
    kit3Links.forEach(function(link) { if (checkout.kit3) link.href = checkout.kit3; });
    }

    function initTimer(storagePrefix, countdown) {
        var timerEnd = localStorage.getItem(storagePrefix + "_timer_end");
        if (!timerEnd) {
            timerEnd = Date.now() + (countdown * 1000);
            localStorage.setItem(storagePrefix + "_timer_end", timerEnd.toString());
        } else {
            timerEnd = parseInt(timerEnd, 10);
        }

        var timerDisplay = document.getElementById("timer-display");
        
        var updateTimer = function() {
            var remaining = Math.max(0, Math.floor((timerEnd - Date.now()) / 1000));
            var minutes = Math.floor(remaining / 60).toString().padStart(2, "0");
            var seconds = (remaining % 60).toString().padStart(2, "0");
            
            if (timerDisplay) {
                timerDisplay.textContent = minutes + ":" + seconds;
            }
            return remaining;
        };

        updateTimer();
        setInterval(function() { updateTimer(); }, 1000);
    }
})();
