if (document.getElementById('audio-player')) {
const socket = io();

let currentSong = null;
let serverOffset = 0;
let playing = false;
let updateInterval;

const audio = document.getElementById('audio-player');
const playBtn = document.getElementById('toggle-play');
const statusEl = document.getElementById('radio-status');
const titleEl = document.getElementById('song-title');
const artistEl = document.getElementById('song-artist');
const coverEl = document.getElementById('cover-image');
const progressEl = document.getElementById('progress');
const timeCurrEl = document.getElementById('current-time');
const timeLeftEl = document.getElementById('time-left');
const titleClone = document.querySelector('.song-title-clone');
const artistClone = document.querySelector('.song-artist-clone');
const queueBoxEl = document.getElementById('queue-box');
const queueListEl = document.getElementById('queue-list');
const likeBtn = document.getElementById('like-btn');
const dislikeBtn = document.getElementById('dislike-btn');
const likeCountEl = document.getElementById('like-count');
const dislikeCountEl = document.getElementById('dislike-count');
let currentQueue = [];

socket.on('connect', () => {
    statusEl.textContent = "Conectado. Sincronizando...";
});

socket.on('disconnect', () => {
    statusEl.textContent = "Desconectado. Reconectando...";
});

socket.on('banned', (data) => {
    statusEl.textContent = "Você foi banido.";
    audio.pause();
});

socket.on('radio_update', (data) => {
    if (!data) {
        currentSong = null;
        titleEl.textContent = "Nenhuma música tocando";
        artistEl.textContent = "";
        if (titleClone) titleClone.textContent = "Nenhuma música tocando";
        if (artistClone) artistClone.textContent = "";
        coverEl.src = "/static/images/logo.png";
        audio.pause();
        playing = false;
        playBtn.innerHTML = '<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Começar a Ouvir';
        statusEl.textContent = "Rádio Offline";
        clearInterval(updateInterval);
        resetProgress();
        currentQueue = [];
        renderQueue();
        updateVoteUI(0, 0, null);
        
        // Hide Favorito and Likes when offline
        favBtn.classList.add('hidden');
        document.querySelector('.vote-pills').classList.add('hidden');
        return;
    }

    statusEl.textContent = "No Ar";
    // Show Favorito and Likes when online
    favBtn.classList.remove('hidden');
    document.querySelector('.vote-pills').classList.remove('hidden');
    currentSong = data;

    titleEl.textContent = data.title;
    artistEl.textContent = data.artist || "Desconhecido";
    if (titleClone) titleClone.textContent = data.title;
    if (artistClone) artistClone.textContent = data.artist || "Desconhecido";

    coverEl.src = data.image_filename ? `/static/images/${data.image_filename}` : "/static/images/default_cover.png";
    currentQueue = data.queue || [];
    renderQueue();
    const voted = getStoredVote(data.song_id);
    updateVoteUI(data.likes || 0, data.dislikes || 0, voted);
    updateFavBtn();

    const currentSrc = audio.src;
    const newSrc = window.location.origin + '/static/music/' + data.filename;

    if (currentSrc !== newSrc) {
        audio.src = newSrc;
        if (playing) {
            audio.play().catch(e => {
                playing = false;
                playBtn.innerHTML = '<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Começar a Ouvir';
            });
        }
    }

    const expectedTime = data.current_time;
    if (Math.abs(audio.currentTime - expectedTime) > 2) {
        audio.currentTime = expectedTime;
    }

    clearInterval(updateInterval);
    updateInterval = setInterval(updateProgress, 1000);
});

function getStoredVote(songId) {
    return localStorage.getItem(`song_vote_${songId}`);
}

function updateVoteUI(likes, dislikes, votedType) {
    likeCountEl.textContent = likes;
    dislikeCountEl.textContent = dislikes;
    
    // Use new pill classes
    likeBtn.classList.remove('active-like');
    dislikeBtn.classList.remove('active-dislike');
    
    if (votedType === 'like') {
        likeBtn.classList.add('active-like');
    } else if (votedType === 'dislike') {
        dislikeBtn.classList.add('active-dislike');
    }
}


async function sendVote(voteType) {
    if (!currentSong) return;
    try {
        const res = await fetch('/api/song_vote', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ song_id: currentSong.song_id || currentSong.id, vote_type: voteType })
        });
        const data = await res.json();
        if (!data.success) return;
        if (data.vote_type) {
            localStorage.setItem(`song_vote_${currentSong.song_id || currentSong.id}`, data.vote_type);
        } else {
            localStorage.removeItem(`song_vote_${currentSong.song_id || currentSong.id}`);
        }
        updateVoteUI(data.likes, data.dislikes, data.vote_type);
    } catch (err) {
        console.error('Vote error:', err);
    }
}

