(function () {
    var form = document.querySelector("[data-login-form]");
    var username = document.getElementById("username");
    var password = document.getElementById("password");
    var remember = document.querySelector("[data-remember-username]");
    var toggle = document.querySelector("[data-password-toggle]");
    var forgot = document.querySelector("[data-forgot-password]");
    var passwordHelp = document.getElementById("password-help");
    var storageKey = "mzh.library.login.username";

    function readStoredUsername() {
        try {
            return window.localStorage.getItem(storageKey) || "";
        } catch (ex) {
            return "";
        }
    }

    function writeStoredUsername(value) {
        try {
            if (value) {
                window.localStorage.setItem(storageKey, value);
            } else {
                window.localStorage.removeItem(storageKey);
            }
        } catch (ex) {
            // Storage may be disabled; login should still submit normally.
        }
    }

    if (username && remember) {
        var storedUsername = readStoredUsername();
        if (storedUsername) {
            remember.checked = true;
            if (!username.value) {
                username.value = storedUsername;
            }
        }
    }

    if (form && username && remember) {
        form.addEventListener("submit", function () {
            writeStoredUsername(remember.checked ? username.value.trim() : "");
        });
    }

    if (toggle && password) {
        toggle.addEventListener("click", function () {
            var nextVisible = password.type !== "text";
            password.type = nextVisible ? "text" : "password";
            toggle.setAttribute("aria-pressed", String(nextVisible));
            toggle.setAttribute("aria-label", nextVisible ? "隐藏密码" : "显示密码");
            password.focus();
        });
    }

    if (forgot && passwordHelp) {
        forgot.addEventListener("click", function () {
            passwordHelp.hidden = !passwordHelp.hidden;
            if (!passwordHelp.hidden) {
                passwordHelp.focus();
            }
        });
    }
}());
