
(() => {
  const $ = (s, r=document) => r.querySelector(s);
  const $$ = (s, r=document) => [...r.querySelectorAll(s)];

  async function refreshNowPlaying() {
    try {
      const res = await fetch('api/nowplaying.php', {cache:'no-store'});
      const data = await res.json();
      const title = (data && data.title ? String(data.title) : '').trim() || 'Underground FX is live now';
      $$('[data-nowplaying]').forEach(el => el.textContent = title);
    } catch (e) {
      $$('[data-nowplaying]').forEach(el => {
        if (!el.textContent.trim()) el.textContent = 'Underground FX is live now';
      });
    }
  }

  function setupParticles() {
    const canvas = document.getElementById('fxParticles');
    if (!canvas) return;
    const ctx = canvas.getContext('2d');
    let w = canvas.width = window.innerWidth;
    let h = canvas.height = window.innerHeight;
    const count = Math.max(36, Math.floor(w / 32));
    const dots = Array.from({length: count}, () => ({
      x: Math.random() * w,
      y: Math.random() * h,
      r: Math.random() * 2.4 + 0.4,
      vx: (Math.random() - 0.5) * 0.25,
      vy: (Math.random() - 0.5) * 0.25,
      a: Math.random() * 0.5 + 0.2,
    }));
    function resize() { w = canvas.width = window.innerWidth; h = canvas.height = window.innerHeight; }
    window.addEventListener('resize', resize);
    function draw() {
      ctx.clearRect(0,0,w,h);
      for (const d of dots) {
        d.x += d.vx; d.y += d.vy;
        if (d.x < -8) d.x = w + 8; if (d.x > w + 8) d.x = -8;
        if (d.y < -8) d.y = h + 8; if (d.y > h + 8) d.y = -8;
        const g = ctx.createRadialGradient(d.x, d.y, 0, d.x, d.y, d.r*6);
        g.addColorStop(0, `rgba(255,190,90,${d.a})`);
        g.addColorStop(0.45, `rgba(255,110,0,${d.a*0.55})`);
        g.addColorStop(1, 'rgba(255,110,0,0)');
        ctx.fillStyle = g;
        ctx.beginPath(); ctx.arc(d.x, d.y, d.r*6, 0, Math.PI*2); ctx.fill();
      }
      requestAnimationFrame(draw);
    }
    draw();
  }

  function setupSparkles() {
    const shell = document.body;
    let last = 0;
    let halo = document.querySelector('.cursor-halo');
    if (!halo) {
      halo = document.createElement('span');
      halo.className = 'cursor-halo';
      document.body.appendChild(halo);
    }
    shell.addEventListener('pointermove', e => {
      halo.style.left = e.clientX + 'px';
      halo.style.top = e.clientY + 'px';
      const now = Date.now();
      if (now - last < 45) return;
      last = now;
      const s = document.createElement('span');
      s.className = 'mouse-sparkle';
      s.style.left = e.clientX + 'px';
      s.style.top = e.clientY + 'px';
      s.style.setProperty('--rot', (Math.random()*180) + 'deg');
      document.body.appendChild(s);
      setTimeout(() => s.remove(), 1300);
    }, {passive:true});
    shell.addEventListener('pointerdown', e => {
      for (let i = 0; i < 7; i++) {
        const s = document.createElement('span');
        s.className = 'mouse-sparkle sparkle-burst';
        s.style.left = e.clientX + 'px';
        s.style.top = e.clientY + 'px';
        s.style.setProperty('--rot', (i * 51) + 'deg');
        s.style.setProperty('--burst-x', ((Math.random()*70)-35) + 'px');
        s.style.setProperty('--burst-y', ((Math.random()*70)-35) + 'px');
        document.body.appendChild(s);
        setTimeout(() => s.remove(), 1200);
      }
    }, {passive:true});
  }



  function setupChatRoom() {
    const form = $('#chatForm');
    if (!form) return;
    const chatStatus = $('#chatStatus');
    const chatMessages = $('#chatMessages');
    const chatNameInput = $('#chatNameInput');
    const chatBox = $('#chatMessageBox');
    const emojiToggle = $('#emojiToggle');
    const emojiPanel = $('#emojiPanel');
    const emojiList = ['😀','😁','😂','🤣','😊','😍','🥰','😎','🤠','🎶','🎵','🎧','🎙️','📻','💚','🔥','👏','🙌','❤️','💯','⭐','🌟','🥳','😇','🤩','👍','🫶','☕','🌙','🎸','🎤','🎷','🎹','🥁','🪩','🚀','✨','🎼','🧡'];
    const nameStorageKey = 'ugfx_chat_name';
    if (emojiPanel) emojiPanel.innerHTML = emojiList.map(e => `<button class="emoji-btn" type="button" data-emoji="${e}">${e}</button>`).join('');
    if (emojiToggle && emojiPanel) {
      emojiToggle.addEventListener('click', ()=> { emojiPanel.hidden = !emojiPanel.hidden; });
      emojiPanel.addEventListener('click', (e)=> {
        const btn = e.target.closest('[data-emoji]');
        if(!btn || !chatBox) return;
        chatBox.value += btn.dataset.emoji;
        chatBox.focus();
      });
    }
    function esc(s){ return (s||'').replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m])); }
    try { const saved = sessionStorage.getItem(nameStorageKey); if (saved && chatNameInput) chatNameInput.value = saved; } catch(e) {}
    if (chatNameInput) chatNameInput.addEventListener('input', ()=> { try { sessionStorage.setItem(nameStorageKey, chatNameInput.value.trim()); } catch(e) {} });
    async function loadChat(){
      try {
        const res = await fetch('api/chat_get.php?ts=' + Date.now(), {cache:'no-store'});
        const data = await res.json();
        if (!chatMessages) return;
        chatMessages.innerHTML = '';
        if (!data.ok) { if (chatStatus) chatStatus.textContent = data.error || 'Chat is offline right now.'; return; }
        if (chatStatus) chatStatus.textContent = 'Chat is live — say hello!';
        const rows = data.messages || [];
        if (!rows.length) {
          chatMessages.innerHTML = '<div class="chat-message"><div class="chat-text">No messages yet. Be the first to jump into the room.</div></div>';
          return;
        }
        rows.forEach(row => {
          const item = document.createElement('div');
          item.className = 'chat-message';
          item.innerHTML = '<div class="chat-meta"><span class="chat-name">' + esc(row.name || 'Guest') + '</span><span class="chat-time">' + esc(row.time || '') + '</span></div><div class="chat-text">' + esc(row.msg || row.message || '') + '</div>';
          chatMessages.appendChild(item);
        });
        chatMessages.scrollTop = chatMessages.scrollHeight;
      } catch (e) { if (chatStatus) chatStatus.textContent = 'Could not load chat right now.'; }
    }
    form.addEventListener('submit', async (e) => {
      e.preventDefault();
      const fd = new FormData(form);
      try {
        const res = await fetch('api/chat_post.php', {method:'POST', body:fd});
        const data = await res.json();
        if (!data.ok) { alert(data.error || 'Could not send message.'); return; }
        if (chatBox) chatBox.value = '';
        if (emojiPanel) emojiPanel.hidden = true;
        loadChat();
      } catch (err) { alert('Could not send message right now.'); }
    });
    loadChat();
    setInterval(loadChat, 15000);
  }

  function setupDJSearch() {
    const input = $('[data-dj-search]');
    if (!input) return;
    input.addEventListener('input', () => {
      const q = input.value.trim().toLowerCase();
      $$('[data-dj-card]').forEach(card => {
        const hay = card.getAttribute('data-search') || '';
        card.style.display = hay.includes(q) ? '' : 'none';
      });
    });
  }

  document.addEventListener('DOMContentLoaded', () => {
    refreshNowPlaying();
    setInterval(refreshNowPlaying, 25000);
    setupParticles();
    setupSparkles();
    setupDJSearch();
    setupChatRoom();
  });
})();
