const local = document.querySelector('html').lang ?? 'en';
const message = {
    en: {
        required: 'Este campo es obligatorio.',
        email: 'Tu dirección de correo electrónico no es válida. Actualízala y vuelve a intentarlo.',
        minLength: 'At least $n characters are required',
        maxLength: 'A maximum of $n characters are allowed',
    }
}
const currentLang = message[local] ? local : 'en';

class FormValidator {
    constructor(formId, options = {}) {
        this.form = document.getElementById(formId);
        if (!this.form) {
            throw new Error(`找不到ID为${formId}的表单`);
        }

        // 默认配置
        this.options = {
            errorClass: 'invalid',
            successClass: 'valid',
            errorMessageClass: 'error-message',
            validateOnBlur: true,
            validateOnInput: true,
            ...options
        };

        // 验证规则
        this.rules = {
            required: {
                validate: (value) => value.trim() !== '',
                message: message[currentLang].required,
            },
            email: {
                validate: (value) => /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(value),
                message: message[currentLang].email,
            },
            minLength: {
                validate: (value, length) => value.length >= parseInt(length),
                message: (length) => message[currentLang].minLength.replace('$n', length),
            },
            maxLength: {
                validate: (value, length) => value.length <= parseInt(length),
                message: (length) => message[currentLang].maxLength.replace('$n', length),
            },
            min: {
                validate: (value, min) => parseFloat(value) >= parseFloat(min),
                message: (min) => `最小值为${min}`
            },
            max: {
                validate: (value, max) => parseFloat(value) <= parseFloat(max),
                message: (max) => `最大值为${max}`
            },
            match: {
                validate: (value, field) => {
                    const targetField = this.form.querySelector(`[name="${field}"]`);
                    return targetField ? value === targetField.value : false;
                },
                message: (field) => `与${this.getFieldLabel(field)}不一致`
            },
            passwordStrength: {
                validate: (value) => /^(?=.*[A-Za-z])(?=.*\d).{8,}$/.test(value),
                message: '密码至少8位，包含字母和数字'
            }
        };

        this.init();
    }

    // 初始化
    init() {
        // 为所有需要验证的字段添加事件监听
        this.getValidatableFields().forEach(field => {
            if (this.options.validateOnBlur) {
                field.addEventListener('blur', () => this.validateField(field));
            }

            if (this.options.validateOnInput) {
                field.addEventListener('input', () => {
                    if (field.value.length > 0) {
                        this.validateField(field);
                    }
                });
            }
        });

        // 表单提交事件
        this.form.addEventListener('submit', (e) => {
            e.preventDefault();
            if (this.validateForm()) {
                this.onSubmit();
            }
        });

        // 处理密码显示/隐藏
        this.setupPasswordToggle();
    }

    // 获取所有需要验证的字段
    getValidatableFields() {
        return Array.from(this.form.querySelectorAll('[data-validate]'));
    }

    // 验证单个字段
    validateField(field) {
        const value = field.value;
        const validations = field.getAttribute('data-validate').split('|');
        const errorElement = this.getErrorElement(field);
        let isValid = true;
        let errorMessage = '';

        // 重置状态
        this.resetFieldStatus(field);

        // 执行所有验证规则
        for (const validation of validations) {
            const [ruleName, param] = validation.split(':');
            const rule = this.rules[ruleName];

            if (!rule) {
                console.warn(`未知的验证规则: ${ruleName}`);
                continue;
            }

            if (!rule.validate(value, param)) {
                isValid = false;
                errorMessage = typeof rule.message === 'function'
                    ? rule.message(param)
                    : rule.message;
                break;
            }
        }

        // 设置验证结果
        if (!isValid) {
            this.setFieldInvalid(field, errorMessage);
        } else if (value.length > 0) {
            this.setFieldValid(field);
        }

        return isValid;
    }

    // 验证整个表单
    validateForm() {
        const fields = this.getValidatableFields();
        let isFormValid = true;

        fields.forEach(field => {
            if (!this.validateField(field)) {
                isFormValid = false;
            }
        });

        // 如果表单无效，滚动到第一个无效字段
        if (!isFormValid) {
            const firstInvalidField = fields.find(field =>
                field.classList.contains(this.options.errorClass)
            );
            if (firstInvalidField) {
                firstInvalidField.scrollIntoView({behavior: 'smooth', block: 'center'});
                firstInvalidField.focus();
            }
        }

        return isFormValid;
    }

    // 获取错误信息元素
    getErrorElement(field) {
        // 查找字段后面的错误信息元素
        let errorElement = field.nextElementSibling;
        if (errorElement && errorElement.classList.contains(this.options.errorMessageClass)) {
            return errorElement;
        }

        // 如果不存在则创建一个
        errorElement = document.createElement('p');
        errorElement.className = this.options.errorMessageClass;
        field.parentNode.insertBefore(errorElement, field.nextSibling);
        return errorElement;
    }

    // 重置字段状态
    resetFieldStatus(field) {
        field.classList.remove(this.options.errorClass, this.options.successClass);
        const errorElement = this.getErrorElement(field);
        errorElement.classList.add('hidden');
        errorElement.textContent = '';
    }

    // 设置字段为无效状态
    setFieldInvalid(field, message) {
        field.classList.remove(this.options.successClass);
        field.classList.add(this.options.errorClass);
        const errorElement = this.getErrorElement(field);
        errorElement.textContent = message;
        errorElement.classList.remove('hidden');
    }

    // 设置字段为有效状态
    setFieldValid(field) {
        field.classList.remove(this.options.errorClass);
        field.classList.add(this.options.successClass);
    }

    // 获取字段标签
    getFieldLabel(fieldName) {
        const label = this.form.querySelector(`label[for="${fieldName}"]`);
        return label ? label.textContent : '此字段';
    }

    // 处理密码显示/隐藏
    setupPasswordToggle() {
        const toggleButtons = this.form.querySelectorAll('.toggle-password');
        toggleButtons.forEach(button => {
            button.addEventListener('click', () => {
                const input = button.parentNode.querySelector('input');
                const type = input.getAttribute('type') === 'password' ? 'text' : 'password';
                input.setAttribute('type', type);

                // 切换图标
                const icon = button.querySelector('i');
                icon.classList.toggle('fa-eye');
                icon.classList.toggle('fa-eye-slash');
            });
        });
    }

    // 表单提交处理
    onSubmit() {
        // 收集表单数据
        const formData = new FormData(this.form);
        const data = {};

        formData.forEach((value, key) => {
            data[key] = value;
        });

        // 在实际应用中，这里会发送数据到服务器
        console.log('表单数据:', data);
        // alert('表单验证通过，准备提交数据！');

        // 可以在这里添加AJAX请求
        // fetch('/api/submit', {
        //     method: 'POST',
        //     body: JSON.stringify(data),
        //     headers: {
        //         'Content-Type': 'application/json'
        //     }
        // });
    }

    // 添加自定义验证规则
    addRule(ruleName, validateFn, message) {
        this.rules[ruleName] = {
            validate: validateFn,
            message: message
        };
    }
}
