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

$settingsFile = __DIR__ . '/data/settings.json';
$settings = [];
if (file_exists($settingsFile)) {
  $settings = json_decode(file_get_contents($settingsFile), true);
  if (!is_array($settings)) $settings = [];
$schedule = smurf_load_schedule_hourmap(__DIR__ . '/data/schedule.json', __DIR__ . '/data/schedule.txt', $SMURF_DAYS_ORDER);
$nn = smurf_schedule_now_next($schedule);
$currentDJ = $nn['now'] ?: 'Cosmic Vibes';
$isLive = smurf_is_live_dj($currentDJ, $settings);
$requireLive = array_key_exists('chat_require_live', $settings) ? !empty($settings['chat_require_live']) : true;
$chatOpen = (!empty($settings['chat_enabled']) && (!$requireLive || $isLive));
}

$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');

  // --- Emoji Picker ---
  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');

  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();
    let html = '';
    for (const [emo, keys] of EMOJIS){
      if (!q || (keys && keys.toLowerCase().includes(q)) || emo.includes(q)){
        html += `<button type="button" class="emoji-pick" data-emo="${emo}">${emo}</button>`;
      }
    }
    emojiGrid.innerHTML = html || '<div style="opacity:.8;padding:8px;">No matches</div>';
  }

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

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

  emojiGrid.addEventListener('click', (e)=>{
    const btn = e.target.closest('.emoji-pick');
    if (!btn) return;
    const emo = btn.getAttribute('data-emo') || '';
    // insert at cursor
    const start = msgEl.selectionStart ?? msgEl.value.length;
    const end   = msgEl.selectionEnd ?? msgEl.value.length;
    msgEl.value = msgEl.value.slice(0,start) + emo + msgEl.value.slice(end);
    msgEl.focus();
    msgEl.selectionStart = msgEl.selectionEnd = start + emo.length;
  });

  document.addEventListener('keydown', (e)=>{
    if (e.key === 'Escape') closeEmoji();
  });
  document.addEventListener('click', (e)=>{
    if (!emojiPanel.classList.contains('open')) return;
    if (emojiPanel.contains(e.target) || emojiToggle.contains(e.target)) return;
    closeEmoji();
  });

  // --- Chat ---
  const storageKey = 'smurf_chat_name';
  const saved = localStorage.getItem(storageKey);
  if (saved) nameEl.value = saved;

  let lastTs = 0;
  let pulling = false;

  const esc = (s)=> String(s||'').replace(/[&<>"']/g, c=>({ '&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;' }[c]));
  function isAtBottom(el){ return (el.scrollTop + el.clientHeight) >= (el.scrollHeight - 20); }

  function render(messages){
    const atBottom = isAtBottom(box);
    let html = '';
    for (const m of (messages||[])){
      const cls = m.role === 'admin' ? 'chat-msg admin' : 'chat-msg';
      const who = esc(m.name || 'Guest');
      const t   = esc(m.time || '');
      const text = esc(m.msg || '');
      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 && j.error) ? 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'; ?>
