/// #upload

 



var statusPaused = false;

var fullscreenLocked = false;

var videoContainer = document.getElementById('video-container');

var timeout;

var password;

var currentTime;

var logado;

var syncStartTime;

let videoList = [];

var isExpanded = false;

var messageInput = document.getElementById('msgInput'); // Variável global ainda existe, mas será rechecada localmente

var last = 0; 

var voiceInterval = 3 * 60 * 1000; 



var listaDeEmojis = [

  "😂","🤣","😆","😄","😅","😊","😁","😃","🙂","😌",



  "😱","😨","😰","😧","😦","😮","😯","😳","😵","🤯",



  "😭","😢","🥺","😿","😥","😓","😣","😫","😩","🥲",



  "😍","🥰","😘","😚","😙","😻","🤤","😳","☺️","🤗",



  "😡","🤬","😤","😠","😒","🙄","😑","😐","🤨","😕",



  "🤡","😈","😏","😎","🤩","😜","🤪","😝","😛","🤭",



  "😟","😔","😞","😖","😢","🥹","😬","😶","😶‍🌫️","🫠",



  "😴","🥱","😪","🤤","😕","🫥","🫣","😯","🫨","😲",



  "🤔","🧐","🤨","🤔","😑","😒","😬","🤥","😳","🤫",



  "😇","🤓","😎","🤠","😌","🤔","😤","🤧","😷","🤒"

];



var emojisPorPagina = 4;

var paginaAtual = 0;



function carregarEmojis() {

  var container = document.getElementById("emojiContainer");

  container.innerHTML = "";



  var inicio = paginaAtual * emojisPorPagina;

  var fim = inicio + emojisPorPagina;

  var emojisPagina = listaDeEmojis.slice(inicio, fim);



  /* Adiciona os emojis */

  for (var i = 0; i < emojisPagina.length; i++) {

    var botao = document.createElement("button");

    botao.className = "emoji-button";

    botao.textContent = emojisPagina[i];



    botao.onclick = (function(e) {

  return function(event) {

    event.stopPropagation();

    sendEmojiMessage(e);

    toggleUIElements(false); // 🔥 oculta tudo igual emoji padrão

  };

})(emojisPagina[i]);



    container.appendChild(botao);

  }



  /* BOTÃO ANTERIOR */

  if (paginaAtual > 0) {

    var btnAnterior = document.createElement("button");

    btnAnterior.className = "emoji-seta";

    btnAnterior.textContent = "←";

    btnAnterior.onclick = function() {

      paginaAtual--;

      carregarEmojis();

    };

    container.appendChild(btnAnterior);

  }



  /* BOTÃO PRÓXIMO */

  if (fim < listaDeEmojis.length) {

    var btnProximo = document.createElement("button");

    btnProximo.className = "emoji-seta";

    btnProximo.textContent = "→";

    btnProximo.onclick = function() {

      paginaAtual++;

      carregarEmojis();

    };

    container.appendChild(btnProximo);

  }

}



/* Carrega tudo ao entrar */

carregarEmojis();



var videoSources = [];

var currentPlay = 0;



/* Carrega os links do TXT */




    player.one('loadedmetadata', function () {

        if (tempoAtual > 0) player.currentTime(tempoAtual);

        if (!statusPaused) player.play();

    });

}



// --- Variável de controle do Overlay ---

var showOverlay = true; 



// Variável Global para Usuários

let usuariosOnline = []; 



var socket = io.connect('https://kimzin.space', {

    path: "/socket.io/",

    transports: ["websocket"]

});



// --- LÓGICA DE USUÁRIO ---

let username = localStorage.getItem("username");



if (!username || username.trim() === "") {

    username = prompt("Qual é o seu nome? (Obrigatório)");

    if (username && username.trim() !== "") {

        username = username.trim();

        localStorage.setItem("username", username);

        if (socket.connected) {

            socket.emit('set_username', { username: username, silencioso: false });

        }

    }

}



// --- CONFIGURAÇÃO DO BOTÃO DE OVERLAY (Ligar/Desligar msg) ---

