<template>
  <p v-if="suggestions?.length" class="suggestions" aria-level="2" role="heading">
    <span class="">منظور شما این بود :</span>
    <a
      :href="urlResolver()"
      @click.prevent="selectSuggestion"
      class="suggestion-text btn"
    >
      <span v-for="(suggest, index) in suggestions" :key="index">
        <b v-if="suggest.options?.length"
          >{{ mostRelavant(suggest) }}
          &nbsp;
        </b>
        <template v-else>
          {{ mostRelavant(suggest) }}
          &nbsp;
        </template>
      </span>
    </a>
  </p>
</template>

<script>
export default {
  props: {
    suggestions: {
      default() {
        return [];
      },
    },
  },
  data() {
    return {
      finalText: "",
    };
  },
  emits: ["on-select-suggestion"],
  methods: {
    mostRelavant(suggestion) {
      let text = suggestion.text;
      if (suggestion.options?.length) {
        text = suggestion.options[0].text;
      }
      return text;
    },
    // findMostRelevant(suggestion) {
    //   let numbers = suggestion;
    //   let max = numbers[0]; // initialize to the first value

    //   for (let i = 1; i < numbers.length; i++) {
    //     if (numbers[i].score > max.score && numbers[i].freq > max.freq) {
    //       max = numbers[i];
    //     }
    //   }
    //   return max;
    // },
    selectSuggestion() {
      this.$emit("on-select-suggestion", this.suggestedText());
    },

    suggestedText() {
      let suggestedText = "";
      this.suggestions.forEach((element, index) => {
        suggestedText += index == 0 ? "" : " ";

        if (element.options?.length) suggestedText += element.options[0].text;
        else suggestedText += element.text;
      });
      return suggestedText;
    },

    urlResolver() {
      const routeData = this.$router.resolve({
        name: this.$route.name,
        query: {
          q: this.suggestedText(),
        },
      });
      return routeData.href;
    },
  },
};
</script>

<style scoped lang="scss">
.suggestions {
  margin: 0.33em 0 17px;
  font-size: medium;

  .suggestion-text {
    color: var(--light-blue-color);
    font-size: 1.2rem;
  }

  .btn {
    word-spacing: -3px;
    padding: 0;
    margin-right: 0.3em;
    &:hover {
      text-decoration: underline;
    }
  }
}
</style>
