/* ============================================================
   Radio Ultra – admin.js
   Hanterar dynamiska stream-rader i add/edit-formulären
   ============================================================ */
(function () {
  'use strict';

  const list       = document.getElementById('streamList');
  const addBtn     = document.getElementById('addStreamBtn');
  if (!list || !addBtn) return;

  function rowIndex() {
    return list.querySelectorAll('.stream-row').length;
  }

  function newRow(idx) {
    const div = document.createElement('div');
    div.className = 'stream-row';
    div.innerHTML = `
      <input name="streams[${idx}][url]"     class="form-control" placeholder="https://stream.example.com/…">
      <select name="streams[${idx}][format]" class="form-control" style="max-width:90px">
        <option>mp3</option><option>aac</option><option>ogg</option><option>hls</option>
      </select>
      <input name="streams[${idx}][bitrate]" class="form-control" type="number" placeholder="kbps" value="128" style="max-width:80px">
      <input name="streams[${idx}][label]"   class="form-control" placeholder="Backup" style="max-width:110px">
      <button type="button" class="btn-rm" onclick="this.closest('.stream-row').remove()">✕</button>
    `;
    return div;
  }

  addBtn.addEventListener('click', () => {
    list.appendChild(newRow(rowIndex()));
    list.lastElementChild.querySelector('input').focus();
  });

  // Auto-generera slug från namn (bara på add-sidan)
  const nameInput = document.querySelector('input[name="name"]');
  const slugInput = document.querySelector('input[name="slug"]');
  if (nameInput && slugInput && !slugInput.value) {
    nameInput.addEventListener('input', () => {
      if (!slugInput.dataset.touched) {
        slugInput.value = nameInput.value
          .toLowerCase()
          .replace(/å/g,'a').replace(/ä/g,'a').replace(/ö/g,'o')
          .replace(/[^a-z0-9]+/g, '-')
          .replace(/^-|-$/g, '');
      }
    });
    slugInput.addEventListener('input', () => { slugInput.dataset.touched = '1'; });
  }
})();