function setupOverlayButton() {

    const container = document.getElementById('video-container');

    if (!container) return;



    if (document.getElementById('toggleOverlayBtn')) return;



    const btn = document.createElement('button');

    btn.id = 'toggleOverlayBtn';

    btn.textContent = '👁️ Msg Tela: ON';

    

    Object.assign(btn.style, {

        position: 'absolute',

        top: '20px',          

        right: '20px',        

        zIndex: '2147483647', 

        padding: '5px 10px',

        backgroundColor: 'rgba(0, 255, 0, 0.3)', 

        color: 'white',

        border: '1px solid #00ff00',

        borderRadius: '5px',

        cursor: 'pointer',

        fontSize: '12px',

        fontWeight: 'bold',

        display: 'none' 

    });



    btn.onclick = function(e) {

        e.stopPropagation(); 

        showOverlay = !showOverlay; 

        if (showOverlay) {

            btn.textContent = '👁️ Msg Tela: ON';

            btn.style.backgroundColor = 'rgba(0, 255, 0, 0.3)';

            btn.style.border = '1px solid #00ff00';

        } else {

            btn.textContent = '🚫 Msg Tela: OFF';

            btn.style.backgroundColor = 'rgba(255, 0, 0, 0.3)';

            btn.style.border = '1px solid #ff0000';

        }

    };



    container.appendChild(btn);

}



// --- CONFIGURAÇÃO DO BOTÃO DE DIGITAR (GLOBAL) ---

function setupChatButton() {

    const container = document.getElementById('video-container');

    if (!container) return;



    // 1. Cria o Input Flutuante

    if (!document.getElementById('fs-msg-input')) {

        const fsInput = document.createElement('input');

        fsInput.id = 'fs-msg-input';

        fsInput.type = 'text';

        fsInput.placeholder = 'Digitando...'; 

        

        Object.assign(fsInput.style, {

            position: 'absolute',

            bottom: '50%', 

            left: '50%',

            transform: 'translate(-50%, 50%)',

            width: '80%',

            padding: '15px',

            fontSize: '18px',

            borderRadius: '10px',

            border: '2px solid #00ff00',

            backgroundColor: 'rgba(0, 0, 0, 0.8)',

            color: '#fff',

            zIndex: '2147483647',

            display: 'none', 

            outline: 'none',

            boxShadow: '0 0 20px rgba(0,0,0,0.8)',

            textAlign: 'center'

        });



        fsInput.addEventListener('keydown', function(e) {

            if (e.key === 'Enter') {

                e.preventDefault();

                enviar(); 

            }

        });



        fsInput.addEventListener('blur', function() {

             setTimeout(() => { 

                 if(fsInput.value === '') fsInput.style.display = 'none'; 

             }, 200);

        });



        container.appendChild(fsInput);

    }



    // 2. Cria o Botão "💬 Digitar"

    if (!document.getElementById('fs-chat-btn')) {

        const chatBtn = document.createElement('button');

        chatBtn.id = 'fs-chat-btn';

        chatBtn.innerHTML = '💬 Digitar';

        

        Object.assign(chatBtn.style, {

            position: 'absolute',

            top: '20px',

            left: '20px', 

            padding: '10px 20px',

            borderRadius: '5px',

            border: 'none',

            backgroundColor: 'rgba(255, 255, 255, 0.2)',

            color: 'white',

            fontWeight: 'bold',

            zIndex: '2147483646',

            display: 'none',

            cursor: 'pointer',

            fontSize: '16px'

        });



        chatBtn.addEventListener('click', function(e) {

            e.stopPropagation(); 

            if (document.fullscreenElement) {

                const fsInput = document.getElementById('fs-msg-input');

                if (fsInput) {

                    fsInput.style.display = 'block';

                    fsInput.focus();

                }

            } else {

                const normalInput = document.getElementById('msgInput');

                if (normalInput) {

                    normalInput.focus();

                    normalInput.scrollIntoView({ behavior: "smooth" });

                }

            }

        });



        container.appendChild(chatBtn);

    }

}









// --- INTERFACE ---

