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

/*
* The following line makes this controller "lazy": it won't be downloaded until needed
* See https://github.com/symfony/stimulus-bridge#lazy-controllers
*/
/* stimulusFetch: 'lazy' */
export default class extends Controller {
  static targets = ['container', 'template', 'item'];

  connect() {
    this.index = this.itemTargets.length;
  }

  add(event) {
    event.preventDefault();
    const template = this.templateTarget.innerHTML.replace(/__name__/g, this.index);
    this.containerTarget.insertAdjacentHTML('beforeend', template);
    this.index++;
  }

  remove(event) {
    event.preventDefault();
    event.target.closest('.collection-item').remove();
  }
}
