function getParam(param) {
    const urlParams = new URLSearchParams(window.location.search);
    return urlParams.get(param) || "";
}

document.addEventListener("DOMContentLoaded", function(){
    const modal = document.getElementById("leadModal");
    const form = document.getElementById("leadForm");
    const phoneInput = document.getElementById("phoneInput");
    const submitBtn = form.querySelector("button[type='submit']");
    const openBtn = document.querySelector("[data-modal-open]");
    const openContactsBtn = document.querySelector("[data-modal-open-contacts]");
    const closeBtns = document.querySelectorAll("[data-modal-close]");
    const messageDiv = document.getElementById("leadMessage");

    openBtn.addEventListener("click", () => {
        modal.classList.add("active");
        document.body.style.overflow = "hidden";
    });

    openContactsBtn.addEventListener("click", () => {
        modal.classList.add("active");
        document.body.style.overflow = "hidden";
    });

    closeBtns.forEach(btn => {
        btn.addEventListener("click", () => {
            modal.classList.remove("active");
            document.body.style.overflow = "";
        });
    });

    document.addEventListener("keydown", e => {
        if(e.key === "Escape"){
            modal.classList.remove("active");
            document.body.style.overflow = "";
        }
    });

    let formStartTime = Date.now();

    const allowedCodes = ["29","33","44","25"];

    phoneInput.value = "+375 ";

    phoneInput.addEventListener("input", function(){

        let value = phoneInput.value.replace(/\D/g, "");

        if(value.startsWith("375")){
            value = value.substring(3);
        }

        value = value.substring(0,9);

        let formatted = "+375 ";

        if(value.length > 0){
            formatted += "(" + value.substring(0,2);
        }
        if(value.length >= 2){
            formatted += ") " + value.substring(2,5);
        }
        if(value.length >= 5){
            formatted += "-" + value.substring(5,7);
        }
        if(value.length >= 7){
            formatted += "-" + value.substring(7,9);
        }

        phoneInput.value = formatted;
    });

    document.getElementById("utm_source").value = getParam("utm_source");
    document.getElementById("utm_medium").value = getParam("utm_medium");
    document.getElementById("utm_campaign").value = getParam("utm_campaign");
    document.getElementById("utm_content").value = getParam("utm_content");
    document.getElementById("utm_term").value = getParam("utm_term");

    // source — можно задать вручную
    document.getElementById("leadSource").value = "modal_main_button";

    /* ===== AJAX SUBMIT ===== */
    form.addEventListener("submit", function(e){
        e.preventDefault();

        const secondsSpent = (Date.now() - formStartTime)/1000;
        if(secondsSpent<3){
            return;
        }

        // Honeypot
        if(form.querySelector("input[name='company']").value!=="") return;

        // Телефон
        const digits = phoneInput.value.replace(/\D/g,"");
        if(digits.length!==12 || !allowedCodes.includes(digits.substring(3,5))){
            messageDiv.style.color="red";
            messageDiv.style.display="block";
            messageDiv.innerText="Введите корректный номер РБ";
            return;
        }

        submitBtn.disabled = true;
        submitBtn.innerText="Отправка...";

        const formData = new FormData(form);

        fetch(form.action, {
            method: "POST",
            headers: {
                "X-Requested-With": "XMLHttpRequest",
                "X-CSRFToken": formData.get("csrfmiddlewaretoken")
            },
            body: formData
        })
        .then(res => res.json())
        .then(data => {
            if(data.status==="ok"){
                messageDiv.style.color="green";
                messageDiv.innerText="Спасибо! Ваша заявка принята";
                messageDiv.style.display="block";
                form.reset();
            } else {
                messageDiv.style.color="red";
                messageDiv.innerText=data.error||"Ошибка отправки заявки";
                messageDiv.style.display="block";
            }
        })
        .catch(err=>{
            messageDiv.style.color="red";
            messageDiv.innerText="Ошибка соединения. Попробуйте позже";
            messageDiv.style.display="block";
        })
        .finally(()=>{
            submitBtn.disabled=false;
            submitBtn.innerText="Отправить заявку";
        });
    });
});
