function renderItems() {
  const wrap = document.getElementById('items-list');
  wrap.innerHTML = Pro.items.map((it, i) => `
    <div class="item-row">
      <input type="text" value="${it.name || ''}" placeholder="ชื่อสินค้า" onchange="updateItem(${i},'name',this.value)">
      <input size=2 type="number" min="0" value="${it.qty || 0}" placeholder="จน." onchange="updateItem(${i},'qty',this.value)">
      <input size=3 type="text" inputmode="numeric" pattern="[0-9]*" value="${it.price || 0}" placeholder="ราคา" onchange="updateItem(${i},'price',this.value)">
      <input size=3 type="text" value="${(((Number(it.qty) || 0) * (Number(it.price) || 0)).toFixed(2))}" readonly style="background:#f0f0f0">
      <button onclick="removeItem(${i})"><i class="fa-solid fa-xmark"></i></button>
      <div class="item-note" style="grid-column:1 / -1">
        <input type="text" placeholder="หมายเหตุ" value="${it.note || ''}" onchange="updateItem(${i},'note',this.value)">
      </div>
    </div>
  `).join('');
  refreshAll();
}

function addItem() {
  Pro.items.push({id: Date.now(), name: '', note: '', qty: 1, price: 0});
  renderItems();
}

function updateItem(i, key, val) {
  if (key === 'qty' || key === 'price') val = parseFloat(val) || 0;
  Pro.items[i][key] = val;
  renderItems();
}

function removeItem(i) {
  Pro.items.splice(i, 1);
  renderItems();
}
