// 邮箱找回密码页交互入口，负责 AJAX 发送重置链接和页面提示。

let passwordForgotControlsBound = false;

/**
 * 读取 CSRF 令牌，供找回密码请求使用。
 *
 * @returns {string}
 */
function getCsrfToken() {
    return document.querySelector('meta[name="csrf-token"]')?.getAttribute("content") ?? "";
}

/**
 * 展示找回密码页面提示。
 *
 * @param {string} message
 * @param {string} type
 * @returns {void}
 */
function showAlert(message, type) {
    const alertBox = document.getElementById("alert-box");
    if (!alertBox) {
        return;
    }

    alertBox.textContent = message;
    alertBox.className = type === "success" ? "alert alert-success" : "alert alert-error";
    alertBox.style.display = "block";
}

/**
 * 提交邮箱找回密码请求。
 *
 * @param {SubmitEvent} event
 * @returns {Promise<void>}
 */
async function submitPasswordRecovery(event) {
    event.preventDefault();

    const form = event.target;
    const submitButton = document.getElementById("submit-btn");
    const alertBox = document.getElementById("alert-box");
    if (!(form instanceof HTMLFormElement)) {
        return;
    }

    if (submitButton instanceof HTMLButtonElement) {
        submitButton.disabled = true;
        submitButton.innerText = "发送中...";
    }
    if (alertBox) {
        alertBox.style.display = "none";
    }

    try {
        const response = await fetch(form.getAttribute("data-password-email-url") ?? form.action, {
            method: "POST",
            credentials: "same-origin",
            headers: {
                "Content-Type": "application/json",
                "X-CSRF-TOKEN": getCsrfToken(),
                Accept: "application/json",
            },
            body: JSON.stringify(Object.fromEntries(new FormData(form).entries())),
        });
        const body = await response.json();

        if (response.status === 200 && body.status === "success") {
            showAlert(body.message, "success");
            form.reset();
            return;
        }

        const errorMessage = body.message || (body.errors ? Object.values(body.errors)[0][0] : "邮件发送失败，请稍后重试。");
        showAlert(errorMessage, "error");
    } catch {
        showAlert("网络或服务器异常，请稍后再试。", "error");
    } finally {
        if (submitButton instanceof HTMLButtonElement) {
            submitButton.disabled = false;
            submitButton.innerText = "发送重置邮件";
        }
    }
}

/**
 * 绑定邮箱找回密码页提交事件。
 *
 * @returns {void}
 */
function bindPasswordForgotControls() {
    if (passwordForgotControlsBound || typeof document === "undefined") {
        return;
    }

    passwordForgotControlsBound = true;
    document.getElementById("password-recovery-form")?.addEventListener("submit", (event) => {
        void submitPasswordRecovery(event);
    });
}

bindPasswordForgotControls();
