(function () {
  function syncRoleFields(form) {
    var category = form.querySelector("[data-roster-category]");
    if (!category) return;

    var isPlayer = category.value === "player";
    var playerBlock = form.querySelector("[data-roster-role-player]");
    var otherBlock = form.querySelector("[data-roster-role-other]");
    var jerseyRow = form.querySelector("[data-roster-jersey-row]");
    var playerSelect = form.querySelector("[data-roster-role-player]");
    var otherInput = form.querySelector("[data-roster-role-other]");
    var jerseyInput = form.querySelector("[data-roster-jersey]");

    if (playerBlock) playerBlock.hidden = !isPlayer;
    if (otherBlock) otherBlock.hidden = isPlayer;
    if (jerseyRow) jerseyRow.hidden = !isPlayer;

    if (playerSelect) {
      playerSelect.disabled = !isPlayer;
      playerSelect.name = isPlayer ? "team_roster_member[role_label]" : "";
    }
    if (otherInput) {
      otherInput.disabled = isPlayer;
      otherInput.name = isPlayer ? "" : "team_roster_member[role_label]";
    }
    if (jerseyInput) jerseyInput.disabled = !isPlayer;
  }

  document.querySelectorAll("[data-roster-form]").forEach(function (form) {
    var category = form.querySelector("[data-roster-category]");
    if (!category) return;

    syncRoleFields(form);
    category.addEventListener("change", function () {
      syncRoleFields(form);
    });
  });
})();
