

<my-nav></my-nav>

@push('scripts')

<script type="text/x-template" id="my-nav-template">
    <nav class="no-mobile container" id="menu">
        <ul class="link-list">
            <!-- Categories expand -->
            <li class="service-li active skewed edited" @click.prevent="getCategories">
                <a href="#" class="categories">
                    <div class="burger">
                        <span class="line line-1"></span>
                        <span class="line line-2"></span>
                        <span class="line line-3"></span>
                    </div>
                    <span class="link-text white-text">{{__('shop::app.header.categories')}}</span>
                </a>
                <!-- Spinner -->
                <div v-if="loading" class="lds-ring"><div></div><div></div><div></div><div></div></div>
                <!-- Spinner end -->
            </li>
            <!-- Categories expand end -->
            <li class="service-li skewed">
                <a href="{{route('shop.cms.page',['slug' => 'eltip-berme-hyzmaty-barada'])}}">
                    <span class="link-text">{{__('shop::app.header.shipment')}}</span>
                </a>
            </li>
            <li class="service-li skewed">
                <a href="{{route('shop.cms.page',['slug' => 'hyzmatlar-merkezi'])}}">
                    <span class="link-text">{{__('shop::app.header.service')}}</span>
                </a>
            </li>
            <li class="service-li skewed">
                <a href="{{route('shop.cms.page',['slug' => 'harydy-gaytarmak-we-calyshmak'])}}">
                    <span class="link-text">{{__('shop::app.header.refund')}}</span>
                </a>
            </li>
            <li class="service-li skewed">
                <a href="{{route('shop.cms.page',['slug' => 'ordering'])}}">
                    <span class="link-text displaced-text">{{__('shop::app.header.ordering')}}</span>
                </a>
            </li>
            <li>
                <div class="cat-dropdown">
                    <div class="cat-dropdown-inner">
                        <ul>
                            <!-- Loop root categories -->
                            <li class="cat-li" v-for="category in categories" @click.capture="expandChildCategories($event)"><span>@{{ category.name }}</span>
                                <div class="cat-arrow">
                                    <img src="{{bagisto_asset('icons/arrow-dropdown.svg')}}" alt="arrow">
                                </div>
                            </li>
                            <!-- Loop root categories end -->
                        </ul>
                    </div>
                </div>

                <!-- Loop root categories -->
                <div class="cat-data-block cat-data" v-for="category in categories" :data-img="category.image_url">
                    <!-- Loop children categories -->
                    <ul v-for="child_category in category.children">
                        <li><a :href="'/' + child_category.url_path" class="data-title">@{{ child_category.name }}</a></li>

                        <!-- Loop grandchildren categories -->
                        <li v-for="grand_child_category in child_category.children">
                            <a :href="'/' + grand_child_category.url_path" class="data-text">@{{grand_child_category.name}}</a>
                        </li>
                        <!-- Loop grandchildren categories end -->
                    </ul>
                    <!-- Loop children categories end -->
                </div>
                <!-- Loop root categories end -->


            </li>
        </ul>
    </nav>
</script>

<script>
    Vue.component('my-nav', {
        template: '#my-nav-template',
        props: {
        },
        data () {
            return {
                categories: [],
                checker: true, // from app.js
                last: undefined, // from app.js

                // Frontend Dom Elements
                catBlock: undefined, // from app.js
                lis: undefined, // from app.js
                cat: undefined, // from app.js

                loading: false,
            }
        },
        methods: {
            getCategories() {
                if(!this.categories.length) { // if we have not fetched categories yet

                    this.setLoading(true)

                    fetch("{!! route('descendant-categories', ['parent_id' => 1,'locale'=>\Illuminate\Support\Facades\App::getLocale()]) !!} ")
                    .then(res => res.json())
                    .then(res => {
                        this.categories = res.data
                    })
                    .then(() => {

                        // when all categories are fetched, query DOM elements
                        this.queryDomElements()

                        // when all categories are fetched, numerator set data attrs
                        this.numerator('cat-li')
                        this.numerator('cat-bg')
                        this.numerator('cat-data-block')

                        // todo: Toggle categories DOM elements
                        this.toggleCategoriesDomElements()

                        // set bg to category blocks
                        this.setBgToCategoryBlocks()

                        this.setLoading(false)
                    })
                    .catch(err => {
                        alert(err)
                        this.categories = []
                        this.checker = true
                        this.last = undefined

                        // Set empty DOM elements
                        this.catBlock = undefined
                        this.lis = undefined
                        this.cat = undefined

                        this.setLoading(false)
                    })
                } else { // if we have already fetched categories
                    // todo: Toggle categories DOM elements
                    this.toggleCategoriesDomElements()
                }
            },

            /**
             * Quering DOM elements after categories are fetched
             * Called one time
             * when categories are fetched - in `promise`
             */
            queryDomElements() {
                this.catBlock = document.querySelectorAll('.cat-data-block');
                this.lis = document.querySelectorAll('.cat-li');
                this.cat = document.querySelector('.cat-dropdown');
            },

            /**
             * Can be called two times
             * when categories are fecthed in `promise`
             * when categories have already been fecthed in `else` section
             */
            toggleCategoriesDomElements() {

                this.cat.classList.toggle('active');

                if (this.checker) {

                    this.catBlock[0].classList.toggle('active');
                    this.lis[0].classList.toggle('active');
                    this.checker = false;
                } else {
                    if (this.last) {
                        this.catBlock[this.last].classList.toggle('active');
                        this.lis[this.last].classList.toggle('active');
                    } else {
                        this.catBlock[0].classList.toggle('active');
                        this.lis[0].classList.toggle('active');
                    }
                }
            },

            /**
             * Set bg to category blocks
             * Call one time
             * when categories are fetched - in `promise`
             */
            setBgToCategoryBlocks() {
                this.catBlock.forEach((el) => {
                    const imgPath = el.getAttribute('data-img');
                    el.style.background = `linear-gradient(
                    to right,
                    rgba(255, 255, 255, 1),
                    rgba(255, 255, 255, 0.4)
                ),
                url(${imgPath}), center, no-repeat`;
                    el.style.backgroundSize = 'cover';
                });
            },

            /**
             * Call one time
             * when categories are fetched - in `promise`
             */
            numerator(className) {
                const items = document.querySelectorAll(`.${className}`);
                items.forEach((el, i) => {
                    el.classList.add(`${className}-${i + 1}`);
                    el.setAttribute('data-index', i + 1);
                });
            },

            /**
             * Show child categories
             */
            expandChildCategories(e) {
                let el = e.target.tagName == 'LI' ? e.target : e.target.parentNode

                this.last = el.getAttribute('data-index') - 1
                this.catBlock.forEach((el) => {
                    el.classList.remove('active');
                })
                this.catBlock[this.last].classList.add('active')
                this.lis.forEach((el) => {
                    el.classList.remove('active');
                });
                el.classList.add('active');
            },

            /**
             * Set loading config while categories are fetched
             */
            setLoading(loading) {
                this.loading = loading
                document.querySelector('a.categories').style.opacity = loading ? 0 : 1
            },
            handleClickOutside(event) {
                if (!this.$el.contains(event.target) && this.cat?.classList?.contains("active")) {
                    this.toggleCategoriesDomElements();
                }
            }
        },
        mounted() {
            document.addEventListener('click', this.handleClickOutside);
        },
        beforeDestroy() {
            document.removeEventListener('click', this.handleClickOutside);
        },
    })
</script>

@endpush