/**
 * Smileys-Tabelle in den Optionen: Sprachwort ↔ Emoji + Liebes/Dirty-Picker.
 */
(function initVoiceSmileysOptions(global) {
  const root = global || globalThis;
  const tbody = document.getElementById('voiceSmileysBody');
  const hiddenRaw = document.getElementById('voiceSmileysRaw');
  const addRowBtn = document.getElementById('voiceSmileyAddRow');
  let saveHandler = null;
  let openPickerRow = null;

  function getPickerSections() {
    return [
      {
        title: 'Liebes & Dirty',
        emojis: root.CHILLICOLLECTIVO_LOVE_DIRTY_EMOJIS || [],
      },
      {
        title: 'Emotionen',
        emojis: root.CHILLICOLLECTIVO_EMOTION_EMOJIS || [],
      },
    ];
  }

  function appendPickerGrid(panel, tr, emojis) {
    const grid = document.createElement('div');
    grid.className = 'voice-smiley-picker-grid';
    emojis.forEach((emoji) => {
      const btn = document.createElement('button');
      btn.type = 'button';
      btn.className = 'voice-smiley-picker-item';
      btn.textContent = emoji;
      btn.addEventListener('click', () => {
        const dataRow = tr.previousElementSibling;
        const input = dataRow?.querySelector('.voice-smiley-emoji');
        if (input) {
          input.value = emoji;
          input.dispatchEvent(new Event('input', { bubbles: true }));
        }
        closeOpenPicker();
        queueSave();
      });
      grid.appendChild(btn);
    });
    panel.appendChild(grid);
  }

  function buildPickerRow() {
    const tr = document.createElement('tr');
    tr.className = 'voice-smiley-picker-row hidden';
    const td = document.createElement('td');
    td.colSpan = 3;

    const panel = document.createElement('div');
    panel.className = 'voice-smiley-picker';

    getPickerSections().forEach((section, index) => {
      if (!section.emojis.length) return;

      const sectionWrap = document.createElement('div');
      sectionWrap.className = 'voice-smiley-picker-section';
      if (index > 0) sectionWrap.classList.add('voice-smiley-picker-section-spaced');

      const title = document.createElement('div');
      title.className = 'voice-smiley-picker-title';
      title.textContent = section.title;
      sectionWrap.appendChild(title);

      appendPickerGrid(sectionWrap, tr, section.emojis);
      panel.appendChild(sectionWrap);
    });

    td.appendChild(panel);
    tr.appendChild(td);
    return tr;
  }

  function readRowsFromTable() {
    if (!tbody) return [];
    const rows = [];
    tbody.querySelectorAll('tr.voice-smiley-data-row').forEach((tr) => {
      rows.push({
        emoji: tr.querySelector('.voice-smiley-emoji')?.value.trim() || '',
        trigger: tr.querySelector('.voice-smiley-trigger')?.value.trim() || '',
      });
    });
    return rows;
  }

  function serializeTableRaw() {
    const serialize = root.chillicollectivoSerializeSmileyRows;
    const raw = typeof serialize === 'function'
      ? serialize(readRowsFromTable())
      : readRowsFromTable()
        .filter((row) => row.trigger && row.emoji)
        .map((row) => `${row.trigger} => ${row.emoji}`)
        .join('\n');
    if (hiddenRaw) hiddenRaw.value = raw;
    return raw;
  }

  function closeOpenPicker() {
    if (!openPickerRow) return;
    const pickerRow = openPickerRow.nextElementSibling;
    openPickerRow.querySelector('.voice-smiley-picker-btn')?.classList.remove('is-open');
    pickerRow?.classList.add('hidden');
    openPickerRow = null;
  }

  function createDataRow(row = {}) {
    const tr = document.createElement('tr');
    tr.className = 'voice-smiley-data-row';

    const emojiTd = document.createElement('td');
    const emojiInput = document.createElement('input');
    emojiInput.type = 'text';
    emojiInput.className = 'voice-smiley-emoji';
    emojiInput.placeholder = '😊';
    emojiInput.value = row.emoji || '';
    emojiInput.spellcheck = false;
    emojiInput.autocomplete = 'off';
    emojiTd.appendChild(emojiInput);

    const triggerTd = document.createElement('td');
    const triggerInput = document.createElement('input');
    triggerInput.type = 'text';
    triggerInput.className = 'voice-smiley-trigger';
    triggerInput.placeholder = 'herz, kuss';
    triggerInput.value = row.trigger || '';
    triggerInput.spellcheck = false;
    triggerInput.autocomplete = 'off';
    triggerTd.appendChild(triggerInput);

    const actionTd = document.createElement('td');
    actionTd.className = 'voice-smiley-actions';

    const pickerBtn = document.createElement('button');
    pickerBtn.type = 'button';
    pickerBtn.className = 'voice-smiley-picker-btn';
    pickerBtn.setAttribute('aria-label', 'Smileys ausklappen');
    pickerBtn.textContent = '▾';
    pickerBtn.addEventListener('click', () => {
      const pickerRow = tr.nextElementSibling;
      if (openPickerRow === tr) {
        closeOpenPicker();
        return;
      }
      closeOpenPicker();
      openPickerRow = tr;
      pickerBtn.classList.add('is-open');
      pickerRow?.classList.remove('hidden');
    });

    const removeBtn = document.createElement('button');
    removeBtn.type = 'button';
    removeBtn.className = 'voice-smiley-remove-btn';
    removeBtn.setAttribute('aria-label', 'Zeile entfernen');
    removeBtn.textContent = '×';
    removeBtn.addEventListener('click', () => {
      closeOpenPicker();
      tr.remove();
      pickerRow?.remove();
      if (!tbody.querySelector('.voice-smiley-data-row')) addRow();
      queueSave();
    });

    actionTd.appendChild(pickerBtn);
    actionTd.appendChild(removeBtn);

    tr.appendChild(emojiTd);
    tr.appendChild(triggerTd);
    tr.appendChild(actionTd);

    const pickerRow = buildPickerRow();

    [emojiInput, triggerInput].forEach((input) => {
      input.addEventListener('input', queueSave);
      input.addEventListener('change', queueSave);
    });

    return { tr, pickerRow };
  }

  function addRow(row = {}) {
    if (!tbody) return;
    const { tr, pickerRow } = createDataRow(row);
    tbody.appendChild(tr);
    tbody.appendChild(pickerRow);
  }

  function fillTable(raw) {
    if (!tbody) return;
    closeOpenPicker();
    tbody.replaceChildren();
    const toRows = root.chillicollectivoSmileyRulesToRows;
    const rows = typeof toRows === 'function' ? toRows(raw) : [];
    if (rows.length) {
      rows.forEach((row) => addRow(row));
    } else {
      addRow();
      addRow();
      addRow();
    }
    serializeTableRaw();
  }

  let saveTimer = null;
  function queueSave() {
    serializeTableRaw();
    clearTimeout(saveTimer);
    saveTimer = setTimeout(() => {
      if (typeof saveHandler === 'function') saveHandler();
    }, 350);
  }

  function init(onSave) {
    saveHandler = onSave;
    if (!tbody) return;

    addRowBtn?.addEventListener('click', () => {
      addRow();
      queueSave();
    });

    document.addEventListener('click', (event) => {
      if (!openPickerRow) return;
      const target = event.target;
      if (target instanceof Element && target.closest('.voice-smiley-picker-row, .voice-smiley-picker-btn')) return;
      closeOpenPicker();
    });
  }

  root.ChillicollectivoVoiceSmileysOptions = {
    init,
    fillTable,
    readRaw: serializeTableRaw,
  };
})(typeof globalThis !== 'undefined' ? globalThis : window);
