import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static targets = ["numberInput", "planFieldsContainer", "template"];

  connect() {
    this.updatePlanFields();
  }

  updatePlanFields() {
    const desiredCount = parseInt(this.numberInputTarget.value || 1, 10);
    const currentCount = this.planFieldsContainerTarget.children.length;

    if (desiredCount > currentCount) {
      this.addPlanFields(desiredCount - currentCount);
    } else if (desiredCount < currentCount) {
      this.removePlanFields(currentCount - desiredCount);
    }
  }

  addPlanFields(count) {
    for (let i = 0; i < count; i++) {
      const newPlanField = this.templateTarget.content.cloneNode(true);
      // Replace '__INDEX__' with a unique value for nested attributes
      // e.g., using Date.now() or a counter
      const uniqueIndex = Date.now() + i;
      newPlanField.innerHTML = newPlanField.innerHTML.replace(/__INDEX__/g, uniqueIndex);
      this.planFieldsContainerTarget.appendChild(newPlanField);
    }
  }

  removePlanFields(count) {
    for (let i = 0; i < count; i++) {
      this.planFieldsContainerTarget.lastElementChild.remove();
    }
  }
}