likeBtn.addEventListener('click', () => sendVote('like'));
dislikeBtn.addEventListener('click', () => sendVote('dislike'));

socket.on('sync', (data) => {
    if (!data) return;
    const expectedTime = data.current_time;
    if (currentSong) {
        currentSong.current_time = expectedTime;
    }
    if (playing && Math.abs(audio.currentTime - expectedTime) > 2) {
        audio.currentTime = expectedTime;
    }
});

playBtn.addEventListener('click', () => {
    if (playing) {
        audio.pause();
        playing = false;
        playBtn.innerHTML = '<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Começar a Ouvir';
    } else {
        // Preserve user intent to listen, even if no track is loaded yet.
        playing = true;
        playBtn.innerHTML = '<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><rect x="6" y="4" width="4" height="16"></rect><rect x="14" y="4" width="4" height="16"></rect></svg> Pausar';

        if (currentSong) {
            audio.currentTime = currentSong.current_time + 0.5;
            audio.play().catch(e => {
                playing = false;
                playBtn.innerHTML = '<svg viewBox="0 0 24 24" width="24" height="24" stroke="currentColor" stroke-width="2" fill="none"><polygon points="5 3 19 12 5 21 5 3"></polygon></svg> Começar a Ouvir';
                console.error("Autoplay blocked:", e);
            });
        } else {
            statusEl.textContent = "Conectado. Aguardando música...";
        }
    }
});

function formatTime(secs) {
    if (isNaN(secs) || secs < 0) secs = 0;
    const m = Math.floor(secs / 60);
    const s = Math.floor(secs % 60);
    return `${m}:${s.toString().padStart(2, '0')}`;
}

function resetProgress() {
    progressEl.style.width = '0%';
    timeCurrEl.textContent = '0:00';
    timeLeftEl.textContent = '-0:00';
}

function updateProgress() {
    if (!currentSong) return;
    
    let cTime;
    if (playing) {
        cTime = audio.currentTime;
        currentSong.current_time = cTime;
    } else {
        currentSong.current_time += 1;
        cTime = currentSong.current_time;
    }

    const dur = currentSong.duration;
    if (cTime > dur) cTime = dur;
    const left = dur - cTime;
    timeCurrEl.textContent = formatTime(cTime);
    timeLeftEl.textContent = '-' + formatTime(left);
    const pct = (cTime / dur) * 100;
    progressEl.style.width = pct + '%';
    
    updateQueueTimers(left);
}

function renderQueue() {
    queueBoxEl.classList.remove('hidden');
    if (currentQueue.length === 0) {
        queueListEl.innerHTML = '<p style="text-align: center; color: var(--text-muted); padding: 20px; font-size: 0.9rem;">Nenhuma música na fila de momento.</p>';
        return;
    }
    
    queueListEl.innerHTML = '';
    currentQueue.forEach((q, index) => {
        const li = document.createElement('li');
        li.innerHTML = `
            <div class="queue-info">
                <span class="queue-title">${q.title}</span>
                <span class="queue-artist">${q.artist || "Desconhecido"}</span>
            </div>
            <div class="queue-times">
                <span class="queue-starts-in" id="q-starts-${index}">--:--</span>
                <span class="queue-duration">Duração: ${formatTime(q.duration)}</span>
            </div>
        `;
        queueListEl.appendChild(li);
    });
}

function updateQueueTimers(timeLeft) {
    if (!currentQueue || currentQueue.length === 0) return;
    
    let cumulativeTime = timeLeft;
    currentQueue.forEach((q, index) => {
        const startsInEl = document.getElementById(`q-starts-${index}`);
        if (startsInEl) {
            startsInEl.textContent = 'Em: ' + formatTime(cumulativeTime);
        }
        cumulativeTime += (q.duration || 0);
    });
}

