const MAX_KEYWORDS = 50;

async function cargarKeywords() {
  const res = await apiFetch(`${API}/keywords.php`);
  if (!res) return;
  const lista = await res.json();
  renderKeywords(lista);
}

function renderKeywords(lista) {
  const wrap = document.getElementById('keywordsWrap');
  const count = document.getElementById('kwCount');
  wrap.innerHTML = '';
  lista.forEach(k => {
    const chip = document.createElement('span');
    chip.className = 'kw-chip';
    chip.innerHTML = `${esc(k.keyword)} <button onclick="eliminarKeyword(${k.id},this.parentElement)" title="Quitar">✕</button>`;
    wrap.appendChild(chip);
  });
  if (count) count.textContent = `${lista.length} / ${MAX_KEYWORDS}`;
}

async function agregarKeyword() {
  const input = document.getElementById('kwInput');
  const keyword = input.value.trim().toLowerCase();
  if (!keyword) return;

  const res = await apiFetch(`${API}/keywords.php`, {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({ keyword }),
  });
  if (!res) return;
  const data = await res.json();
  if (!res.ok) { showMsg('kwMsg', data.error || 'Error'); return; }

  input.value = '';
  document.getElementById('kwMsg').style.display = 'none';
  cargarKeywords();
}

async function eliminarKeyword(id, chip) {
  const res = await apiFetch(`${API}/keywords.php?id=${id}`, { method: 'DELETE' });
  if (res && res.ok) {
    chip.remove();
    const wrap = document.getElementById('keywordsWrap');
    const count = document.getElementById('kwCount');
    if (count) {
      const n = wrap.querySelectorAll('.kw-chip').length;
      count.textContent = `${n} / ${MAX_KEYWORDS}`;
    }
  }
}

document.getElementById('kwInput').addEventListener('keydown', e => {
  if (e.key === 'Enter') { e.preventDefault(); agregarKeyword(); }
});

function esc(s) { return s ? s.replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;') : ''; }

cargarKeywords();
