function setupHomologue(product) {
  return {
    nextStep() {
      if (typeof this.allowedSteps[this.activeStepIndex + 1] === 'object' && this.allowedSteps[this.activeStepIndex + 1] !== null) {
        this.scrollToElement('#homologues-steps');
        setTimeout(() => {
          this.activeStepIndex += 1;
          this.activeStepId = this.allowedSteps[this.activeStepIndex].id;
          if (typeof this.allowedSteps[this.activeStepIndex + 1] === 'object' && this.allowedSteps[this.activeStepIndex + 1] !== null) {
            this.stepName.next = this.allowedSteps[this.activeStepIndex + 1].name;
          } else {
            this.stepName.next = null;
          }
          this.stepName.prev = this.allowedSteps[this.activeStepIndex - 1].name;
        }, 500);
      } else {
        this.stepName.next = null;
      }

      this.stepName.current = this.allowedSteps[this.activeStepIndex].name;
    },


    setStep(step_index) {
      this.scrollToElement('#homologues-steps');
      setTimeout(() => {
        this.activeStepIndex = step_index;
        this.activeStepId = this.allowedSteps[this.activeStepIndex].id;

        // Réinitialise le compteur de sous-étapes actif à zéro
        this.activeSubstepIndex = 0;


        if (typeof this.allowedSteps[this.activeStepIndex + 1] === 'object' && this.allowedSteps[this.activeStepIndex + 1] !== null) {
          this.stepName.next = this.allowedSteps[this.activeStepIndex + 1].name;
        } else {
          this.stepName.next = null;
        }

        if (typeof this.allowedSteps[this.activeStepIndex - 1] === 'object' && this.allowedSteps[this.activeStepIndex - 1] !== null) {
          this.stepName.prev = this.steps[this.activeStepIndex - 1].name;
        } else {
          this.stepName.prev = null;
        }

        this.stepName.current = this.allowedSteps[this.activeStepIndex].name;
      }, 500);
    },

    add_to_cart() {
      let _this = this;
      _this.loader = true;
      this.cleanErrors();

      if (!_this.verifyOptionsSelection()) {
        _this.add_to_cart_errors.push({message: "Merci de faire un choix pour chacune des options proposées."});
        _this.loader = false;
      } else {
        fetch("/homologue/cart?op=up&action=add&qty=" + (_this.quantity) + "&id_product=" + (_this.product_id) + "&add=1", {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
          },
          body: json_uri_encode({user_choices: _this.user_choices, quantity: _this.quantity}),
        })
          .then(response => {
            return response.json();
          })
          .then(function (response) {
            if (response.code == 200) {
              _this.product_added = response.data.products.pop();
              $('#blockcart-modal').modal('show');
            } else {
              console.warn("GET request failed", response);
            }
            _this.loader = false;
          })
          .catch(() => {
            _this.loader = false;
            this.message = 'Ooops! Something went wrong!'
          })
      }
    },

    loadConfiguration(product_id, default_img) {

      let _this = this;
      _this.loader = true;

      fetch('/homologue/configuration', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: json_uri_encode({id_product: product_id}),
      })
        .then(response => response.json())
        .then(function (data) {
          _this.product_id = data.data.product_id;
          _this.steps = data.data.steps;
          _this.loader = false;
          // console.log("FIRST "+ _this.steps[0].id );
          _this.activeStepId = _this.steps[0].id;
          _this.getAllowedSteps();
          _this.activeStepIndex = 0;
          _this.stepName.current = _this.steps[0].name;

          if (typeof _this.steps[_this.activeStepIndex + 1] === 'object' && _this.steps[_this.activeStepIndex + 1] !== null) {
            _this.stepName.next = _this.steps[_this.activeStepIndex + 1].name;
          }
          _this.previewUri = default_img;
          _this.compute();
        })
        .catch(() => {
          this.message = 'Ooops! Something went wrong ! - load configuration'
        })
    },

    getAllowedSteps() {
      let _this = this;
      _this.allowedSteps = [];
      let allowedStepIds = [];
      let allowedSubstepIds = [];
      _this.steps.forEach((step) => {
        let step_to_check = step;
        step_to_check.allowedSubsteps = [];
        if (
          typeof step_to_check.depend_of_option == 'undefined' ||
          parseInt(step_to_check.depend_of_option) == 0 ||
          _this.verifyDependenceOption(step_to_check.depend_of_option)
        ) {
          step.substeps.forEach((substep) => {
            let substep_to_check = substep;
            if (
              typeof substep_to_check.depend_of_option == 'undefined' ||
              parseInt(substep_to_check.depend_of_option) == 0 ||
              _this.verifyDependenceOption(substep_to_check.depend_of_option)
            ) {
              allowedSubstepIds.push(parseInt(substep_to_check.id));
              step_to_check.allowedSubsteps.push(substep_to_check);
            }
          });

          if (step_to_check.allowedSubsteps.length > 0) {
            allowedStepIds.push(parseInt(step_to_check.id));
            _this.allowedSteps.push(step_to_check);
          }
        }
      });

      let user_choices = [];
      _this.user_choices.forEach((user_choice) => {
        if (allowedStepIds.includes(user_choice.step_id) && allowedSubstepIds.includes(user_choice.substep_id))
          user_choices.push(user_choice);
      });
      _this.user_choices = user_choices;
    },

    verifyOptionsSelection() {
      let _this = this;
      var validate = true;

      _this.allowedSteps.forEach((step) => {
        step.allowedSubsteps.forEach((substep) => {
          if (!_this.verifySubtepInUserChoices(substep)) {
            console.log(['validation failed for substep', substep]);
            validate = false;
          }
        });
      });

      if (!_this.verifyDependenceUserChoices()) {
        validate = false;
      }

      return validate;
    },

    verifySubtepInUserChoices(substep) {
      let _this = this;
      return _this.user_choices.find((user_choice) => {
        return parseInt(user_choice.substep_id) == parseInt(substep.id)
          && (
            !user_choice.params.has_variants
            || (user_choice.params.has_variants
              && user_choice.params.combination_code_selected != undefined)
          );
      }) != undefined;
    },

    verifyDependenceOption(depend_of_id) {
      let _this = this;
      if (typeof depend_of_id != 'undefined' && parseInt(depend_of_id) > 0) {
        return typeof _this.user_choices.find((user_choice) => {
          return parseInt(user_choice.option_id) == parseInt(depend_of_id);
        }) != 'undefined';
      }
      return true;
    },

    verifyValueMinMax() {

      // Vérification des champs de type paramètres en fonction des limites dans la matrice de calcul
      if ($('.homologues--step-substep-option').css('display') != 'none') {

        $("input[type='number']").change(function () {
          msgError = "";

          $.each($('input[type=number]'), function () {
            var max = parseInt($(this).attr('max'));
            var min = parseInt($(this).attr('min'));
            var placeholder = ($(this).attr('placeholder'));

            // On vérifie que les inputs dont le parent est visible
            if ($(this).parent().parent().css('display') != 'none') {

              if ($(this).val() > max) {
                msgError = msgError + "Le champ '" + placeholder + "' doit être inférieur à " + max + " cm.<br />";
              }

              if ($(this).val() < min) {
                msgError = msgError + "Le champ '" + placeholder + "' doit être supérieur à " + min + " cm.<br />";
              }

              // Vérification spécifique pour les coussins trapèze. La grande base doit être plus petite que la largeur et la hauteur
              if ($("#trapeze_grandebase").val() > 0 && this.id == "trapeze_grandebase") {
                var hauteur = $("#trapeze_height").val();
                var largeur = $("#trapeze_width").val();
                var grandebase = $("#trapeze_grandebase").val();

                if (largeur > hauteur) {
                  maxtaille = hauteur;
                } else {
                  maxtaille = largeur;
                }

                if (grandebase >= maxtaille) {
                  msgError = msgError + "Le champ 'Grande base' doit être inférieur à " + maxtaille + " cm. <br />";
                }
              }

              if ($("#trapeze_petitebase").val() > 0 && this.id == "trapeze_petitebase") {
                // Vérification spécifique pour les coussins trapèze. La petite base doit être plus petite que la grande base
                var petitebase = $("#trapeze_petitebase").val();
                var grandebase = $("#trapeze_grandebase").val();

                if (petitebase > grandebase) {
                  msgError = msgError + "Le champ 'Petite Base' doit être inférieur à " + grandebase + " cm. <br />";

                }
              }

              // affiche Message d'erreur
              document.getElementById('errorname').innerHTML = msgError;
            }

          });
        });
      }

    },

    verifyDependenceUserChoices() {
      let _this = this;
      var validation = true
      _this.user_choices.forEach((user_choice) => {
        if (typeof user_choice.params.depend_of != 'undefined' && parseInt(user_choice.params.depend_of) > 0) {
          validation = typeof _this.user_choices.find((user_choice_to_scan) => {
            return parseInt(user_choice_to_scan.option_id) == parseInt(user_choice.params.depend_of);
          }) != 'undefined';
        }
      });
      return validation;
    },

    resetUserChoices() {
      //console.log("reset");
      this.user_choices = [];

      let _this = this;
      _this.reset = 1;
    },

    setOption(step_id, substep_id, option_id, params) {
      let _this = this;
      _this.cleanErrors();
      _this.reset = 0;

      this.activeStepIndex;

      // console.log("step : "+ this.activeStepIndex);
      // console.log("substep : "+this.activeSubstepIndex);

      // Lorsque l'id de la sous étape == à firstStep on reset les choix de l'utilisateur
      if( _this.firstStep == substep_id){
        _this.resetUserChoices();

      }


      // On récupère l'id de la première étape et de la première sous étape
      if (this.activeStepIndex == 0 && this.activeSubstepIndex == 0) {
        _this.firstStep = substep_id;
      }



      // Incrémente le compteur de sous-étapes actif
      _this.activeSubstepIndex++;

      let user_choice = _this.user_choices.find(function (choice) {
        return parseInt(choice.step_id) == parseInt(step_id) && parseInt(choice.substep_id) == parseInt(substep_id)
      });


      if (typeof user_choice === 'object') {
        var new_params = {
          ...user_choice.params,
          ...params,
        };
        user_choice.option_id = parseInt(option_id);
        user_choice.params = new_params;
      } else {
        _this.user_choices.push({
          step_id: parseInt(step_id),
          substep_id: parseInt(substep_id),
          option_id: parseInt(option_id),
          params: params
        });
      }

      if (params && params.variant_vmr && params.variant_vmr !== "" && params.variant_vmr !== null) {
        _this.previewUri = params.variant_vmr;
      }

      _this.verifyValueMinMax();
      _this.getAllowedSteps();
      _this.compute();
    },

    setSubVariantTab(product_id) {
      this.tab = parseInt(product_id)
    },

    updateQuantity(operation) {
      let _this = this;
      if (operation < 0) {
        _this.quantity += parseInt(operation);
      } else if (operation > 0) {
        _this.quantity += parseInt(operation);
      }

      if (_this.quantity === 0) {
        alert('quantity > 0 only');
        _this.quantity = 1;
      }

      this.compute();
    },

    setQuantity(quantity) {
      let _this = this;
      if (quantity > 0) {
        _this.quantity = parseInt(quantity);
      } else {
        alert('quantity > 0 only');
        _this.quantity = 1;
      }

      this.compute();
    },

    compute() {
      let _this = this;
      _this.loader = true;

      fetch('/?sq=1', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/x-www-form-urlencoded; charset=UTF-8'
        },
        body: json_uri_encode({options: _this.user_choices, quantity: _this.quantity, product_id: _this.product_id}),
      })
        .then(response => response.json())
        .then(function (data) {
          _this.base_price_with_taxes = data.base_price.with_taxes;
          _this.base_price_without_taxes = data.base_price.without_taxes;
          _this.unit_price_with_taxes = data.unit_price.with_taxes;
          _this.unit_price_without_taxes = data.unit_price.without_taxes;
          _this.total_price_with_taxes = data.total_price.with_taxes;
          _this.total_price_without_taxes = data.total_price.without_taxes;

          _this.steps.forEach(function (step) {
            step.substeps.forEach(function (substep) {
              substep.options.forEach(function (option) {

                // ADD CLASS SELECTED OPTION

                _this.user_choices.forEach((user_choice) => {
                  $(".homologues--step-substep-option").addClass("TEST3");
                });
                // END ADD  CLASS SELECTED OPTION




                if (_this.reset == 1) {
                  // console.log("Reset on : "+_this.reset);
                  if (option.fields) {
                    option.fields.forEach(function (field) {
                      // console.log('key, value', field);
                      field.value = "0";
                    })
                  }
                }

                /* if (data.pop_ids.includes(parseInt(option.id))) {
                   console.log('IN POPIDS', option.id)
                   if (option.fields) {
                     option.fields.forEach(function (field) {
                       console.log('key, value', field);
                       field.value = "";
                     })
                   }
                 }*/
              })
            })
          })
          _this.loader = false;

        })
        .catch(() => {
          _this.loader = false;
          this.message = 'Ooops! Something went wrong ! compute'
        })
    },

    optionSelected(option_id) {
      let _this = this;

      return _this.user_choices.find((user_choice) => {
        return parseInt(user_choice.option_id) == parseInt(option_id)
      });
    },

    subOptionSelected(item_id) {
      let _this = this;
      return _this.user_choices.find((user_choice) => {
        return parseInt(user_choice.params.combination_code_selected) == parseInt(item_id)
      });
    },

    cleanErrors() {
      let _this = this;
      _this.add_to_cart_errors = [];
    },

    optionIsSelected(step_id, substep_id, option_id) {
      let result = false;
      let _this = this;
      if (_this.user_choices.length > 0) {
        _this.user_choices.forEach((choice) => {
          if (choice.step_id == step_id && choice.substep_id == substep_id && choice.option_id == option_id) {
            result = true;
          }
        });
      }
      return result;
    },

    scrollToElement(target) {
      var element = document.querySelector(target);
      console.log(element);
      if (element != null) {
        element.scrollIntoView({behavior: 'smooth'});
      }
    },

    checkStepCompleted(step_id) {
      const form = document.getElementById('form-step-' + step_id);
      return form.checkValidity();
    },

    reset : 0, // à 1 si on est dans la première étape et sous étape
    firstStep: 0,
    activeSubstepIndex: 0,
    activeStepId: null,
    activeStepIndex: null,
    add_to_cart_errors: [],
    allowedSteps: [],
    base_price_with_taxes: 0,
    base_price_without_taxes: 0,
    isOpen: false,
    loader: false,
    previewUri: "",
    product: product,
    product_added: null,
    product_id: null,
    quantity: 1,
    stepName: {
      prev: null,
      current: null,
      next: null,
    },
    steps: [],
    tab: false,
    total_price_with_taxes: 0,
    total_price_without_taxes: 0,
    unit_price_with_taxes: 0,
    unit_price_without_taxes: 0,
    user_choices: [],
  };
};