let currentCaptcha = "";

function generateCaptcha() {
    const canvas = document.getElementById('captcha-canvas');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    
    // Clear canvas
    ctx.clearRect(0, 0, canvas.width, canvas.height);
    ctx.fillStyle = '#f5f5f5';
    ctx.fillRect(0, 0, canvas.width, canvas.height);
    
    // Generate random string
    const chars = 'ABCDEFGHJKLMNPQRSTUVWXYZabcdefghjkmnpqrstuvwxyz23456789';
    let captchaStr = '';
    for (let i = 0; i < 5; i++) {
        captchaStr += chars.charAt(Math.floor(Math.random() * chars.length));
    }
    currentCaptcha = captchaStr;
    
    // Add noise lines
    for (let i = 0; i < 6; i++) {
        ctx.strokeStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255}, 0.8)`;
        ctx.beginPath();
        ctx.moveTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.lineTo(Math.random() * canvas.width, Math.random() * canvas.height);
        ctx.stroke();
    }
    
    // Draw text
    ctx.font = 'bold 26px Outfit, sans-serif';
    ctx.textAlign = 'center';
    ctx.textBaseline = 'middle';
    
    for (let i = 0; i < 5; i++) {
        ctx.save();
        ctx.translate(25 + i * 25, 25);
        ctx.rotate((Math.random() - 0.5) * 0.6);
        ctx.fillStyle = `rgb(${Math.random()*150},${Math.random()*150},${Math.random()*150})`; // Darker colors
        ctx.fillText(captchaStr[i], 0, 0);
        ctx.restore();
    }
    
    // Add noise dots
    for (let i = 0; i < 40; i++) {
        ctx.fillStyle = `rgba(${Math.random()*255},${Math.random()*255},${Math.random()*255}, 0.6)`;
        ctx.beginPath();
        ctx.arc(Math.random() * canvas.width, Math.random() * canvas.height, 1.5, 0, Math.PI * 2);
        ctx.fill();
    }
}

document.addEventListener("DOMContentLoaded", () => {
    generateCaptcha();
    const refreshBtn = document.getElementById('refresh-captcha');
    if(refreshBtn) refreshBtn.addEventListener('click', generateCaptcha);
});

document.getElementById('recommend-form').addEventListener('submit', async (e) => {
    e.preventDefault();
    const title = document.getElementById('rec-title').value;
    const artist = document.getElementById('rec-artist').value;
    const captchaInput = document.getElementById('captcha-input').value;
    const msg = document.getElementById('rec-msg');
    
    if (captchaInput !== currentCaptcha) {
        msg.textContent = "Captcha incorreto! Tente novamente.";
        msg.style.color = "#e74c3c";
        msg.classList.remove('hidden');
        generateCaptcha();
        document.getElementById('captcha-input').value = '';
        setTimeout(() => msg.classList.add('hidden'), 3000);
        return;
    }
    
    msg.style.color = "#2ecc71"; // reset to success

    try {
        const email = document.getElementById('rec-email').value;
        const res = await fetch('/api/recommend', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ title, artist, email })
        });
        const data = await res.json();
        if (data.success) {
            msg.textContent = "Recomendação enviada com sucesso!";
            msg.classList.remove('hidden');
            document.getElementById('recommend-form').reset();
            generateCaptcha();
            setTimeout(() => msg.classList.add('hidden'), 3000);
        }
    } catch (err) {
        console.error(err);
    }
});

/* ════════════════════════════════════════════════════
   FAVORITOS
   ════════════════════════════════════════════════════ */
const FAV_KEY = 'ig_radio_favorites';
const favBtn       = document.getElementById('fav-btn');
const favIcon      = document.getElementById('fav-icon');
const favSection   = document.getElementById('favorites-section');
const favBox       = document.getElementById('fav-box');
const favList      = document.getElementById('fav-list');
const favEmpty     = document.getElementById('fav-empty');
const clearFavsBtn = document.getElementById('clear-favs-btn');

function getFavorites() {
    try { return JSON.parse(localStorage.getItem(FAV_KEY)) || []; }
    catch { return []; }
}
function saveFavorites(favs) {
    localStorage.setItem(FAV_KEY, JSON.stringify(favs));
}
function isFavorite(songId) {
    return getFavorites().some(f => f.id === songId);
}

function updateFavBtn() {
    if (!currentSong) { favBtn.classList.remove('active'); return; }
    const id = currentSong.song_id || currentSong.id;
    if (isFavorite(id)) {
        favBtn.classList.add('active');
        favIcon.setAttribute('fill', '#ff5078');
        favIcon.setAttribute('stroke', '#ff5078');
    } else {
        favBtn.classList.remove('active');
        favIcon.setAttribute('fill', 'none');
        favIcon.setAttribute('stroke', 'currentColor');
    }
}

function renderFavorites() {
    const favs = getFavorites();
    favList.innerHTML = '';
    
    if (favs.length === 0) {
        favSection.classList.add('hidden');
        favEmpty.classList.remove('hidden');
        return;
    }
    
    favSection.classList.remove('hidden');
    favEmpty.classList.add('hidden');
    favs.forEach(f => {
        const li = document.createElement('li');
        li.innerHTML = `
            <div class="fav-song-info">
                <span class="fav-song-title">${f.title}</span>
                <span class="fav-song-artist">${f.artist || 'Desconhecido'}</span>
            </div>
            <button class="fav-remove-btn" title="Remover dos favoritos" data-id="${f.id}">✕</button>
        `;
        favList.appendChild(li);
    });
    // Bind remove buttons
    favList.querySelectorAll('.fav-remove-btn').forEach(btn => {
        btn.addEventListener('click', () => {
            const id = Number(btn.dataset.id);
            let favs = getFavorites().filter(f => f.id !== id);
            saveFavorites(favs);
            renderFavorites();
            updateFavBtn();
            if (favs.length === 0) favSection.classList.add('hidden');
        });
    });
}

favBtn.addEventListener('click', () => {
    if (!currentSong) return;
    const id = currentSong.song_id || currentSong.id;
    let favs = getFavorites();
    if (isFavorite(id)) {
        favs = favs.filter(f => f.id !== id);
    } else {
        favs.unshift({ id, title: currentSong.title, artist: currentSong.artist || 'Desconhecido' });
    }
    saveFavorites(favs);
    updateFavBtn();
    renderFavorites();
    if (favs.length === 0) favSection.classList.add('hidden');
});

clearFavsBtn.addEventListener('click', () => {
    saveFavorites([]);
    renderFavorites();
    updateFavBtn();
    favSection.classList.add('hidden');
});

// Render favorites on load
renderFavorites();
if (getFavorites().length === 0) favSection.classList.add('hidden');

/* ════════════════════════════════════════════════════
   PARTILHAR LINK
   ════════════════════════════════════════════════════ */
const shareBtn    = document.getElementById('share-btn');
const sharePanel  = document.getElementById('share-panel');
const shareCopy   = document.getElementById('share-copy');
const shareWA     = document.getElementById('share-wa');
const shareTW     = document.getElementById('share-tw');
const shareFB     = document.getElementById('share-fb');
const shareCopied = document.getElementById('share-copied');

shareBtn.addEventListener('click', () => {
    sharePanel.classList.toggle('hidden');
});

function getShareText() {
    const shareUrl = 'https://igradio.tbhwf.com';
    if (currentSong) {
        return `🎵 A ouvir "${currentSong.title}" de ${currentSong.artist || 'Desconhecido'} na IG Radio! Ouve aqui: ${shareUrl}`;
    }
    return `🎵 Ouve a IG Radio aqui: ${shareUrl}`;
}

shareCopy.addEventListener('click', async () => {
    const shareUrl = 'https://igradio.tbhwf.com';
    try {
        await navigator.clipboard.writeText(shareUrl);
        shareCopied.classList.remove('hidden');
        setTimeout(() => shareCopied.classList.add('hidden'), 2500);
    } catch {
        // fallback
        const ta = document.createElement('textarea');
        ta.value = shareUrl;
        document.body.appendChild(ta);
        ta.select();
        document.execCommand('copy');
        document.body.removeChild(ta);
        shareCopied.classList.remove('hidden');
        setTimeout(() => shareCopied.classList.add('hidden'), 2500);
    }
});

shareWA.addEventListener('click', () => {
    const text = encodeURIComponent(getShareText());
    window.open(`https://api.whatsapp.com/send?text=${text}`, '_blank');
});

