Vue.component('search-widget', {
  props: ['merchant','page_name'],
  inject: ['_get','params','session_path','getUrlParam','updateUrlParam'],
  data: () => ({
    dialog: {
      shown: false,
    },
    search: '',
    last_search: '',
    page: 1,
    limit: 12,
    total: 0,
    data: [],
    loading: false,
  }),
  mounted () {
    if (this.getUrlParam('q')) {
      this.dialog.shown = true;
      this.search = this.getUrlParam('q');
      this.searchItem(this.search);
    }
  },
  methods: {
    clickSearch() {
      this.dialog.shown = true;
      let _this = this;
      setTimeout(function(){
        _this.$refs.search.focus();
      },300);
    },
    goHome () {
      var current_params = new URLSearchParams(window.location.search);
      location.assign(this.session_path+"?"+current_params.toString());
    },
    removeSearchQuery () {
      var params = new URLSearchParams(window.location.search);
      params.delete("q");
      window.history.replaceState({}, document.title, decodeURIComponent(`${window.location.pathname}?${params}`));
    },
    searchItem (search) {
      if (search != this.last_search) {
        this.loading = true
        this.page = 1
        gtag('event', 'search', {
          search_term: search
        })
        var query = this.params({
          "view": "website",
          "guest_id": "<?=$_gid;?>",
          page: this.page, 
          per_page: this.limit,
          search: this.search,
          with: ['variants', 'media'],
          with_count: ['quantity', 'sold'],
        })
        axios.get("<?=$apiEndpoint;?>"+"products"+"?"+query).then(res=>{
          this.data = res.data.data
          this.total = res.data.meta.total

          gtag('event', 'view_search_results', {
            search_term: this.search,
            items: this.data.map((product,i)=>({
              "item_id": product.id,
              "item_name": product.name,
              "item_brand": this.merchant.name,
              "item_category": (product.product_category||{}).name,
              "item_variant": this._get(product,'variants.0.name'),
              "item_list_id": "search_results",
              "item_list_name": "Search Results",
              "list_position": 1+i,
              "index": 1+i, // UA - list_position
              "currency": this.merchant.currency,
              "price": (this._get(product,'variants.0.discounted_price')===0)?0:(this._get(product,'variants.0.discounted_price')||this._get(product,'variants.0.price')),
            }))
          });
          fbq('track','Search',{
            search_string: this.search,
            content_type: 'product_group',
            content_ids: this.data.map(product=>product.id)
          })
        }).finally(()=>{
          if (search) {
            this.updateUrlParam({name:'q',value: search});
          } else {
            this.removeSearchQuery();
          }
          this.loading = false
          this.last_search = search
        })
      }
    },
    onIntersect (entries, observer, isIntersecting) {
      if (isIntersecting) {
        this.getMoreProducts();
      }
    },
    getMoreProducts () {
      if (this.page * this.limit < this.total) {
        this.loading = true
        var query = this.params({
          "view": "website",
          "guest_id": "<?=$_gid;?>",
          page: ++this.page, 
          per_page: this.limit,
          search: this.search,
          with: ['variants', 'media'],
          with_count: ['quantity', 'sold'],
        })
        axios.get("<?=$apiEndpoint;?>"+"products"+"?"+query).then(res=>{
          this.data = this.data.concat(res.data.data)
          this.total = res.data.meta.total

          gtag('event', 'view_search_results', {
            search_term: this.search,
            items: res.data.data.map((product,i)=>({
              "item_id": product.id,
              "item_name": product.name,
              "item_brand": this.merchant.name,
              "item_category": (product.product_category||{}).name,
              "item_variant": this._get(product,'variants.0.name'),
              "item_list_id": "search_results",
              "item_list_name": "Search Results",
              "list_position": 1+i,
              "index": 1+i, // UA - list_position
              "currency": this.merchant.currency,
              "price": (this._get(product,'variants.0.discounted_price')===0)?0:(this._get(product,'variants.0.discounted_price')||this._get(product,'variants.0.price')),
            }))
          });
          fbq('track','Search',{
            search_string: this.search,
            content_type: 'product_group',
            content_ids: res.data.data.map(product=>product.id)
          })
        }).finally(()=>{
          this.loading = false
        })
      }
    },
  },
  template:
`<div>
  <v-btn icon color="primary" @click="clickSearch">
    <v-icon>mdi-magnify</v-icon>
  </v-btn>
  <v-dialog
    v-model="dialog.shown"
    fullscreen
    hide-overlay
    transition="fade-transition"
  >
    <v-app-bar
      color="white"
      class="app-toolbar"
      fixed
      app
      dense
      elevation="2"
    >
      <v-row class="mx-n3" no-gutters>
        <v-col cols="12" md="10" offset-md="1" lg="8" offset-lg="2">
          <v-row no-gutters align="center">
            <v-scale-transition origin="center">
              <v-col cols="auto">
                <v-btn icon color="primary" @click="removeSearchQuery();dialog.shown=false;">
                  <v-icon>mdi-close</v-icon>
                </v-btn>
              </v-col>
            </v-scale-transition>
            <v-col cols="auto" @click="goHome()" style="cursor: pointer">
              <v-img width="38px" height="38px" style="border-radius: 50%;" v-if="merchant && merchant.image_url" :src="merchant.image_url" alt="Logo">
                <template v-slot:placeholder>
                  <v-skeleton-loader
                    height="100%"
                    class="mx-auto"
                    type="image"
                  ></v-skeleton-loader>
                </template>
              </v-img>
              <v-avatar size="38px" color="primary" style="border-radius:50%" v-else>
                <span class="white--text headline">{{((merchant && merchant.name)||'').substr(0,1)}}</span>
              </v-avatar>
            </v-col>
            <v-col class="px-2" style="overflow:hidden;" @click="goHome()" style="cursor: pointer">
              <h1>
                <v-list-item-title class="font-weight-black">{{(merchant||{}).name}}</v-list-item-title>
              </h1>
            </v-col>
          </v-row>
        </v-col>
      </v-row>
    </v-app-bar>
    <v-card style="background: linear-gradient(white, #fafafa)">
      <v-card-text class="py-2 px-3">
        <v-main>
          <div class="page-wrapper">
            <v-container class="pa-0" fluid>
              <v-row no-gutters class="mb-2">
                <v-col cols="12" md="10" offset-md="1" lg="8" offset-lg="2">
                  <v-text-field
                    v-model="search"
                    color="primary"
                    background-color="grey lighten-3"
                    solo
                    flat
                    dense
                    light
                    clearable
                    single-line
                    :loading="loading && (page==1)"
                    :append-icon="search?'':'mdi-magnify'"
                    :label="$t('search.keywords')"
                    @change="(e)=>searchItem(e)"
                    @click:clear="$refs.search.blur()"
                    ref="search"
                    type="search"
                  >
                  </v-text-field>
                  <div v-if="last_search && (!loading || (page > 1))">
                    <div>{{$t('search.result', {count: total})}}</div>
                    <v-row align="stretch" dense>
                      <v-col cols="6" sm="4" md="3" v-for="(product, i) in data" :key="product.id" v-intersect="(entries, observer, isIntersecting)=>(i==(data.length-1))?onIntersect(entries, observer, isIntersecting):''">
                        <product-card-item :merchant="merchant" :product="product" :index="i" :page_name="page_name"></product-card-item>
                      </v-col>
                      <v-col cols="6" sm="4" md="3" v-if="loading">
                        <v-card flat outlined class="product-card" height="100%">
                          <v-skeleton-loader
                            height="100%"
                            class="mx-auto"
                            type="card"
                          ></v-skeleton-loader>
                        </v-card>
                      </v-col>
                    </v-row>
                  </div>
                </v-col>
              <v-row>
            </v-container>
          </div>
        </v-main>
      </v-card-text>
    </v-card>
  </v-dialog>
</div>`
});