document.addEventListener("DOMContentLoaded", async () => {
    const challengesGrid = document.querySelector(".challenges-grid");

    try {
        // Fetch data from the API
        const response = await fetch(`${API_BASE_URL}/api/retos`); // Replace with your API URL
        const challenges = await response.json();

        // Clear existing content
        challengesGrid.innerHTML = "";

        // Populate the grid with data from the API
        challenges.forEach(challenge => {
            const challengeCard = document.createElement("div");
            challengeCard.classList.add("challenge-card");

            challengeCard.innerHTML = `
                <h3>${challenge.nombre}</h3>
                <video controls width="100%">
                    <source src="videos/${challenge.ubicacionVideo}" type="video/mp4">
                    Tu navegador no soporta la reproducción de videos.
                </video>
                <p>${challenge.descripcion}</p>
                <a href="fichas/${challenge.ubicacionFicha}" class="btn btn-outline btn-full" target="_blank">Ver ficha</a>
                <button class="btn btn-primary btn-full open-modal-btn">Aplicar al reto</button>
            `;

            // Append the challenge card to the grid
            challengesGrid.appendChild(challengeCard);

            // Add event listener to open the modal for the current challenge
            const openModalBtn = challengeCard.querySelector(".open-modal-btn");
            openModalBtn.addEventListener("click", () => {
                // Create and display the modal
                const modal = document.createElement("div");
                modal.classList.add("modal");
                modal.innerHTML = `
                    <div class="modal-content">
                        <span class="close-modal">&times;</span>
                        <h2>Aplicar al Reto ${challenge.id} : ${challenge.nombre}</h2>
                        <form id="application-form" enctype="multipart/form-data">
                            <label for="name">Nombre:</label>
                            <input type="text" id="name" name="name" required>
                            
                            <label for="email">Correo Electrónico:</label>
                            <input type="email" id="email" name="email" required>
                            
                            <label for="message">Mensaje:</label>
                            <textarea id="message" name="message" rows="4" required></textarea>
                            
                            <button type="submit" class="btn btn-primary">Enviar</button>
                        </form>
                    </div>
                `;

                // Append the modal to the body
                document.body.appendChild(modal);

                // Close modal functionality
                const closeModal = modal.querySelector(".close-modal");
                closeModal.addEventListener("click", () => {
                    modal.remove();
                });

                // Handle form submission
                const form = modal.querySelector("#application-form");
                form.addEventListener("submit", (event) => {
                    event.preventDefault();
                    const formData = new FormData(form);
                    console.log("Form submitted:", Object.fromEntries(formData.entries()));
                    alert("Formulario enviado con éxito!");
                    modal.remove();
                });
            });
        });

    } catch (error) {
        console.error("Error fetching challenges:", error);
        challengesGrid.innerHTML = "<p>Error loading challenges. Please try again later.</p>";
    }
});
