/**
 * VibeLoop – schöne Emoji-Darstellung (Twemoji + Styling).
 */
const VlEmoji = (function () {
  const CDN = 'https://cdn.jsdelivr.net/gh/twitter/twemoji@14.0.2/assets/';

  function toCodePoint(emoji) {
    const chars = Array.from(String(emoji || ''));
    if (!chars.length) return '';
    return chars
      .map((ch) => {
        const cp = ch.codePointAt(0);
        if (cp > 0xffff) {
          const hi = ((cp - 0x10000) >> 10) + 0xd800;
          const lo = ((cp - 0x10000) & 0x3ff) + 0xdc00;
          return (hi.toString(16) + '-' + lo.toString(16));
        }
        return cp.toString(16);
      })
      .join('-');
  }

  function url(emoji, size) {
    const folder = size >= 64 ? '72x72' : '72x72';
    return CDN + folder + '/' + toCodePoint(emoji) + '.png';
  }

  function escAttr(s) {
    return String(s || '')
      .replace(/&/g, '&amp;')
      .replace(/"/g, '&quot;')
      .replace(/</g, '&lt;');
  }

  function html(emoji, className, size) {
    const s = size || 32;
    const cls = 'cp-emoji' + (className ? ' ' + className : '');
    const ch = String(emoji || '').trim();
    if (!ch) return '';
    return (
      '<img class="' + cls + '" src="' + url(ch, s) + '" alt="' + escAttr(ch) +
      '" width="' + s + '" height="' + s + '" draggable="false" loading="lazy" decoding="async" aria-hidden="true">'
    );
  }

  function fromGift(gift, className, size) {
    return html(gift?.emoji || '🎁', className, size);
  }

  function parseNode(el) {
    if (!el || el.dataset.cpEmojiDone) return;
    const raw = el.getAttribute('data-emoji');
    if (!raw) return;
    const size = parseInt(el.getAttribute('data-emoji-size') || '32', 10);
    const cls = el.getAttribute('data-emoji-class') || '';
    el.innerHTML = html(raw, cls, size);
    el.dataset.cpEmojiDone = '1';
  }

  function upgradeAll(root) {
    (root || document).querySelectorAll('[data-emoji]').forEach(parseNode);
  }

  return { html, fromGift, url, upgradeAll, toCodePoint };
})();

if (typeof window !== 'undefined') window.VlEmoji = VlEmoji;
