<template>

    <section class="bundleCreator">


        <div v-for="itemList in itemLists" class="bundleLists" :id="itemList.id" :class="[overlayVisible ? 'showOverlay' : '', itemList.classes]">


            <div class="container">

                <div class="wrapper">

                    <button class="button closeButton" v-if="itemList.isOverlay" @click.prevent="openOverlay(false)" aria-label="Close">
                        <i class="far fa-times"></i>
                    </button>

                </div> <!-- .wrapper -->

                <div class="innerBunderWrapper">

                    <div class="bundlesContain">

                        <div class="wrapper">

                            <div class="introBlock bundleTitles" v-if="itemList.title">

                                <div class="innerIntro">
                                  
                                    <h3 class="introTitle" v-html="itemList.title"></h3>

                                    <div class="introContentWrap" v-html="itemList.subtitle" v-if="itemList.subtitle"></div>

                                    <div class="buttonWrap">

                                        <button
                                                @click="submit()"
                                                class="button"
                                                v-if="itemList.showBasketButton && selectedItems.length"
                                                v-text="buttonLabelSubmitSelectedItems || 'Submit'"
                                        >
                                        </button>

                                        <button
                                                @click.prevent="openOverlay(true)"
                                                class="button buttonAlt"
                                                v-if="itemList.showViewPackButton"
                                        >
                                            Add more items
                                        </button>

                                    </div>

                                </div> <!-- .innerIntro -->

                            </div> <!-- .introBlock -->


                            <div class="filterContainer">
  
                              <div class="filterSidebar">
                                
                                  <button 
                                      type="button" 
                                      class="button buttonAlt mobileFilterToggle"
                                      @click.prevent="toggleMobileFilters()"
                                  >
                                    <span v-text="mobileFilterText">Show filters</span>
                                  </button>
                                
                                  <ul v-if="itemList.showFilters" v-show="mobileFiltersVisible" class="filterList">
                                    
                                      <li class="resetFilters" :class="[!selectedFilters.length ? 'active' : '']">
                                          <button
                                              type="checkbox"
                                              @click.prevent="resetFilters()"
                                              value="y"
                                          >
                                            Show all
                                          </button>
                                      </li>
                                    
                                      <li v-for="filter_item in availableFilters" :class="[selectedFilters.includes(filter_item.label) ? 'active' : '']">

                                          <div class="iconWrap">
                                              <img :src="filter_item.icon"/>
                                          </div> <!-- .iconWrap -->
                                        
                                          <button
                                              type="checkbox"
                                              @click.prevent="toggleFilter(filter_item.label)"
                                              value="y"
                                              class="filterButton"
                                          >
                                            <span v-text="filter_item.label"></span>
                                            <i class="far fa-times" v-if="selectedFilters.includes(filter_item.label)"></i>
                                          </button>
                                        
                                      </li>
                                    
                                  </ul>
                                
                              </div> <!-- .filterSidebar -->
  
                              <div class="filterContent">
                                
                                  <div v-if="!itemList.dataset.length" class="emptyMessage">
    
                                    <p>
                                      {{ itemList.emptySetMessage }}
                                    </p>
    
                                  </div>
    
                                  <ul v-else class="itemsBrowse landingItems">
    
                                    <li v-for="item in itemList.dataset">
    
                                      <div class="innerItem">
    
                                        <div class="itemHeader">
    
                                          <h2>{{ item.display_name }}</h2>
    
                                          <!-- Using static version until the main category data is available -->
                                          <!--<h4>{{ item.main_category }}</h4>-->
                                          <h4>Vitamins</h4>
    
                                        </div> <!-- .itemHeader -->

                                        <!-- Removed the image via css for now -->
                                        <div class="itemImageWrap">
    
                                          <picture class="innerImage">
    
                                            <!-- Using static version until the main image data is available -->
                                            <img
                                                src="/sites/default/images/placeholders/no-image-items.png"
                                                :alt="item.display_name"/>
    
                                          </picture> <!-- .innerImage -->
    
                                        </div> <!-- .itemImageWrap -->
    
                                        <div class="innerTextBox">
    
                                          <div class="productDescription" v-if="item.shop_item.custom.description__product_card">
                                            <p v-html="item.shop_item.custom.description__product_card"></p>
                                          </div> <!-- .productDescription -->
    
                                          <div class="itemFooter">
    
                                            <div class="itemPriceWrap">
                                              <span v-text="'£' + item.display_price"></span>
                                            </div>
    
                                            <div class="itemLinkWrap">
                                              <a :href="item.product_page_url" target="_blank">
                                                <span class="itemLink">More info</span>
                                              </a>
                                            </div> <!-- .itemLink -->
    
                                          </div> <!-- .itemFooter -->
    
                                          <div class="bundleButtons" v-if="itemList.isOverlay">
                                            <button @click.prevent="itemList.buttonAction(item)" class="button buttonAlert" v-text="itemList.buttonLabel"></button>
                                          </div> <!-- .bundleButtons -->
    
                                          <div class="bundleButtons" v-else="itemList.isOverlay">
                                            <button
                                                @click.prevent="itemList.buttonAction(item)"
                                                class="button"
                                                v-text="itemList.buttonLabel"
                                            ></button>
                                          </div> <!-- .bundleButtons -->
    
                                        </div><!-- .innerTextBox -->
    
                                      </div> <!-- .innerItem -->
    
                                    </li>
    
                                  </ul>
                                
                              </div> <!-- .filterContent -->
                              
                            </div> <!-- .filterContainer -->
                          
                        </div> <!-- .wrapper -->

                    </div> <!-- .bundlesContain -->

                </div> <!-- .innerBunderWrapper -->

            </div> <!-- .container -->

        </div>


    </section>

