const socket = io();
const roomId = window.location.pathname.split('/').pop();
const form = document.getElementById('chatForm');
const input = document.getElementById('messageInput');
const chatBox = document.getElementById('chatBox');

// Entra na sala
socket.emit('joinRoom', roomId);

// Recebe mensagens
socket.on('chatMessage', (data) => {
    const div = document.createElement('div');

    if (data.type === 'text') {
        const msg = data.content;
        const isMine = msg.startsWith('eu:');
        const content = isMine ? msg.replace('eu:', '') : msg;

        div.className = isMine
            ? 'self-end bg-blue-500 text-white px-4 py-2 rounded-xl max-w-xs'
            : 'self-start bg-gray-600 text-white px-4 py-2 rounded-xl max-w-xs';

        div.textContent = content;
    }

    if (data.type === 'image') {
        const img = document.createElement('img');
        img.src = data.content;
        img.alt = 'imagem';
        img.className = 'max-w-xs rounded-xl shadow';
        div.className = 'mb-2';
        div.appendChild(img);
    }

    chatBox.appendChild(div);
    chatBox.scrollTop = chatBox.scrollHeight;
});

// Envia mensagens via socket
form.addEventListener('submit', (e) => {
    e.preventDefault();

    // Se houver texto, envia como mensagem
    if (input.value.trim() !== '') {
        const message = 'eu:' + input.value.trim();
        socket.emit('chatMessage', { type: 'text', content: message });
        input.value = '';
    }
});

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

imageInput.addEventListener('change', () => {
    const file = imageInput.files[0];
    if (!file) return;

    const reader = new FileReader();

    reader.onload = () => {
        const base64 = reader.result;
        socket.emit('chatMessage', { type: 'image', content: base64 });
    };

    reader.readAsDataURL(file);
});


// Mostrar e copiar link da sala
const link = window.location.href;
document.getElementById('roomLink').textContent = link;

document.getElementById('copyBtn').addEventListener('click', () => {
    navigator.clipboard.writeText(link)
        .then(() => {
            document.getElementById('copyBtn').textContent = 'Link copiado!';
            setTimeout(() => {
                document.getElementById('copyBtn').textContent = 'Copiar Link da Sala';
            }, 2000);
        })
        .catch(err => {
            alert('Erro ao copiar link');
            console.error(err);
        });
});

// Download do QR Code
const qrImg = document.querySelector('.qr-code');
const downloadLink = document.getElementById('downloadQr');

// Esperar a imagem carregar para gerar o link real
qrImg.addEventListener('load', () => {
    downloadLink.href = qrImg.src;
});


