@php
    $template = 'template' . $site_configurations->template_id;
@endphp
@extends('frontend.app')
@section('title', $general_settings->title)
@section('meta_title', $general_settings->meta_title)
@section('meta_description', $general_settings->meta_description)
@section('meta_key', $general_settings->meta_key)
@section('meta_content', $general_settings->meta_content)
@section('content')


    <!--============ Banner Area Start ============-->
    <div class="banner_area section_padding_bottom">
        <div class="banner_area">
            <div class="banner_template_container">
                <div class="slider_banner_active owl-carousel">
                    @foreach ($sliders as $slider)
                        <div class="slider_banner_item">
                            <a href="{{ $slider->url }}" target="_blank">
                                <img src="{{ asset('storage/' . $slider->image) }}" alt="{{ $slider->url }}">
                            </a>
                        </div>
                    @endforeach

                </div>
            </div>
        </div>
    </div>
    <!--============ Banner Area End ============-->

    <!--============ Delicery Features Area Start ============-->
    @include('frontend.pages.delivery_features')
    <!--============ Delicery Features Area End ============-->

    <!--============ Category Area Start ============-->
    <section class="category_area section_padding_bottom">
        <div class="container">
            <div class="row">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="section_title text-center">
                        <h2>Categories</h2>
                        <div>
                            <hr class="title_bottom_underline">
                            <div class="title_bottom_over_underline"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container section_top_space">
            <div class="row">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="category_container">
                        @foreach ($top_section_categories as $category)
                            <div class="category_item">
                                <a href="{{ route('product.category', [$category->slug]) }}" class="category_item_link">
                                    <div class="category_image">
                                        <img src="{{ asset('storage/' . $category->icon_image) }}"
                                            alt="{{ $category->name }}" style="aspect-ratio:{{ $site_configurations->image_aspect_ratio }}">
                                    </div>
                                    <div class="category_name">
                                        <p>{{ $category->name }}</p>
                                    </div>
                                </a>
                            </div>
                        @endforeach
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!--============ Category Area End ============-->


    <!--============ New Arrival Products Area Start ============-->
    <section class="new_arrival_area section_padding_bottom">
        <div class="container">
            <div class="row">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="section_title text-center">
                        <h2>New Arrival Products</h2>
                        <div>
                            <hr class="title_bottom_underline">
                            <div class="title_bottom_over_underline"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container section_top_space">
            <div class="row gy-2 gx-2 gy-lg-3 gx-lg-3">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="carousel_new_arrival_content">
                        <button class="carousel_new_arrival_pre_btn">
                            <i class="fa-solid fa-arrow-right"></i>
                        </button>
                        <button class="carousel_new_arrival_next_btn">
                            <i class="fa-solid fa-arrow-left"></i>
                        </button>
                        <div class="carousel_new_arrival_table_cell">
                            @foreach ($new_arrival_products as $product)
                                <div class="carousel_new_arrival_item">
                                    @include("frontend.components.product_content.$template", ['product' => $product])
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!--============ New Arrival Products Area End ============-->

    <!--============ Top Selling Products Area Start ============-->
    <section class="top_sell_area section_padding_bottom">
        <div class="container">
            <div class="row">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="section_title text-center">
                        <h2>Top Selling Products</h2>
                        <div>
                            <hr class="title_bottom_underline">
                            <div class="title_bottom_over_underline"></div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
        <div class="container section_top_space">
            <div class="row gy-2 gx-2 gy-lg-3 gx-lg-3">
                <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                    <div class="carousel_top_sell_content">
                        <button class="carousel_top_sell_pre_btn">
                            <i class="fa-solid fa-arrow-right"></i>
                        </button>
                        <button class="carousel_top_sell_next_btn">
                            <i class="fa-solid fa-arrow-left"></i>
                        </button>
                        <div class="carousel_top_sell_table_cell">
                            @foreach ($top_selling_products as $product)
                                <div class="carousel_top_sell_item">
                                    @include("frontend.components.product_content.$template", ['product' => $product])
                                </div>
                            @endforeach
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
    <!--============ NeTop Selling Products Area End ============-->

    <!--============ Advertisement Banner Area Start ============-->
    <div class="advertisement_area section_padding_bottom">
        <div class="container">
            <div class="row gy-md-3 gx-md-3 gy-2 gx-2">
                @foreach ($after_top_selling_banner as $banner)
                    <div class="col-xxl-6 col-xl-6 col-lg-6 col-md-6 col-sm-6 col-6">
                        <div class="advertisement_image">
                            <a href="{{ $banner->url }}">
                                <img src="{{ asset('storage/' . $banner->banner) }}" alt="advertisement">
                            </a>
                        </div>
                    </div>
                @endforeach
            </div>
        </div>
    </div>
    <!--============ Advertisement Banner Area End ============-->

    <!--============ Category Wise Multiple Product Area Start ============-->
    <div id="loadmore_category_product">
    </div>
    <!--============ Category Wise Multiple Product Area End ============-->

    <!--================Loading Spinner Start==========================-->
    <div id="spinner" style=" display: none;text-align: center;">
        <img src="{{ asset('frontend/images/spinner/200w.gif') }}" alt="Loading...">
    </div>
    <!--================Loading Spinner end==========================-->

    <!--============ Advertisement Banner Area Start ============-->
    @if ($before_footer_section)
        <div class="advertisement_area section_padding_bottom">
            <div class="container">
                <div class="row gy-md-3 gx-md-3 gy-2 gx-2">
                    <div class="col-xxl-12 col-xl-12 col-lg-12 col-md-12 col-sm-12 col-12">
                        <div class="advertisement_image">
                            <a href="{{ $before_footer_section->url }}">
                                <img src="{{ asset('storage/' . $before_footer_section->banner) }}" alt="advertisement">
                            </a>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    @endif
    <!--============ Advertisement Banner Area End ============-->

    <!--============ Customer Review Section Area Start    ============-->
    @if ($cus_review->isNotEmpty())
        @include('frontend.pages.review', ['cus_review' => $cus_review])
    @endif
    <!--============ Customer Review Section Area End    ============-->



