window.validationMixin = {
  methods: {
    isVisible() {
      // If fields or dependencies do not exist, field is visible
      if (!this.fields || !Array.isArray(this.fields.dependencies)) {
        return true;
      }
      // dependencies is an array, safe to use every()
      return this.fields.dependencies.every(dep => {
        if (!dep || !dep.field) return true;
        const depValue = this.$parent?.$refs[dep.field]?.value;
        return depValue === dep.value;
      });
    },
    validateField() {
      // Check if fields exists before accessing it
      if (!this.fields) {
        return true; // If fields is undefined, consider validation passed
      }
      
      const visible = this.isVisible();
      const required = this.fields.required === true;
      const value = this.field_value;

      // Must be unique for each field instance!
      const uniqueFieldId = this.field_id || (this.fields && this.fields.field_id);

      const isValid = !required || (visible && value !== undefined && value !== null && value !== '');

      // Only emit if we have a field_id
      if (uniqueFieldId) {
        this.$root.$emit('field-validation', {
          fieldId: uniqueFieldId,
          isValid
        });
      }

      return isValid;
    }
  },
  watch: {
    field_value() {
      // Only call validateField if it exists
      if (typeof this.validateField === 'function') {
        this.validateField();
        const isValid = this.validateField();
      }
    }
  },
  mounted() {
    // Only call validateField if it exists
    if (typeof this.validateField === 'function') {
      this.validateField();
    }
  }
};
