<?php
declare(strict_types=1);

/**
 * /includes/emoji_picker.php
 * Єдиний Emoji picker для всіх сторінок:
 * - Працює для будь-якого блоку .vm-emoji-wrap з textarea.js-emoji-target
 * - i18n підтягує з $vmEmojiI18n (якщо задано), інакше використовує t()
 * - Зберігає "recent" у localStorage (vm_emoji_recent_v1)
 *
 * Використання на сторінці:
 *   $vmEmojiI18n = [
 *     'searchPh' => '...',
 *     'recentEmpty' => '...',
 *     'tabRecent' => '...',
 *     'tabSmileys' => '...',
 *     'tabGestures' => '...',
 *     'tabLove' => '...',
 *     'tabFood' => '...',
 *     'tabObjects' => '...'
 *   ];
 *   require __DIR__ . '/includes/emoji_picker.php';
 */

if (!function_exists('t')) {
    // fallback якщо include підключили не через start.php
    function t(string $k): string { return $k; }
}

$vmEmojiI18n = $vmEmojiI18n ?? [];

$__i18n = [
  'searchPh'     => (string)($vmEmojiI18n['searchPh']     ?? t('emoji_search')),
  'recentEmpty'  => (string)($vmEmojiI18n['recentEmpty']  ?? t('emoji_recent_empty')),
  'tabRecent'    => (string)($vmEmojiI18n['tabRecent']    ?? t('emoji_tab_recent')),
  'tabSmileys'   => (string)($vmEmojiI18n['tabSmileys']   ?? t('emoji_tab_smileys')),
  'tabGestures'  => (string)($vmEmojiI18n['tabGestures']  ?? t('emoji_tab_gestures')),
  'tabLove'      => (string)($vmEmojiI18n['tabLove']      ?? t('emoji_tab_love')),
  'tabFood'      => (string)($vmEmojiI18n['tabFood']      ?? t('emoji_tab_food')),
  'tabObjects'   => (string)($vmEmojiI18n['tabObjects']   ?? t('emoji_tab_objects')),
];

// Якщо в i18n ключів ще нема — ставимо нормальні дефолти (три мови вже є у тебе на сторінках через $T)
foreach ($__i18n as $k => $v) {
  if ($v === '' || $v === $k) {
    // дуже базові дефолти англ
    $fallback = [
      'searchPh' => 'Search emoji...',
      'recentEmpty' => 'No recent emoji yet',
      'tabRecent' => 'Recent',
      'tabSmileys' => 'Smileys',
      'tabGestures' => 'Gestures',
      'tabLove' => 'Love',
      'tabFood' => 'Food',
      'tabObjects' => 'Objects',
    ];
    $__i18n[$k] = $fallback[$k] ?? $k;
  }
}
?>

