document.addEventListener("DOMContentLoaded", () => {
  const form = document.querySelector("[data-quotation-form]");
  if (!form) return;

  const items = form.querySelector("[data-items]");
  const template = document.querySelector("[data-item-template]");
  const total = form.querySelector("[data-grand-total]");
  const currency = new Intl.NumberFormat("en-IN", {
    style: "currency",
    currency: "INR",
    minimumFractionDigits: 2,
  });

  const numberValue = (input) => {
    const value = Number.parseFloat(input?.value || "0");
    return Number.isFinite(value) ? value : 0;
  };

  const updateTotals = () => {
    let grandTotal = 0;
    const rows = [...items.querySelectorAll("[data-item-row]")];
    rows.forEach((row) => {
      const quantity = numberValue(row.querySelector("[data-quantity]"));
      const price = numberValue(row.querySelector("[data-price]"));
      const lineTotal = Math.round(quantity * price * 100) / 100;
      grandTotal += lineTotal;
      row.querySelector("[data-line-total]").textContent =
        currency.format(lineTotal);
      row.querySelector("[data-remove-item]").disabled = rows.length === 1;
    });
    total.textContent = currency.format(Math.round(grandTotal * 100) / 100);
  };

  const addRow = () => {
    const fragment = template.content.cloneNode(true);
    items.appendChild(fragment);
    const newRow = items.lastElementChild;
    newRow.querySelector('input[name="item_name[]"]').focus();
    updateTotals();
  };

  document
    .querySelectorAll("[data-add-item]")
    .forEach((button) => button.addEventListener("click", addRow));

  items.addEventListener("input", (event) => {
    if (
      event.target.matches("[data-quantity]") ||
      event.target.matches("[data-price]")
    ) {
      updateTotals();
    }
  });

  items.addEventListener("click", (event) => {
    const remove = event.target.closest("[data-remove-item]");
    if (!remove || remove.disabled) return;
    remove.closest("[data-item-row]").remove();
    updateTotals();
  });

  updateTotals();
});
