(() => {
    const form = document.getElementById("promoForm");
    const walletInput = document.getElementById("wallet");
    const nameInput = document.getElementById("name");
    const promoCodeInput = document.getElementById("promoCode");
    const submitButton = document.getElementById("submitButton");

    const loadingState = document.getElementById("loadingState");
    const errorState = document.getElementById("errorState");
    const successState = document.getElementById("successState");

    const successAmount = document.getElementById("successAmount");
    const successWallet = document.getElementById("successWallet");
    const successName = document.getElementById("successName");
    const successSignature = document.getElementById("successSignature");
    const successExplorerUrl = document.getElementById("successExplorerUrl");

    const params = new URLSearchParams(window.location.search);
    const walletFromQuery = (params.get("wallet") || "").trim();
    if (walletFromQuery && !walletInput.value.trim()) {
        walletInput.value = walletFromQuery;
    }

    form.addEventListener("submit", async (event) => {
        event.preventDefault();
        hideMessages();
        toggleLoading(true);

        try {
            const payload = {
                wallet: walletInput.value.trim(),
                name: nameInput.value.trim(),
                promoCode: promoCodeInput.value.trim()
            };

            const response = await fetch("/api/promo/top-up", {
                method: "POST",
                headers: {
                    "Content-Type": "application/json"
                },
                body: JSON.stringify(payload)
            });

            const result = await response.json();
            if (!result.success) {
                showError(result.message || "Не удалось выполнить операцию");
                return;
            }

            showSuccess(result);
        } catch (error) {
            showError("Ошибка сети или недоступен backend");
        } finally {
            toggleLoading(false);
        }
    });

    function toggleLoading(active) {
        submitButton.disabled = active;
        loadingState.classList.toggle("hidden", !active);
        submitButton.textContent = active ? "Отправляем..." : "Пополнить тестовый счёт";
    }

    function hideMessages() {
        errorState.classList.add("hidden");
        successState.classList.add("hidden");
    }

    function showError(message) {
        errorState.textContent = message;
        errorState.classList.remove("hidden");
    }

    function showSuccess(data) {
        successAmount.textContent = data.amountSol || "0.1";
        successWallet.textContent = data.wallet || "—";
        successName.textContent = data.name || "—";
        successSignature.textContent = data.signature || "—";
        successExplorerUrl.href = data.explorerUrl || "#";
        successState.classList.remove("hidden");
    }
})();
