import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
    static targets = ["exceptionItemTemplate", "exceptionItemContainer", "exceptionItem", "exceptionItemButton"]

    connect() {
        // if (this.exceptionItemTargets.length > 0) {
        //     const content = this.#newExemptionItem()
        //     this.exceptionItemButtonTarget.insertAdjacentHTML('beforebegin', content);
        // }
    }

    addExemptionItem(event) {
        event.preventDefault()
        event.stopPropagation()

        const content = this.#newExemptionItem()

        this.exceptionItemButtonTarget.insertAdjacentHTML('beforebegin', content);
        // this.containerTarget.insertAdjacentHTML("beforeend", content)
    }

    removeExemptionItem(event) {
        console.log("in remove")
        event.preventDefault();
        const wrapper = event.target.closest(".exception-item");
        if (wrapper.dataset.newRecord === "true") {
            wrapper.remove();
        } else {
            wrapper.style.display = "none";
            const destroyInput = wrapper.querySelector("input[name*='[_destroy]']");
            if (destroyInput) {
                destroyInput.value = "1";
            }
        }
    }

    #newExemptionItem() {
        const nextIndex = this.exceptionItemTargets.length
        console.log(nextIndex)
        const buttonElement = this.exceptionItemButtonTarget;
    
        // Get the computed style (returns rgb/rgba value)
        const bgColor = window.getComputedStyle(buttonElement).backgroundColor;
        const newColor = `[${bgColor}]`

        return this.exceptionItemTemplateTarget.innerHTML
                            .replace(/NEW_ITEM_RECORD/g, nextIndex)
                            .replace(/NEXT_COLOR/g, newColor)


    }
}
