
<?php
session_start();
$pageTitle = 'Live Chat — Oldies And More Radio';
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/sidebar.php';
require_once __DIR__ . '/includes/app_lib.php';
$settings = oldies_read_settings();
?>
<div class="main-wrap"><div class="content-panel">
  <div class="content-box center-text"><h1 class="section-title">💬 Live Chat</h1><p class="about-text">Chat with fellow listeners while the oldies roll.</p></div>
  <div class="vinyl-divider center-divider"></div>
  <?php if (empty($settings['chat_enabled'])): ?>
    <div class="content-box center-text"><p class="about-text">Chat is offline right now.</p></div>
  <?php else: ?>
    <div class="neon-card chat-card">
      <div class="request-field"><label>Your Name</label><input id="chatName" class="request-input" maxlength="24" placeholder="Jukebox Fan"></div>
      <div id="chatBox" class="chat-box" aria-live="polite"></div>
      <div class="request-field" style="margin-top:14px;"><label>Your Message</label><input id="chatMsg" class="request-input" maxlength="240" placeholder="Say hello to the room..."></div>
      <div class="button-row"><button id="emojiToggle" type="button" class="admin-btn">😊 Emojis</button><button id="sendBtn" type="button" class="button radio-static" style="width:auto;">Send</button></div>
      <div id="emojiPanel" class="emoji-panel" aria-hidden="true"><input id="emojiSearch" class="request-input" type="text" placeholder="Search emoji keywords"><div id="emojiGrid" class="emoji-grid"></div></div>
    </div>
  <?php endif; ?>
<?php include __DIR__ . '/includes/footer.php'; ?>
</div></div>
<script>
(function(){
  const box = document.getElementById('chatBox'), nameEl = document.getElementById('chatName'), msgEl = document.getElementById('chatMsg'), sendEl = document.getElementById('sendBtn');
  if (!box || !nameEl || !msgEl || !sendEl) return;
  const emojiToggle = document.getElementById('emojiToggle'), emojiPanel = document.getElementById('emojiPanel'), emojiGrid = document.getElementById('emojiGrid'), emojiSearch = document.getElementById('emojiSearch');
  const EMOJIS = [['😀','smile'],['😂','laugh'],['😊','happy'],['😍','love'],['🤠','cowboy'],['🎵','music'],['🎶','music'],['🎧','headphones'],['🎤','mic'],['📻','radio'],['🔥','fire'],['✨','sparkle'],['💙','heart'],['⭐','star'],['👏','clap'],['🎉','party'],['🕺','dance'],['💬','chat']];
  const esc = s => String(s||'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));
  function renderEmoji(q=''){ const needle = q.toLowerCase().trim(); emojiGrid.innerHTML = EMOJIS.filter(([e,k])=>!needle || k.includes(needle)).map(([e])=>`<button class="emoji-pick" type="button" data-e="${e}">${e}</button>`).join('') || '<div>No matches</div>'; }
  emojiToggle.addEventListener('click', ()=>{ emojiPanel.classList.toggle('open'); renderEmoji(emojiSearch.value); });
  emojiSearch.addEventListener('input', ()=>renderEmoji(emojiSearch.value));
  emojiGrid.addEventListener('click', e=>{ const btn=e.target.closest('.emoji-pick'); if(!btn) return; msgEl.value += btn.dataset.e; msgEl.focus(); });
  nameEl.value = localStorage.getItem('oldies_chat_name') || '';
  async function pull(){ try { const r = await fetch('/api/chat_get.php',{cache:'no-store'}); const j = await r.json(); if(!j.ok) return; box.innerHTML = (j.messages||[]).map(m => `<div class="chat-msg ${m.role==='admin'?'admin':''}"><div class="meta"><span>${esc(m.name)}</span><span>${esc(m.time)}</span></div><div class="text">${esc(m.msg)}</div></div>`).join(''); box.scrollTop = box.scrollHeight; } catch(e){} }
  async function send(){ const name=(nameEl.value||'').trim(), msg=(msgEl.value||'').trim(); if(!name||!msg) return; localStorage.setItem('oldies_chat_name', name); const fd=new FormData(); fd.append('name',name); fd.append('msg',msg); const r=await fetch('/api/chat_post.php',{method:'POST',body:fd}); const j=await r.json(); if(j.ok){ msgEl.value=''; pull(); } else { alert(j.error || 'Unable to send'); } }
  sendEl.addEventListener('click', send); msgEl.addEventListener('keydown', e=>{ if(e.key==='Enter'){ e.preventDefault(); send(); } }); pull(); setInterval(pull, 4000);
})();
</script>
