/** 
 * パスワード正規表現パターン
 */ 
const RegexPatterns = {
    is_password_alphabet: /[A-Za-z]/,
    is_password_number: /[0-9]/,
    is_password_symbol: /^[!-~]+$/,
    is_password_range: /^.{8,20}$/,
    is_password_consecutive: /(.)\1{4,}/
};

/**
 * パスワードバリデーション
 */
$.validator.addMethod("isPassword", function(value, element) {
    const errors = []

    // 入力がない場合 trueを返す
    if (!value) return true;

    // 英字、数字、文字数チェック
    const hasAlphabet = RegexPatterns.is_password_alphabet.test(value);
    const hasNumber = RegexPatterns.is_password_number.test(value);
    const hasValidRange = RegexPatterns.is_password_range.test(value);
    
    // 上記の条件に一致しない場合、統一メッセージを追加
    if (!hasAlphabet || !hasNumber || !hasValidRange) {
        errors.push("パスワードは英数字を含む8桁以上20桁以下で設定してください。");
    }

    // 同一文字連続(5文字以上)チェック
    if (!RegexPatterns.is_password_symbol.test(value)
        ) errors.push("パスワードは、半角英数字と[!\"#$%&'()*+,-./:;<=>?@[\\]^_`{|}~]のみご使用になれます。");
    
    if (errors.length > 0) {
        $(element).data("errorMessage", errors);
        return false;
    } else {
        $(element).removeData("data-errorMessages", errors);
        return true;
    }
}, function(_, element) {
    return ($(element).data("errorMessage") || []).join("<br>");
})

/**
 * パスワード表示/非表示 切り替え
 */
function visibilityPassword() {
    //パスワード表示
    $(".eye-slash-solid").on("click", function () {
        const targetId = $(this).data("target");
        const $input = $("#" + targetId);

        // 包んでいる要素で限定
        const $container = $(this.closest(".password-wrapper"));

        $container.find(".eye-slash-solid").hide();
        $container.find(".eye-solid").show();
        $input.attr("type", "text");
    });

    // パスワード非表示
    $(".eye-solid").on("click", function () {
        const targetId = $(this).data("target");
        const $input = $("#" + targetId);
    
        // 包んでいる要素で限定
        const $container = $(this.closest(".password-wrapper"));
    
        $container.find(".eye-solid").hide();
        $container.find(".eye-slash-solid").show();
        $($input).attr("type", "password");
    });
}