<template>
  <div class="row q-col-gutter-xs q-pb-xs">
    <div class="col-xs-12 col-sm-4 q-mb-sm">
      <q-input dense outlined stack-label lazy-rules
        v-model="values.name"
        type   ="text"
        :label ="$t('form.labels.name')"
        placeholder="Digite um nome"
        :rules="[isInvalid('name')]"
      />
    </div>
    <div class="col-xs-12 col-sm-4 q-mb-sm">
      <q-input dense outlined stack-label lazy-rules
        v-model="values.email"
        type   ="text"
        :label ="$t('form.labels.email')"
        placeholder="Digite um e-mail"
        :rules="[isInvalid('email')]"
      />
    </div>
    <div class="col-xs-12 col-sm-4 q-mb-sm">
      <q-input dense outlined stack-label lazy-rules unmasked-value
        v-model="values.phone"
        type   ="text"
        :label ="$t('form.labels.phone')"
        :mask  ="phoneMask"
        placeholder="Digite um telefone"
        @keydown="handlePhoneKeydown"
        @input="handlePhoneInput"
        @paste="handlePhonePaste"
      />
    </div>
  </div>
</template>

<script>
export default {
  props  : {
    values       : {
      type    : Object,
      required: true,
    },
  },
  data() {
    return {
      useCellphoneMask: false,
    };
  },
  computed: {
    phoneMask() {
      const v = this.values && this.values.phone ? this.values.phone : '';
      const digits = this.normalizePhoneDigits(v);
      return this.useCellphoneMask || digits.length > 10
        ? '(##) #####-####'
        : '(##) ####-####';
    },
  },

  methods: {
    normalizePhoneDigits(phone) {
      return (phone || '').toString().replace(/\D/g, '');
    },

    handlePhoneKeydown(event) {
      if (!event || !/^\d$/.test(event.key)) return;

      const digits = this.normalizePhoneDigits(this.values && this.values.phone);
      if (digits.length >= 10) {
        this.useCellphoneMask = true;
      }
    },

    handlePhoneInput(value) {
      this.useCellphoneMask = this.normalizePhoneDigits(value).length > 10;
    },

    handlePhonePaste(event) {
      const pasted = event && event.clipboardData
        ? event.clipboardData.getData('text')
        : '';
      const current = this.values && this.values.phone ? this.values.phone : '';
      if (this.normalizePhoneDigits(current + pasted).length > 10) {
        this.useCellphoneMask = true;
      }
    },

    isInvalid(key) {
      return val => {
        if (!(val && val.length > 0))
          return this.$t('messages.fieldRequired');

          if (key === "name") {
            const containsInvalidChars = /[^a-zA-ZÀ-ÿ\s]/.test(val);
            const hasMultipleSpaces = /\s{2,}/.test(val);
            const words = val.trim().split(/\s+/);

            const hasMinimumWords = words.length >= 2;
            const hasMinimumLength = val.length >= 3;

            const hasConsecutiveConsonants = /[bcdfghjklmnpqrstvwxz]{5,}/i.test(val);
            const hasConsecutiveChars = /(.)\1{3,}/.test(val);

            if (containsInvalidChars || hasMultipleSpaces || !hasMinimumWords ||
                !hasMinimumLength || hasConsecutiveConsonants || hasConsecutiveChars) {
                return this.$t("messages.nameInvalid");
            }
        }

        if (key === "email") {
            const emailRegex = /^[^\s@]+@[^\s@]+\.[^\s@]+$/; // Verifica o formato básico de e-mail
            const hasRepetitivePatterns = /(.)\1{2,}/.test(val); // Rejeita padrões como "aaa" ou "zzz"

            // Separar a parte do usuário e o domínio
            const [localPart, domain] = val.split("@");

            if (!emailRegex.test(val) || !localPart || !domain) {
                return this.$t("messages.emailInvalid");
            }

            // Verificar diversidade de caracteres no local-part e domínio
            const localPartUniqueChars = new Set(localPart.toLowerCase());
            const domainUniqueChars = new Set(domain.toLowerCase());
            const isLocalPartDiverse = localPartUniqueChars.size >= localPart.length / 2;
            const isDomainDiverse = domainUniqueChars.size >= domain.length / 2;

            // Rejeitar e-mails com padrões inválidos ou baixa diversidade
            if (hasRepetitivePatterns || !isLocalPartDiverse || !isDomainDiverse || localPart.length < 6) {
                return this.$t("messages.emailInvalid");
            }
        }

        if (key == 'phone') {
          const digits = (val || '').replace(/\D/g, '');
          if (!(digits.length >= 10 && digits.length <= 11))
            return this.$t('messages.phoneInvalid');
        }

        return true;
      };
    },
  },
};
</script>