document.getElementById('toggleChat').addEventListener('click', function(event) {

    event.stopPropagation();

    var smallChat = document.getElementById('smallChat');

    var isHidden = smallChat.style.display === 'none' || smallChat.style.display === '';

    if (isHidden) { smallChat.style.display = 'block'; toggleUIElements(false); } 

    else { smallChat.style.display = 'none'; toggleUIElements(true); }

});



function updateSmallChat() {

    const smallChat = document.getElementById('smallChat');

    const messages = document.getElementById('messages').children;

    smallChat.innerHTML = '';

    const startIndex = Math.max(0, messages.length - 4);

    for (let i = startIndex; i < messages.length; i++) {

        smallChat.appendChild(messages[i].cloneNode(true));

    }

}



var observer = new MutationObserver(function(mutations) {

    mutations.forEach(function(mutation) { if (mutation.type === 'childList') updateSmallChat(); });

});

observer.observe(document.getElementById('messages'), { childList: true });



var player = videojs('videoPlayer');

player.controls(false);



async function requestWakeLock() {

  try {

    wakeLock = await navigator.wakeLock.request('screen');

    wakeLock.addEventListener('release', () => requestWakeLock());

  } catch (err) { console.error('Erro Wake Lock:', err); }

}



function displaySystemMessage(message) {

    var messagesContainer = document.getElementById('messages');

    var newMessage = document.createElement('div');

    newMessage.className = 'message system-message';

    newMessage.innerHTML = `<p><i>[SISTEMA]</i>: <strong>${message}</strong></p>`;

    messagesContainer.insertBefore(newMessage, messagesContainer.firstChild);

    while (messagesContainer.childElementCount > 4) messagesContainer.lastElementChild.remove();

}



player.on('loadeddata', function() {

    displaySystemMessage("O vídeo está pronto para ser reproduzido!");

});



window.onload = function() {

    const savedLogin = localStorage.getItem('logado');

    const savedPassword = localStorage.getItem('senha');

    setupChatButton(); 

    setupOverlayButton();  

    if (savedLogin === 'true' && savedPassword) {

        logado = true;

        password = savedPassword;

    }

};



requestWakeLock();



function enviar() {

    var fsInput = document.getElementById('fs-msg-input');

    var messageInput = document.getElementById('msgInput');

    

    var textoParaEnviar = "";

    

    if (fsInput && fsInput.value.trim() !== "") {

        textoParaEnviar = fsInput.value.trim();

        fsInput.value = ""; 

        fsInput.style.display = 'none'; 

        fsInput.blur();

    } 

    else if (messageInput && messageInput.value.trim() !== "") {

        textoParaEnviar = messageInput.value.trim();

        messageInput.value = "";

    }



    var message = textoParaEnviar;

    var lowerMessage = message.toLowerCase();



    const comandosRapidos = {

        '/p': '/pausar', '/d': '/despausar', '/l': '/lista',

        '/c': '/control', '/s': '/sync', '/ps': '/playsync', '/v': '/vídeo'

    };

    if (comandosRapidos[lowerMessage]) {

        lowerMessage = comandosRapidos[lowerMessage];

        message = comandosRapidos[lowerMessage];

    }



    if (message !== '') {

        if (lowerMessage.startsWith('/adm ')) {

            var senha = message.substring(5).trim();

            if (senha) { socket.emit('authenticate_password', { password: senha }); password = senha; }

            return;

        }

        if (lowerMessage.startsWith('/emotes ')) { mudarEmojis(message.substring(8).trim().split(/\s+/)); return; }

        if (lowerMessage === '/pausar' && logado) { socket.emit('pause_video', password); return; }

        if (lowerMessage === '/despausar' && logado) { socket.emit('resume_video', password); return; }

        if (lowerMessage === '/control' && logado) { unlockVideoControls(); return; }

        if (lowerMessage === '/lista' && logado) { socket.emit('pedir_lista'); return; }

        if (lowerMessage.startsWith('/escolher ') && logado) {

            const numero = parseInt(message.substring(9).trim()) - 1;

            if (videoList[numero]) socket.emit('change_video', `https://kimzin.space/rave/${videoList[numero].directory}/${videoList[numero].filename}`, password);

            return;

        }

        if (lowerMessage === '/sync' && logado) { syncTime(); return; }

        if (lowerMessage === '/playsync' && logado) { socket.emit('resume_video', password); syncTime(); return; }

        if (lowerMessage.startsWith('/vídeo ') && logado) { socket.emit('change_video', message.substring(7).trim(), password); return; }



        if (username !== null) {

            socket.emit('message', { 'user': username, 'message': message });

        } else {

            alert('Defina um nome de usuário.');

        }

    }

}



