// Autocompletado sencillo con datalist + fetch
async function fetchJSON(url){
  const r = await fetch(url);
  if(!r.ok) throw new Error('HTTP '+r.status);
  return await r.json();
}

async function setupAutocomplete(id, type){
  const input = document.getElementById(id);
  const dataId = id + "-data";
  const datalist = document.getElementById(dataId);

  input.addEventListener('input', async (e)=>{
    const q = input.value.trim();
    if(q.length<2) return;
    try{
      const res = await fetchJSON(`../api/search.php?type=${encodeURIComponent(type)}&q=${encodeURIComponent(q)}`);
      datalist.innerHTML = "";
      res.forEach(item=>{
        const opt = document.createElement('option');
        opt.value = item.label;
        opt.dataset.id = item.id;
        datalist.appendChild(opt);
      });
    }catch(err){ console.error(err); }
  });
}

// Unidades dinámicas por forma farmacéutica
function onFormaChange(){
  const forma = document.getElementById('forma_farmaceutica').value;
  const unidadTotal = document.getElementById('unidad_total');
  const umComp = document.querySelectorAll('.um-comp');
  let totalUnit = 'g';
  let compUnits = ['mg','ug','UI'];

  if(['cremas','Gel','Ungüento'].includes(forma)){ totalUnit='g'; compUnits=['%']; }
  else if(['Locion','laca','shampoo','spray'].includes(forma)){ totalUnit='ml'; compUnits=['%']; }
  else if(['Jarabe','gotas'].includes(forma)){ totalUnit='ml'; compUnits=['mg/ml','%']; }
  else if(['cápsulas'].includes(forma)){ totalUnit='cápsulas'; compUnits=['mg','ug','UI']; }
  else if(['supositorios'].includes(forma)){ totalUnit='supositorios'; compUnits=['mg']; }
  else if(['polvo'].includes(forma)){ totalUnit='g'; compUnits=['mg','%']; }

  unidadTotal.textContent = totalUnit;
  umComp.forEach(sel=>{
     sel.innerHTML = ""; compUnits.forEach(u=>{
       const o=document.createElement('option'); o.value=u; o.textContent=u; sel.appendChild(o);
     });
  });
}

document.addEventListener('click', (e)=>{
  if(e.target.matches('.add-comp')){
    const tpl = document.getElementById('row-comp-template');
    const cont = document.getElementById('componentes-rows');
    cont.insertAdjacentHTML('beforeend', tpl.innerHTML);
  }
  if(e.target.matches('.del-comp')){
    const row = e.target.closest('.row-comp');
    if(row) row.remove();
  }
});

document.addEventListener('DOMContentLoaded', ()=>{
  if(document.getElementById('forma_farmaceutica')) onFormaChange();
});
