/* kits.js — KREMER Régis v2.4.0 (Lot 4)
   Gestion Kits/BOM simplifiée (CRUD).
*/

(function(){
  const root = document.getElementById('kitsPage');
  if(!root) return;

  const elTable = document.getElementById('kitsTable');
  const elBody = elTable ? elTable.querySelector('tbody') : null;
  const elSearch = document.getElementById('kitSearch');

  let kits = [];
  let products = [];

  function esc(s){ return (s??'').toString().replace(/[&<>"']/g,m=>({"&":"&amp;","<":"&lt;",">":"&gt;","\"":"&quot;","'":"&#039;"}[m])); }

  function productLabel(pid){
    const p = products.find(x=>String(x.id)===String(pid));
    if(!p) return `#${pid}`;
    return `${p.name||''} ${p.sku?('('+p.sku+')'):''}`.trim();
  }

  function render(){
    if(!elBody) return;
    const q = (elSearch?.value||'').trim().toLowerCase();
    let list = kits;
    if(q){
      list = list.filter(k => (k.name||'').toLowerCase().includes(q) || (k.sku||'').toLowerCase().includes(q));
    }

    elBody.innerHTML = list.map(k=>{
      const comps = Array.isArray(k.components)?k.components:[];
      const compTxt = comps.slice(0,3).map(c=>`${esc(productLabel(c.productId))} × ${esc(c.qty)} ${esc(c.unit)}`).join('<br>') + (comps.length>3?`<br><span class="text-muted">+${comps.length-3}</span>`:'');
      const st = k.active===false ? '<span class="badge badge-muted">Inactif</span>' : '<span class="badge badge-success">Actif</span>';
      return `
        <tr>
          <td><strong>${esc(k.name)}</strong></td>
          <td>${esc(k.sku||'')}</td>
          <td style="min-width:320px">${compTxt||'<span class="text-muted">—</span>'}</td>
          <td>${st}</td>
          <td>
            <button class="btn btn-secondary btn-sm" data-act="edit" data-id="${esc(k.id)}">Éditer</button>
            <button class="btn btn-danger btn-sm" data-act="del" data-id="${esc(k.id)}">Supprimer</button>
          </td>
        </tr>`;
    }).join('');
  }

  async function load(){
    products = await Api.products();
    kits = await Api.kits();
    render();
  }

  function openEditor(existing){
    const isEdit = !!existing;
    const comps = (existing && Array.isArray(existing.components)) ? existing.components : [];

    const compRows = comps.map((c,i)=>`
      <div style="display:flex;gap:8px;align-items:center;flex-wrap:wrap;margin-top:8px" data-comp-row>
        <select class="sel" data-comp-pid style="flex:1;min-width:220px">
          ${products.map(p=>`<option value="${p.id}" ${String(p.id)===String(c.productId)?'selected':''}>${esc(p.name)}${p.sku?(' — '+esc(p.sku)) : ''}</option>`).join('')}
        </select>
        <input class="inp" data-comp-qty type="number" step="0.001" value="${esc(c.qty)}" style="width:120px" />
        <input class="inp" data-comp-unit value="${esc(c.unit||'piece')}" style="width:120px" />
        <button class="btn btn-danger btn-sm" data-comp-del>✕</button>
      </div>`).join('');

    const html = `
      <div>
        <div class="form-grid">
          <div class="form-group">
            <label>Nom</label>
            <input class="inp" id="kitName" value="${esc(existing?.name||'')}" />
          </div>
          <div class="form-group">
            <label>SKU</label>
            <input class="inp" id="kitSku" value="${esc(existing?.sku||'')}" />
          </div>
          <div class="form-group">
            <label>Actif</label>
            <select class="sel" id="kitActive">
              <option value="1" ${(existing?.active===false)?'':'selected'}>Oui</option>
              <option value="0" ${(existing?.active===false)?'selected':''}>Non</option>
            </select>
          </div>
        </div>

        <div style="margin-top:12px">
          <div style="display:flex;justify-content:space-between;align-items:center;gap:8px">
            <strong>Composants</strong>
            <button class="btn btn-secondary btn-sm" id="btnAddComp">＋ Ajouter</button>
          </div>
          <div id="compHost">${compRows || '<div class="text-muted" style="margin-top:8px">Aucun composant.</div>'}</div>
        </div>

        <div style="margin-top:12px">
          <label>Note</label>
          <textarea class="inp" id="kitNote" rows="3">${esc(existing?.note||'')}</textarea>
        </div>

        <div class="row" style="justify-content:flex-end;gap:8px;margin-top:14px">
          <button class="btn btn-secondary" id="btnCancel">Annuler</button>
          <button class="btn btn-primary" id="btnSave">${isEdit?'Enregistrer':'Créer'}</button>
        </div>
      </div>`;

    Modal.show({
      title: isEdit ? 'Éditer un kit' : 'Nouveau kit',
      sub: 'Définissez la composition et les unités.',
      icon: 'box',
      html
    });

    const host = document.getElementById('compHost');
    function bindRow(row){
      const del = row.querySelector('[data-comp-del]');
      if(del) del.onclick = ()=>{ row.remove(); if(!host.querySelector('[data-comp-row]')) host.innerHTML = '<div class="text-muted" style="margin-top:8px">Aucun composant.</div>'; };
    }
    host.querySelectorAll('[data-comp-row]').forEach(bindRow);

    const btnAdd = document.getElementById('btnAddComp');
    if(btnAdd) btnAdd.onclick = ()=>{
      if(host.textContent.includes('Aucun composant')) host.innerHTML='';
      const row = document.createElement('div');
      row.setAttribute('data-comp-row','1');
      row.className = 'row';
      row.style.cssText = 'gap:8px;align-items:center;margin-top:8px';
      row.innerHTML = `
        <select class="input" data-comp-pid style="flex:1;min-width:200px">
          ${products.map(p=>`<option value="${p.id}">${esc(p.name)}${p.sku?(' — '+esc(p.sku)) : ''}</option>`).join('')}
        </select>
        <input class="input" data-comp-qty type="number" step="0.001" value="1" style="width:120px" />
        <input class="input" data-comp-unit value="piece" style="width:120px" />
        <button class="btn btn-danger btn-sm" data-comp-del>✕</button>`;
      host.appendChild(row);
      bindRow(row);
    };

    const btnCancel = document.getElementById('btnCancel');
    if(btnCancel) btnCancel.onclick = ()=>Modal.close();

    const btnSave = document.getElementById('btnSave');
    if(btnSave) btnSave.onclick = async ()=>{
      const name = (document.getElementById('kitName')?.value||'').trim();
      const sku  = (document.getElementById('kitSku')?.value||'').trim();
      const active = (document.getElementById('kitActive')?.value||'1')==='1';
      const note = (document.getElementById('kitNote')?.value||'').trim();

      const rows = Array.from(host.querySelectorAll('[data-comp-row]'));
      const components = rows.map(r=>({
        productId: Number(r.querySelector('[data-comp-pid]')?.value||0),
        qty: Number(r.querySelector('[data-comp-qty]')?.value||0),
        unit: (r.querySelector('[data-comp-unit]')?.value||'piece').trim()
      })).filter(c=>c.productId>0 && c.qty>0);

      if(!name){ toast('Nom obligatoire.','error'); return; }
      if(!components.length){ toast('Ajoute au moins 1 composant.','error'); return; }

      try{
        if(isEdit){
          await Api.kitUpdate({ id: existing.id, name, sku, active, note, components });
          toast('Kit mis à jour.','success');
        } else {
          await Api.kitCreate({ name, sku, active, note, components });
          toast('Kit créé.','success');
        }
        Modal.close();
        await load();
      } catch(e){
        toast(e?.message || 'Erreur', 'error');
      }
    };
  }

  async function onClick(e){
    const btn = e.target.closest('button[data-act]');
    if(!btn) return;
    const id = btn.getAttribute('data-id');
    const act = btn.getAttribute('data-act');
    const k = kits.find(x=>String(x.id)===String(id));
    if(!k) return;

    if(act==='edit') openEditor(k);
    if(act==='del'){
      if(!confirm('Supprimer ce kit ?')) return;
      try{ await Api.kitDelete(id); toast('Kit supprimé.','success'); await load(); } catch(err){ toast(err?.message||'Erreur','error'); }
    }
  }

  document.getElementById('btnKitReload')?.addEventListener('click', load);
  document.getElementById('btnKitCreate')?.addEventListener('click', ()=>openEditor(null));
  elSearch?.addEventListener('input', render);
  elBody?.addEventListener('click', onClick);

  load();
})();