function mudarEmojis(novosEmojis) {

    const container = document.getElementById('emojiContainer');

    container.innerHTML = '';

    novosEmojis.forEach(emoji => {

        const botao = document.createElement('button');

        botao.className = 'emoji-button';

        botao.textContent = emoji;

        container.appendChild(botao);

    });

    ativarEmojiListeners();

}



function syncTime() {

    if (logado) {

        var player = videojs('videoPlayer');

        socket.emit('sync_time', { currentTime: player.currentTime(), totalTime: player.duration() }, password);

        if (player.paused()) player.play();

    } else {

        alert('Acesse o menu personalizado para sincronizar.');

    }

}



function updatePlayerTime() {

    try {

        if (currentTime > 0) {

            let elapsedTime = (Date.now() - syncStartTime) / 1000;

            let newTime = currentTime + elapsedTime;

            var player = videojs('videoPlayer');

            if (Math.abs(newTime - player.currentTime()) > 2) socket.emit('toggle_fullscreen');

        }

    } catch (e) {}

}



socket.on('authentication_result', function(result) {

    logado = result?.success === true;

    if (logado) {

        alert('Autenticado com sucesso!');

        localStorage.setItem('logado', 'true');

        localStorage.setItem('senha', password);

    }

});



socket.on('video_resumed', function() { player.play(); statusPaused = false; });

socket.on('video_paused_status', function(paused) {

    const btn = document.getElementById("pauseBtn");

    if (paused) {

        statusPaused = true; player.pause();

        if(btn) { btn.textContent = "Despausar"; btn.setAttribute("onclick", "comando('/despausar')"); }

    } else {

        statusPaused = false;

        if(btn) { btn.textContent = "Pausar"; btn.setAttribute("onclick", "comando('/pausar')"); }

    }

});



socket.on('connect', function() {

    socket.emit('check_video_paused');

    socket.emit('toggle_fullscreen');

    let currentUser = localStorage.getItem("username");

    if (currentUser && currentUser.trim() !== "") {

        socket.emit('set_username', { username: currentUser.trim(), silencioso: false });

    }

    player.ready(function() {

        if (document.fullscreenElement === videoContainer && !statusPaused) player.play();

    });

});



socket.on('message', function (data) {

    var messagesContainer = document.getElementById('messages');

    var newMessage = document.createElement('div');

    newMessage.className = 'message';

    if (data.profileImageUrl) {

        var profileImage = document.createElement('img');

        profileImage.src = data.profileImageUrl;

        Object.assign(profileImage.style, { maxWidth: '70px', maxHeight: '70px', marginRight: '10px' });

        profileImage.addEventListener('click', function () {

            document.getElementById('modalImage').src = data.profileImageUrl;

            document.getElementById('imageModal').style.display = 'flex';

        });

        newMessage.appendChild(profileImage);

    }

    var messageText = document.createElement('p');

    messageText.innerHTML = `<strong>${data.user}:</strong> ${data.message}`;

    newMessage.appendChild(messageText);

    messagesContainer.insertBefore(newMessage, messagesContainer.firstChild);

    while (messagesContainer.childElementCount > 4) messagesContainer.lastElementChild.remove();

    

    var messageOverlay = document.getElementById('message-overlay');

    if (messageOverlay && showOverlay && !data.message.includes("resgatou uma mensagem de voz")) {

        messageOverlay.textContent = `${data.user}: ${data.message}`;

        messageOverlay.style.display = 'block';

        setTimeout(() => messageOverlay.style.display = 'none', 3000);

    }

});