shareTW.addEventListener('click', () => {
    const text = encodeURIComponent(getShareText());
    window.open(`https://twitter.com/intent/tweet?text=${text}`, '_blank');
});

shareFB.addEventListener('click', () => {
    const shareUrl = 'https://igradio.tbhwf.com';
    const url = encodeURIComponent(shareUrl);
    window.open(`https://www.facebook.com/sharer/sharer.php?u=${url}`, '_blank');
});

// Close share panel when clicking outside
document.addEventListener('click', (e) => {
    if (!sharePanel.classList.contains('hidden') &&
        !sharePanel.contains(e.target) &&
        e.target !== shareBtn &&
        !shareBtn.contains(e.target)) {
        sharePanel.classList.add('hidden');
    }
});

// Update fav button state when song changes has been merged into main radio_update listener

/* ════════════════════════════════════════════════════
   AI CHAT SYSTEM
   ════════════════════════════════════════════════════ */

const aiMessagesEl = document.getElementById('ai-messages');
const aiInputEl = document.getElementById('ai-input');
const aiSendBtn = document.getElementById('ai-send-btn');

function addAIMessage(text, isBot) {
    const messageDiv = document.createElement('div');
    messageDiv.className = isBot ? 'ai-message-bot' : 'ai-message-user';
    messageDiv.style.alignSelf = isBot ? 'flex-start' : 'flex-end';
    
    if (isBot) {
        messageDiv.innerHTML = `
            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                <img src="/static/images/logo.png" alt="IG Radio" style="width: 32px; height: 32px; border-radius: 50%;">
                <span style="font-weight: 700; color: #ff007f; font-size: 0.85rem;">IG Radio IA</span>
            </div>
            <p>${text.replace(/\n/g, '<br>')}</p>
        `;
    } else {
        messageDiv.innerHTML = `
            <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px; justify-content: flex-end;">
                <span style="font-weight: 700; color: #e0e0e0; font-size: 0.85rem;">Utilizador</span>
                <div style="width: 32px; height: 32px; border-radius: 50%; background: linear-gradient(135deg, #ff007f, #7b2cbf); display: flex; align-items: center; justify-content: center; font-weight: 700; color: white; font-size: 0.9rem;">U</div>
            </div>
            <p>${text.replace(/\n/g, '<br>')}</p>
        `;
    }
    
    aiMessagesEl.appendChild(messageDiv);
    aiMessagesEl.scrollTop = aiMessagesEl.scrollHeight;
    return messageDiv;
}

