import Vue from 'vue'
import './SntApp.scss'
import { getSlot } from 'vuetify/lib/util/helpers'
import { mapActions, mapGetters } from 'vuex'

export default Vue.extend({
  name: 'SntApp',
  data () {
    return {
      scrollY: 0,
      scrollUp: 0,
      lastScrollTop: 0
    }
  },
  computed: {
    ...mapGetters({
      subdomain: 'salePage/subdomain',
      customer: 'salePage/customer',
      theme: 'salePage/theme',
      productBrands: 'salePage/productBrands',
      productCategories: 'salePage/productCategories',
      purchasesQuantity: 'cart/purchasesQuantity'
    }),
    isMobileDevice () {
      return /Android|webOS|iPhone|iPad|Mac|Macintosh|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent)
    },
    isAuth () {
      return this.customer?.id || false
    },
    customerName () {
      return this.customer?.name || 'Guest'
    }
  },
  beforeDestroy () {
    if (typeof window !== 'undefined') {
      window.removeEventListener('scroll', this.handleScroll)
    }
  },
  created () {
    this.handleScroll = this.$_.throttle(() => {
      const pageYOffset = window.pageYOffset || document.documentElement.scrollTop
      this.scrollY = window.scrollY
      this.scrollUp = this.lastScrollTop - pageYOffset
      this.lastScrollTop = pageYOffset <= 0 ? 0 : pageYOffset
    }, 30)
    if (typeof window !== 'undefined') {
      window.addEventListener('scroll', this.handleScroll)
    }
  },
  methods: {
    ...mapActions({
      addToCart: 'cart/addToCart'
    }),
    getContentSlot () {
      return getSlot(this, 'default', {
        _: this.$_,
        subdomain: this.subdomain,
        isMobileDevice: this.isMobileDevice,
        isAuth: this.isAuth,
        customer: this.customer,
        router: this.$router,
        route: this.$route,
        theme: this.theme,
        productBrands: this.productBrands,
        productCategories: this.productCategories,
        purchasesQuantity: this.purchasesQuantity,
        breakpoint: this.$shipnity.breakpoint,
        goTo: this.$shipnity.goTo,
        addToCart: this.addToCart,
        scrollY: this.scrollY,
        scrollUp: this.scrollUp,
        $shipnity: this.$shipnity,
        customerName: this.customerName
      }, false) || []
    }
  },
  render (h) {
    return h('div', {
      staticClass: 'snt-app',
      attrs: {
        'data-app': true
      }
    }, this.getContentSlot())
  }
})
