<?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((string)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'] ?: 'DJ BLAZE';
$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 = $chatOpen;
?>
<main class="content-area">
  <div class="smurf-divider"></div>
  <div class="content-wrapper">
    <section class="content-card chat-hero-card">
      <div class="chat-hero-copy">
        <span class="section-kicker">Thunder Mountain Radio</span>
        <h1>💬 Live Chat</h1>
        <p>Hang out with Thunder Mountain listeners while the music rolls. Drop a message, throw in an emoji, and keep it friendly.</p>
        <div class="chat-status-row">
          <span class="status-pill <?= ($chatEnabled && $chatLiveNow) ? 'is-live' : 'is-offline' ?>">
            <?= ($chatEnabled && $chatLiveNow) ? 'Chat is live now' : 'Chat is currently offline' ?>
          </span>
          <span class="status-pill">Now on air: <?= htmlspecialchars($currentDJ) ?></span>
        </div>
      </div>
      <div class="chat-hero-side">
        <div class="chat-side-panel">
          <h3>House Rules</h3>
          <ul class="chat-rule-list">
            <li>Be kind to other listeners and DJs.</li>
            <li>No spam, abuse, or flooding the room.</li>
            <li>Emoji-friendly, but keep it readable.</li>
          </ul>
        </div>
      </div>
    </section>

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

    <?php if (!$chatEnabled || !$chatLiveNow): ?>
      <section class="content-card chat-offline-card">
        <h2>Chat is currently offline</h2>
        <p>We open the room when a live DJ is on air. Check back soon or keep listening for the next live show.</p>
      </section>
    <?php else: ?>
      <section class="content-card chat-shell">
        <div class="chat-shell-header">
          <div>
            <h2>Listener Lounge</h2>
            <p>Jump in, request a shoutout, or just enjoy the conversation.</p>
          </div>
          <div class="status-pill is-live">Live room open</div>
        </div>

        <div id="chatBox" class="chat-box thunder-chat-box" aria-live="polite"></div>

        <div class="chat-controls thunder-chat-controls">
          <div class="chat-form-grid">
            <div class="request-field">
              <label for="chatName">Your nickname</label>
              <input id="chatName" class="request-input" type="text" placeholder="How should we call you?" maxlength="24">
            </div>
            <div class="request-field">
              <label for="chatMsg">Your message</label>
              <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>
          </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>
        </div>
      </section>
    <?php endif; ?>
  </div>
  <div class="smurf-divider"></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');

  const EMOJIS = [
    ["😀","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"],
    ["❤️","heart"],["🧡","heart"],["💛","heart"],["💚","heart"],["💙","heart"],["💜","heart"],["🖤","heart"],["🤍","heart"],["🤎","heart"],["💖","sparkle"],
    ["💘","heart"],["💝","gift"],["💞","hearts"],["💕","hearts"],["💓","heart"],["💗","heart"],["💯","100"],
    ["🎵","music"],["🎶","music"],["🎧","headphones"],["🎤","mic"],["🎸","guitar"],["🎻","violin"],["🥁","drum"],["🎹","piano"],["📻","radio"],["🔊","loud"],
    ["🔥","fire"],["✨","sparkle"],["🌟","star"],["⚡","zap"],["💥","boom"],["👏","clap"],["🙌","yay"],["👍","thumbs up"],["👎","thumbs down"],["👌","ok"],
    ["🤠","cowboy"],["🐎","horse"],["🌵","cactus"],["🏜️","desert"],["🪕","banjo"],["🥃","drink"],["🍻","cheers"],["🍔","burger"],["🍕","pizza"],
    ["✅","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"],["😺","cat"],["🐶","dog"],["🦋","butterfly"]
  ];

  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', ()=> emojiPanel.classList.contains('open') ? closeEmoji() : 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') || '';
    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();
  });

  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, 4000);
})();
</script>
<?php include __DIR__ . '/includes/footer.php'; ?>