socket.on('video', function (videoLink) {  

    var player = videojs('videoPlayer');  

    if (player.currentSrc() !== videoLink) {

        player.src({ src: videoLink, type: 'video/mp4' });  

        player.addRemoteTextTrack({ src: '9.vtt', kind: 'subtitles', srclang: 'pt', label: 'Português', default: true }, false);  

    }

});



function toggleFullScreen() {

    if (!username) { alert("Defina um nome de usuário."); return; }

    if (statusPaused) { alert("Vídeo pausado."); return; }

    if (fullscreenLocked) { alert("Bloqueado pelo ADM."); return; }

    if (!document.fullscreenElement) {

        player.play(); updatePlayerTime(); videoContainer.requestFullscreen();

    } else if (document.exitFullscreen) { document.exitFullscreen(); }

}



socket.on('sync_time', function (receivedTime) {

    currentTime = receivedTime;

    syncStartTime = Date.now();

    videojs('videoPlayer').currentTime(currentTime);

});



socket.on('usuarios_online', (lista) => {

    usuariosOnline = lista; 

    const ul = document.getElementById('usuarios-online');

    if (ul && ul.style.display === 'block') renderizarLista();

});



function toggleUsuarios() {

    const ul = document.getElementById('usuarios-online');

    if (ul.style.display === 'block') { ul.style.display = 'none'; } 

    else { renderizarLista(); ul.style.display = 'block'; }

}



function renderizarLista() {

    const ul = document.getElementById('usuarios-online');

    ul.innerHTML = ''; 

    const validos = usuariosOnline.filter(u => u && u.trim() !== "" && u !== "Usuario Sem Username");

    if (validos.length === 0) { ul.innerHTML = '<li style="padding:10px; color: #ccc;">Ninguém online...</li>'; return; }

    validos.forEach(username => {

        const li = document.createElement('li');

        Object.assign(li.style, { display: "flex", alignItems: "center", padding: "8px 5px", borderBottom: "1px solid rgba(255,255,255,0.1)", color: "white" });

        const icon = document.createElement('span');

        Object.assign(icon.style, { display: "inline-block", width: "10px", height: "10px", backgroundColor: "#00ff00", borderRadius: "50%", marginRight: "10px", boxShadow: "0 0 5px #00ff00" });

        li.appendChild(icon);

        li.appendChild(document.createTextNode(username));

        ul.appendChild(li);

    });

}



function toggleExitFullScreenButton() {

    toggleUIElements(true);

    clearTimeout(timeout);

    timeout = setTimeout(() => toggleUIElements(false), 3000);

}



function toggleUIElements(show) {

    var ids = ['exit-fullscreen-button', 'emojiContainer', 'adjustVideoSizeButton', 'toggleChat', 'start-btn', 'fs-chat-btn', 'toggleOverlayBtn'];

    var displayValue = show ? 'block' : 'none';

    

    ids.forEach(id => { 

        var el = document.getElementById(id); 

        if (el) el.style.display = displayValue;

    });

    

    const fsInput = document.getElementById('fs-msg-input');

    if (fsInput && document.fullscreenElement && fsInput.value.length > 0) {

        fsInput.style.display = 'block';

    }

}



function adjustVideoSize() { isExpanded = !isExpanded; }



var video = videoContainer.querySelector('video');

var initialDistance = 0, currentScale = 1, isDragging = false;

var initialX = 0, initialY = 0, offsetX = 0, offsetY = 0, lastTouchX = 0, lastTouchY = 0;



function getDistance(touches) {

    return Math.sqrt(Math.pow(touches[0].clientX - touches[1].clientX, 2) + Math.pow(touches[0].clientY - touches[1].clientY, 2));

}



videoContainer.addEventListener('touchstart', function (e) {

    if (!isExpanded) return;

    if (e.touches.length === 2) initialDistance = getDistance(e.touches);

    else if (e.touches.length === 1) {

        isDragging = true;

        initialX = e.touches[0].clientX - offsetX;

        initialY = e.touches[0].clientY - offsetY;

        lastTouchX = e.touches[0].clientX;

        lastTouchY = e.touches[0].clientY;

    }

});



