<?php include 'includes/header.php'; ?>
<style>
.chat-shell{max-width:1200px;margin:0 auto;}
.chat-panel,.chat-side{background:rgba(59,43,32,.94);border:2px solid var(--accent-color);border-radius:18px;box-shadow:0 10px 24px rgba(0,0,0,.28);}
.chat-panel{padding:1.2rem;}
.chat-log{min-height:460px;max-height:460px;overflow:auto;padding:1rem;background:rgba(0,0,0,.25);border:1px solid rgba(0,204,136,.45);border-radius:14px;}
.chat-message{padding:.85rem 1rem;margin-bottom:.85rem;border-radius:14px;background:rgba(0,0,0,.28);border:1px solid rgba(0,204,136,.22);}
.chat-meta{display:flex;justify-content:space-between;gap:10px;align-items:center;margin-bottom:.35rem;flex-wrap:wrap;}
.chat-name{font-weight:700;color:var(--accent-color);}
.chat-time{opacity:.8;font-size:.92rem;}
.chat-text{white-space:pre-wrap;word-break:break-word;color:#fff;}
.chat-side{padding:1.2rem;}
.chat-side label{display:block;margin-bottom:.35rem;}
.chat-side .form-control{background:rgba(0,0,0,.28);border:1px solid var(--accent-color);color:#fff;}
.chat-side .form-control::placeholder{color:#9fe9cf;}
.chat-toolbar{display:flex;gap:.6rem;flex-wrap:wrap;margin:.4rem 0 1rem;}
.emoji-panel{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:.4rem;margin-top:.6rem;padding:.8rem;background:rgba(0,0,0,.24);border:1px solid rgba(0,204,136,.28);border-radius:14px;}
.emoji-btn{border:1px solid rgba(0,204,136,.35);background:rgba(0,0,0,.22);color:#fff;border-radius:10px;padding:.45rem;font-size:1.1rem;line-height:1;cursor:pointer;}
.emoji-btn:hover{background:rgba(0,204,136,.18);}
.chat-status{margin-bottom:1rem;color:var(--accent-color);}
@media (max-width: 767px){.emoji-panel{grid-template-columns:repeat(6,minmax(0,1fr));}.chat-log{min-height:340px;max-height:340px;}}
</style>
<div class="container content-box mt-5 chat-shell">
  <div class="text-center mb-4"><h1>Live Chat</h1><p class="subtext">Join the Home Time Radio chat room</p></div>
  <div class="row g-4">
    <div class="col-lg-8">
      <div class="chat-panel">
        <div id="chatStatus" class="chat-status">Loading chat…</div>
        <div id="chatMessages" class="chat-log"></div>
      </div>
    </div>
    <div class="col-lg-4">
      <div class="chat-side">
        <form id="chatForm">
          <div class="mb-3"><label>Your name</label><input type="text" class="form-control" name="name" maxlength="24" required></div>
          <div class="mb-3"><label>Message</label><textarea id="chatMessageBox" class="form-control" name="msg" rows="6" maxlength="240" placeholder="Type your message here…" required></textarea></div>
          <div class="chat-toolbar">
            <button class="btn btn-dark" type="submit">Send Message</button>
            <button class="btn btn-accent" type="button" id="emojiToggle">😊 Emojis</button>
          </div>
          <div id="emojiPanel" class="emoji-panel" hidden></div>
        </form>
      </div>
    </div>
  </div>
</div>
<script>
const emojiList = ['😀','😁','😂','🤣','😊','😍','🥰','😎','🤠','🎶','🎵','🎧','🎙️','📻','💚','🔥','👏','🙌','❤️','💯','⭐','🌟','🥳','😇','🤩','👍','🫶','☕','🌙','🎸','🎤','🎷'];
const emojiPanel = document.getElementById('emojiPanel');
const emojiToggle = document.getElementById('emojiToggle');
const chatBox = document.getElementById('chatMessageBox');
const chatStatus = document.getElementById('chatStatus');
emojiPanel.innerHTML = emojiList.map(e => `<button class="emoji-btn" type="button" data-emoji="${e}">${e}</button>`).join('');
emojiToggle.addEventListener('click', ()=> { emojiPanel.hidden = !emojiPanel.hidden; });
emojiPanel.addEventListener('click', (e)=> { const btn = e.target.closest('[data-emoji]'); if(!btn) return; chatBox.value += btn.dataset.emoji; chatBox.focus(); });
function esc(s){ return (s||'').replace(/[&<>"]/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;'}[m])); }
async function loadChat(){
  try {
    const res=await fetch('api/chat_get.php?ts='+Date.now(),{cache:'no-store'});
    const data=await res.json();
    const wrap=document.getElementById('chatMessages');
    wrap.innerHTML='';
    if(!data.ok){
      chatStatus.textContent = data.error || 'Chat is unavailable right now.';
      return;
    }
    chatStatus.textContent = 'Chat is live — say hello!';
    const rows = data.messages || [];
    if (!rows.length) {
      wrap.innerHTML = '<div class="chat-message"><div class="chat-text">No messages yet. Be the first to say hello.</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>';
      wrap.appendChild(item);
    });
    wrap.scrollTop=wrap.scrollHeight;
  } catch (err) {
    chatStatus.textContent = 'Could not load chat right now.';
  }
}
document.getElementById('chatForm').addEventListener('submit',async function(e){
  e.preventDefault();
  const fd=new FormData(this);
  const res=await fetch('api/chat_post.php',{method:'POST',body:fd});
  const data=await res.json();
  if(data.ok){ this.reset(); emojiPanel.hidden = true; loadChat(); } else { alert(data.error||'Could not send message.'); }
});
loadChat(); setInterval(loadChat,15000);
</script>
<?php include 'includes/footer.php'; ?>
