import Vue from 'vue';
import { config } from './config.js';
window.globalConfig = config;

// Import vue-wrapper for side effects (VueResource setup, directives, filters)
import './vue-wrapper.js';

// Set production mode when not in development
if (process.env.NODE_ENV === 'production') {
  Vue.config.productionTip = false;
}

import {EventBus, vueEventHub} from "./event-bus";
window.EventBus = EventBus;
window.vueEventHub = vueEventHub;

// Vue component that renders menu structure with dropdowns and mega menus (desktop hover/click behavior)
import mtcMenu from '@components/navigation/menu.vue';
Vue.component("mtc-menu", mtcMenu);

import trustpilotWidget from '@components/shop/item/partials/trustpilot.vue';
Vue.component("trustpilot-widget",trustpilotWidget);

/*
* Font awesome
*/
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/vue-fontawesome';

/* import specific icons */
import { faUpload } from '@fortawesome/pro-regular-svg-icons/faUpload';
import { faCircleXmark } from '@fortawesome/pro-regular-svg-icons/faCircleXmark';
import { faXmark } from '@fortawesome/pro-regular-svg-icons/faXmark';
import { faMagnifyingGlass } from '@fortawesome/pro-regular-svg-icons/faMagnifyingGlass';
import { faTrash } from '@fortawesome/pro-regular-svg-icons/faTrash';
library.add(faUpload, faCircleXmark, faXmark, faMagnifyingGlass, faTrash);
Vue.component('font-awesome-icon', FontAwesomeIcon);

// Slider (Vue 2 compatible wrapper around Swiper 8 core)
import 'swiper/css';
// Optional module CSS (Swiper 8)
import 'swiper/css/navigation';
import 'swiper/css/pagination';
import 'swiper/css/thumbs';
import 'swiper/css/effect-fade';

import MtcSliderWrapper from '@components/mtc_slider_wrapper.vue';
import SwiperCompat from '@components/swiper/Swiper.vue';
import SwiperSlideCompat from '@components/swiper/SwiperSlide.vue';

Vue.component('mtc-slider', MtcSliderWrapper);
Vue.component('mtc-swiper', SwiperCompat);
Vue.component('mtc-slide', SwiperSlideCompat);

/*
* Core
 */
import "@core/js/functions.js";
import "@core/js/plugins/mtc_mobile_menu.js";
import "@core/js/plugins/mtc_multi_currency.js";
import "@core/js/plugins/mtc_responsive_tables.js";
import "@core/js/plugins/mtc_number_arrows.js";
import "@core/js/plugins/mtc_tabs.js";
import "@core/js/plugins/mtc_waypoints.js";
import "@core/js/plugins/mtc_waysticky.js";
import "@core/js/site_scripts/mtc_show_hide_menus.js";
import "@core/js/plugins/mtc_zoom.js";
import "../../../cms/js/mtc_contact.js";
import "../../../cms/js/mtc_faq_section.js";
import "../../../modules/Members/js/mtc_members.js";
import "@plugins/GoogleMaps/js/mtc_google_maps.js";
import "@plugins/Judopay/js/judopay.js";
import "@shop/js/mtc_checkout.js";
import "@shop/js/mtc_checkout_mobile.js";
import "@shop/js/mtc_checkout_stripe.js";
import "@shop/js/mtc_checkout_worldpay.js";
import "@shop/js/mtc_payment_button.js";


import mtcMinibasket from '@components/shop/basket/mtc_minibasket.vue';
Vue.component('mtc-minibasket', mtcMinibasket);

import loadingSpinner from '@components/loading_spinner.vue';
Vue.component("loading-spinner", loadingSpinner);

import componentRegistry from '@components/component_registry.vue';
Vue.component("component-registry", componentRegistry);

import productSidebar from "@components/shop/item/product_sidebar.vue";
Vue.component('product-sidebar', productSidebar);

import BrowsePage from "@components/shop/browse/browse_page.vue";
Vue.component('browse-page', BrowsePage);

import multiCurrencyPrice from "@components/multi_currency_price.vue";
Vue.component('multi-currency-price', multiCurrencyPrice);

import stockBadge from '@components/shop/item/partials/stock_badge.vue';
Vue.component("stock-badge", stockBadge);

import productCard from "@components/shop/item/product_card.vue";
Vue.component("product-card", productCard);

import productImages from "@components/shop/item/partials/product_images.vue";
Vue.component("product-images", productImages);

import productSlider from "@components/shop/featured/product_slider.vue";
Vue.component("product-slider", productSlider);

import categoryProducts from "@components/shop/browse/category_products.vue";
Vue.component("category-products", categoryProducts);

import assessmentSteps from "@components/assessment/external/assessment_steps.vue";
Vue.component("assessment-steps", assessmentSteps);

import assessmentForm from "@components/assessment/assessment_form.vue";
Vue.component("assessment-form", assessmentForm);

import gpSurgerySearch from '@components/gp_surgery_search.vue';
Vue.component("gp-surgery-search", gpSurgerySearch);

// jQuery script that adds mobile accordion behavior and menu ready state (complements the mtc-menu Vue component)
import "@site_scripts/mtc_menu.js";
import "@site_scripts/mtc_accordions.js";
import "@site_scripts/mtc_content_sidebar.js";
import "@site_scripts/mtc_item.js";
import "@site_scripts/mtc_faqs.js";