videoContainer.addEventListener('touchmove', function (e) {

    if (!isExpanded) return;

    if (e.touches.length === 2) {

        e.preventDefault();

        var currentDistance = getDistance(e.touches);

        currentScale = Math.min(Math.max(currentScale * (currentDistance / initialDistance), 0.5), 3);

        initialDistance = currentDistance;

        video.style.transform = `scale(${currentScale}) translate(${offsetX}px, ${offsetY}px)`;

    } else if (isDragging && e.touches.length === 1) {

        e.preventDefault();

        offsetX = Math.min(Math.max(offsetX + (e.touches[0].clientX - lastTouchX), -((video.offsetWidth * currentScale) - videoContainer.offsetWidth)/2), ((video.offsetWidth * currentScale) - videoContainer.offsetWidth)/2);

        offsetY = Math.min(Math.max(offsetY + (e.touches[0].clientY - lastTouchY), -((video.offsetHeight * currentScale) - videoContainer.offsetHeight)/2), ((video.offsetHeight * currentScale) - videoContainer.offsetHeight)/2);

        video.style.transform = `scale(${currentScale}) translate(${offsetX}px, ${offsetY}px)`;

        lastTouchX = e.touches[0].clientX;

        lastTouchY = e.touches[0].clientY;

    }

});

videoContainer.addEventListener('touchend', (e) => { if (e.touches.length < 2) initialDistance = 0; if (e.touches.length === 0) isDragging = false; });



function exitFullScreen() {

    if (document.fullscreenElement === videoContainer) {

        if (document.exitFullscreen) document.exitFullscreen();

        else if (document.webkitExitFullscreen) document.webkitExitFullscreen();

    }

}



document.addEventListener("fullscreenchange", function() {

    var fsInput = document.getElementById('fs-msg-input');

    

    if (document.fullscreenElement === videoContainer) {

        player.el().style.pointerEvents = 'none';

        document.getElementById('fullscreen-button').style.display = 'none';

        videoContainer.addEventListener('click', toggleExitFullScreenButton);

        document.getElementById('exit-fullscreen-button').addEventListener('click', exitFullScreen);

        toggleUIElements(false);

    } else {

        toggleUIElements(false);

        if(document.getElementById('smallChat')) document.getElementById('smallChat').style.display = 'none';

        document.getElementById('fullscreen-button').style.display = 'block';

        videoContainer.removeEventListener('click', toggleExitFullScreenButton);

        

        if(fsInput) fsInput.style.display = 'none'; 

    }

});



function unlockVideoControls() {

    var player = videojs('videoPlayer');

    var stylesheet = document.styleSheets[0];

    if (player.controls()) {

        player.controls(false);

        player.addClass('hide-controls');

        player.el().style.pointerEvents = 'none';

        document.getElementById('unlock-button').textContent = 'Desbloquear Controles';

        stylesheet.insertRule('video::-webkit-media-controls-timeline { display: none !important; pointer-events: none !important; }', stylesheet.cssRules.length);

    } else {

        player.controls(true);

        player.removeClass('hide-controls');

        player.el().style.pointerEvents = 'auto';

        document.getElementById('unlock-button').textContent = 'Bloquear Controles';

        stylesheet.insertRule('video::-webkit-media-controls-timeline { display: block !important; pointerEvents: auto !important; }', stylesheet.cssRules.length);

    }

}





ativarEmojiListeners();



function ativarEmojiListeners() {

  document.querySelectorAll('#emojiContainer .emoji-button').forEach(button => {

    button.addEventListener('click', (event) => {

      event.stopPropagation();

      console.log("Emoji clicado:", button.textContent);

      sendEmojiMessage(button.textContent);

      

    });

  });

}