@endsection

@section('scripts')

    <!-- new arrival slide -->
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const carousels = document.querySelectorAll('.carousel_new_arrival_table_cell');
            const carouselNxtBtn = document.querySelectorAll('.carousel_new_arrival_next_btn');
            const carouselPreBtn = document.querySelectorAll('.carousel_new_arrival_pre_btn');

            function updateCarouselLayout() {
                carousels.forEach(carousel => {
                    const items = carousel.querySelectorAll('.carousel_new_arrival_item');
                    let itemsToShow = {{ $site_configurations->carousel_card_row }};

                    if (window.innerWidth < 1500) {
                        itemsToShow = {{ $site_configurations->carousel_card_row }};
                    }
                    if (window.innerWidth < 1400) {
                        itemsToShow = 4;
                    }
                    if (window.innerWidth < 1200) {
                        itemsToShow = 3;
                    }
                    if (window.innerWidth < 992) {
                        itemsToShow = 3;
                    }
                    if (window.innerWidth < 768) {
                        itemsToShow = 2;
                    }
                    if (window.innerWidth < 576) {
                        itemsToShow = 2;
                    }

                    const itemWidth = carousel.offsetWidth / itemsToShow;
                    items.forEach(item => {
                        item.style.width = `${itemWidth}px`;
                    });

                    carousel.dataset.itemWidth = itemWidth;

                    // Check if carousel has overflow
                    if (carousel.scrollWidth > carousel.clientWidth) {
                        carouselNxtBtn.forEach(btn => btn.style.display = "block");
                        carouselPreBtn.forEach(btn => btn.style.display = "block");
                    } else {
                        carouselNxtBtn.forEach(btn => btn.style.display = "none");
                        carouselPreBtn.forEach(btn => btn.style.display = "none");
                    }
                });
            }

            carousels.forEach((carousel, i) => {
                const items = [...carousel.querySelectorAll('.carousel_new_arrival_item')];
                const itemWidth = items[0].offsetWidth;

                items.forEach(item => carousel.appendChild(item.cloneNode(true)));

                const resetScrollPosition = () => {
                    if (carousel.scrollLeft + itemWidth >= carousel.scrollWidth / 2) {
                        carousel.scrollLeft = 0; 
                    }
                };

                carouselNxtBtn[i].addEventListener('click', () => {
                    carousel.scrollLeft += itemWidth;
                    resetScrollPosition();
                });

                carouselPreBtn[i].addEventListener('click', () => {
                    if (carousel.scrollLeft <= 0) {
                        carousel.scrollLeft = carousel.scrollWidth / 2;
                    } else {
                        carousel.scrollLeft -= itemWidth;
                    }
                });

                let isHovering = false;

                carousel.addEventListener("mouseenter", () => {
                    isHovering = true;
                    clearInterval(autoplayInterval);  
                });
                carousel.addEventListener("mouseleave", () => {
                    isHovering = false;
                    autoplayInterval = setInterval(() => {
                        if (!isHovering) {
                            carousel.scrollLeft += itemWidth;
                            resetScrollPosition();
                        }
                    }, 3000); 
                });

                // Start autoplay
                let autoplayInterval = setInterval(() => {
                    if (!isHovering) {
                        carousel.scrollLeft += itemWidth;
                        resetScrollPosition();
                    }
                }, 3000); 

                // Mouse drag scrolling functionality
                let isDragging = false;
                let startX, scrollLeft;

                carousel.addEventListener('mousedown', (e) => {
                    isDragging = true;
                    startX = e.pageX - carousel.offsetLeft;
                    scrollLeft = carousel.scrollLeft;
                    carousel.style.cursor = 'grabbing';
                });

                carousel.addEventListener('mouseleave', () => {
                    isDragging = false;
                    carousel.style.cursor = 'grab';
                });

                carousel.addEventListener('mouseup', () => {
                    isDragging = false;
                    carousel.style.cursor = 'grab';
                });

                carousel.addEventListener('mousemove', (e) => {
                    if (!isDragging) return;

                    e.preventDefault();  
                    const x = e.pageX - carousel.offsetLeft;
                    const walk = (x - startX) * 1;  
                    carousel.scrollLeft = scrollLeft - walk;
                });
            });

            // Listen for window resizing and update layout
            window.addEventListener("resize", updateCarouselLayout);
            updateCarouselLayout();
        });
    </script>

    <!-- Top selling paroduct slide -->
    <script>
        document.addEventListener("DOMContentLoaded", () => {
            const carousels = document.querySelectorAll('.carousel_top_sell_table_cell');
            const carouselNxtBtn = document.querySelectorAll('.carousel_top_sell_next_btn');
            const carouselPreBtn = document.querySelectorAll('.carousel_top_sell_pre_btn');

            function updateCarouselLayout() {
                carousels.forEach(carousel => {
                    const items = carousel.querySelectorAll('.carousel_top_sell_item');
                    let itemsToShow = {{ $site_configurations->carousel_card_row }};

                    if (window.innerWidth < 1500) {
                        itemsToShow = {{ $site_configurations->carousel_card_row }};
                    }
                    if (window.innerWidth < 1400) {
                        itemsToShow = 4;
                    }
                    if (window.innerWidth < 1200) {
                        itemsToShow = 3;
                    }
                    if (window.innerWidth < 992) {
                        itemsToShow = 3;
                    }
                    if (window.innerWidth < 768) {
                        itemsToShow = 2;
                    }
                    if (window.innerWidth < 576) {
                        itemsToShow = 2;
                    }

                    const itemWidth = carousel.offsetWidth / itemsToShow;
                    items.forEach(item => {
                        item.style.width = `${itemWidth}px`;
                    });

                    carousel.dataset.itemWidth = itemWidth;

                    // Check if carousel has overflow
                    if (carousel.scrollWidth > carousel.clientWidth) {
                        carouselNxtBtn.forEach(btn => btn.style.display = "block");
                        carouselPreBtn.forEach(btn => btn.style.display = "block");
                    } else {
                        carouselNxtBtn.forEach(btn => btn.style.display = "none");
                        carouselPreBtn.forEach(btn => btn.style.display = "none");
                    }
                });
            }

            carousels.forEach((carousel, i) => {
                const items = [...carousel.querySelectorAll('.carousel_top_sell_item')];
                const itemWidth = items[0].offsetWidth;

                items.forEach(item => carousel.appendChild(item.cloneNode(true)));

                const resetScrollPosition = () => {
                    if (carousel.scrollLeft + itemWidth >= carousel.scrollWidth / 2) {
                        carousel.scrollLeft = 0; 
                    }
                };

                carouselNxtBtn[i].addEventListener('click', () => {
                    carousel.scrollLeft += itemWidth;
                    resetScrollPosition();
                });

                carouselPreBtn[i].addEventListener('click', () => {
                    if (carousel.scrollLeft <= 0) {
                        carousel.scrollLeft = carousel.scrollWidth / 2;
                    } else {
                        carousel.scrollLeft -= itemWidth;
                    }
                });

                let isHovering = false;

                carousel.addEventListener("mouseenter", () => {
                    isHovering = true;
                    clearInterval(autoplayInterval);  
                });
                carousel.addEventListener("mouseleave", () => {
                    isHovering = false;
                    autoplayInterval = setInterval(() => {
                        if (!isHovering) {
                            carousel.scrollLeft += itemWidth;
                            resetScrollPosition();
                        }
                    }, 3000); 
                });

                // Start autoplay
                let autoplayInterval = setInterval(() => {
                    if (!isHovering) {
                        carousel.scrollLeft += itemWidth;
                        resetScrollPosition();
                    }
                }, 3000); 

                // Mouse drag scrolling functionality
                let isDragging = false;
                let startX, scrollLeft;

                carousel.addEventListener('mousedown', (e) => {
                    isDragging = true;
                    startX = e.pageX - carousel.offsetLeft;
                    scrollLeft = carousel.scrollLeft;
                    carousel.style.cursor = 'grabbing';
                });

                carousel.addEventListener('mouseleave', () => {
                    isDragging = false;
                    carousel.style.cursor = 'grab';
                });

                carousel.addEventListener('mouseup', () => {
                    isDragging = false;
                    carousel.style.cursor = 'grab';
                });

                carousel.addEventListener('mousemove', (e) => {
                    if (!isDragging) return;

                    e.preventDefault();  
                    const x = e.pageX - carousel.offsetLeft;
                    const walk = (x - startX) * 1;  
                    carousel.scrollLeft = scrollLeft - walk;
                });
            });

            // Listen for window resizing and update layout
            window.addEventListener("resize", updateCarouselLayout);
            updateCarouselLayout();
        });
    </script>

    <script>
        var isLoading = false;
        //================load data========================
        function loadData() {
            console.log('loading....');
            isLoading = true; // Set loading flag to true
            $('#spinner').show();

            var data = {
                page: 1,
                limit: 2
            };

            $.ajax({
                url: "{{ route('load.more.category.product') }}",
                type: 'POST',
                dataType: 'json',
                data: {
                    page: data.page,
                    limit: data.limit
                },
                success: function(res) {
                    $('#loadmore_category_product').append(res.data);
                    isLoading = false;
                    $('#spinner').hide();
                },
                error: function(xhr, status, error) {
                    console.error(error);
                    isLoading = false;
                }
            });
        }



        //==========================load more data===========================
        $(function() {
            loadData();

            isLoading = true; // Set loading flag to true
            $('#spinner').show();

            var data = {
                page: 2,
                limit: 2
            };

            var obj = $(document).loadMore({
                loadType: 'auto',
                url: "{{ route('load.more.category.product') }}",
                dataType: 'json',
                type: 'post',
                scrollBottom: 700,
                data: {
                    page: data.page,
                    limit: data.limit
                },
                success: function(res) {
                    if (res.category_length == 0) {
                        this.ajaxSwitch = false;
                    }
                    data.page += 1;
                    obj.updatePram('data', data);
                    render(res.data);

                    isLoading = false;
                    $('#spinner').hide();
                }
            });

            function render(data) {
                $("#loadmore_category_product").append(data);
            }


        });
    </script>
@endsection
