<?php $pageTitle='Live Chat — Almost Heaven Radio'; include __DIR__ . '/header.php'; include __DIR__ . '/menu.php'; ?>
<main class="content-area"><div class="content-wrapper page-shell"><section class="content-card"><h1>💬 Live Chat</h1><p>Chat with other listeners in Almost Heaven.</p><div id="chat-box" class="comment-item" style="min-height:320px;max-height:480px;overflow:auto;margin-top:18px;"></div><div class="comment-form-row" style="margin-top:14px;"><input id="chat-name" type="text" placeholder="Your name"><textarea id="chat-message" placeholder="Your message"></textarea><button id="chat-send" class="play-button" type="button">Send</button></div></section></div></main>
<?php include __DIR__ . '/footer.php'; ?>
<script>
const box=document.getElementById('chat-box'),nameEl=document.getElementById('chat-name'),msgEl=document.getElementById('chat-message'),sendEl=document.getElementById('chat-send');
const chatGetUrl='api/chat_get.php', chatPostUrl='api/chat_post.php';
function esc(s){return String(s||'').replace(/[&<>"']/g,c=>({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[c]));}
function render(messages){box.innerHTML=(messages||[]).map(m=>`<div class="comment-item" style="margin-bottom:10px;"><strong>${esc(m.name||'Guest')}</strong><br>${esc(m.msg||'')}</div>`).join('') || '<div class="comment-item">No messages yet.</div>'; box.scrollTop=box.scrollHeight;}
async function pull(){try{const r=await fetch(chatGetUrl,{cache:'no-store'});const j=await r.json(); if(j.ok) render(j.messages||[]); else box.innerHTML='<div class="comment-item">'+esc(j.error||'Chat offline')+'</div>'; }catch(e){ box.innerHTML='<div class="comment-item">Unable to load chat right now.</div>'; }}
async function send(){const fd=new FormData();fd.append('name',nameEl.value.trim());fd.append('msg',msgEl.value.trim()); if(!fd.get('name')||!fd.get('msg')) return; try{const r=await fetch(chatPostUrl,{method:'POST',body:fd});const j=await r.json(); if(j.ok){msgEl.value=''; pull();} else if(j.error){ alert(j.error); }}catch(e){}}
sendEl.addEventListener('click',send); pull(); setInterval(pull,5000);
</script>