<?php
session_start();
$pageTitle = "Live Chat";
include __DIR__ . '/includes/header.php';
include __DIR__ . '/includes/nav.php';

$settingsFile = __DIR__ . '/data/settings.json';
$settings = [];
if (file_exists($settingsFile)) {
  $settings = json_decode(file_get_contents($settingsFile), true);
  if (!is_array($settings)) $settings = [];
}

$chatEnabled = !empty($settings['chat_enabled']);
$chatLiveNow = !empty($settings['chat_live_now']);

?>
<main class="content-area">
  <div class="content-wrapper">
<div class="content-card">
    <h1 style="margin:0 0 6px 0;">💬 Live Chat</h1>
    <div style="opacity:.85;">Chat with other listeners in Smurfy Village.</div>
  </div>

  <div class="smurf-divider"></div>

  <?php if (!$chatEnabled || !$chatLiveNow): ?>
    <div class="content-card" style="text-align:center; padding:26px;">
      <div style="font-size:1.2em;font-weight:800;">Chat is currently offline</div>
      <div style="opacity:.85;margin-top:8px;">We open chat when a live DJ is on air. Check back soon!</div>
    </div>
  <?php else: ?>
    <div class="content-card chat-card" style="text-align:left;">
      <div id="chatBox" class="chat-box" aria-live="polite"></div>

      <div class="chat-controls">
        <input id="chatName" class="request-input" type="text" placeholder="Your nickname" maxlength="24">
        <div class="chat-input-row">
          <input id="chatMsg" class="request-input" type="text" placeholder="Type a message…" maxlength="240">
          <button id="chatSend" class="btn btn-accent" type="button">Send</button>
        </div>

        <div class="chat-emoji">
  <button type="button" id="emojiToggle" class="btn btn-accent btn-emoji">😊 Emojis</button>
  <div id="emojiPanel" class="emoji-panel" aria-hidden="true">
    <div class="emoji-search-row">
      <input id="emojiSearch" class="request-input emoji-search" type="text" placeholder="Search… (try: heart, music, smile)" maxlength="30">
      <button type="button" id="emojiClose" class="btn btn-accent btn-emoji-close">Close</button>
    </div>
    <div id="emojiGrid" class="emoji-grid"></div>
  </div>
</div>

<div class="chat-hint">Be kind. Spam gets auto-blocked. 🙂</div>
Be kind. Spam gets auto-blocked. 🙂</div>
      </div>
    </div>
  <?php endif; ?>
  </div>
</main>

