<?php include 'includes/header.php'; ?>
<style>
.chat-shell{max-width:1380px;margin:0 auto;}
.chat-layout{display:flex;flex-direction:column;gap:1.2rem;}
.chat-panel,.chat-compose{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:560px;max-height:560px;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-compose{padding:1.2rem;}
.chat-compose label{display:block;margin-bottom:.35rem;}
.chat-compose .form-control{background:rgba(0,0,0,.28);border:1px solid var(--accent-color);color:#fff;}
.chat-compose .form-control::placeholder{color:#9fe9cf;}
.chat-compose textarea.form-control{min-height:140px;resize:vertical;}
.chat-form-grid{display:grid;grid-template-columns:minmax(220px,300px) minmax(0,1fr);gap:1rem;align-items:start;}
.chat-toolbar{display:flex;gap:.6rem;flex-wrap:wrap;margin:.4rem 0 1rem;}
.emoji-panel{display:grid;grid-template-columns:repeat(12,minmax(0,1fr));gap:.45rem;margin-top:.6rem;padding:.9rem;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:.55rem;font-size:1.15rem;line-height:1;cursor:pointer;}
.emoji-btn:hover{background:rgba(0,204,136,.18);}
.chat-status{margin-bottom:1rem;color:var(--accent-color);}
.chat-help{opacity:.82;font-size:.92rem;margin-top:.35rem;}
@media (max-width: 991px){
  .chat-form-grid{grid-template-columns:1fr;}
  .emoji-panel{grid-template-columns:repeat(8,minmax(0,1fr));}
}
@media (max-width: 767px){
  .chat-log{min-height:360px;max-height:360px;}
  .emoji-panel{grid-template-columns:repeat(6,minmax(0,1fr));}
}
</style>
<div class="container content-box mt-5 chat-shell">
  <div class="text-center mb-4"><h1>Underground FX Chat</h1><p class="subtext">Jump into the website chat or hit Discord for the wider Underground FX live community.</p><div class="ugfx-sticker-strip justify-content-center mt-3"><img src="/assets/images/ugfx-equalizer.gif" alt=""><img src="/assets/images/ugfx-vinyl.gif" alt=""><img src="/assets/images/ugfx-mic.gif" alt=""></div></div>
  <div class="chat-layout">
    <div class="chat-panel">
      <div id="chatStatus" class="chat-status">Loading chat…</div>
      <div id="chatMessages" class="chat-log"></div>
    </div>

    <div class="chat-compose">
      <form id="chatForm">
        <div class="chat-form-grid">
          <div>
            <div class="mb-3">
              <label for="chatNameInput">Your name</label>
              <input type="text" id="chatNameInput" class="form-control" name="name" maxlength="24" placeholder="Enter your chat name" required>
              <div class="chat-help">Your name stays filled in while you keep this page open.</div>
            </div>
          </div>
          <div>
            <div class="mb-3">
              <label for="chatMessageBox">Message</label>
              <textarea id="chatMessageBox" class="form-control" name="msg" rows="5" 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>
          </div>
        </div>
      </form>
    </div>
  </div>
</div>
<script>
const emojiList = ['😀','😁','😂','🤣','😊','😍','🥰','😎','🤠','🎶','🎵','🎼','🎧','🎙️','📻','📀','💿','🪩','🎚️','🎛️','🎤','🎷','🎸','🥁','🕺','💃','🔥','⚡','🌟','⭐','💯','🙌','👏','🫶','❤️','🧡','💛','💚','💙','💜','🎉','🥳','🚀','🌙','☕','🎵','🎶','📡','🔊','🔉','🔈','🎵','🎶','🤩','😇','👍'];
const emojiPanel = document.getElementById('emojiPanel');
const emojiToggle = document.getElementById('emojiToggle');
const chatBox = document.getElementById('chatMessageBox');
const chatNameInput = document.getElementById('chatNameInput');
const chatStatus = document.getElementById('chatStatus');
const chatForm = document.getElementById('chatForm');
const nameStorageKey = 'ugfx_chat_name';
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])); }
try {
  const savedName = sessionStorage.getItem(nameStorageKey);
  if (savedName) chatNameInput.value = savedName;
} catch (e) {}
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();
    const wrap=document.getElementById('chatMessages');
    wrap.innerHTML='';
    if(!data.ok){
      chatStatus.textContent = data.error || 'Chat is unavailable right now.';
      return;
    }
    chatStatus.textContent = 'Underground FX chat is live — say hello and drop a music emoji!';
    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.';
  }
}
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){
    chatBox.value='';
    emojiPanel.hidden = true;
    try { sessionStorage.setItem(nameStorageKey, chatNameInput.value.trim()); } catch (e) {}
    loadChat();
    chatBox.focus();
  } else {
    alert(data.error||'Could not send message.');
  }
});
loadChat(); setInterval(loadChat,15000);
</script>
<?php include 'includes/footer.php'; ?>