function updateAIMessage(messageDiv, text) {
    const p = messageDiv.querySelector('p');
    if (p) {
        p.innerHTML = text.replace(/\n/g, '<br>');
    }
    aiMessagesEl.scrollTop = aiMessagesEl.scrollHeight;
}

// ── Typewriter engine ──────────────────────────────
// All received text goes into a queue and is displayed
// character by character, regardless of network timing.
let _twQueue = '';       // pending characters to type
let _twDisplayed = '';   // characters already shown
let _twDiv = null;       // the bot bubble being filled
let _twTimer = null;     // setInterval handle
let _twDone = false;     // has the server finished sending?

const TYPEWRITER_SPEED_MS = 18; // ms per character

const THINKING_HTML = '<span class="ai-thinking"><span></span><span></span><span></span></span>';
let _twStarted = false;  // true once first char has been typed

function twStart(botDiv) {
    _twQueue    = '';
    _twDisplayed = '';
    _twDiv      = botDiv;
    _twDone     = false;
    _twStarted  = false;
    if (_twTimer) clearInterval(_twTimer);
    _twTimer = setInterval(_twTick, TYPEWRITER_SPEED_MS);
}

function twPush(text) {
    _twQueue += text;
}

function twFinish() {
    _twDone = true;
}

function _twTick() {
    if (_twQueue.length > 0) {
        if (!_twStarted) {
            // First character — replace thinking dots with real text
            _twStarted = true;
        }
        _twDisplayed += _twQueue[0];
        _twQueue = _twQueue.slice(1);
        updateAIMessage(_twDiv, _twDisplayed + '<span class="ai-cursor">|</span>');
    } else if (_twDone) {
        clearInterval(_twTimer);
        _twTimer = null;
        if (_twDisplayed) {
            updateAIMessage(_twDiv, _twDisplayed);
        }
        aiSendBtn.disabled = false;
    }
    // while queue empty and not done → thinking dots remain
}
// ──────────────────────────────────────────────────

