<template>
  <div>
    <mz-slide-autocomplete
      v-if="slideDown && matches.length > 0"
      :query-param="queryParam"
      :matches="matches"
      :search-url="searchUrl"
      :query-on-hover="queryOnHover"
      :placeholder="placeholder"
    >
    </mz-slide-autocomplete>
    <template v-if="!slideDown && matches.length > 0">
      <mz-search-box
        v-for="input of matches"
        :key="input.id"
        :input="input"
        :query-param="queryParam"
        :search-url="searchUrl"
        :placement="placement"
        :delay="delay"
        :query-on-hover="queryOnHover"
        :placeholder="placeholder"
        @change="onChange"
      ></mz-search-box>
    </template>
  </div>
</template>

<script>
import MzShopifySearchBox from './MzShopifySearchBox'
import MzSlideAutocomplete from './MzSlideAutocomplete'

export default {
  components: {
    'mz-search-box': MzShopifySearchBox,
    MzSlideAutocomplete
  },
  props: {
    selector: {
      type: String,
      required: false,
      default: 'input[name="q"]'
    },
    slideDown: {
      type: Boolean,
      required: false,
      default: false
    },
    searchUrl: {
      type: String,
      required: true
    },
    queryParam: {
      type: String,
      required: false,
      default: 'q'
    },
    placement: {
      type: String,
      required: false,
      default: undefined
    },
    delay: {
      type: Number,
      required: false,
      default: 0
    },
    queryOnHover: {
      type: Boolean,
      required: false,
      default: true
    },
    placeholder: {
      type: String,
      default: 'Search by typing keywords...'
    }
  },
  data() {
    return {
      matches: []
    }
  },
  mounted() {
    // load suggestions
    const self = this
    setTimeout(() => self.loadAutocomplete(), 200)
  },
  methods: {
    loadAutocomplete() {
      const itemList = document.querySelectorAll(this.selector)
      let inputs = []
      Array.from(itemList).forEach(function (item) {
        inputs.push(item)
      })
      this.matches = inputs
    },
    onChange({ input, value }) {
      input.value = value
    }
  }
}
</script>