<style>
/* ===== Emoji picker (global) ===== */
.vm-emoji-wrap{ position:relative; }
.vm-emoji-btn{
  position:absolute;
  right:10px;
  bottom:10px;
  width:34px;
  height:34px;
  border-radius:12px;
  border:1px solid rgba(0,0,0,.12);
  background:#fff;
  cursor:pointer;
  display:flex;
  align-items:center;
  justify-content:center;
  font-size:18px;
  line-height:1;
}
.vm-emoji-btn:hover{ background:#f8f9fa; }
.vm-emoji-btn:active{ transform: translateY(1px); }

.vm-emoji-pop{
  position:absolute;
  right:0;
  top:100%;
  margin-top:8px;
  width:340px;
  max-width:92vw;
  background:#fff;
  border:1px solid rgba(0,0,0,.12);
  border-radius:16px;
  box-shadow: 0 10px 30px rgba(0,0,0,.12);
  z-index: 60;
  overflow:hidden;
}

.vm-emoji-head{
  display:flex;
  align-items:center;
  justify-content:space-between;
  gap:10px;
  padding:10px 10px 8px 10px;
  border-bottom:1px solid rgba(0,0,0,.08);
}
.vm-emoji-tabs{ display:flex; gap:6px; flex-wrap:wrap; }
.vm-emoji-tab{
  border:1px solid rgba(0,0,0,.10);
  background:#fff;
  border-radius:12px;
  padding:4px 8px;
  cursor:pointer;
  font-size:14px;
  line-height:1;
}
.vm-emoji-tab.active{ background:#f1f3f5; }

.vm-emoji-close{
  width:30px;
  height:30px;
  border-radius:10px;
  border:1px solid rgba(0,0,0,.12);
  background:#fff;
  cursor:pointer;
}

.vm-emoji-search{ padding:8px 10px; border-bottom:1px solid rgba(0,0,0,.06); }
.vm-emoji-grid{
  padding:10px;
  display:grid;
  grid-template-columns: repeat(8, 1fr);
  gap:6px;
  max-height: 260px;
  overflow:auto;
}
.vm-emoji-item{
  width:100%;
  aspect-ratio: 1 / 1;
  border-radius:12px;
  border:1px solid transparent;
  background:#fff;
  cursor:pointer;
  font-size:20px;
  display:flex;
  align-items:center;
  justify-content:center;
}
.vm-emoji-item:hover{ background:#f8f9fa; border-color: rgba(0,0,0,.08); }
.vm-emoji-foot{ padding:8px 10px 10px 10px; border-top:1px solid rgba(0,0,0,.06); }
@media (max-width: 420px){
  .vm-emoji-grid{ grid-template-columns: repeat(7, 1fr); }
}
</style>

<script>
(function(){
  const EMOJI_I18N = <?= json_encode($__i18n, JSON_UNESCAPED_UNICODE) ?>;

  const EMOJI = [
    { id:'recent',  label:'🕘', title: EMOJI_I18N.tabRecent, items:[] },
    { id:'smileys', label:'😀', title: EMOJI_I18N.tabSmileys, items:[
      '😀','😁','😂','🤣','😅','😊','🙂','😉','😍','😘','😋','😎','🤩','🥳','😴','😪','😮','😯','😲','😳','😤','😡','🤬','😭','😱','🤔','🤗','😇','🙃','😐','😑','🙄','😬','🤐','😷','🤒','🤕'
    ]},
    { id:'gest',    label:'👍', title: EMOJI_I18N.tabGestures, items:[
      '👍','👎','👏','🙏','🤝','👌','✌️','🤞','🤟','🤘','👊','✊','🤜','🤛','🫶','💪','🖐️','✋','🤚','👋','🫡','🤌','🫵'
    ]},
    { id:'love',    label:'❤️', title: EMOJI_I18N.tabLove, items:[
      '❤️','🧡','💛','💚','💙','💜','🖤','🤍','🤎','💔','❤️‍🔥','❤️‍🩹','💕','💞','💓','💗','💖','💘','💝','💟','😍','😘'
    ]},
    { id:'food',    label:'🍕', title: EMOJI_I18N.tabFood, items:[
      '☕','🍵','🍔','🍟','🍕','🌭','🥪','🍗','🍖','🥗','🍣','🍱','🍜','🍩','🍪','🍰','🍫','🍎','🍌','🍇','🍓'
    ]},
    { id:'obj',     label:'🔥', title: EMOJI_I18N.tabObjects, items:[
      '🔥','✨','💥','⭐','🌟','⚡','💡','📌','📎','🧠','💻','📱','📷','🎥','🎧','🎮','🎁','✅','❌','⚠️','💬','🗨️','📢','🔒','🔓'
    ]}
  ];

  const RECENT_KEY = 'vm_emoji_recent_v1';
  const RECENT_MAX = 24;

  function loadRecent(){
    try{
      const raw = localStorage.getItem(RECENT_KEY);
      const arr = raw ? JSON.parse(raw) : [];
      return Array.isArray(arr) ? arr.filter(s => typeof s === 'string') : [];
    }catch(e){ return []; }
  }
  function saveRecent(arr){
    try{ localStorage.setItem(RECENT_KEY, JSON.stringify(arr.slice(0, RECENT_MAX))); }catch(e){}
  }
  function pushRecent(ch){
    const cur = loadRecent();
    const next = [ch, ...cur.filter(x => x !== ch)];
    saveRecent(next);
  }

  function insertAtCursor(textarea, text){
    if (!textarea) return;
    textarea.focus();
    const start = (textarea.selectionStart ?? textarea.value.length);
    const end   = (textarea.selectionEnd ?? textarea.value.length);
    const before = textarea.value.slice(0, start);
    const after  = textarea.value.slice(end);
    textarea.value = before + text + after;
    const pos = start + text.length;
    textarea.setSelectionRange(pos, pos);
    try{ textarea.dispatchEvent(new Event('input', { bubbles:true })); }catch(e){}
  }

  function escapeHtml(s){
    return String(s).replace(/[&<>"']/g, m => ({'&':'&amp;','<':'&lt;','>':'&gt;','"':'&quot;',"'":'&#039;'}[m]));
  }

  function buildPickerHtml(){
    return `
      <button type="button" class="vm-emoji-btn js-emoji-btn" aria-label="emoji" aria-haspopup="dialog" aria-expanded="false" title="Emoji">🙂</button>
      <div class="vm-emoji-pop d-none js-emoji-pop" role="dialog" aria-label="Emoji picker">
        <div class="vm-emoji-head">
          <div class="vm-emoji-tabs js-emoji-tabs"></div>
          <button type="button" class="vm-emoji-close js-emoji-close" aria-label="close">×</button>
        </div>
        <div class="vm-emoji-search">
          <input type="text" class="form-control form-control-sm js-emoji-search" placeholder="${escapeHtml(EMOJI_I18N.searchPh)}">
        </div>
        <div class="vm-emoji-grid js-emoji-grid" aria-label="Emoji list"></div>
        <div class="vm-emoji-foot small text-muted js-emoji-hint"></div>
      </div>
    `;
  }

  function initPickerForWrap(wrap){
    const ta = wrap.querySelector('textarea.js-emoji-target');
    if (!ta) return;

    if (wrap.dataset.emojiInit === '1') return;
    wrap.dataset.emojiInit = '1';

    wrap.insertAdjacentHTML('beforeend', buildPickerHtml());

    const btn   = wrap.querySelector('.js-emoji-btn');
    const pop   = wrap.querySelector('.js-emoji-pop');
    const tabs  = wrap.querySelector('.js-emoji-tabs');
    const grid  = wrap.querySelector('.js-emoji-grid');
    const close = wrap.querySelector('.js-emoji-close');
    const search= wrap.querySelector('.js-emoji-search');
    const hint  = wrap.querySelector('.js-emoji-hint');

    let activeCat = 'smileys';

    function setExpanded(v){ btn && btn.setAttribute('aria-expanded', v ? 'true' : 'false'); }
    function isOpen(){ return pop && !pop.classList.contains('d-none'); }
    function open(){
      if (!pop) return;
      pop.classList.remove('d-none');
      setExpanded(true);
      const r = loadRecent();
      const def = (r.length ? 'recent' : 'smileys');
      activateTab(def);
      setTimeout(() => search && search.focus(), 0);
    }
    function closePop(){
      if (!pop) return;
      pop.classList.add('d-none');
      setExpanded(false);
      if (search) search.value = '';
    }

    function getCategory(id){
      return EMOJI.find(c => c.id === id) || EMOJI.find(c => c.id === 'smileys');
    }

    function renderTabs(){
      if (!tabs) return;
      tabs.innerHTML = '';
      EMOJI.forEach(cat => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = 'vm-emoji-tab';
        b.dataset.cat = cat.id;
        b.title = cat.title;
        b.textContent = cat.label;
        b.addEventListener('click', () => activateTab(cat.id));
        tabs.appendChild(b);
      });
    }

    function renderGrid(catId, query=''){
      if (!grid) return;
      const cat = getCategory(catId);
      let items = cat.items.slice();
      if (cat.id === 'recent') items = loadRecent();

      const q = (query || '').trim().toLowerCase();

      if (q){
        const all = EMOJI.filter(c => c.id !== 'recent').flatMap(c => c.items);
        const map = {
          heart: ['❤️','🧡','💛','💚','💙','💜','🖤','🤍','🤎','💔','💕','💞','💓','💗','💖','💘','💝','💟'],
          fire: ['🔥','❤️‍🔥','💥','⚡'],
          like: ['👍','👎','👏','🙏','🤝'],
          smile: ['😀','😁','😊','🙂','😉','😍','😘','😋','😎','🤩','🥳'],
          sad: ['😭','😢','😞','😔','😫','😩','😪'],
          ok: ['✅','👌','👍'],
          warn: ['⚠️','❌'],
          love: ['❤️','😍','😘','💕','💞']
        };
        const fromMap = map[q] || [];
        items = fromMap.length ? fromMap : all;
        if (hint) hint.textContent = '';
      } else {
        if (hint) hint.textContent = (cat.id === 'recent' && items.length === 0) ? EMOJI_I18N.recentEmpty : '';
      }

      grid.innerHTML = '';
      items.slice(0, 240).forEach(ch => {
        const b = document.createElement('button');
        b.type = 'button';
        b.className = 'vm-emoji-item';
        b.textContent = ch;
        b.addEventListener('click', () => {
          insertAtCursor(ta, ch);
          pushRecent(ch);
          if (activeCat === 'recent' && !(search && search.value)) renderGrid('recent', '');
        });
        grid.appendChild(b);
      });
    }

    function activateTab(catId){
      activeCat = catId;
      tabs && tabs.querySelectorAll('.vm-emoji-tab').forEach(t => {
        t.classList.toggle('active', t.dataset.cat === catId);
      });
      renderGrid(catId, search ? search.value : '');
    }

    renderTabs();

    btn && btn.addEventListener('click', () => { isOpen() ? closePop() : open(); });
    close && close.addEventListener('click', closePop);
    search && search.addEventListener('input', () => renderGrid(activeCat, search.value));

    document.addEventListener('click', (e) => {
      if (!isOpen()) return;
      const t = e.target;
      if (!t) return;
      if (wrap.contains(t)) return;
      closePop();
    });

    document.addEventListener('keydown', (e) => {
      if (!isOpen()) return;
      if (e.key === 'Escape') closePop();
    });
  }

  function initAll(){
    document.querySelectorAll('.vm-emoji-wrap').forEach(initPickerForWrap);
  }

  // init on load
  initAll();

  // якщо десь DOM міняється — можна викликати window.VMEmojiInit()
  window.VMEmojiInit = initAll;
})();
</script>