<script>
(function(){
  const enabled = <?= ($chatEnabled && $chatLiveNow) ? 'true' : 'false' ?>;
  if (!enabled) return;

  const box = document.getElementById('chatBox');
  const nameEl = document.getElementById('chatName');
  const msgEl  = document.getElementById('chatMsg');
  const sendEl = document.getElementById('chatSend');
  
  
const emojiToggle = document.getElementById('emojiToggle');
const emojiPanel  = document.getElementById('emojiPanel');
const emojiGrid   = document.getElementById('emojiGrid');
const emojiSearch = document.getElementById('emojiSearch');
const emojiClose  = document.getElementById('emojiClose');

// A few hundred emojis (curated) + keywords for search
const EMOJIS = [
  // smileys
  ["😀","smile"],["😁","grin"],["😂","laugh"],["🤣","rofl"],["😊","happy"],["😍","love"],["🥰","love"],["😘","kiss"],["😎","cool"],["🤠","cowboy"],
  ["🙂","smile"],["😉","wink"],["😇","angel"],["🤩","star"],["🥳","party"],["😴","sleep"],["🤔","think"],["🙃","silly"],["😬","awkward"],["😭","cry"],
  ["😡","angry"],["😱","shock"],["🤗","hug"],["🤐","zip"],["🤫","shh"],["😜","tongue"],["😋","yum"],["😌","relief"],["🥺","please"],["😅","sweat"],
  // hearts
  ["❤️","heart"],["🧡","heart"],["💛","heart"],["💚","heart"],["💙","heart"],["💜","heart"],["🖤","heart"],["🤍","heart"],["🤎","heart"],["💖","sparkle"],
  ["💘","heart"],["💝","gift"],["💞","hearts"],["💕","hearts"],["💓","heart"],["💗","heart"],["💯","100"],
  // music
  ["🎵","music"],["🎶","music"],["🎧","headphones"],["🎤","mic"],["🎸","guitar"],["🎻","violin"],["🥁","drum"],["🎹","piano"],["📻","radio"],["🔊","loud"],
  // fire / hype
  ["🔥","fire"],["✨","sparkle"],["🌟","star"],["⚡","zap"],["💥","boom"],["👏","clap"],["🙌","yay"],["👍","thumbs up"],["👎","thumbs down"],["👌","ok"],
  // country / fun
  ["🤠","cowboy"],["🐎","horse"],["🌵","cactus"],["🏜️","desert"],["🪕","banjo"],["🥃","drink"],["🍻","cheers"],["🍔","burger"],["🍕","pizza"],
  // misc
  ["✅","check"],["❌","x"],["🕺","dance"],["💃","dance"],["🎉","party"],["🎁","gift"],["🏆","trophy"],["📣","megaphone"],["📝","note"],["📌","pin"],
  ["👀","eyes"],["🫶","hands"],["🙏","pray"],["🤝","shake"],["💬","chat"],["📢","announce"],["🔔","bell"],["⏰","clock"],["🌈","rainbow"],["☀️","sun"],
  ["🌙","moon"],["⭐","star"],["☕","coffee"],["🍀","luck"],["🎯","target"],["🚀","rocket"],["🧠","brain"],["🧡","heart"],["💙","heart"],["😺","cat"],
  ["🐶","dog"],["🐼","panda"],["🦊","fox"],["🐸","frog"],["🐵","monkey"],["🦋","butterfly"],["🌸","flower"],["🌻","flower"],["🌹","rose"],["🍁","leaf"],
  ["❄️","snow"],["🌊","wave"],["🏝️","island"],["🏕️","camp"],["🏠","home"],["🚗","car"],["✈️","plane"],["📸","photo"],["🎬","movie"],["📺","tv"]
];

function buildEmojiGrid(filterText){
  const q = (filterText||'').trim().toLowerCase();
  emojiGrid.innerHTML = '';
  let shown = 0;
  for (const [ch, key] of EMOJIS){
    if (q && !(key.includes(q) || ch === q)) continue;
    const b = document.createElement('button');
    b.type = 'button';
    b.className = 'emoji-pick';
    b.textContent = ch;
    b.title = key;
    b.addEventListener('click', () => {
      msgEl.value = (msgEl.value || '') + ch;
      msgEl.focus();
    });
    emojiGrid.appendChild(b);
    shown++;
  }
  if (!shown){
    const d = document.createElement('div');
    d.className = 'emoji-empty';
    d.textContent = 'No matches. Try: heart, music, smile, party…';
    emojiGrid.appendChild(d);
  }
}

function openEmoji(){
  emojiPanel.setAttribute('aria-hidden','false');
  emojiPanel.classList.add('open');
  buildEmojiGrid(emojiSearch.value);
  setTimeout(()=>emojiSearch.focus(), 0);
}
function closeEmoji(){
  emojiPanel.setAttribute('aria-hidden','true');
  emojiPanel.classList.remove('open');
}

emojiToggle?.addEventListener('click', () => {
  if (emojiPanel.classList.contains('open')) closeEmoji();
  else openEmoji();
});
emojiClose?.addEventListener('click', closeEmoji);
emojiSearch?.addEventListener('input', () => buildEmojiGrid(emojiSearch.value));

const storageKey = 'smurf_chat_name';
  nameEl.value = localStorage.getItem(storageKey) || '';

  let lastTs = 0;
  let pulling = false;

  function esc(s){ return (s||'').replace(/[&<>"]/g, c=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;' }[c])); }

  function render(messages){
    if (!Array.isArray(messages)) return;
    let atBottom = (box.scrollTop + box.clientHeight + 40) >= box.scrollHeight;

    let html = '';
    for (const m of messages){
      const cls = (m.role === 'admin') ? 'chat-msg admin' : 'chat-msg';
      const who = esc(m.name || 'Guest');
      const text = esc(m.msg || '');
      const t = m.time ? esc(m.time) : '';
      html += `<div class="${cls}"><div class="meta"><span class="who">${who}</span><span class="time">${t}</span></div><div class="text">${text}</div></div>`;
    }
    box.innerHTML = html;

    if (atBottom) box.scrollTop = box.scrollHeight;
  }

  async function pull(){
    if (pulling) return;
    pulling = true;
    try{
      const r = await fetch('/api/chat_get.php?since=' + encodeURIComponent(lastTs), {cache:'no-store'});
      const j = await r.json();
      if (j && j.ok){
        lastTs = j.ts || lastTs;
        render(j.messages || []);
      }
    }catch(e){}
    pulling = false;
  }

  async function send(){
    const name = (nameEl.value || '').trim();
    const msg  = (msgEl.value || '').trim();
    if (!name || !msg) return;

    localStorage.setItem(storageKey, name);

    sendEl.disabled = true;
    try{
      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 && j.ok){
        msgEl.value = '';
        await pull();
      } else {
        alert(j.error || 'Unable to send message');
      }
    }catch(e){
      alert('Unable to send message');
    }
    sendEl.disabled = false;
  }

  sendEl.addEventListener('click', send);
  msgEl.addEventListener('keydown', (e)=>{ if (e.key === 'Enter') send(); });    });
  });

  pull();
  setInterval(pull, 2000);
})();
</script>

<?php include __DIR__ . '/includes/footer.php'; ?>
