(function ($) {
    "use strict";
    /*===================================================================================*/
    /*	OWL CAROUSEL
    /*===================================================================================*/
    $(document).ready(function () {
        var dragging = true;
        var owlElementID = "#owl-main";

        function fadeInReset() {
            if (!dragging) {
                $(owlElementID + " .caption .fadeIn-1, " + owlElementID + " .caption .fadeIn-2, " + owlElementID + " .caption .fadeIn-3").stop().delay(800).animate({ opacity: 0 }, { duration: 400, easing: "easeInCubic" });
            }
            else {
                $(owlElementID + " .caption .fadeIn-1, " + owlElementID + " .caption .fadeIn-2, " + owlElementID + " .caption .fadeIn-3").css({ opacity: 0 });
            }
        }

        function fadeInDownReset() {
            if (!dragging) {
                $(owlElementID + " .caption .fadeInDown-1, " + owlElementID + " .caption .fadeInDown-2, " + owlElementID + " .caption .fadeInDown-3").stop().delay(800).animate({ opacity: 0, top: "-15px" }, { duration: 400, easing: "easeInCubic" });
            }
            else {
                $(owlElementID + " .caption .fadeInDown-1, " + owlElementID + " .caption .fadeInDown-2, " + owlElementID + " .caption .fadeInDown-3").css({ opacity: 0, top: "-15px" });
            }
        }

        function fadeInUpReset() {
            if (!dragging) {
                $(owlElementID + " .caption .fadeInUp-1, " + owlElementID + " .caption .fadeInUp-2, " + owlElementID + " .caption .fadeInUp-3").stop().delay(800).animate({ opacity: 0, top: "15px" }, { duration: 400, easing: "easeInCubic" });
            }
            else {
                $(owlElementID + " .caption .fadeInUp-1, " + owlElementID + " .caption .fadeInUp-2, " + owlElementID + " .caption .fadeInUp-3").css({ opacity: 0, top: "15px" });
            }
        }

        function fadeInLeftReset() {
            if (!dragging) {
                $(owlElementID + " .caption .fadeInLeft-1, " + owlElementID + " .caption .fadeInLeft-2, " + owlElementID + " .caption .fadeInLeft-3").stop().delay(800).animate({ opacity: 0, left: "15px" }, { duration: 400, easing: "easeInCubic" });
            }
            else {
                $(owlElementID + " .caption .fadeInLeft-1, " + owlElementID + " .caption .fadeInLeft-2, " + owlElementID + " .caption .fadeInLeft-3").css({ opacity: 0, left: "15px" });
            }
        }

        function fadeInRightReset() {
            if (!dragging) {
                $(owlElementID + " .caption .fadeInRight-1, " + owlElementID + " .caption .fadeInRight-2, " + owlElementID + " .caption .fadeInRight-3").stop().delay(800).animate({ opacity: 0, left: "-15px" }, { duration: 400, easing: "easeInCubic" });
            }
            else {
                $(owlElementID + " .caption .fadeInRight-1, " + owlElementID + " .caption .fadeInRight-2, " + owlElementID + " .caption .fadeInRight-3").css({ opacity: 0, left: "-15px" });
            }
        }

        function fadeIn() {
            $(owlElementID + " .active .caption .fadeIn-1").stop().delay(500).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeIn-2").stop().delay(700).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeIn-3").stop().delay(1000).animate({ opacity: 1 }, { duration: 800, easing: "easeOutCubic" });
        }

        function fadeInDown() {
            $(owlElementID + " .active .caption .fadeInDown-1").stop().delay(500).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInDown-2").stop().delay(700).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInDown-3").stop().delay(1000).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
        }

        function fadeInUp() {
            $(owlElementID + " .active .caption .fadeInUp-1").stop().delay(500).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInUp-2").stop().delay(700).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInUp-3").stop().delay(1000).animate({ opacity: 1, top: "0" }, { duration: 800, easing: "easeOutCubic" });
        }

        function fadeInLeft() {
            $(owlElementID + " .active .caption .fadeInLeft-1").stop().delay(500).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInLeft-2").stop().delay(700).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInLeft-3").stop().delay(1000).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
        }

        function fadeInRight() {
            $(owlElementID + " .active .caption .fadeInRight-1").stop().delay(500).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInRight-2").stop().delay(700).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
            $(owlElementID + " .active .caption .fadeInRight-3").stop().delay(1000).animate({ opacity: 1, left: "0" }, { duration: 800, easing: "easeOutCubic" });
        }

        $(owlElementID).owlCarousel({

            autoPlay: 5000,
            stopOnHover: true,
            navigation: true,
            pagination: true,
            singleItem: true,
            addClassActive: true,
            transitionStyle: "fade",
            navigationText: ["<i class='icon fa fa-angle-left'></i>", "<i class='icon fa fa-angle-right'></i>"],

            afterInit: function () {
                fadeIn();
                fadeInDown();
                fadeInUp();
                fadeInLeft();
                fadeInRight();
            },

            afterMove: function () {
                fadeIn();
                fadeInDown();
                fadeInUp();
                fadeInLeft();
                fadeInRight();
            },

            afterUpdate: function () {
                fadeIn();
                fadeInDown();
                fadeInUp();
                fadeInLeft();
                fadeInRight();
            },

            startDragging: function () {
                dragging = true;
            },

            afterAction: function () {
                fadeInReset();
                fadeInDownReset();
                fadeInUpReset();
                fadeInLeftReset();
                fadeInRightReset();
                dragging = false;
            }

        });

        if ($(owlElementID).hasClass("owl-one-item")) {
            $(owlElementID + ".owl-one-item").data('owlCarousel').destroy();
        }

        $(owlElementID + ".owl-one-item").owlCarousel({
            singleItem: true,
            navigation: false,
            pagination: false
        });

        $('#transitionType li a').click(function () {

            $('#transitionType li a').removeClass('active');
            $(this).addClass('active');

            var newValue = $(this).attr('data-transition-type');

            $(owlElementID).data("owlCarousel").transitionTypes(newValue);
            $(owlElementID).trigger("owl.next");

            return false;

        });

        $('.home-owl-carousel').each(function () {
            var owl = $(this);
            var itemPerLine = owl.data('item') || 4; // Default to 4 items per row

            owl.owlCarousel({
                items: itemPerLine,
                loop: false,
                margin: 10,
                nav: true,
                dots: true,
                autoplay: false,
                autoplayTimeout: 3000,
                responsive: {
                    0: { items: 2 }, // 2 items per row on mobile
                    600: { items: 2 }, // 2 items per row on tablets
                    1000: { items: 4 } // 4 items per row on desktops
                }
            });
        });

        // $('.home-owl-carousel').each(function(){
        //     var owl = $(this);
        //     var totalItems = owl.find('.product-item').length; // Count total products
        //     var itemPerLine = owl.data('item') || 4; // Default to 4 items per row

        //     // Ensure proper item count for the slider
        //     var itemsToShow = totalItems < itemPerLine ? totalItems : itemPerLine;

        //     owl.owlCarousel({
        //         items: itemsToShow, 
        //         loop: totalItems >= itemPerLine, // Disable loop if fewer items exist
        //         margin: 10,
        //         nav: true,
        //         dots: true,
        //         autoplay: false,
        //         autoplayTimeout: 3000,
        //         responsive: {
        //             0: { items: Math.min(2, totalItems) },  // Adjust dynamically
        //             600: { items: Math.min(2, totalItems) },
        //             1000: { items: itemsToShow } // Set actual product count or 4 max
        //         }
        //     });
        // });


        $('.homepage-owl-carousel').each(function () {

            var owl = $(this);
            var itemPerLine = owl.data('item');
            if (!itemPerLine) {
                itemPerLine = 4;
            }
            owl.owlCarousel({
                items: itemPerLine,
                itemsTablet: [768, 2],
                itemsDesktop: [1199, 2],
                navigation: true,
                pagination: false,

                navigationText: ["", ""]
            });
        });

        $('#owl-main').owlCarousel({
            items: 1,
            loop: true,
            nav: false,
            dots: true,
            autoplay: true,
            autoplayTimeout: 5000,
            smartSpeed: 1000
        });

        $(".blog-slider").owlCarousel({
            items: 3,
            itemsDesktopSmall: [979, 2],
            itemsDesktop: [1199, 2],
            navigation: true,
            slideSpeed: 300,
            pagination: false,
            navigationText: ["", ""]
        });

        $(".best-seller").owlCarousel({
            items: 3,
            navigation: true,
            itemsDesktopSmall: [979, 2],
            itemsDesktop: [1199, 2],
            slideSpeed: 300,
            pagination: false,
            paginationSpeed: 400,
            navigationText: ["", ""]
        });

        $(".sidebar-carousel").owlCarousel({
            items: 1,
            itemsTablet: [768, 2],
            itemsDesktopSmall: [979, 2],
            itemsDesktop: [1199, 1],
            navigation: true,
            slideSpeed: 300,
            pagination: false,
            paginationSpeed: 400,
            navigationText: ["", ""]
        });

        $(".brand-slider").owlCarousel({
            items: 6,
            navigation: true,
            slideSpeed: 300,
            pagination: false,
            paginationSpeed: 400,
            navigationText: ["", ""]
        });
        $("#advertisement").owlCarousel({
            items: 1,
            itemsDesktopSmall: [979, 2],
            itemsDesktop: [1199, 1],
            navigation: true,
            slideSpeed: 300,
            pagination: true,
            paginationSpeed: 400,
            navigationText: ["", ""]
        });

        var $owl_controls_custom = $('.owl-controls-custom');
        $('.owl-next', $owl_controls_custom).click(function (event) {
            var selector = $(this).data('owl-selector');
            var owl = $(selector).data('owlCarousel');
            owl.next();
            return false;
        });
        $('.owl-prev', $owl_controls_custom).click(function (event) {
            var selector = $(this).data('owl-selector');
            var owl = $(selector).data('owlCarousel');
            owl.prev();
            return false;
        });

        $(".owl-next").click(function () {
            $($(this).data('target')).trigger('owl.next');
            return false;
        });

        $(".owl-prev").click(function () {
            $($(this).data('target')).trigger('owl.prev');
            return false;
        });

    });

    // Lazy load removed to fix ReferenceError

    /*===================================================================================*/
    /*  RATING
    /*===================================================================================*/

    $(document).ready(function () {
        $('.rating').rateit({ max: 5, step: 1, value: 4, resetable: false, readonly: true });
    });

    /*===================================================================================*/
    /* PRICE SLIDER
    /*===================================================================================*/
    $(document).ready(function () {

        // Price Slider
        if ($('.price-slider').length > 0) {
            $('.price-slider').slider({
                min: 100,
                max: 700,
                step: 10,
                value: [200, 500],
                handle: "square"

            });

        }

    });


    /*===================================================================================*/
    /* SINGLE PRODUCT GALLERY
    /*===================================================================================*/
    $(document).ready(function () {
        $('#owl-single-product').owlCarousel({
            items: 1,
            itemsTablet: [768, 2],
            itemsDesktop: [1199, 1]

        });

        $('#owl-single-product-thumbnails').owlCarousel({
            items: 4,
            pagination: true,
            rewindNav: true,
            itemsTablet: [768, 4],
            itemsDesktop: [1199, 3]
        });

        $('#owl-single-product2-thumbnails').owlCarousel({
            items: 6,
            pagination: true,
            rewindNav: true,
            itemsTablet: [768, 4],
            itemsDesktop: [1199, 3]
        });

        $('.single-product-slider').owlCarousel({
            stopOnHover: true,
            rewindNav: true,
            singleItem: true,
            pagination: true
        });

        $(".slider-next").click(function () {
            var owl = $($(this).data('target'));
            owl.trigger('owl.next');
            return false;
        });

        $(".slider-prev").click(function () {
            var owl = $($(this).data('target'));
            owl.trigger('owl.prev');
            return false;
        });

        $('.single-product-gallery .horizontal-thumb').click(function () {
            var $this = $(this), owl = $($this.data('target')), slideTo = $this.data('slide');
            owl.trigger('owl.goTo', slideTo);
            $this.addClass('active').parent().siblings().find('.active').removeClass('active');
            return false;
        });
    });


    /*===================================================================================*/
    /*  QUANTITY
    /*===================================================================================*/

    $('.quant-input .plus').click(function () {
        var val = $(this).parent().next().val();
        val = parseInt(val) + 1;
        $(this).parent().next().val(val);
    });
    $('.quant-input .minus').click(function () {
        var val = $(this).parent().next().val();
        if (val > 0) {
            val = parseInt(val) - 1;
            $(this).parent().next().val(val);
        }
    });


    /*===================================================================================*/
    /*  WOW 
    /*===================================================================================*/

    $(document).ready(function () {
        new WOW().init();
    });


    /*===================================================================================*/
    /*  TOOLTIP 
    /*===================================================================================*/
    // $("[data-toggle='tooltip']").tooltip(); // Disabled - Using Bootstrap 5 vanilla JS tooltips instead

    $('#transitionType li a').click(function () {

        $('#transitionType li a').removeClass('active');
        $(this).addClass('active');

        var newValue = $(this).attr('data-transition-type');

        $(owlElementID).data("owlCarousel").transitionTypes(newValue);
        $(owlElementID).trigger("owl.next");

        return false;

    });





    /*===================================================================================*/
    /*  AJAX ACTIONS WITH TOAST & COUNTER UPDATES
    /*===================================================================================*/
    $(document).ready(function () {

        // Inject Toast Container
        if ($('#am-toast').length === 0) {
            $('body').append('<div id="am-toast"><i class="fa fa-info-circle"></i> <span>Message</span></div>');
        }

        // Toast Function
        function showToast(message, type = 'success') {
            var $toast = $('#am-toast');
            var icon = type === 'success' ? 'fa-check-circle' : 'fa-exclamation-circle';

            $toast.find('i').attr('class', 'fa ' + icon);
            $toast.find('span').text(message);
            $toast.removeClass('success error').addClass(type);
            $toast.addClass('show');

            setTimeout(function () {
                $toast.removeClass('show');
            }, 3000);
        }

        // Helper to extract URL params (Fixed order: url, param)
        function getParamFromUrl(url, param) {
            if (!url) return null;
            var parts = url.split('?');
            if (parts.length < 2) return null;
            var params = new URLSearchParams(parts[1]);
            return params.get(param);
        }

        // Add to Cart (Detail Page)
        $(document).on('click', '#addToCartBtn', function (e) {
            e.preventDefault();
            var $this = $(this);
            var id = $this.data('id');
            var qty = parseInt($('#mainQty').val()) || 1;

            if (!id) return;

            $.ajax({
                type: "POST",
                url: "ajax_action.php",
                dataType: "json",
                data: {
                    action: 'add_to_cart',
                    id: id,
                    quantity: qty
                },
                success: function (response) {
                    if (response.status === 'success') {
                        showToast(response.message, 'success');
                        if (response.cart_count !== undefined) {
                            var $count = $('#cart-count');
                            $count.text(response.cart_count);
                            $count.show();
                            $count.css('transform', 'scale(1.2)');
                            setTimeout(function () { $count.css('transform', 'scale(1)'); }, 200);
                        }
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function () {
                    showToast('An error occurred while adding to cart.', 'error');
                }
            });
        });

        // Add to Cart (App/Loop Buttons)
        $(document).on('click', '.btn-add-cart-app', function (e) {
            e.preventDefault();
            var $this = $(this);
            var href = $this.attr('href');
            var id = getParamFromUrl(href, 'id');

            if (!id) return;

            $.ajax({
                type: "POST",
                url: "ajax_action.php",
                dataType: "json",
                data: {
                    action: 'add_to_cart',
                    id: id
                },
                success: function (response) {
                    if (response.status === 'success') {
                        showToast(response.message, 'success');

                        // Update Cart Counter
                        if (response.cart_count !== undefined) {
                            var $count = $('#cart-count');
                            $count.text(response.cart_count);
                            $count.show(); // Ensure visibility if it was hidden

                            // Optional: simple bounce animation
                            $count.css('transform', 'scale(1.2)');
                            setTimeout(function () { $count.css('transform', 'scale(1)'); }, 200);
                        }
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function () {
                    showToast('An error occurred while adding to cart.', 'error');
                }
            });
        });

        // Wishlist Delete Button Click
        $(document).on('click', '.btn-wishlist-delete', function (e) {
            console.log('Delete button clicked!');
            e.preventDefault();
            e.stopPropagation();

            var $this = $(this);
            var delId = $this.data('del-id');
            console.log('Delete ID:', delId);

            if (!delId) {
                console.error('No delete ID found!');
                showToast('Invalid item ID', 'error');
                return;
            }

            // Use custom confirmation with SweetAlert-style approach
            // Create a simple inline confirm overlay
            var confirmHtml = `
                <div class="am-confirm-overlay" style="position: fixed; top: 0; left: 0; right: 0; bottom: 0; background: rgba(0,0,0,0.5); z-index: 9999; display: flex; align-items: center; justify-content: center;">
                    <div style="background: white; padding: 30px; border-radius: 8px; max-width: 400px; text-align: center; box-shadow: 0 10px 40px rgba(0,0,0,0.3);">
                        <div style="font-size: 48px; color: #ff4757; margin-bottom: 20px;">
                            <i class="fa fa-trash-o"></i>
                        </div>
                        <h3 style="margin-bottom: 10px; color: #333;">Remove from Wishlist?</h3>
                        <p style="color: #666; margin-bottom: 25px;">This item will be removed from your wishlist.</p>
                        <div style="display: flex; gap: 10px; justify-content: center;">
                            <button class="btn-confirm-yes" style="background: #ff4757; color: white; border: none; padding: 10px 30px; border-radius: 5px; cursor: pointer; font-weight: 600;">Yes, Remove</button>
                            <button class="btn-confirm-no" style="background: #e0e0e0; color: #333; border: none; padding: 10px 30px; border-radius: 5px; cursor: pointer; font-weight: 600;">Cancel</button>
                        </div>
                    </div>
                </div>
            `;

            var $confirm = $(confirmHtml).appendTo('body');

            // Handle Yes button
            $confirm.find('.btn-confirm-yes').on('click', function () {
                $confirm.remove();
                console.log('User confirmed deletion');
                console.log('Sending AJAX request to remove wishlist item:', delId);

                $.ajax({
                    type: "POST",
                    url: "ajax_action.php",
                    dataType: "json",
                    data: {
                        action: 'remove_wishlist',
                        wid: delId
                    },
                    beforeSend: function () {
                        console.log('AJAX request starting...');
                    },
                    success: function (response) {
                        console.log('Server response:', response);
                        if (response.status === 'success') {
                            console.log('Success! Removing item from page...');
                            // Find the parent column and remove it with animation
                            var $parent = $this.closest('.col-6, .col-md-4, .col-xl-3');
                            console.log('Parent element found:', $parent.length);
                            $parent.fadeOut(300, function () {
                                $(this).remove();
                                console.log('Item removed from DOM');
                            });
                            showToast(response.message, 'success');
                        } else {
                            console.error('Server returned error:', response.message);
                            showToast(response.message || 'Failed to remove item', 'error');
                        }
                    },
                    error: function (xhr, status, error) {
                        console.error('AJAX Error:', status, error);
                        console.error('Response Text:', xhr.responseText);
                        console.error('Status Code:', xhr.status);
                        showToast('An error occurred while removing from wishlist.', 'error');
                    }
                });
            });

            // Handle No/Cancel button
            $confirm.find('.btn-confirm-no').on('click', function () {
                console.log('User cancelled deletion');
                $confirm.remove();
            });

            // Handle clicking outside
            $confirm.on('click', function (e) {
                if ($(e.target).hasClass('am-confirm-overlay')) {
                    console.log('User cancelled deletion (clicked outside)');
                    $confirm.remove();
                }
            });
        });

        // Add to Wishlist Click (for product cards)
        $(document).on('click', '.btn-wishlist-app:not(.btn-wishlist-delete)', function (e) {
            e.preventDefault();

            var $this = $(this);
            var id = $this.data('id');
            var href = $this.attr('href');
            var delId = $this.data('del-id');

            // Del specific logic
            if (!delId && href) {
                delId = getParamFromUrl(href, 'del');
            }

            if (delId) {
                if (confirm("Are you sure you want to remove this from wishlist?")) {
                    $.ajax({
                        type: "POST",
                        url: "ajax_action.php",
                        dataType: "json",
                        data: {
                            action: 'remove_wishlist',
                            wid: delId
                        },
                        success: function (response) {
                            if (response.status === 'success') {
                                // Find the parent column and remove it with animation
                                $this.closest('.col-6, .col-md-4, .col-xl-3').fadeOut(300, function () {
                                    $(this).remove();
                                });
                                showToast(response.message, 'success');
                            } else {
                                showToast(response.message || 'Failed to remove item', 'error');
                            }
                        },
                        error: function (xhr, status, error) {
                            console.error('AJAX Error:', status, error);
                            showToast('An error occurred while removing from wishlist.', 'error');
                        }
                    });
                }
                return;
            }

            // Fallback to href pid if no data-id
            if (!id && href) {
                id = getParamFromUrl(href, 'pid') || getParamFromUrl(href, 'id');
            }

            if (!id) return;

            $.ajax({
                type: "POST",
                url: "ajax_action.php",
                dataType: "json",
                data: {
                    action: 'add_to_wishlist',
                    id: id
                },
                success: function (response) {
                    if (response.status === 'success') {
                        showToast(response.message, 'success');
                    } else if (response.status === 'info') {
                        showToast(response.message, 'success');
                    } else if (response.status === 'redirect') {
                        showToast(response.message, 'error');
                        setTimeout(function () { window.location.href = response.url; }, 1500);
                    } else {
                        showToast(response.message, 'error');
                    }
                },
                error: function () {
                    showToast('An error occurred.', 'error');
                }
            });
        });

    });

})(jQuery);