</template>


<script>

    export default {

        props: {
            preselectedItemIds: {
                type: Array,
                default: () => [],
            },
            availableItems: {
                type: Array,
                default: () => [],
            },
            availableFilters: {
                type: Array,
                default: () => [],
            },
            urlSubmitSelectedItems: {
                type: String,
                default: null,
            },
            buttonLabelSubmitSelectedItems: {
                type: String,
                default: null,
            },
            bundleId: {
                type: String,
                default: null,
            },
        },


        data() {
            return {
                selectedItems: [],
                overlayVisible: false,
                selectedFilters: [],
                mobileFiltersVisible: false,
                mobileFilterText: 'Show Filters'
            }
        },
      
        mounted() {
          
          const vm = this;

          vm.mobileFilterResize($(window).width());
          
          $(window).on('resize', () => {
              vm.mobileFilterResize($(window).width());
          });
            
        },


        computed: {

            itemLists() {

                return [

                    {
                        id: 'bundleList',
                        title: 'Your pack',
                        subtitle: 'Build your pack or start questionnaire to let us guide you.',
                        buttonLabel: 'Remove item',
                        buttonAction: (i) => this.unselectItem(i),
                        dataset: this.selectedItems,
                        emptySetMessage: "Your pack is currently empty.",
                        showBasketButton: true,
                        showViewPackButton: true,
                        classes: 'bundleItems',
                        isOverlay: false,
                        showFilters: false,
                    },

                    {
                        id: 'bundleAvailableItems',
                        title: 'Available items',
                        subtitle: 'Select the items you would like to add to your pack.',
                        buttonLabel: 'Add to your pack',
                        buttonLabelActive: 'Remove from pack',
                        buttonAction: (i) => this.selectItem(i),
                        buttonActionAlt: (i) => this.unselectItem(i),
                        dataset: this.unselectedItems,
                        emptySetMessage: "Your bundle contains all currently available items.",
                        showBasketButton: false,
                        showViewPackButton: false,
                        classes: 'bundleItemsSelected',
                        isOverlay: true,
                        showFilters: true,
                    },

                ];
            },


            unselectedItems() {
                let tempItems = this.availableItems.filter( item => ! this.selectedItems.includes(item) );

                if (this.selectedFilters.length > 0) {
                    tempItems = tempItems.filter( (item) => {
                        let item_tags = item.shop_item.filter_tags.map(t => t.label);
                        let intersection = this.selectedFilters.filter(f => item_tags.includes(f));

                        if (intersection.length == this.selectedFilters.length) return true;
                    });
                }

                return tempItems;
            },

        },


        created() {
            for (let i = 0; i < this.availableItems.length; i++) {
                if (this.preselectedItemIds.includes(this.availableItems[i].id)) {
                    this.selectedItems.push(this.availableItems[i]);
                }
            }
        },


        methods: {
          
            mobileFilterResize(width) {
              
                if(width <= 750) {
                    this.mobileFiltersVisible = false;
                }else{
                  this.mobileFiltersVisible = true;
                }
                
            },
          
            toggleMobileFilters() {
                this.mobileFiltersVisible = !this.mobileFiltersVisible;
                
                if(!this.mobileFiltersVisible) {
                    this.mobileFilterText = 'Show Filters';
                }else{
                  this.mobileFilterText = 'Done Filtering';
                }
            },

            submit() {
                let itemIDs = this.selectedItems.map((i) => i.id);

                this.$http.post(this.urlSubmitSelectedItems, {
                    item_ids: itemIDs,
                    bundle_id: this.bundleId,
                })
                .then((res) => {
                    if (res.data.success) {
                        let redirect_url = res.data.redirect_url || '/shop/checkout/basket.php';
                        window.location = redirect_url;
                    }
                })
                .catch((error) => {
                    console.error(error);
                });

            },


            scrollTo(id) {

                let $ele = $('#' + id);

                if ($ele.length) {

                    let offset = $ele.offset();

                    if (offset.hasOwnProperty('top')) {

                        $('html, body').stop(true, true).delay(200).animate({
                            scrollTop: (offset.top - 40)
                        }, 1000);

                    }

                }

            },


            selectItem(i) {
                this.selectedItems.push(i);
            },

            unselectItem(i) {
                let indexToRemove = this.selectedItems.indexOf(i);
                this.selectedItems.splice(indexToRemove, 1);
            },


            selectFilter(f) {
                this.selectedFilters.push(f);
            },

            unselectFilter(f) {
                let indexToRemove = this.selectedFilters.indexOf(f);
                this.selectedFilters.splice(indexToRemove, 1);
            },

            toggleFilter(f) {
                if (this.selectedFilters.includes(f)) {
                    this.unselectFilter(f);
                } else {
                    this.selectFilter(f);
                }
            },
          
            resetFilters() {
                this.selectedFilters = [];
            },
          
            openOverlay(open) {

                this.overlayVisible = open;
                let target = document.querySelector('.siteInnerWrapper');

                if (this.overlayVisible) {
                    target.classList.toggle('bundleOverlayOpen');
                } else {
                    target.classList.remove('bundleOverlayOpen');
                }

            }

        },

    }

</script>