function sendEmojiMessage(emoji) {

  var normalInput = document.getElementById('msgInput');

  if (normalInput) {

    normalInput.value = emoji;

    normalInput.focus();

    enviar();

    document.getElementById('emojiContainer').style.display = 'none';

  } else {

    console.error("Input msgInput não encontrado");

  }

}

function comando(texto) { document.getElementById('msgInput').value = texto; enviar(); }

document.getElementById('enviarBtn').addEventListener('dblclick', () => { const m = document.getElementById('controlMenu'); m.style.display = m.style.display === 'none' ? 'block' : 'none'; });



socket.on('lista_videos', (videos) => {

    videoList = videos;

    if (videoList.length === 0) { alert('Nenhum vídeo.'); return; }

    alert('Vídeos:\n' + videoList.map((v, i) => `${i + 1}. ${v.filename}`).join('\n'));

});



const recognition = new (window.SpeechRecognition || window.webkitSpeechRecognition)();

recognition.lang = "pt-BR";

recognition.continuous = true; 

recognition.interimResults = false;

document.getElementById("start-btn")?.addEventListener("click", () => recognition.start());

recognition.onaudiostart = () => { if (!statusPaused) { toggleUIElements(false); player.play(); } };

recognition.onresult = (e) => { messageInput.value = e.results[e.results.length - 1][0].transcript; enviar(); };

recognition.onerror = () => { messageInput.value = "Erro na voz."; };



function sendAudioMessage() {

    var currentTime = Date.now();

    if (currentTime - last < voiceInterval) { alert(`Aguarde ${Math.ceil((voiceInterval - (currentTime - last))/1000)}s.`); return; }

    if (messageInput.value.trim() !== "") {

        socket.emit("iaudio", messageInput.value.trim());

        messageInput.value = "";

        last = currentTime;

        socket.emit('message', { 'user': username, 'message': 'resgatou uma mensagem de voz' });

    }

}



socket.on('audio_ready', (filename) => {

    const caminho = 'https://kimzin.space/rave/static/' + filename;

    fetch(caminho, { method: 'HEAD' }).then(res => {

        if (res.ok) {

            const audio = document.createElement('audio');

            audio.src = caminho; audio.controls = true; audio.autoplay = true;

            audio.onended = () => document.getElementById('audio-container')?.removeChild(audio);

            document.getElementById('audio-container')?.appendChild(audio);

        }

    });

});



document.addEventListener('keydown', function(event) {

    if (document.activeElement.tagName === 'INPUT' || document.activeElement.tagName === 'TEXTAREA') {

        if (event.key === 'Enter') {

            event.preventDefault();

            if(document.activeElement === messageInput) enviar();

        }

        return;

    }



    if (event.key === 'ArrowDown') {

        event.preventDefault();

        recognition.start();

        return;

    }



    var targetInput;

    if (document.fullscreenElement) {

        targetInput = document.getElementById('fs-msg-input');

    } else {

        targetInput = messageInput;

    }



    if (!targetInput) return;



    if (event.key === 'Enter') {

        event.preventDefault();

        enviar();

        return;

    }



    if (event.key === 'Backspace') {

        event.preventDefault();

        targetInput.value = targetInput.value.slice(0, -1);

        if (document.fullscreenElement && targetInput.value === '') {

            targetInput.style.display = 'none';

        }

        return;

    }



    if (!event.ctrlKey && !event.altKey && !event.metaKey && event.key.length === 1 && event.key !== ' ') {

        event.preventDefault(); 

        targetInput.value += event.key;

        if (document.fullscreenElement) {

            targetInput.style.display = 'block';

        }

    }

});

/* --- FILTROS DE OTIMIZAÇÃO CINEMATOGRÁFICA --- */
function aplicarFiltro(tipo) {
    const video = document.querySelector('#videoPlayer_html5_api') || document.querySelector('video');
    if (!video) return;

    const filtros = {
        'hdr': 'contrast(1.2) saturate(1.3) brightness(1.1)',
        'noturno': 'sepia(0.3) brightness(0.9) contrast(1.1)',
        'frio': 'hue-rotate(180deg) saturate(0.8) brightness(1.1)',
        'vivido': 'saturate(1.6) contrast(1.1)',
        'suave': 'blur(0.4px) brightness(1.05)',
        'claro': 'brightness(1.4) contrast(0.9)',
        'normal': 'none'
    };

    const valorFiltro = filtros[tipo] || 'none';
    video.style.setProperty('filter', valorFiltro, 'important');
    video.style.setProperty('-webkit-filter', valorFiltro, 'important');
}

