const modal = document.getElementById("commentModal");
const closeCommentModal = document.getElementById("closeCommentModal");
const cancelCommentBtn = document.getElementById("cancelCommentBtn");
const submitCommentBtn = document.getElementById("submitCommentBtn");
const commentTextarea = document.getElementById("commentTextarea");
const commentForm = document.getElementById("commentForm");
const titleComment = document.getElementById("titleComment");
const selectCommentTypeForm = document.getElementById("selectCommentTypeForm");
const selectOptions = document.getElementById("selectOptions");

export const COMMENT_TYPES = {
    LIBRE : 0,
    DESPLEGABLE : 1
}

export async function getComment(type, options=[]) {
    // 1. Limpiar estado anterior
    commentTextarea.value = "";
    selectOptions.innerHTML = ""; 

    if (type === COMMENT_TYPES.LIBRE) {
        commentForm.classList.remove("hidden");
        selectCommentTypeForm.classList.add("hidden");
        submitCommentBtn.disabled = true; // Deshabilitar al inicio
        commentTextarea.value = options[0] || "";
    } else if (type === COMMENT_TYPES.DESPLEGABLE) {
        selectCommentTypeForm.classList.remove("hidden");
        commentForm.classList.add("hidden");
        
        options.forEach(option => {
            const optionElement = document.createElement("button");
            optionElement.type = "button";
            optionElement.className = "flex items-center gap-2 px-4 py-2 rounded-lg border border-gray-300 hover:bg-gray-50 transition-colors";
            optionElement.textContent = option;
            // Usamos dataset para guardar el valor, por si es diferente al texto
            optionElement.dataset.value = option 
            selectOptions.appendChild(optionElement);
        });
    } else {
        return; // Tipo no válido
    }

    modal.classList.remove("hidden");

    // 2. Gestionar listeners de forma aislada para ESTA promesa
    return new Promise((resolve) => {
        
        // --- Handlers (las funciones que se ejecutarán) ---
        const disableEvent = (event) => {
            event.preventDefault();
            event.stopPropagation();
        };
        const handleInput = () => {
            submitCommentBtn.disabled = commentTextarea.value.trim() === "";
        };

        const handleSubmit = (event) => {
            if (event) event.preventDefault();
            cleanup(); // Limpiar todos los listeners
            resolve(commentTextarea.value);
        };

        const handleCancel = () => {
            cleanup();
            resolve(null);
        };

        const handleOptionClick = (event) => {
            const button = event.target.closest('button');
            if (!button) return; // Clic no fue en un botón

            cleanup();
            resolve(button.dataset.value); // Resolver con el valor del dataset
        };

        // --- Función de limpieza ---
        // Elimina todos los listeners de esta instancia


        const cleanup = () => {
            modal.classList.add("hidden");
            commentTextarea.removeEventListener("input", handleInput);
            commentForm.removeEventListener("submit", handleSubmit);
            submitCommentBtn.removeEventListener("click", handleSubmit);
            cancelCommentBtn.removeEventListener("click", handleCancel);
            closeCommentModal.removeEventListener("click", handleCancel);
            selectOptions.removeEventListener("click", handleOptionClick);
            selectCommentTypeForm.removeEventListener("submit", disableEvent);
            commentForm.removeEventListener("submit", disableEvent);
        };

        // --- Asignar Listeners ---
        // Asignamos solo los listeners necesarios para este 'type'
        
        if (type === COMMENT_TYPES.LIBRE) {
            commentTextarea.addEventListener("input", handleInput);
            commentForm.addEventListener("submit", handleSubmit);
            submitCommentBtn.addEventListener("click", handleSubmit);
            commentForm.addEventListener("submit", disableEvent);
        } else {
            // DESPLEGABLE
            selectOptions.addEventListener("click", handleOptionClick);
            selectCommentTypeForm.removeEventListener("submit", disableEvent);
        }
        
        // Listeners de cancelación siempre se asignan
        cancelCommentBtn.addEventListener("click", handleCancel);
        closeCommentModal.addEventListener("click", handleCancel);
    });
}