// Delivery timer functionality: mtc_countdown.js provides the jQuery countdown plugin library, mtc_timers.js initializes it for basket delivery cutoff times
import "@site_scripts/mtc_countdown.js";
import "@site_scripts/mtc_timers.js";

// Vue search component for autocomplete functionality and jQuery handlers for search toggle
import "@site_scripts/mtc_search.js";
import "@site_scripts/mtc_overlay.js";

// Members verification
import "@site_scripts/mtc_account_verify.js";

// B2B trade account orders (self-guarding: no-ops when B2B elements absent)
import "@site_scripts/mtc_b2b_account_orders.js";

//Sidebar Functionality
import "@site_scripts/mtc_sidebar.js";

// Main script file
import "./script.js";

import DatePicker from '@components/date_picker.vue';
Vue.component('datepicker', DatePicker);

import Chosen from '@components/chosen.vue';
Vue.component('chosen', Chosen);

/*
* Replacement for tagit
 */
import VueTagsInput from '@johmun/vue-tags-input';
Vue.component('vue-tags-input', VueTagsInput);

import MtcTagInput from '@components/mtc_tag_input.vue';
Vue.component('mtc-tag-input', MtcTagInput);

//Assessment Store
import store from '@components/store/store.js';


$(function () {
    if ($.fn.mtcOverlay) {
        $('.alternativeTrigger').mtcOverlay({
            content_class: 'overlaySidePanel alternativeOverlayBox',
            margin_vertical: 0,
            margin_horizontal: 0
        });
    }

    if (!document.getElementById('alternative-overlay-inline-css')) {
        $('head').append(
            '<style id="alternative-overlay-inline-css">' +
                '.alternativeAddForm .js-alt-status { font-size:13px; margin-left:8px; min-width:120px; }' +
                '.alternativeAddForm .js-alt-status.is-success { color: var(--primary_color, #2e8b57); }' +
                '.alternativeAddForm .js-alt-status.is-error { color: var(--alert_color, #b02a37); }' +
                '.alternativeAddForm .js-alt-size.is-error { border-color: var(--alert_color, #b02a37); }' +
                '.alternativeAddForm .buttonAlt.is-loading { opacity: 0.6; pointer-events: none; }' +
            '</style>'
        );
    }

    $(document).on('change', '.alternativeAddForm .js-alt-size', function () {
        $(this).removeClass('is-error');
        const $status = $(this).closest('.alternativeAddForm').find('.js-alt-status');
        $status.text('').removeClass('is-error is-success');
    });

    $(document).on('click', '.js-alt-add', function (event) {
        event.preventDefault();

        const $button = $(this);
        const $container = $button.closest('.alternativeAddForm');
        const itemId = Number($container.data('item-id'));
        const redirectUrl = $container.data('redirect') || '';
        const $sizeField = $container.find('.js-alt-size').first();
        const requiresSize = $sizeField.length && $sizeField.is('select') && $sizeField.prop('required');
        const sizeValue = $sizeField.val();
        const $qtyField = $container.find('.js-alt-qty').first();
        const quantity = Math.max(parseInt($qtyField.val(), 10) || 1, 1);
        const $status = $container.find('.js-alt-status');

        let hideStatusTimer = $status.data('altTimer');
        if (hideStatusTimer) {
            clearTimeout(hideStatusTimer);
        }

        $status.removeClass('is-error is-success');

        if (!itemId) {
            return;
        }

        if (requiresSize && !sizeValue) {
            $sizeField.addClass('is-error');
            $status.text('Choose a pack size.').addClass('is-error');
            return;
        }

        const payload = {
            ajax: 1,
            id: itemId,
            quantity,
            url_redirect: redirectUrl
        };

        if (typeof sizeValue !== 'undefined') {
            payload.size = sizeValue || '';
        }

        $button.addClass('is-loading').prop('disabled', true);
        $.ajax({
            url: '/shop/addtobasket.php',
            method: 'POST',
            dataType: 'json',
            data: payload
        })
            .done(function (response) {
                const status = response && response.status;

                if (status === 'ok') {
                    $status.text('Added to basket.').addClass('is-success');
                    if (window.EventBus && typeof window.EventBus.$emit === 'function') {
                        window.EventBus.$emit('receiveBasketUpdate');
                    }

                    window.setTimeout(function () {
                        const $overlayBox = $button.closest('.overlayBox');
                        if ($overlayBox.length) {
                            $overlayBox.find('.overlayCloseButton > a').trigger('click');
                        }
                    }, 300);
                } else {
                    const message = (response && response.message) || 'Unable to add to basket.';
                    $status.text(message).addClass('is-error');

                    if (response && response.error === 'size' && requiresSize) {
                        $sizeField.addClass('is-error');
                    }
                }
            })
            .fail(function () {
                $status.text('Unable to add to basket.').addClass('is-error');
            })
            .always(function () {
                $button.removeClass('is-loading').prop('disabled', false);
                const timer = window.setTimeout(function () {
                    $status.text('').removeClass('is-error is-success');
                }, 4000);
                $status.data('altTimer', timer);
            });
    });
});
$.holdReady(true);

window.vue_environment = new Vue({
    el: '#vue_environment',
    store,
    delimiters: ['[%', '%]'],
    mounted() {
        $.holdReady(false);
    }
});