/* --- SELETOR ULTRA-COMPACTO COM AUTO-HIDE FORÇADO --- */
let timerMenuGlobal;

function criarMenuFiltrosCine() {
    const container = document.getElementById('video-container') || document.querySelector('.video-js') || document.body;
    if (document.getElementById('filtro-compacto-box')) return;

    const menuBox = document.createElement('div');
    menuBox.id = 'filtro-compacto-box';
    
    Object.assign(menuBox.style, {
        position: 'absolute',
        top: '170px',
        right: '20px',
        zIndex: '9999999',
        display: 'none', // Começa escondido
        opacity: '0',
        transition: 'opacity 0.3s ease, transform 0.3s ease',
        transform: 'translateY(-10px)'
    });

    const seletor = document.createElement('select');
    Object.assign(seletor.style, {
        backgroundColor: 'rgba(0, 0, 0, 0.8)',
        backdropFilter: 'blur(8px)',
        color: 'white',
        border: '1px solid rgba(255, 255, 255, 0.2)',
        borderRadius: '15px',
        padding: '5px 12px',
        fontSize: '12px',
        cursor: 'pointer',
        outline: 'none'
    });

    const opcoes = [
        { label: '🎬 Original', valor: 'normal' },
        { label: '✨ HDR', valor: 'hdr' },
        { label: '🌙 Noturno', valor: 'noturno' },
        { label: '🎭 Vívido', valor: 'vivido' },
        { label: '❄️ Frio', valor: 'frio' },
        { label: '🔦 Claro', valor: 'claro' }
    ];

    opcoes.forEach(opt => {
        let o = document.createElement('option');
        o.value = opt.valor;
        o.textContent = opt.label;
        o.style.backgroundColor = '#111';
        seletor.appendChild(o);
    });

    menuBox.appendChild(seletor);
    container.appendChild(menuBox);

    // FUNÇÃO PARA SUMIR (FORÇADO)
    const sumirAgora = () => {
        menuBox.style.opacity = '0';
        menuBox.style.transform = 'translateY(-10px)';
        setTimeout(() => {
            menuBox.style.display = 'none';
        }, 300);
    };

    // FUNÇÃO PARA APARECER E CONTAR 2 SEGUNDOS
    const mostrarEResetarTimer = () => {
        clearTimeout(timerMenuGlobal);
        
        // Se já estiver escondido, mostra
        if (menuBox.style.display === 'none') {
            menuBox.style.display = 'block';
            setTimeout(() => {
                menuBox.style.opacity = '1';
                menuBox.style.transform = 'translateY(0)';
            }, 10);
        }

        // Inicia contagem para sumir em 2 segundos
        timerMenuGlobal = setTimeout(() => {
            // Só some se o mouse não estiver em cima do seletor
            if (!menuBox.matches(':hover')) {
                sumirAgora();
            }
        }, 2000);
    };

    // GATILHO: Ao mover o mouse no vídeo ou clicar, o menu aparece
    container.addEventListener('mousemove', mostrarEResetarTimer);
    container.addEventListener('click', mostrarEResetarTimer);

    // Quando mudar o filtro, aguarda 2s e some
    seletor.onchange = (e) => {
        aplicarFiltro(e.target.value);
        timerMenuGlobal = setTimeout(sumirAgora, 2000);
    };

    // Garante que se o mouse sair do seletor, ele comece a contagem de 2s
    menuBox.onmouseleave = () => {
        clearTimeout(timerMenuGlobal);
        timerMenuGlobal = setTimeout(sumirAgora, 2000);
    };
}

// Inicia
setTimeout(criarMenuFiltrosCine, 2000);


carregarPlaysDoTxt();
