function rowTemplate() {
  const defaultHsn = document.getElementById('defaultHsnValue')?.value || '';
  return `<tr>
    <td class="row-index"></td>
    <td><input name="description" class="form-control" value="Tissue Paper" required></td>
    <td><select name="paper_type" class="form-select" required><option>Soft</option><option>Semi Soft</option><option>Hard</option></select></td>
    <td><input name="hsn_code" class="form-control" value="${defaultHsn}"></td>
    <td><input name="quantity" type="number" step="0.001" min="0" class="form-control calc" required></td>
    <td><input name="rate" type="number" step="0.01" min="0" class="form-control calc" required></td>
    <td><input name="discount_percent" type="number" step="0.01" min="0" value="0" class="form-control calc"></td>
    <td class="line-taxable text-end">0.00</td>
    <td class="line-total text-end">0.00</td>
    <td><button type="button" class="btn btn-sm btn-outline-danger remove-row">×</button></td>
  </tr>`;
}

function renumber() {
  document.querySelectorAll('#itemsBody tr').forEach((row, index) => row.querySelector('.row-index').textContent = index + 1);
}

function calculate() {
  const sellerState = document.querySelector('[name="seller_state_code"]')?.value || '';
  const buyerState = document.querySelector('[name="customer_state_code"]')?.value || '';
  const cgstPercent = Number(document.querySelector('[name="settings_cgst"]')?.value || 0);
  const sgstPercent = Number(document.querySelector('[name="settings_sgst"]')?.value || 0);
  const igstPercent = Number(document.querySelector('[name="settings_igst"]')?.value || 0);
  let taxable = 0;
  let cgst = 0;
  let sgst = 0;
  let igst = 0;
  document.querySelectorAll('#itemsBody tr').forEach((row) => {
    const quantity = Number(row.querySelector('[name="quantity"]').value || 0);
    const rate = Number(row.querySelector('[name="rate"]').value || 0);
    const discount = Number(row.querySelector('[name="discount_percent"]').value || 0);
    const lineTaxable = quantity * rate * (1 - discount / 100);
    const sameState = String(sellerState) === String(buyerState);
    const lineCgst = sameState ? lineTaxable * cgstPercent / 100 : 0;
    const lineSgst = sameState ? lineTaxable * sgstPercent / 100 : 0;
    const lineIgst = sameState ? 0 : lineTaxable * igstPercent / 100;
    taxable += lineTaxable;
    cgst += lineCgst;
    sgst += lineSgst;
    igst += lineIgst;
    row.querySelector('.line-taxable').textContent = lineTaxable.toFixed(2);
    row.querySelector('.line-total').textContent = (lineTaxable + lineCgst + lineSgst + lineIgst).toFixed(2);
  });
  const raw = taxable + cgst + sgst + igst;
  const total = Math.round(raw);
  document.getElementById('taxablePreview').textContent = taxable.toFixed(2);
  document.getElementById('cgstPreview').textContent = cgst.toFixed(2);
  document.getElementById('sgstPreview').textContent = sgst.toFixed(2);
  document.getElementById('igstPreview').textContent = igst.toFixed(2);
  document.getElementById('roundPreview').textContent = (total - raw).toFixed(2);
  document.getElementById('grandPreview').textContent = total.toFixed(2);
}

document.addEventListener('DOMContentLoaded', () => {
  const body = document.getElementById('itemsBody');
  const add = document.getElementById('addRow');
  if (!body || !add) return;
  add.addEventListener('click', () => { body.insertAdjacentHTML('beforeend', rowTemplate()); renumber(); calculate(); });
  body.addEventListener('click', (event) => { if (event.target.classList.contains('remove-row') && body.children.length > 1) { event.target.closest('tr').remove(); renumber(); calculate(); } });
  document.addEventListener('input', (event) => { if (event.target.classList.contains('calc') || event.target.name === 'customer_state_code') calculate(); });
  document.getElementById('same_as_buyer')?.addEventListener('change', (event) => document.getElementById('consigneeFields').classList.toggle('d-none', event.target.checked));
  renumber(); calculate();
});
