import { Controller } from '@hotwired/stimulus'

export default class extends Controller {
  static targets = ['template', 'container']

  addCode(event) {
    event.preventDefault()

    const template = this.templateTarget.content.cloneNode(true)
    const timestamp = new Date().getTime()
    template.querySelectorAll('[name*="NEW_RECORD"]').forEach(el => {
      el.name = el.name.replace('NEW_RECORD', timestamp)
    })
    template.querySelectorAll('[disabled]').forEach(el => el.disabled = false)
    this.containerTarget.appendChild(template)

    // Focus the new input
    const newInput = template.querySelector('input[name*="[code]"]')
    if (newInput) {
      newInput.focus()
    }
  }

  removeCode(event) {
    event.preventDefault()
    // The backend will handle the actual deletion by comparing IDs
    const row = event.target.closest('.manual-attribution-code-row')
    row.remove()
  }
}
