<template>
    <div class="inputWrap">
        <div :class="fieldsClass">
            <div
                v-for="(field, index) in fields"
                :key="index"
                class="row"
                :class="{ 'hideme': field.hidden }"
            >
                <input
                    :type="field.hidden ? 'hidden' : 'text'"
                    :value="field.value"
                    @input="onInput(index, $event)"
                    @focus="$emit('clear-error')"
                    @blur="validateField(index, $event)"
                    :placeholder="field.placeholder"
                    :maxlength="field.length"
                    :id="`id_check_${type}_${index}`"
                    :ref="`field_${index}`"
                />
            </div>
        </div>

        <div class="exampleValue">
            <span>Example:</span>
            <span v-html="exampleText"></span>
        </div>
    </div>
</template>

<script>
export default {
    name: 'id-check-fields',

    props: {
        type: {
            type: String,
            required: true,
            validator: value => ['passport', 'drivers_license', 'id_card'].includes(value)
        },
        fields: {
            type: Array,
            required: true
        },
        exampleText: {
            type: String,
            default: ''
        }
    },

    computed: {
        fieldsClass() {
            const classMap = {
                'passport': 'idCheckFields passportFields',
                'drivers_license': 'idCheckFields driversLicenseFields',
                'id_card': 'idCheckFields idCardFields'
            };
            return classMap[this.type] || 'idCheckFields';
        }
    },

    methods: {
        onInput(index, event) {
            const value = event.target.value;

            // Update the field value
            this.$emit('update-field', { type: this.type, index, value });

            // Check if we should advance to next field
            const field = this.fields[index];
            if (value.length >= field.length) {
                this.focusNextField(index);
            }

            // Build the combined ID number
            this.$emit('build-id-number', this.type);
        },

        validateField(index, event) {
            const field = this.fields[index];
            let value = field.value?.trim() || '';

            // Add chevrons if needed
            if (field.addChevrons && value.length > 0) {
                while (value.length < field.length) {
                    value += '<';
                }
                this.$emit('update-field', { type: this.type, index, value });
            }

            // Validate against regex
            const regex = new RegExp(`^${field.regex}{${field.length}}$`, 'i');
            const isValid = value === '' || regex.test(value);

            // Add/remove error class
            if (event && event.target) {
                const wrapper = event.target.parentElement;
                if (wrapper) {
                    if (!isValid && value !== '') {
                        wrapper.classList.add('errorWrap');
                    } else {
                        wrapper.classList.remove('errorWrap');
                    }
                }
            }

            this.$emit('validate-field', { type: this.type, index, isValid });
            this.$emit('build-id-number', this.type);
        },

        focusNextField(currentIndex) {
            // Find next visible field that doesn't start with chevron
            for (let i = currentIndex + 1; i < this.fields.length; i++) {
                const field = this.fields[i];
                const firstChar = field.value?.[0];

                if (!field.hidden && firstChar !== '<') {
                    this.$nextTick(() => {
                        const refKey = `field_${i}`;
                        const refs = this.$refs[refKey];
                        if (refs && refs[0]) {
                            refs[0].focus();
                        }
                    });
                    break;
                }
            }
        }
    }
};
</script>

<style lang="less" scoped>
.hideme {
    display: none;
}
</style>
