jQuery(document).ready(function ($) {
    // Chat widget functionality
    $(".askany-chat-widget").each(function () {
        var $widget = $(this);
        var $toggle = $widget.find(".askany-chat-toggle");
        var $container = $widget.find(".askany-chat-container");
        var $messagesContainer = $widget.find(".askany-chat-messages");
        var $productsContainer = $widget.find(".askany-chat-products");
        var $form = $widget.find("#askany-chat-form");
        var $input = $form.find("input");
        var $emojiBtn = $widget.find(".emoji-btn");
        var $emojiPicker = $widget.find(".emoji-picker");
        var $promptItems = $widget.find(".prompt-item");
        var $expandBtn = $widget.find(".expand-btn");
        var $minimizeBtn = $widget.find(".minimize-btn");
        var sessionId = "";
        var isExpanded = false;
        var isMinimized = false;
        var apiProvider = $widget.data('api-provider');
        var fallbackEnabled = $widget.data('fallback-enabled') === 'true';

        var widgetState = localStorage.getItem('askany_widget_state') || 'closed';


        // Handle main tab switching (Home/Messages) - only if main tabs exist
        $widget.find('.main-tab-btn').on('click', function () {
            var tabId = $(this).data('tab');

            // Update active main tab button
            $widget.find('.main-tab-btn').removeClass('active');
            $(this).addClass('active');

            // Show corresponding main tab content
            $widget.find('.askany-main-tab-content').hide();
            $widget.find('#' + tabId + '-tab').show();

            // If switching to messages tab, start chat session and scroll to bottom
            if (tabId === 'messages') {
                startChatSession();
                // Force scroll to bottom when switching to messages tab
                setTimeout(function () {
                    forceScrollToBottom();
                }, 100);
            } else if (tabId === 'home') {
                // Stop chat session when going back to home
                stopChatSession();
            }
        });


        // Function to update cart count in header/nav
        function updateCartCount(count) {
            // Update WooCommerce cart count if elements exist
            $('.cart-count, .cart-contents-count, .woocommerce-cart-count').text(count);

            // Update cart fragments if WooCommerce supports it
            if (typeof wc_add_to_cart_params !== 'undefined') {
                $(document.body).trigger('wc_fragment_refresh');
            }
        }

    });
});