async function sendAIMessage() {
    const prompt = aiInputEl.value.trim();
    if (!prompt) return;

    addAIMessage(prompt, false);
    aiInputEl.value = '';
    aiSendBtn.disabled = true;

    // Stop any running typewriter
    if (_twTimer) { clearInterval(_twTimer); _twTimer = null; }

    // Show thinking dots while waiting for first token
    const botMessageDiv = addAIMessage(THINKING_HTML, true);
    twStart(botMessageDiv);

    try {
        const response = await fetch('/api/ai/ask', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ prompt })
        });

        if (!response.ok) {
            // Parse server error message (rate limit, ban, etc.)
            let errMsg = '❌ Erro ' + response.status;
            try {
                const errData = await response.json();
                if (errData.error) errMsg = '⚠️ ' + errData.error;
            } catch (_) {}
            twFinish();
            updateAIMessage(botMessageDiv, errMsg);
            aiSendBtn.disabled = false;
            return;
        }

        if (!response.body) {
            const text = await response.text();
            twPush(text || '❌ Sem conteúdo');
            twFinish();
            return;
        }

        // Read SSE stream — push chunks into typewriter queue
        const reader = response.body.getReader();
        const decoder = new TextDecoder();
        let buffer = '';

        while (true) {
            const { done, value } = await reader.read();
            if (done) break;

            buffer += decoder.decode(value, { stream: true });
            const lines = buffer.split(/\r?\n/);

            for (let i = 0; i < lines.length - 1; i++) {
                const line = lines[i].trim();
                if (!line || !line.startsWith('data: ')) continue;
                const payload = line.slice(6).trim();
                if (!payload) continue;
                try {
                    const data = JSON.parse(payload);
                    if (data.response) twPush(data.response);
                    if (data.error) twPush('❌ ' + data.error);
                } catch (e) {
                    console.error('Parse error:', e, payload);
                }
            }
            buffer = lines[lines.length - 1];
        }

        // Handle remaining buffer
        if (buffer.trim().startsWith('data: ')) {
            const payload = buffer.trim().slice(6).trim();
            if (payload) {
                try {
                    const data = JSON.parse(payload);
                    if (data.response) twPush(data.response);
                    if (data.error) twPush('❌ ' + data.error);
                } catch (e) { /* ignore */ }
            }
        }

        twFinish();

    } catch (err) {
        twFinish();
        updateAIMessage(botMessageDiv, '❌ Erro de conexão: ' + err.message);
        aiSendBtn.disabled = false;
        console.error(err);
    }
}

aiSendBtn.addEventListener('click', sendAIMessage);
aiInputEl.addEventListener('keypress', (e) => {
    if (e.key === 'Enter' && !aiSendBtn.disabled) {
        e.preventDefault();
        sendAIMessage();
    }
});

// Clear chat history
const aiClearBtn = document.getElementById('ai-clear-btn');
if (aiClearBtn) {
    aiClearBtn.addEventListener('click', async () => {
        if (!confirm('Tem a certeza que deseja apagar todo o histórico de conversa?')) return;
        
        try {
            const response = await fetch('/api/ai/clear-history', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' }
            });
            
            const data = await response.json();
            if (data.success) {
                // Clear all messages except the initial greeting
                aiMessagesEl.innerHTML = `
                    <div class="ai-message-bot" style="align-self: flex-start;">
                        <div style="display: flex; align-items: center; gap: 10px; margin-bottom: 8px;">
                            <img src="/static/images/logo.png" alt="IG Radio" style="width: 32px; height: 32px; border-radius: 50%;">
                            <span style="font-weight: 700; color: #ff007f; font-size: 0.85rem;">IG Radio IA</span>
                        </div>
                        <p>🎤 Olá! Sou o assistente IA do IG Radio. Qual é a tua pergunta?</p>
                    </div>
                `;
                alert('Histórico apagado com sucesso!');
            } else {
                alert('Erro ao apagar histórico: ' + (data.error || 'Erro desconhecido'));
            }
        } catch (err) {
            alert('Erro de conexão: ' + err.message);
        }
    });
}
/* ----------------------------------------------------
   MURAL DE VOTA��O
   ---------------------------------------------------- */
