/**
 * Auto-Korrekturen-Tabelle in den Optionen: falsch erkannt ↔ richtig.
 */
(function initVoiceCorrectionsOptions(global) {
  const root = global || globalThis;
  const tbody = document.getElementById('autoCorrectionsBody');
  const hiddenRaw = document.getElementById('autoCorrectionsRaw');
  const addRowBtn = document.getElementById('autoCorrectionAddRow');
  let saveHandler = null;

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

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

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

    const wrongTd = document.createElement('td');
    const wrongInput = document.createElement('input');
    wrongInput.type = 'text';
    wrongInput.className = 'voice-correction-wrong voice-smiley-trigger';
    wrongInput.placeholder = 'falsch erkannt';
    wrongInput.value = row.wrong || '';
    wrongInput.spellcheck = false;
    wrongInput.autocomplete = 'off';
    wrongTd.appendChild(wrongInput);

    const correctTd = document.createElement('td');
    const correctInput = document.createElement('input');
    correctInput.type = 'text';
    correctInput.className = 'voice-correction-correct voice-smiley-trigger';
    correctInput.placeholder = 'richtig';
    correctInput.value = row.correct || '';
    correctInput.spellcheck = false;
    correctInput.autocomplete = 'off';
    correctTd.appendChild(correctInput);

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

    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', () => {
      tr.remove();
      if (!tbody.querySelector('.voice-correction-data-row')) addRow();
      queueSave();
    });

    actionTd.appendChild(removeBtn);

    tr.appendChild(wrongTd);
    tr.appendChild(correctTd);
    tr.appendChild(actionTd);

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

    return tr;
  }

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

  function fillTable(raw) {
    if (!tbody) return;
    tbody.replaceChildren();
    const toRows = root.chillicollectivoCorrectionRulesToRows;
    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;
    addRowBtn?.addEventListener('click', () => {
      addRow();
      queueSave();
    });
  }

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