document.addEventListener("DOMContentLoaded", function () {
  function bindRowHandlers(widget) {
    widget.querySelectorAll(".remove-workout-set").forEach(function (btn) {
      btn.addEventListener("click", function () {
        var row = btn.closest(".workout-set-row");
        if (row) row.remove();
      });
    });
  }

  document.querySelectorAll(".workout-sets-widget").forEach(function (widget) {
    bindRowHandlers(widget);
    var addBtn = widget.querySelector(".add-workout-set-row");
    if (!addBtn) return;

    addBtn.addEventListener("click", function () {
      var template = widget.querySelector(".workout-set-row");
      if (!template) return;
      var row = template.cloneNode(true);
      row.querySelectorAll("input").forEach(function (input) {
        input.value = "";
      });
      row.querySelectorAll("select").forEach(function (select) {
        select.selectedIndex = 0;
      });
      widget.querySelector(".workout-sets-list").appendChild(row);
      bindRowHandlers(widget);
    });
  });
});
