document.addEventListener("DOMContentLoaded", function () {
    const assignBtn = document.getElementById("ajaxAssignBtn");
    if (!assignBtn) return;

    assignBtn.addEventListener("click", function () {
        const form = document.getElementById("ajaxAssignForm");
        const eventId = form.dataset.event;
        const heat = form.querySelector("input[name='heat_number']").value;
        const selectedOptions = Array.from(document.querySelectorAll("#participantSelect option:checked"))
            .map(o => o.value);

        if (!heat || selectedOptions.length === 0) {
            alert("Select heat and at least one participant.");
            return;
        }

        fetch("ajax_assign_participants.php", {
            method: "POST",
            headers: {
                "Content-Type": "application/json"
            },
            body: JSON.stringify({
                event_id: eventId,
                heat_number: heat,
                participant_ids: selectedOptions
            })
        })
        .then(res => res.json())
        .then(data => {
            if (data.success) {
                alert("Assigned successfully. Reloading...");
                window.location.reload();
            } else {
                alert("Error: " + (data.error || "Unknown"));
            }
        })
        .catch(err => {
            alert("Request failed");
            console.error(err);
        });
    });
});