async function loadPoll() {
    const pollList = document.getElementById("poll-list");
    const pollBox = document.getElementById("poll-box");
    if (!pollList) return;

    try {
        const res = await fetch("/api/poll/list");
        const data = await res.json();

        if (data.success && data.songs.length > 0) {
            pollBox.classList.remove("hidden");
            pollList.innerHTML = "";
            data.songs.forEach(s => {
                const li = document.createElement("li");
                const canVote = !data.has_voted_any;
                li.innerHTML = `
                    <div class="poll-info">
                        <strong>${s.title}</strong>
                        <small>${s.artist}</small>
                    </div>
                    <div class="poll-actions">
                        <span class="vote-count" id="votes-${s.id}">${s.votes} votos</span>
                        <button class="btn small ${s.voted ? "success" : "secondary"}" 
                                onclick="votePoll(${s.id})" ${(!canVote && !s.voted) ? "disabled" : ""}>
                            ${s.voted ? "Votado" : "Votar"}
                        </button>
                    </div>
                `;
                pollList.appendChild(li);
            });
        } else {
            pollBox.classList.remove("hidden");
            pollList.innerHTML = '<p style="text-align: center; color: var(--text-muted); padding: 20px; font-size: 0.9rem;">Nenhuma votação ativa de momento.</p>';
        }
    } catch (err) {
        console.error("Poll load error:", err);
    }
}

async function votePoll(id) {
    try {
        const res = await fetch(`/api/poll/vote/${id}`, { method: "POST" });
        const data = await res.json();
        if (data.success) {
            loadPoll(); // Reload to update UI
        } else {
            alert(data.error || "Erro ao votar.");
        }
    } catch (err) {
        console.error("Vote poll error:", err);
    }
}

    // Load poll on start
    document.addEventListener("DOMContentLoaded", () => {
        loadPoll();
    });
}

// Mobile menu toggle
document.addEventListener("DOMContentLoaded", () => {
    const menuBtn = document.querySelector('.mobile-menu-btn');
    if (menuBtn) {
        menuBtn.onclick = toggleMobileMenu;
    }
});

function toggleMobileMenu() {
    const overlay = document.getElementById('mobileOverlay');
    const btn = document.querySelector('.mobile-menu-btn');
    if (!overlay) return;
    
    overlay.classList.toggle('active');
    btn.textContent = overlay.classList.contains('active') ? '✕' : '☰';
    document.body.style.overflow = overlay.classList.contains('active') ? 'hidden' : '';
}

// Theme toggle: apply/persist theme and update button icon
function applyTheme(theme) {
    document.documentElement.setAttribute('data-theme', theme);
    const btn = document.getElementById('theme-toggle');
    if (btn) {
        btn.textContent = theme === 'light' ? '🌞' : '🌙';
        btn.setAttribute('aria-pressed', theme === 'light' ? 'true' : 'false');
    }
}

(function initTheme(){
    const saved = localStorage.getItem('theme');
    const prefersLight = window.matchMedia && window.matchMedia('(prefers-color-scheme: light)').matches;
    const theme = saved || (prefersLight ? 'light' : 'dark');

    document.addEventListener('DOMContentLoaded', () => {
        applyTheme(theme);

        const tbtn = document.getElementById('theme-toggle');
        if (tbtn) {
            tbtn.addEventListener('click', () => {
                const current = document.documentElement.getAttribute('data-theme') === 'light' ? 'dark' : 'light';
                applyTheme(current);
                localStorage.setItem('theme', current);
            });
        }
    });
})();

