import React, { useState, useRef, useEffect } from "react"
import { motion, AnimatePresence } from "framer-motion"

import {
  Bot,
  User,
  Send,
  Mic,
  MicOff,
  Volume2,
  VolumeX,
  RotateCcw,
  X,
  Copy,
  Share2,
  ThumbsUp,
  ThumbsDown,
  FileText,
  Paperclip,
  ShoppingCart,
  Info,
  Star,
  Headphones,
  Search,
  Package,
  Heart,
  CreditCard,
  Shield,
  Zap,
  Crown,
  TrendingUp,
  Filter,
  Edit,
  Bell,
  AlertCircle,
  HelpCircle,
  MessageCircle,
  Mail,
  Settings,
} from "lucide-react"
import "./AIChatAssistant.css"
import { useSelector } from "react-redux"
import {
  useGetProductsQuery,
} from "../store/slices/productApiSlice"
import { getFullApiUrl } from "../utils/apiConfig"
import {
  useGetWishlistsQuery,
  useGetCartsQuery,
  useGetOrdersQuery,
} from "../store/slices/userApiSlice"

const AIChatAssistant = ({ isOpen: externalIsOpen, setIsOpen: setExternalIsOpen, style }) => {

  const [internalIsOpen, setInternalIsOpen] = useState(false)
  const isOpen = externalIsOpen !== undefined ? externalIsOpen : internalIsOpen
  const setIsOpen = setExternalIsOpen || setInternalIsOpen

  const [isFullScreen, setIsFullScreen] = useState(true)
  const [messages, setMessages] = useState([])
  const [inputMessage, setInputMessage] = useState("")
  const [isTyping, setIsTyping] = useState(false)
  const [isSpeaking, setIsSpeaking] = useState(false)
  const [isListening, setIsListening] = useState(false)
  const [voiceEnabled, setVoiceEnabled] = useState(false)
  const [showTooltip, setShowTooltip] = useState(true)
  const [tooltipTimeoutRef] = useState(useRef(null))

  const inputRef = useRef(null)
  const messagesEndRef = useRef(null)
  const recognitionRef = useRef(null)

  const { userData, isLoggedIn } = useSelector((state) => state.auth)
  const userId = userData?._id
  const user = userData 

  const { data: productsData, isLoading: productsLoading } = useGetProductsQuery()
  const { data: wishlistsData, isLoading: wishlistsLoading } = useGetWishlistsQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })
  const { data: cartsData, isLoading: cartsLoading } = useGetCartsQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })
  const { data: ordersData, isLoading: ordersLoading } = useGetOrdersQuery(undefined, {
    skip: !isLoggedIn || !userData,
    refetchOnMountOrArgChange: false,
    pollingInterval: 0,
  })

  const [currentSearchResults, setCurrentSearchResults] = useState([])
  const [currentCartItems, setCurrentCartItems] = useState([])
  const [currentWishlistItems, setCurrentWishlistItems] = useState([])
  const [currentOrders, setCurrentOrders] = useState([])
  const [isProcessing, setIsProcessing] = useState(false)
  const [currentTask, setCurrentTask] = useState(null)
  const [searchHistory, setSearchHistory] = useState([])

  const [conversationContext, setConversationContext] = useState({
    currentTopic: null,
    lastAction: null,
    userPreferences: {
      favoriteCategories: [],
      favoriteBrands: [],
      priceRange: { min: 0, max: 50000 },
      preferredPaymentMethods: [],
      shoppingFrequency: 'occasional',
      interests: []
    },
    searchHistory: [],
    currentFilters: {},
    pendingAction: null,
    conversationFlow: [],
    userPersonality: {
      communicationStyle: 'friendly',
      decisionStyle: 'careful',
      urgencyLevel: 'normal',
      techSavviness: 'moderate'
    },
    sessionData: {
      startTime: new Date(),
      messageCount: 0,
      topicsDiscussed: [],
      satisfactionLevel: 5
    }
  })

  const [currentSubActions, setCurrentSubActions] = useState(null)
  const [subActionHistory, setSubActionHistory] = useState([])
  const [fallbackProductsData, setFallbackProductsData] = useState({ products: [] })

  useEffect(() => {
    const fetchFallbackProducts = async () => {
    
      if ((!productsData?.products || productsData.products.length === 0) && 
          (!fallbackProductsData?.products || fallbackProductsData.products.length === 0)) {
        try {
          const response = await fetch(`${getFullApiUrl()}/products`)
          if (response.ok) {
            const data = await response.json()
            if (data.success && Array.isArray(data.products)) {
              setFallbackProductsData({ products: data.products })
            }
          }
        } catch (error) {
          
        }
      }
    }

    fetchFallbackProducts()
  }, [productsData, fallbackProductsData])

  const quickActions = [
    {
      action: 'search_products',
      label: 'Search Products',
      icon: Search,
      color: '#667eea',
      subActions: [
        { action: 'search_by_name', label: 'Search by Name', icon: Search, color: '#667eea' },
        { action: 'search_by_category', label: 'Search by Category', icon: Package, color: '#764ba2' },
        { action: 'search_by_price', label: 'Search by Price', icon: CreditCard, color: '#f093fb' },
        { action: 'search_by_brand', label: 'Search by Brand', icon: Crown, color: '#667eea' },
        { action: 'advanced_search', label: 'Advanced Search', icon: Filter, color: '#764ba2' },
        { action: 'trending_products', label: 'Trending Products', icon: TrendingUp, color: '#f093fb' },
        { action: 'view_products', label: 'View All Products', icon: Package, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'cart_management',
      label: 'My Cart',
      icon: ShoppingCart,
      color: '#764ba2',
      subActions: [
        { action: 'view_cart', label: 'View Cart', icon: ShoppingCart, color: '#764ba2' },
        { action: 'navigate_to_cart', label: 'Manage Cart', icon: Edit, color: '#f093fb' },
        { action: 'checkout', label: 'Proceed to Checkout', icon: CreditCard, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'wishlist_management',
      label: 'My Wishlist',
      icon: Heart,
      color: '#f093fb',
      subActions: [
        { action: 'view_wishlist', label: 'View Wishlist', icon: Heart, color: '#f093fb' },
        { action: 'navigate_to_wishlist', label: 'Manage Wishlist', icon: Edit, color: '#667eea' },
        { action: 'share_wishlist', label: 'Share Wishlist', icon: Share2, color: '#f093fb' },
        { action: 'price_alerts', label: 'Price Alerts', icon: Bell, color: '#667eea' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'order_tracking',
      label: 'Track Orders',
      icon: Package,
      color: '#667eea',
      subActions: [
        { action: 'view_orders', label: 'View All Orders', icon: Package, color: '#667eea' },
        { action: 'navigate_to_orders', label: 'Manage Orders', icon: Edit, color: '#764ba2' },
        { action: 'track_specific_order', label: 'Track Specific Order', icon: Search, color: '#764ba2' },
        { action: 'order_status', label: 'Check Order Status', icon: Info, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'payment_help',
      label: 'Payment Help',
      icon: CreditCard,
      color: '#764ba2',
      subActions: [
        { action: 'payment_methods', label: 'Payment Methods', icon: CreditCard, color: '#764ba2' },
        { action: 'payment_issues', label: 'Payment Issues', icon: AlertCircle, color: '#f093fb' },
        { action: 'refund_status', label: 'Refund Status', icon: RotateCcw, color: '#667eea' },
        { action: 'billing_help', label: 'Billing Help', icon: FileText, color: '#764ba2' },
        { action: 'security_info', label: 'Security Info', icon: Shield, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },

    {
      action: 'recommendations',
      label: 'Recommendations',
      icon: Star,
      color: '#667eea',
      subActions: [
        { action: 'personalized_recommendations', label: 'Personalized', icon: Star, color: '#667eea' },
        { action: 'trending_recommendations', label: 'Trending', icon: TrendingUp, color: '#764ba2' },
        { action: 'category_recommendations', label: 'By Category', icon: Package, color: '#f093fb' },
        { action: 'price_recommendations', label: 'By Price Range', icon: CreditCard, color: '#667eea' },
        { action: 'similar_products', label: 'Similar Products', icon: Copy, color: '#764ba2' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    },
    {
      action: 'customer_support',
      label: 'Customer Support',
      icon: Headphones,
      color: '#764ba2',
      subActions: [
        { action: 'contact_support', label: 'Contact Support', icon: Headphones, color: '#764ba2' },
        { action: 'faq', label: 'FAQ', icon: HelpCircle, color: '#f093fb' },
        { action: 'live_chat', label: 'Live Chat', icon: MessageCircle, color: '#667eea' },
        { action: 'email_support', label: 'Email Support', icon: Mail, color: '#764ba2' },
        { action: 'technical_help', label: 'Technical Help', icon: Settings, color: '#f093fb' },
        { action: 'back_to_main', label: '← Back to Main', icon: RotateCcw, color: '#667eea' }
      ]
    }
  ]

  const suggestions = [
    "Show me trending products",
    "Help me find a gift",
    "Track my order",
    "Customer support"
  ]

  const quickReplies = [
    "Yes, please!",
    "No, thanks",
    "Tell me more",
    "I need help"
  ]

  const contextualSuggestions = {
    general: ["What's trending today?", "Show me Premium watches", "Help me find a gift", "Check my order status"],
    product: ["Tell me more about this item", "Show similar products", "Check availability", "Add to wishlist"],
    order: ["Track my recent order", "Change delivery address", "Cancel an order", "Return policy"],
    support: ["Speak to a human agent", "Report an issue", "Account settings", "Billing questions"],
  }

  useEffect(() => {
    if (productsData?.products) {
      setCurrentSearchResults(productsData.products)
    }
  }, [productsData])

  useEffect(() => {
    if (cartsData?.carts?.[0]?.cartItems) {
      const mappedCartItems = cartsData.carts[0].cartItems.map(item => ({
        ...item,
        quantity: item.qty || 1, 
        productId: item.productId,
        name: item.name,
        price: item.price,
        category: item.category,
        image: item.image
      }))
      setCurrentCartItems(mappedCartItems)
    }
  }, [cartsData])

  useEffect(() => {

    if (wishlistsData?.wishlist) {
      const mappedWishlistItems = wishlistsData.wishlist.map(item => ({
        ...item,
        productId: item.productId,
        name: item.name,
        price: item.price,
        category: item.category,
        image: item.image
      }))
      setCurrentWishlistItems(mappedWishlistItems)
    }
  }, [wishlistsData, wishlistsLoading, userId])

  useEffect(() => {
    if (ordersData?.orders) {
      const mappedOrders = ordersData.orders.map(order => ({
        ...order,
        orderItems: order.orderItems?.map(item => ({
          ...item,
          quantity: item.qty || 1, 
          productId: item.productId,
          name: item.name,
          price: item.price,
          category: item.category
        })) || []
      }))
      setCurrentOrders(mappedOrders)
    }
  }, [ordersData])

  useEffect(() => {
    if (messages.length === 0) {
      const timeOfDay = new Date().getHours()
      let greeting = ''

      if (timeOfDay < 12) {
        greeting = 'Good morning'
      } else if (timeOfDay < 17) {
        greeting = 'Good afternoon'
      } else {
        greeting = 'Good evening'
      }

      setMessages([
        {
          id: 1,
          type: "ai",
          message: `${greeting}! 👋 I'm your personalized AI shopping assistant at MKCart! 🤖\n\nI'm here to make your shopping experience amazing with:\n\n🎯 Smart Functions & Sub-Functions:\n\n🔍 Search Products\n• Search by Name\n• Search by Category\n• Search by Price Range\n• Search by Brand\n• Advanced Search\n• Trending Products\n\n🛒 Cart Management\n• View Cart\n• Add to Cart\n• Remove from Cart\n• Update Quantity\n• Clear Cart\n• Proceed to Checkout\n\n💖 Wishlist Management\n• View Wishlist\n• Add to Wishlist\n• Remove from Wishlist\n• Share Wishlist\n• Price Alerts\n\n📦 Order Tracking\n• View All Orders\n• Track Specific Order\n• Check Order Status\n• Cancel Order\n• Return Order\n\n⭐ Recommendations\n• Personalized Picks\n• Trending Items\n• Category Recommendations\n• Price-based Recommendations\n• Similar Products\n\n💳 Payment Help\n• Payment Methods\n• Payment Issues\n• Refund Status\n• Billing Help\n• Security Info\n\n📋 Product Details\n• Product Information\n• Product Reviews\n• Compare Products\n• Check Availability\n• Specifications\n\n🎧 Customer Support\n• Contact Support\n• FAQ\n• Live Chat\n• Email Support\n• Technical Help\n\n🎤 Voice Interaction: I can understand and respond to voice commands!\n\n💬 ChatGPT-like Experience: I provide intelligent, contextual responses and remember our conversations.\n\nWhat would you like to explore today? Just type or speak naturally!`,
          timestamp: new Date(),
        },
      ])
    }
  }, [])

  const searchProducts = async (keyword, filters = {}) => {
    try {
      
      const searchParams = new URLSearchParams({
        keyword: keyword || '',
        category: filters.category || '',
        minPrice: filters.minPrice || '',
        maxPrice: filters.maxPrice || '',
        brand: filters.brand || '',
        rating: filters.rating || '',
        availability: filters.availability || '',
        stock: filters.stock || '',
        seller: filters.seller || '',
        premiumBadge: filters.premiumBadge || ''
      })

      const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)

      if (!response.ok) {
        throw new Error(`API request failed: ${response.status}`)
      }

      const data = await response.json()

      if (data.success && data.products && Array.isArray(data.products)) {
        setCurrentSearchResults(data.products)

        const productList = data.products.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
        ).join('\n')

        const suggestions = [
          keyword.toLowerCase().includes('phone') ? 'smartphone' : 'electronics',
          keyword.toLowerCase().includes('shirt') ? 'clothing' : 'fashion',
          keyword.toLowerCase().includes('book') ? 'literature' : 'books'
        ]

        const popularSearches = ['smartphones', 'laptops', 'shoes', 'watches', 'headphones']
        const categories = ['Electronics', 'Fashion', 'Home & Garden', 'Sports', 'Beauty']

        let searchResponse = getRandomResponse(responseLibraries.search, 'results')
          .replace('{query}', keyword)
          .replace('{count}', data.products.length)
          .replace('{products}', productList)

        if (data.products.length < 3) {
          const suggestionResponse = getRandomResponse(responseLibraries.search, 'suggestions')
            .replace('{suggestion1}', suggestions[0])
            .replace('{suggestion2}', suggestions[1])
            .replace('{suggestion3}', suggestions[2])
            .replace('{popular1}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{popular2}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{category1}', categories[Math.floor(Math.random() * categories.length)])
            .replace('{category2}', categories[Math.floor(Math.random() * categories.length)])

          searchResponse += `\n\n${suggestionResponse}`
        }

        if (filters.brand && data.products.length === 0) {
          const fallbackResults = await searchProducts(filters.brand)
          if (fallbackResults.products && fallbackResults.products.length > 0) {
            return {
              success: true,
              products: fallbackResults.products,
              message: `🏷️ Found ${fallbackResults.products.length} products related to "${filters.brand}":\n\n${fallbackResults.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
            }
          }
        }

        return {
          success: true,
          products: data.products,
          message: searchResponse
        }
      }

      if (productsData?.products) {
        let filteredProducts = productsData.products

        if (keyword) {
          filteredProducts = filteredProducts.filter(product =>
            product.name?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.description?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.category?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.seller?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.PremiumBadge?.toLowerCase().includes(keyword.toLowerCase()) ||
            product.specifications?.Material?.toLowerCase().includes(keyword.toLowerCase())
          )
        }

        if (filters.category) {
          filteredProducts = filteredProducts.filter(product =>
            product.category?.toLowerCase().includes(filters.category.toLowerCase())
          )
        }

        if (filters.brand) {
          const brandFilter = filters.brand.toLowerCase()
          filteredProducts = filteredProducts.filter(product => {
          
            const productName = product.name?.toLowerCase() || ''
            const productBrand = product.brand?.toLowerCase() || ''
            const productSeller = product.seller?.toLowerCase() || ''
            const productManufacturer = product.manufacturer?.toLowerCase() || ''
            const productCompany = product.company?.toLowerCase() || ''
            const productMake = product.make?.toLowerCase() || ''

            const productDescription = product.description?.toLowerCase() || ''
            const productSpecs = JSON.stringify(product.specifications || {}).toLowerCase()
            
            return productName.includes(brandFilter) ||
                   productBrand.includes(brandFilter) ||
                   productSeller.includes(brandFilter) ||
                   productManufacturer.includes(brandFilter) ||
                   productCompany.includes(brandFilter) ||
                   productMake.includes(brandFilter) ||
                   productDescription.includes(brandFilter) ||
                   productSpecs.includes(brandFilter)
          })
        }

        if (filters.minPrice || filters.maxPrice) {
          filteredProducts = filteredProducts.filter(product => {
            const price = parseFloat(product.price) || 0
            const minPrice = parseFloat(filters.minPrice) || 0
            const maxPrice = parseFloat(filters.maxPrice) || Infinity

            if (maxPrice === Infinity) {
              
              return price >= minPrice
            } else if (minPrice === 0) {
              
              return price <= maxPrice
            } else {
              
              return price >= minPrice && price <= maxPrice
            }
          })
        }

        if (filters.stock) {
          filteredProducts = filteredProducts.filter(product =>
            product.stock > 0
          )
        }

        if (filters.premiumBadge) {
          filteredProducts = filteredProducts.filter(product =>
            product.PremiumBadge
          )
        }

        filteredProducts.sort((a, b) => {
          
          if (b.ratings !== a.ratings) {
            return b.ratings - a.ratings
          }
          
          return a.price - b.price
        })

        setCurrentSearchResults(filteredProducts)

        if (filteredProducts.length > 0) {
          const productList = filteredProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
          ).join('\n')

          let searchResponse = getRandomResponse(responseLibraries.search, 'results')
            .replace('{query}', keyword)
            .replace('{count}', filteredProducts.length)
            .replace('{products}', productList)

          return {
            success: true,
            products: filteredProducts,
            message: searchResponse
          }
        } else {
          
          const suggestions = [
            keyword.toLowerCase().includes('phone') ? 'smartphone' : 'electronics',
            keyword.toLowerCase().includes('shirt') ? 'clothing' : 'fashion',
            keyword.toLowerCase().includes('book') ? 'literature' : 'books'
          ]

          const popularSearches = ['smartphones', 'laptops', 'shoes', 'watches', 'headphones']
          const categories = ['Electronics', 'Fashion', 'Home & Garden', 'Sports', 'Beauty']

          let noResultsResponse = getRandomResponse(responseLibraries.search, 'noResults')
            .replace('{query}', keyword)

          const suggestionResponse = getRandomResponse(responseLibraries.search, 'suggestions')
            .replace('{suggestion1}', suggestions[0])
            .replace('{suggestion2}', suggestions[1])
            .replace('{suggestion3}', suggestions[2])
            .replace('{popular1}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{popular2}', popularSearches[Math.floor(Math.random() * popularSearches.length)])
            .replace('{category1}', categories[Math.floor(Math.random() * categories.length)])
            .replace('{category2}', categories[Math.floor(Math.random() * categories.length)])

          noResultsResponse += `\n\n${suggestionResponse}`

          return {
            success: false,
            products: [],
            message: noResultsResponse
          }
        }
      }

      return {
        success: false,
        products: [],
        message: "Sorry, I couldn't search for products right now. Please try again later."
      }
    } catch (error) {

      if (productsData?.products) {
        const filteredProducts = productsData.products.filter(product =>
          product.name?.toLowerCase().includes((keyword || '').toLowerCase())
        )
        setCurrentSearchResults(filteredProducts)

        return {
          success: true,
          products: filteredProducts,
          message: `Found ${filteredProducts.length} products matching "${keyword}":\n\n` +
            filteredProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} (${product.rating || 4.0}⭐)`
            ).join('\n')
        }
      }

      return {
        success: false,
        products: [],
        message: "Sorry, there was an error searching for products. Please try again."
      }
    }
  }

  const getCartSummary = () => {
    if (!currentCartItems || currentCartItems.length === 0) {
      return {
        count: 0,
        total: 0,
        items: [],
        message: getRandomResponse(responseLibraries.cart, 'empty')
      }
    }

    const validItems = currentCartItems.filter(item =>
      item && item.productId && (item.name || item.productName)
    )

    const total = validItems.reduce((sum, item) => {
      const quantity = parseInt(item.quantity || item.qty || 1)
      const price = parseFloat(item.price || item.productPrice || 0)
      return sum + (price * quantity)
    }, 0)

    const subtotal = Math.round(total * 100) / 100
    const shipping = subtotal > 999 ? 'Free' : '₹99'
    const tax = Math.round(subtotal * 0.18 * 100) / 100 
    const finalTotal = subtotal + (shipping === 'Free' ? 0 : 99) + tax

    const itemsList = validItems.map(item => {
      const quantity = parseInt(item.quantity || item.qty || 1)
      const price = parseFloat(item.price || item.productPrice || 0)
      const itemTotal = quantity * price
      return `• ${item.name || item.productName} x${quantity} - ₹${itemTotal}`
    }).join('\n')

    const recommendations = generateRandomData.products()
    const recommendationsList = `• ${recommendations.name} - ${recommendations.price} (${recommendations.rating}⭐)`

    let cartResponse = getRandomResponse(responseLibraries.cart, 'items')
      .replace('{items}', itemsList)
      .replace('{subtotal}', `₹${subtotal}`)
      .replace('{shipping}', shipping)
      .replace('{tax}', `₹${tax}`)
      .replace('{total}', `₹${finalTotal}`)

    if (validItems.length > 0) {
      const recommendationResponse = getRandomResponse(responseLibraries.cart, 'recommendations')
        .replace('{recommendations}', recommendationsList)
      cartResponse += `\n\n${recommendationResponse}`
    }

    return {
      count: validItems.length,
      total: finalTotal,
      items: validItems.map(item => ({
        ...item,
        productId: item.productId || item._id,
        name: item.name || item.productName || 'Unknown Product',
        quantity: parseInt(item.quantity || item.qty || 1),
        price: parseFloat(item.price || item.productPrice || 0),
        category: item.category || 'General',
        image: item.image || item.productImage || ''
      })),
      message: cartResponse,
      subtotal: subtotal,
      shipping: shipping,
      tax: tax
    }
  }

  const getWishlistSummary = () => {
    console.log('getWishlistSummary called with currentWishlistItems:', currentWishlistItems)
    if (!currentWishlistItems || currentWishlistItems.length === 0) {
      console.log('No wishlist items found, returning empty summary')
      return {
        count: 0,
        items: [],
        message: getRandomResponse(responseLibraries.wishlist, 'empty')
      }
    }

    const validItems = currentWishlistItems.filter(item =>
      item && item.productId && (item.name || item.productName)
    )

    console.log('Valid wishlist items found:', validItems.length)

    const itemsList = validItems.map(item => {
      const price = parseFloat(item.price || item.productPrice || 0)
      const rating = item.rating || 4.0
      return `• ${item.name || item.productName} - ₹${price} (${rating}⭐)`
    }).join('\n')

    const hasPriceDrops = Math.random() > 0.7 
    let wishlistResponse = getRandomResponse(responseLibraries.wishlist, 'items')
      .replace('{items}', itemsList)

    if (hasPriceDrops && validItems.length > 0) {
      const priceDropItem = validItems[Math.floor(Math.random() * validItems.length)]
      const originalPrice = parseFloat(priceDropItem.price || priceDropItem.productPrice || 0)
      const newPrice = Math.round(originalPrice * 0.8) 

      const priceDropsList = `• ${priceDropItem.name || priceDropItem.productName} - Now ₹${newPrice} (was ₹${originalPrice})`

      const priceAlertResponse = getRandomResponse(responseLibraries.wishlist, 'priceAlerts')
        .replace('{priceDrops}', priceDropsList)

      wishlistResponse += `\n\n${priceAlertResponse}`
    }

    return {
      count: validItems.length,
      items: validItems.map(item => ({
        ...item,
        productId: item.productId || item._id,
        name: item.name || item.productName || 'Unknown Product',
        price: parseFloat(item.price || item.productPrice || 0),
        category: item.category || 'General',
        image: item.image || item.productImage || '',
        rating: item.rating || 0
      })),
      message: wishlistResponse
    }
  }

  const getOrderSummary = () => {
    if (!currentOrders || currentOrders.length === 0) {
      return {
        count: 0,
        items: [],
        message: "📦 No orders found in your account.\n\n💡 Start shopping to see your order history here!\n\n✨ New customer? Welcome! Your orders will appear here once you make your first purchase."
      }
    }

    const validOrders = currentOrders.filter(order =>
      order && (order._id || order.orderId)
    )

    const ordersList = validOrders.slice(0, 5).map(order => {
      const orderId = order._id || order.orderId
      const amount = parseFloat(order.amount || order.total || 0)
      const status = order.status || 'Processing'
      const orderDate = new Date(order.createdAt || order.orderDate || new Date())
      const formattedDate = orderDate.toLocaleDateString('en-IN')

      return `• Order #${orderId.slice(-6)} - ₹${amount} (${status}) - ${formattedDate}`
    }).join('\n')

    let orderResponse = getRandomResponse(responseLibraries.tracking, 'multiple')
      .replace('{orders}', ordersList)

    const statusCounts = validOrders.reduce((acc, order) => {
      const status = order.status || 'Processing'
      acc[status] = (acc[status] || 0) + 1
      return acc
    }, {})

    const statusSummary = Object.entries(statusCounts)
      .map(([status, count]) => `${status}: ${count}`)
      .join(', ')

    orderResponse += `\n\n📊 Order Status Summary:\n${statusSummary}`

    return {
      count: validOrders.length,
      items: validOrders.map(order => ({
        ...order,
        orderId: order._id || order.orderId,
        amount: parseFloat(order.amount || order.total || 0),
        status: order.status || 'Processing',
        orderDate: order.createdAt || order.orderDate || new Date(),
        orderItems: (order.orderItems || []).map(item => ({
          ...item,
          productId: item.productId || item._id,
          name: item.name || item.productName || 'Unknown Product',
          quantity: parseInt(item.quantity || item.qty || 1),
          price: parseFloat(item.price || item.productPrice || 0)
        }))
      })),
      message: orderResponse
    }
  }

  const generateRecommendations = async () => {
   
    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    
    if (!availableProducts || !Array.isArray(availableProducts) || availableProducts.length === 0) {
     
      const trendingProducts = await getTrendingProducts()
      return trendingProducts
    }

    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()

    const userItems = [...cartSummary.items, ...wishlistSummary.items]
    const userCategories = [...new Set(userItems.map(item => item.category).filter(Boolean))]
    const userBrands = [...new Set(userItems.map(item => item.brand).filter(Boolean))]

    let recommendations = []

    if (userCategories.length > 0) {
      const categoryRecs = availableProducts
        .filter(product =>
          userCategories.includes(product.category) &&
          !userItems.some(item => item.productId === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 3)
      recommendations.push(...categoryRecs)
    }

    if (userBrands.length > 0) {
      const brandRecs = availableProducts
        .filter(product =>
          userBrands.includes(product.brand) &&
          !userItems.some(item => item.productId === product._id) &&
          !recommendations.some(rec => rec._id === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 2)
      recommendations.push(...brandRecs)
    }

    if (recommendations.length < 5) {
      const trendingRecs = availableProducts
        .filter(product =>
          !userItems.some(item => item.productId === product._id) &&
          !recommendations.some(rec => rec._id === product._id)
        )
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5 - recommendations.length)
      recommendations.push(...trendingRecs)
    }

    return recommendations.slice(0, 5)
  }

  useEffect(() => {
    if (typeof window !== "undefined") {
      
      if ("webkitSpeechRecognition" in window || "SpeechRecognition" in window) {
        const SpeechRecognition = window.SpeechRecognition || window.webkitSpeechRecognition
        recognitionRef.current = new SpeechRecognition()
        recognitionRef.current.continuous = false
        recognitionRef.current.interimResults = false
        recognitionRef.current.lang = "en-US"

        recognitionRef.current.onstart = () => {
          setIsListening(true)
          
          const aiMessage = {
            id: Date.now(),
            type: "ai",
            message: "🎤 I'm listening... Please speak clearly!",
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, aiMessage])
        }

        recognitionRef.current.onresult = (event) => {
          const transcript = event.results[0][0].transcript
          setInputMessage(transcript)
          setIsListening(false)

          const aiMessage = {
            id: Date.now(),
            type: "ai",
            message: `🎤 I heard: "${transcript}"\n\nProcessing your voice command...`,
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, aiMessage])

          setTimeout(() => {
            handleSendMessage()
          }, 1000)
        }

        recognitionRef.current.onerror = (event) => {
          setIsListening(false)
          console.error('Speech recognition error:', event.error)

          const errorMessage = {
            id: Date.now(),
            type: "ai",
            message: "❌ Sorry, I couldn't understand that. Please try speaking again or type your message.",
            timestamp: new Date(),
          }
          setMessages(prev => [...prev, errorMessage])
        }

        recognitionRef.current.onend = () => {
          setIsListening(false)
        }
      }

    }
  }, [])

  useEffect(() => {
    if (messages.length > 0) {
      const lastMessage = messages[messages.length - 1]
      if (lastMessage.type === 'ai') {
        scrollToBottom()
      }
    }
  }, [messages])

  const scrollToBottom = () => {
    setTimeout(() => {
      messagesEndRef.current?.scrollIntoView({ behavior: "smooth" })
    }, 100) 
  }

  const handleDirectKeywords = async (userMessage, lowerMessage) => {
    
    const productKeywords = ['iphone', 'laptop', 'shoes', 'headphones', 'watch', 'camera', 'phone', 'tablet', 'computer', 'mouse', 'keyboard', 'speaker', 'earphones', 'samsung', 'apple', 'dell', 'hp', 'lenovo', 'nike', 'adidas', 'puma', 'sony', 'lg', 'canon', 'nikon']

    const categoryKeywords = ['mobile phones', 'accessories', 'laptops', 'headphones', 'shoes', 'electronics', 'men', 'women', 'toys', 'musical instruments', 'mobile', 'phones', 'phone', 'laptop', 'computer', 'headphone', 'earphones', 'shoe', 'footwear', 'electronic', 'tech', 'toy', 'music', 'instrument', 'smartphone', 'notebook', 'pc', 'audio', 'sound', 'sneakers', 'boots', 'gadgets', 'devices', 'games', 'play', 'children', 'kids']

    const actionKeywords = {
      'cart': ['cart', 'basket', 'shopping cart', 'add to cart', 'remove from cart', 'view cart', 'show cart', 'checkout', 'buy', 'purchase'],
      'wishlist': ['wishlist', 'favorites', 'favourite', 'save', 'wish', 'add to wishlist', 'remove from wishlist', 'view wishlist', 'show wishlist'],
      'orders': ['order', 'orders', 'track', 'tracking', 'delivery', 'shipping', 'status', 'my orders', 'order status', 'track order'],
      'price': ['price', 'cost', 'budget', 'under', 'above', 'between', 'cheap', 'expensive', 'affordable', 'deal', 'discount', 'sale'],
      'help': ['help', 'support', 'assist', 'problem', 'issue', 'trouble', 'question', 'how', 'what', 'why'],
      'recommendations': ['recommend', 'suggestion', 'advise', 'best', 'top', 'popular', 'trending', 'trend', 'suggest'],
      'compare': ['compare', 'comparison', 'vs', 'versus', 'difference', 'similar', 'alike'],
      'availability': ['stock', 'available', 'availability', 'in stock', 'out of stock', 'check stock', 'inventory'],
      'reviews': ['review', 'reviews', 'rating', 'ratings', 'stars', 'feedback', 'opinion'],
      'specifications': ['specs', 'specifications', 'details', 'features', 'technical', 'specification'],
      'payment': ['payment', 'pay', 'credit card', 'debit card', 'upi', 'cash', 'billing', 'payment method'],
      'return': ['return', 'refund', 'exchange', 'replace', 'cancel', 'cancellation'],
      'contact': ['contact', 'support', 'help', 'email', 'phone', 'call', 'chat', 'live chat'],
      'account': ['account', 'profile', 'settings', 'login', 'sign in', 'register', 'sign up', 'password']
    }

    for (const keyword of productKeywords) {
      if (lowerMessage.includes(keyword)) {
        const results = await searchProducts(keyword)
        if (results.products && results.products.length > 0) {
          return {
            response: `🔍 I found ${results.length} products matching "${keyword}":\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`,
            contextUpdate: { currentTopic: 'search_results', lastAction: 'direct_search' }
          }
        }
      }
    }

    for (const keyword of categoryKeywords) {
      if (lowerMessage.includes(keyword)) {
        const categoryProducts = await getCategoryProducts(keyword)

        if (categoryProducts.length > 0) {
          return {
            response: `📦 I found ${categoryProducts.length} products in the ${keyword} category:\n\n${categoryProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${keyword} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks`,
            contextUpdate: { currentTopic: 'search_results', lastAction: 'category_search' }
          }
        }
      }
    }

    for (const [action, keywords] of Object.entries(actionKeywords)) {
      for (const keyword of keywords) {
        if (lowerMessage.includes(keyword)) {
          switch (action) {
            case 'cart':
              const cartSummary = getCartSummary()
              return {
                response: cartSummary.message,
                contextUpdate: { currentTopic: 'cart', lastAction: 'view_cart' },
                action: () => cartActions()
              }

            case 'wishlist':
              const wishlistSummary = getWishlistSummary()
              return {
                response: wishlistSummary.message,
                contextUpdate: { currentTopic: 'wishlist', lastAction: 'view_wishlist' },
                action: () => wishlistActions()
              }

            case 'orders':
              const orderSummary = getOrderSummary()
              return {
                response: orderSummary.message,
                contextUpdate: { currentTopic: 'orders', lastAction: 'view_orders' },
                action: () => orderActions()
              }

            case 'price':
              
              const pricePatterns = [
                
                { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
                
                { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
                
                { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
                
                { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
                
                { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
                
                { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
                
                { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
                
                { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
              ]

              let minPrice = 0
              let maxPrice = 0
              let priceRangeFound = false

              for (const { pattern, type } of pricePatterns) {
                const match = userMessage.match(pattern)
                if (match) {
                  priceRangeFound = true

                  if (type === 'range') {
                    minPrice = parseInt(match[1])
                    maxPrice = parseInt(match[2])
                  } else if (type === 'under') {
                    minPrice = 0
                    maxPrice = parseInt(match[1])
                  } else if (type === 'above') {
                    minPrice = parseInt(match[1])
                    maxPrice = Infinity
                  }
                  break
                }
              }

              if (priceRangeFound) {
                const results = await searchProducts('', { minPrice, maxPrice })

                const filteredResults = (results.products || []).filter(product => {
                  const price = parseFloat(product.price) || 0
                  if (maxPrice === Infinity) {
                    return price >= minPrice
                  } else {
                    return price >= minPrice && price <= maxPrice
                  }
                })

                if (filteredResults.length > 0) {
                  const rangeText = maxPrice === Infinity
                    ? `₹${minPrice}+`
                    : minPrice === 0
                      ? `Under ₹${maxPrice}`
                      : `₹${minPrice} - ₹${maxPrice}`

                  return {
                    response: `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
                      `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
                    ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`,
                    contextUpdate: { currentTopic: 'search_results', lastAction: 'price_search' }
                  }
                } else {
                  const rangeText = maxPrice === Infinity
                    ? `₹${minPrice}+`
                    : minPrice === 0
                      ? `Under ₹${maxPrice}`
                      : `₹${minPrice} - ₹${maxPrice}`

                  return {
                    response: `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`,
                    contextUpdate: { currentTopic: 'search_results', lastAction: 'price_search' }
                  }
                }
              }
              break

            case 'help':
              return {
                response: `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 Search & Discovery\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 Shopping Experience\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 Payment & Orders\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 Customer Support\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\nWhat specific help do you need?`,
                contextUpdate: { currentTopic: 'help', lastAction: 'help_request' }
              }

            case 'recommendations':
              const recommendations = await generateRecommendations()
              if (recommendations.length > 0) {
                return {
                  response: `⭐ Personalized Recommendations for you:\n\n${recommendations.slice(0, 5).map(product =>
                    `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                  ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get category-specific picks\n• Find similar products`,
                  contextUpdate: { currentTopic: 'recommendations', lastAction: 'view_recommendations' }
                }
              } else {
                const trendingProducts = await getTrendingProducts()
                return {
                  response: `⭐ Here are some trending products:\n\n${trendingProducts.slice(0, 5).map(product =>
                    `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                  ).join('')}\n\nWould you like to:\n• Add any to cart\n• Browse categories\n• Search for specific items\n• Get personalized picks`,
                  contextUpdate: { currentTopic: 'recommendations', lastAction: 'view_recommendations' }
                }
              }

            case 'compare':
              return {
                response: `📊 Product Comparison!\n\nI can help you compare products:\n\n• Compare prices and features\n• Side-by-side specifications\n• User reviews and ratings\n• Value for money analysis\n\nWhat products would you like to compare?\n\nExamples:\n• "Compare iPhone vs Samsung"\n• "Compare laptop brands"\n• "Compare shoes prices"`,
                contextUpdate: { currentTopic: 'compare', lastAction: 'compare_request' }
              }

            case 'availability':
              return {
                response: `📦 Stock Availability Check!\n\nI can check stock for any product:\n\n• Real-time inventory status\n• Stock notifications\n• Alternative sellers\n• Similar products in stock\n\nWhat product would you like me to check?\n\nExamples:\n• "Check iPhone stock"\n• "Is laptop available"\n• "Shoe availability"`,
                contextUpdate: { currentTopic: 'availability', lastAction: 'availability_check' }
              }

            case 'reviews':
              return {
                response: `⭐ Product Reviews!\n\nI can show you reviews for any product:\n\n• User ratings and feedback\n• Detailed reviews\n• Pros and cons\n• Verified purchase reviews\n\nWhat product would you like reviews for?\n\nExamples:\n• "iPhone reviews"\n• "Laptop ratings"\n• "Shoe feedback"`,
                contextUpdate: { currentTopic: 'reviews', lastAction: 'reviews_request' }
              }

            case 'specifications':
              return {
                response: `📋 Product Specifications!\n\nI can show detailed specs for any product:\n\n• Technical specifications\n• Features and capabilities\n• Size and dimensions\n• Material and build quality\n\nWhat product would you like specs for?\n\nExamples:\n• "iPhone specifications"\n• "Laptop specs"\n• "Shoe details"`,
                contextUpdate: { currentTopic: 'specifications', lastAction: 'specs_request' }
              }

            case 'payment':
              return {
                response: `💳 Payment Methods!\n\nWe accept various payment methods:\n\n• Credit/Debit Cards\n• UPI (Google Pay, PhonePe, Paytm)\n• Net Banking\n• Cash on Delivery\n• EMI options available\n\nWould you like to:\n• Learn about payment security\n• Check EMI eligibility\n• Set up payment preferences\n• Get billing help`,
                contextUpdate: { currentTopic: 'payment', lastAction: 'payment_info' }
              }

            case 'return':
              return {
                response: `🔄 Returns & Refunds!\n\nOur return policy:\n\n• 7-day return window\n• Easy return process\n• Full refund guarantee\n• Free return shipping\n• Exchange options available\n\nWould you like to:\n• Start a return\n• Check return status\n• Learn about return policy\n• Contact support`,
                contextUpdate: { currentTopic: 'return', lastAction: 'return_info' }
              }

            case 'contact':
              return {
                response: `📞 Contact Support!\n\nI can help you get in touch:\n\n• Live Chat: Available 24/7\n• Email: support@mkcart.com\n• Phone: +91-XXXXXXXXXX\n• WhatsApp: +91-XXXXXXXXXX\n\nWould you like to:\n• Start live chat\n• Send email\n• Call support\n• Report an issue`,
                contextUpdate: { currentTopic: 'contact', lastAction: 'contact_request' }
              }

            case 'account':
              return {
                response: `👤 Account Management!\n\nI can help with your account:\n\n• Profile settings\n• Order history\n• Saved addresses\n• Payment methods\n• Account preferences\n\nWould you like to:\n• View profile\n• Update settings\n• Check order history\n• Manage addresses`,
                contextUpdate: { currentTopic: 'account', lastAction: 'account_request' }
              }
          }
        }
      }
    }

    return null 
  }

  const handleSendMessage = async () => {
    if (!inputMessage.trim() || isTyping) return

    const userMessage = inputMessage.trim()
    setInputMessage("")

    const newUserMessage = {
      id: Date.now(),
      message: userMessage,
      type: "user",
      timestamp: new Date(),
    }

    setMessages(prev => [...prev, newUserMessage])

    setIsProcessing(true)
    setCurrentTask('Processing your request...')

    const typingMessage = {
      id: Date.now() + 1,
      type: "ai",
      message: "🤔 Thinking...",
      timestamp: new Date(),
      isTyping: true
    }
    setMessages(prev => [...prev, typingMessage])

    try {
      const lowerMessage = userMessage.toLowerCase()
      let response = ""
      let actionTaken = false
      let contextUpdate = {}

      const nluAnalysis = comprehensiveNLU(userMessage)
      const { intent, sentiment, entities, emotions, urgency, personality, context, confidence, suggestions, responseType } = nluAnalysis

      updateConversationMemory(userMessage, null, {
        intent,
        sentiment,
        entities,
        emotions,
        urgency,
        personality,
        context,
        confidence,
        responseType
      })

      const directKeywordResult = await handleDirectKeywords(userMessage, lowerMessage)
      if (directKeywordResult) {
        response = directKeywordResult.response
        contextUpdate = directKeywordResult.contextUpdate
        actionTaken = true

        if (directKeywordResult.action) {
          try {
            const actionResult = directKeywordResult.action()
            if (actionResult && actionResult.success) {
              
              response += `\n\n${actionResult.message}`
            }
          } catch (error) {
            
          }
        }
      }
      
      else if (conversationContext.pendingAction) {
        
        const pendingActionWithMessage = {
          ...conversationContext.pendingAction,
          userMessage: userMessage
        }
        const pendingResult = await handlePendingAction(pendingActionWithMessage)

        response = pendingResult
        contextUpdate = { pendingAction: null }
        actionTaken = true
      }
      
      else if (conversationContext.currentTopic === 'add_to_cart') {
        response = `🛒 To add items to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nI can help you:\n• Search for products\n• Navigate to cart page\n• Show product recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'add_to_cart' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'remove_from_cart') {
        response = `🛒 To remove items from your cart, please navigate to the cart page where you can manage your items.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'remove_from_cart' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'update_quantity') {
        response = `🛒 To update quantities in your cart, please navigate to the cart page where you can modify item quantities.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations\n\nWhat would you like to do?`
        contextUpdate = { currentTopic: 'cart', lastAction: 'update_quantity' }
        actionTaken = true
      }

      else if (lowerMessage.includes('search') || lowerMessage.includes('find') || lowerMessage.includes('look for') ||
        (conversationContext.currentTopic === 'advanced_search' && userMessage.trim())) {

        const combinedFilterMatch = userMessage.match(/(\w+)\s+(under|above|between)\s+(\d+)(?:\s+and\s+(\d+))?/i)

        if (combinedFilterMatch) {
          const keyword = combinedFilterMatch[1]
          const filterType = combinedFilterMatch[2].toLowerCase()
          const price1 = parseInt(combinedFilterMatch[3])
          const price2 = parseInt(combinedFilterMatch[4])

          let minPrice = 0
          let maxPrice = 0

          if (filterType === 'under') {
            maxPrice = price1
          } else if (filterType === 'above') {
            minPrice = price1
            maxPrice = Infinity
          } else if (filterType === 'between') {
            minPrice = price1
            maxPrice = price2
          }

          const results = await searchProducts(keyword, { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `🔍 I found ${filteredResults.length} products matching "${keyword}" ${rangeText}:\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
          } else {
            response = `🔍 No products found matching "${keyword}" ${rangeText}.\n\nWould you like me to:\n• Try a different price range\n• Search for similar products\n• Browse all products\n• Get recommendations`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'advanced_search' }
          actionTaken = true
        } else {
          
          const searchTerm = userMessage.replace(/search|find|look for/gi, '').trim()
          if (searchTerm) {
            const results = await searchProducts(searchTerm)
            if (results.products && results.products.length > 0) {
              response = `🔍 I found ${results.length} products matching "${searchTerm}":\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
              ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
            } else {
              response = `🔍 No products found matching "${searchTerm}".\n\nWould you like me to:\n• Search with different keywords\n• Browse all products\n• Show trending items\n• Get recommendations`
            }
            contextUpdate = { currentTopic: 'search', lastAction: 'search', searchHistory: [...conversationContext.searchHistory, searchTerm] }
            actionTaken = true
          }
        }
      }

      else if (lowerMessage.includes('cart') || lowerMessage.includes('shopping cart')) {
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          response = `🛒 Your cart has ${cartSummary.count} items:\n\n${cartSummary.items.map(item =>
            `• ${item.name} - Qty: ${item.quantity} - ₹${item.price * item.quantity}\n`
          ).join('')}\n\nTotal: ₹${cartSummary.total}\n\nI can help you:\n• Update quantities\n• Remove items\n• Add more products\n• Proceed to checkout\n• Apply discounts`
        } else {
          response = `🛒 Your cart is empty. Would you like me to:\n• Show trending products\n• Search for specific items\n• Show personalized recommendations\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'cart', lastAction: 'view_cart' }
        actionTaken = true
      }

      else if (lowerMessage.includes('wishlist') || lowerMessage.includes('favorites')) {
        const wishlistSummary = getWishlistSummary()
        if (wishlistSummary.count > 0) {
          response = `💖 Your wishlist has ${wishlistSummary.count} items:\n\n${wishlistSummary.items.map(item =>
            `• ${item.name} - ₹${item.price} - ${item.category}\n`
          ).join('')}\n\nI can help you:\n• Add items to cart\n• Remove items\n• Share wishlist\n• Get price alerts\n• Find similar items`
        } else {
          response = `💖 Your wishlist is empty. Would you like me to:\n• Show trending products\n• Search for items to add\n• Show personalized picks\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'wishlist', lastAction: 'view_wishlist' }
        actionTaken = true
      }

      else if (lowerMessage.includes('order') || lowerMessage.includes('track') || lowerMessage.includes('delivery')) {
        const orderSummary = getOrderSummary()
        if (orderSummary.count > 0) {
          response = `📦 You have ${orderSummary.count} orders:\n\n${orderSummary.items.map(order =>
            `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
          ).join('')}\n\nI can help you:\n• Track specific orders\n• Check delivery status\n• Cancel orders\n• Return items\n• Contact support`
        } else {
          response = `📦 You don't have any orders yet. Would you like me to:\n• Show your cart\n• Browse products\n• Show trending items\n• Help you place your first order`
        }
        contextUpdate = { currentTopic: 'orders', lastAction: 'view_orders' }
        actionTaken = true
      }

      else if (lowerMessage.includes('add to cart') || lowerMessage.includes('buy') || lowerMessage.includes('purchase')) {
        
        const productName = userMessage.replace(/add to cart|buy|purchase/gi, '').trim()
        if (productName) {
          const product = currentSearchResults.find(p =>
            p.name.toLowerCase().includes(productName.toLowerCase())
          )
          if (product) {
            response = `🛒 To add "${product.name}" to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nPrice: ₹${product.price}\nCategory: ${product.category}\n\nI can help you:\n• Navigate to cart page\n• Search for more products\n• Show recommendations\n• Continue shopping`
            contextUpdate = { currentTopic: 'cart', lastAction: 'add_to_cart', pendingAction: null }
            actionTaken = true
          } else {
            response = `I couldn't find "${productName}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories\n• Check if it's available`
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_price') {
        
        const pricePatterns = [
          
          { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
          
          { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
          
          { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
        ]

        let minPrice = 0
        let maxPrice = 0
        let priceRangeFound = false

        for (const { pattern, type } of pricePatterns) {
          const match = userMessage.match(pattern)
          if (match) {
            priceRangeFound = true

            if (type === 'range') {
              minPrice = parseInt(match[1])
              maxPrice = parseInt(match[2])
            } else if (type === 'under') {
              minPrice = 0
              maxPrice = parseInt(match[1])
            } else if (type === 'above') {
              minPrice = parseInt(match[1])
              maxPrice = Infinity
            }
            break
          }
        }

        if (priceRangeFound) {
          const results = await searchProducts('', { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
            contextUpdate = { currentTopic: 'search_results', lastAction: 'price_search' }
            actionTaken = true
          } else {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            response = `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`
            contextUpdate = { currentTopic: 'search_results', lastAction: 'price_search' }
            actionTaken = true
          }
        } else {
          response = `💰 Please specify your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n• "Between 1000 and 2000"\n\nWhat's your budget range?`
          contextUpdate = { currentTopic: 'search_by_price', lastAction: 'search_by_price' }
          actionTaken = true
        }
      }
      else if (conversationContext.currentTopic === 'search_by_name') {
        
        let productName = userMessage.trim()

        if (productName && !productName.includes(' ')) {
          
          const results = await searchProducts(productName)
          if (results.products && results.products.length > 0) {
            response = `🔍 I found ${results.length} products matching "${productName}":\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
            ).join('')}\n\nWould you like me to:\n• Show more results\n• Add any to cart\n• Check availability\n• Compare prices\n• Get recommendations`
          } else {
            response = `🔍 No products found matching "${productName}".\n\nWould you like me to:\n• Search with different keywords\n• Browse all products\n• Show trending items\n• Get recommendations`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_name' }
          actionTaken = true
        } else {
          
          productName = extractProductName(userMessage)

          if (!productName || productName.trim() === '') {
            response = `🔍 Please tell me what product you're looking for!\n\nExamples:\n• "iPhone"\n• "laptop"\n• "shoes"\n• "headphones"\n\nWhat would you like to search for?`
            contextUpdate = { currentTopic: 'search_by_name', lastAction: 'search_by_name' }
            actionTaken = true
          } else {
            const results = await searchProducts(productName)
            if (results.products && results.products.length > 0) {
              response = `🔍 Real-time Search Results for "${productName}":\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock} - ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n`
              ).join('')}\n\nI can help you:\n• Add any to cart\n• Add to wishlist\n• See more results\n• Search for something else\n• Get recommendations\n• Compare products\n• Check stock availability`
            } else {
              response = `🔍 No products found for "${productName}".\n\nWould you like to:\n• Try different keywords\n• Browse all products\n• Show trending items\n• Get recommendations\n• Search by category`
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_name' }
            actionTaken = true
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_category') {
        const category = extractCategory(userMessage)

        const categoryMap = {
          'mobile phones': ['mobile phones', 'mobile', 'phones', 'smartphone', 'phone', 'mobile devices'],
          'accessories': ['accessories', 'accessory', 'add-ons', 'extras'],
          'laptops': ['laptops', 'laptop', 'computer', 'notebook', 'pc'],
          'headphones': ['headphones', 'headphone', 'earphones', 'audio', 'sound'],
          'shoes': ['shoes', 'shoe', 'footwear', 'sneakers', 'boots'],
          'electronics': ['electronics', 'electronic', 'tech', 'technology', 'gadgets', 'devices'],
          'men': ['men', 'mens', 'male', 'gents'],
          'women': ['women', 'womens', 'female', 'ladies'],
          'toys': ['toys', 'toy', 'games', 'play', 'children', 'kids'],
          'musical instruments': ['musical instruments', 'music', 'instrument', 'musical']
        }

        let matchedCategory = category
        for (const [mainCategory, variations] of Object.entries(categoryMap)) {
          if (variations.some(v => category.toLowerCase().includes(v))) {
            matchedCategory = mainCategory
            break
          }
        }

        const categoryProducts = await getCategoryProducts(matchedCategory)

        if (categoryProducts.length > 0) {
          response = `📦 Great choice! Here are ${categoryProducts.length} products in the ${matchedCategory} category:\n\n${categoryProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
          ).join('')}\n\nI can help you:\n• Add any to cart\n• See more ${matchedCategory} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks\n• Browse other categories`
        } else {
          const availableCategories = await getAvailableCategories()
          const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
          response = `📦 I found some ${matchedCategory} products, but let me show you what's available:\n\nAvailable categories:\n${categoryList}\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items\n• Get recommendations`
        }
        contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_category' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'search_by_price') {

        const priceMatch = userMessage.match(/(\d+)\s*-\s*(\d+)|under\s+(\d+)|above\s+(\d+)|(\d+)\s*to\s*(\d+)/i)

        if (priceMatch) {
          let minPrice = 0
          let maxPrice = 0

          if (priceMatch[1] && priceMatch[2]) {
            
            minPrice = parseInt(priceMatch[1])
            maxPrice = parseInt(priceMatch[2])
           
          } else if (priceMatch[3]) {
            
            maxPrice = parseInt(priceMatch[3])
           
          } else if (priceMatch[4]) {
            
            minPrice = parseInt(priceMatch[4])
           
          } else if (priceMatch[5] && priceMatch[6]) {
            
            minPrice = parseInt(priceMatch[5])
            maxPrice = parseInt(priceMatch[6])
           
          }

          const results = await searchProducts('', { minPrice, maxPrice })

          if (results.products && results.products.length > 0) {
            response = `💰 Products in your price range (₹${minPrice}${maxPrice > 0 ? ` - ₹${maxPrice}` : '+'}):\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
          } else {
            response = `💰 No products found in your price range (₹${minPrice}${maxPrice > 0 ? ` - ₹${maxPrice}` : '+'}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_price' }
          actionTaken = true
        } else {

          const numbers = userMessage.match(/\d+/g)
          if (numbers && numbers.length >= 2) {
            const minPrice = parseInt(numbers[0])
            const maxPrice = parseInt(numbers[1])

            const results = await searchProducts('', { minPrice, maxPrice })

            if (results.products && results.products.length > 0) {
              response = `💰 Products in your price range (₹${minPrice} - ₹${maxPrice}):\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
            } else {
              response = `💰 No products found in your price range (₹${minPrice} - ₹${maxPrice}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_price' }
            actionTaken = true
          } else {
            response = `💰 Please specify your price range:\n\nExamples:\n• "1000-5000"\n• "Under 2000"\n• "Above 5000"\n• "1000 to 5000"\n\nWhat's your budget?`
          }
        }
      }

      else if (conversationContext.currentTopic === 'search_by_brand') {
        
        let brand = userMessage.trim().toLowerCase()

        if (brand && !brand.includes(' ')) {
          
          const results = await searchProducts('', { brand: brand })
          if (results.products && results.products.length > 0) {
            response = `🏷️ ${brand.charAt(0).toUpperCase() + brand.slice(1)} products:\n\n${results.products.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${brand.charAt(0).toUpperCase() + brand.slice(1)} products\n• Browse other brands\n• Get recommendations`
          } else {
       
            const alternativeResults = await searchProducts(brand)
            if (alternativeResults.products && alternativeResults.products.length > 0) {
              response = `🏷️ Found ${alternativeResults.products.length} products related to "${brand}":\n\n${alternativeResults.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
            } else {
              response = `🏷️ No products found for ${brand.charAt(0).toUpperCase() + brand.slice(1)} brand.\n\nWould you like to:\n• Try a different brand\n• Browse all products\n• Show trending items\n• Search by category`
            }
          }
          contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_brand' }
          actionTaken = true
        } else {
          
          brand = extractBrand(userMessage)

          if (!brand || brand.trim() === '') {
            response = `🏷️ Please tell me which brand you're looking for!\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• Asus, Acer, MSI\n• And many more!\n\nWhich brand are you looking for?`
            contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand' }
            actionTaken = true
          } else {
            const results = await searchProducts('', { brand: brand })
            if (results.products && results.products.length > 0) {
              response = `🏷️ ${brand} products:\n\n${results.products.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${brand} products\n• Browse other brands\n• Get recommendations`
            } else {
              
              const alternativeResults = await searchProducts(brand)
              if (alternativeResults.products && alternativeResults.products.length > 0) {
                response = `🏷️ Found ${alternativeResults.products.length} products related to "${brand}":\n\n${alternativeResults.products.slice(0, 5).map(product =>
                  `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
                ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more related products\n• Try a different brand\n• Get recommendations`
              } else {
                response = `🏷️ No products found for ${brand} brand.\n\nWould you like to:\n• Try a different brand\n• Browse all products\n• Show trending items\n• Search by category`
              }
            }
            contextUpdate = { currentTopic: 'search_results', lastAction: 'search_by_brand' }
            actionTaken = true
          }
        }
      }

      else if (lowerMessage.includes('remove') || lowerMessage.includes('delete')) {
        if (conversationContext.currentTopic === 'cart') {
          response = `To remove items from your cart, please tell me:\n• The product name you want to remove\n• Or say "show cart" to see all items\n• Or say "clear cart" to remove everything`
        } else if (conversationContext.currentTopic === 'wishlist') {
          response = `To remove items from your wishlist, please tell me:\n• The product name you want to remove\n• Or say "show wishlist" to see all items\n• Or say "clear wishlist" to remove everything`
        } else {
          response = `I can help you remove items from:\n• Your cart - say "remove from cart"\n• Your wishlist - say "remove from wishlist"\n\nWhat would you like to remove?`
        }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'clear_cart') {
        if (lowerMessage.includes('yes') || lowerMessage.includes('confirm')) {
          
          const cartItems = getCartSummary().items
          let clearedCount = 0

          response = `🛒 To clear your cart, please navigate to the cart page where you can remove all items.\n\nI can help you:\n• Navigate to cart page\n• Browse products\n• Search for items\n• View recommendations`
          contextUpdate = { currentTopic: null, lastAction: 'clear_cart' }
          actionTaken = true
        } else {
          response = `Cart clearing cancelled. Your cart still has ${getCartSummary().count} items.\n\nWould you like to:\n• View your cart\n• Update quantities\n• Remove specific items\n• Continue shopping`
        }
      }

      else if (conversationContext.currentTopic === 'add_to_wishlist') {
        const productName = extractProductName(userMessage)

        if (!productName || productName.trim() === '') {
          response = `➕ Please tell me what product you'd like to add to your wishlist!\n\nExamples:\n• "Add iPhone to wishlist"\n• "Save laptop"\n• "Wishlist shoes"\n\nWhat would you like to add?`
          contextUpdate = { currentTopic: 'add_to_wishlist', lastAction: 'add_to_wishlist' }
          actionTaken = true
        } else {
          
          const results = await searchProducts(productName)
          const product = results.find(p =>
            p.name && p.name.toLowerCase().includes(productName.toLowerCase())
          )

          if (product) {
            
            const existingItem = currentWishlistItems.find(item => item.productId === product._id)
            if (existingItem) {
              response = `ℹ️ "${product.name}" is already in your wishlist!\n\nWould you like to:\n• View your wishlist\n• Add to cart\n• Search for other products\n• Continue shopping`
            } else {
              response = `💖 To add "${product.name}" to your wishlist, please navigate to the product page and use the "Add to Wishlist" button.\n\n📊 Product Details:\n• Price: ₹${product.price}\n• Category: ${product.category}\n• Seller: ${product.seller}\n• Rating: ⭐${product.ratings || 'N/A'}\n• Stock: ${product.stock} available\n• ${product.PremiumBadge ? '🏆 ' + product.PremiumBadge : ''}\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations\n• Continue shopping`
            }
          } else {
            response = `I couldn't find "${productName}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories\n• Search by name`
          }
          contextUpdate = { currentTopic: 'wishlist', lastAction: 'add_to_wishlist' }
          actionTaken = true
        }
      } else if (conversationContext.currentTopic === 'remove_from_wishlist') {
        const wishlistItems = getWishlistSummary().items;
        const product = wishlistItems.find(item =>
          item.name &&
          userMessage &&
          item.name.toLowerCase().includes(userMessage.toLowerCase())
        );

        if (product) {
          response = `💖 To remove "${product.name}" from your wishlist, please navigate to the wishlist page where you can manage your saved items.\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations\n• Continue shopping`
        } else {
          response = `I couldn't find "${userMessage}" in your wishlist. Your current items:\n\n${wishlistItems.map(item =>
            `• ${item.name} - ₹${item.price}\n`
          ).join('')}\n\nTo manage your wishlist items, please navigate to the wishlist page.`
        }
        contextUpdate = { currentTopic: 'wishlist', lastAction: 'remove_from_wishlist' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'track_specific_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails) {
            response = `📦 Order #${orderId.slice(-6)} Details:\n\nStatus: ${orderDetails.status}\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'orders', lastAction: 'track_order' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Track order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'order_status') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderStatus = getOrderStatus(orderId)

          if (orderStatus) {
            response = `📊 Order #${orderId.slice(-6)} Status:\n\nStatus: ${orderStatus.status}\nLast Updated: ${orderStatus.lastUpdated}\nEstimated Delivery: ${orderStatus.estimatedDelivery}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'orders', lastAction: 'check_status' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Check status 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'cancel_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails && orderDetails.status === 'pending') {
            response = `❌ Cancel Order #${orderId.slice(-6)}\n\nAre you sure you want to cancel this order?\n\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nType "yes" to confirm or "no" to cancel.`
            contextUpdate = { currentTopic: 'cancel_order', lastAction: 'cancel_order', pendingAction: { type: 'cancel_order', orderId } }
          } else if (orderDetails) {
            response = `❌ Order #${orderId.slice(-6)} cannot be cancelled.\n\nStatus: ${orderDetails.status}\n\nOnly pending orders can be cancelled.\n\nWould you like to:\n• Return items\n• Contact support\n• Track delivery`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Cancel order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'return_order') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          const orderDetails = getOrderDetails(orderId)

          if (orderDetails) {
            response = `🔄 Return Order #${orderId.slice(-6)}\n\nI can help you return items from this order.\n\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Return all items\n• Return specific items\n• Contact support\n• Track return status`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
          contextUpdate = { currentTopic: 'return_order', lastAction: 'return_order' }
          actionTaken = true
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Return order 123456"`
        }
      }

      else if (conversationContext.currentTopic === 'payment_issues') {
        response = `⚠️ Payment Issue Support\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nPlease describe your specific issue, and I'll guide you through the resolution process.`
        contextUpdate = { currentTopic: 'payment_support', lastAction: 'payment_issues' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'refund_status') {
        const orderMatch = userMessage.match(/order\s*#?(\w+)/i) || userMessage.match(/(\w{6,})/i)
        if (orderMatch) {
          const orderId = orderMatch[1]
          response = `💰 Refund Status for Order #${orderId.slice(-6)}\n\nI'll check your refund status.\n\nRefund Status: Processing\nEstimated Time: 5-7 business days\n\nWould you like to:\n• Track refund progress\n• Contact support\n• Check other orders`
        } else {
          response = `Please provide your order number:\n\nExamples:\n• "Order #123456"\n• "123456"\n• "Check refund 123456"`
        }
        contextUpdate = { currentTopic: 'refund_status', lastAction: 'refund_status' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'category_recommendations') {
        const category = userMessage.toLowerCase()
        const categoryProducts = productsData?.filter(p =>
          p.category.toLowerCase().includes(category)
        ) || []

        if (categoryProducts.length > 0) {
          response = `📦 ${userMessage} Recommendations:\n\n${categoryProducts.slice(0, 5).map(product =>
            `• ${product.name} - ₹${product.price} - ⭐${product.rating || 'N/A'}\n`
          ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more ${userMessage} products\n• Browse other categories\n• Get personalized picks`
        } else {
          response = `No products found in ${userMessage} category.\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items`
        }
        contextUpdate = { currentTopic: 'category_recommendations', lastAction: 'category_recommendations' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'price_recommendations') {
        const priceMatch = userMessage.match(/(\d+)-(\d+)|under (\d+)|above (\d+)/i)
        if (priceMatch) {
          let minPrice = 0
          let maxPrice = 0

          if (priceMatch[1] && priceMatch[2]) {
            minPrice = parseInt(priceMatch[1])
            maxPrice = parseInt(priceMatch[2])
          } else if (priceMatch[3]) {
            maxPrice = parseInt(priceMatch[3])
          } else if (priceMatch[4]) {
            minPrice = parseInt(priceMatch[4])
          }

          const priceProducts = productsData?.filter(p =>
            p.price >= minPrice && (maxPrice === 0 || p.price <= maxPrice)
          ) || []

          if (priceProducts.length > 0) {
            response = `💰 Recommendations in your price range:\n\n${priceProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get personalized picks`
          } else {
            response = `No products found in your price range.\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items`
          }
          contextUpdate = { currentTopic: 'price_recommendations', lastAction: 'price_recommendations' }
          actionTaken = true
        } else {
          response = `Please specify your price range:\n\nExamples:\n• "1000-5000"\n• "Under 2000"\n• "Above 5000"\n\nWhat's your budget?`
        }
      }

      else if (conversationContext.currentTopic === 'similar_products') {
        const productsArray = productsData?.products || []
  const product = productsArray.find(p =>
          p.name.toLowerCase().includes(userMessage.toLowerCase())
        )

        if (product) {
          const similarProducts = productsData?.filter(p =>
            p.category === product.category && p._id !== product._id
          ).slice(0, 5) || []

          if (similarProducts.length > 0) {
            response = `🔄 Similar products to ${product.name}:\n\n${similarProducts.map(p =>
              `• ${p.name} - ₹${p.price} - ⭐${p.rating || 'N/A'}\n`
            ).join('')}\n\nWould you like to:\n• Add any to cart\n• Add to wishlist\n• See more similar products\n• Compare products`
          } else {
            response = `No similar products found for ${product.name}.\n\nWould you like to:\n• Browse ${product.category} products\n• Show trending items\n• Get recommendations`
          }
        } else {
          response = `I couldn't find "${userMessage}" in our products. Would you like me to:\n• Search for similar items\n• Show trending products\n• Browse categories`
        }
        contextUpdate = { currentTopic: 'similar_products', lastAction: 'similar_products' }
        actionTaken = true
      }

      else if (conversationContext.currentTopic === 'technical_help') {
        response = `🔧 Technical Support\n\nI can help you with:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nPlease describe your specific technical issue, and I'll guide you through the resolution process.`
        contextUpdate = { currentTopic: 'technical_support', lastAction: 'technical_help' }
        actionTaken = true
      }

      else if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
        if (conversationContext.lastAction === 'search') {
          response = `💰 Price information for your search results:\n\n${currentSearchResults.slice(0, 5).map(product =>
            `• ${product.name}: ₹${product.price}\n`
          ).join('')}\n\nI can help you:\n• Filter by price range\n• Find cheaper alternatives\n• Compare prices\n• Set price alerts`
        } else {
          response = `💰 I can help you with pricing:\n• Search for products and see prices\n• Compare prices across products\n• Find deals and discounts\n• Set price alerts\n\nWhat would you like to know about?`
        }
        contextUpdate = { currentTopic: 'pricing', lastAction: 'price_inquiry' }
        actionTaken = true
      }

      else if (lowerMessage.includes('recommend') || lowerMessage.includes('suggestion') || lowerMessage.includes('similar')) {
        const recommendations = await generateRecommendations()
        if (recommendations.length > 0) {
          response = `⭐ Based on your preferences, here are my recommendations:\n\n${recommendations.map(product =>
            `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
          ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get trending items\n• Browse by category`
        } else {
          response = `⭐ I'd be happy to recommend products! Please:\n• Browse some products first\n• Add items to your wishlist\n• Tell me what you're looking for\n• Let me show you trending items`
        }
        contextUpdate = { currentTopic: 'recommendations', lastAction: 'get_recommendations' }
        actionTaken = true
      }

      else if (lowerMessage.includes('help') || lowerMessage.includes('support') || lowerMessage.includes('assist')) {
        response = `🆘 I'm here to help! Here's what I can do:\n\n🛒 Shopping:\n• Search products\n• Add to cart\n• View wishlist\n• Track orders\n\n📊 Account:\n• Check cart status\n• View order history\n• Manage wishlist\n• Payment help\n\n🔍 Search:\n• Find specific products\n• Browse categories\n• Get recommendations\n• Price comparisons\n\n💬 Support:\n• Order tracking\n• Return assistance\n• Payment issues\n• General questions\n\nWhat would you like help with?`
        contextUpdate = { currentTopic: 'help', lastAction: 'help_request' }
        actionTaken = true
      }

      else if (lowerMessage.includes('hello') || lowerMessage.includes('hi') || lowerMessage.includes('hey')) {
        const cartSummary = getCartSummary()
        const wishlistSummary = getWishlistSummary()
        const userInsights = getUserInsights()
        const timeOfDay = new Date().getHours()

        let greeting = ''
        if (timeOfDay < 12) {
          greeting = 'Good morning'
        } else if (timeOfDay < 17) {
          greeting = 'Good afternoon'
        } else {
          greeting = 'Good evening'
        }

        let personalization = ''
        if (userInsights.favoriteCategory !== 'No preference') {
          personalization = `I noticed you love ${userInsights.favoriteCategory} products! `
        }

        response = `${greeting}! 👋 Welcome back to MKCart! I'm your personalized AI shopping assistant. 🤖\n\n${personalization}I'm here to make your shopping experience amazing!\n\n📊 Your Shopping Summary:\n• Cart: ${cartSummary.count} items (₹${cartSummary.total})\n• Wishlist: ${wishlistSummary.count} items\n• Orders: ${getOrderSummary().count} orders\n\n🎯 I can help you with:\n\n🔍 Smart Search\n• Search by name, category, price, brand\n• Advanced filters and sorting\n• Trending and popular items\n\n🛒 Cart Management\n• Add, remove, update quantities\n• Quick checkout process\n• Save for later options\n\n💖 Wishlist Features\n• Save favorite items\n• Price drop alerts\n• Share with friends\n\n📦 Order Tracking\n• Real-time order status\n• Delivery tracking\n• Easy returns and refunds\n\n⭐ Personalized Experience\n• Smart recommendations\n• Based on your preferences\n• Deals and discounts\n\n🎤 Voice Commands\n• Speak naturally to me\n• I understand voice input\n• Hands-free shopping\n\n💬 ChatGPT-like Experience\n• Intelligent conversations\n• Context-aware responses\n• Memory of our chats\n\nWhat would you like to explore today? Just type or speak naturally! 😊`
        contextUpdate = { currentTopic: 'greeting', lastAction: 'greeting' }
        actionTaken = true
      }

      else if (lowerMessage.includes('thank') || lowerMessage.includes('thanks')) {
        response = `😊 You're welcome! I'm here to make your shopping experience amazing.\n\nIs there anything else I can help you with?\n\n• Continue shopping\n• Check your cart\n• Browse recommendations\n• Track orders`
        contextUpdate = { currentTopic: 'gratitude', lastAction: 'thank_you' }
        actionTaken = true
      }

      else if (lowerMessage.includes('bye') || lowerMessage.includes('goodbye')) {
        response = `👋 Goodbye! Thanks for shopping with MKCart!\n\nDon't forget to:\n• Check your cart before leaving\n• Save items to wishlist\n• Track your orders\n\nCome back anytime! I'll be here to help! 😊`
        contextUpdate = { currentTopic: 'farewell', lastAction: 'goodbye' }
        actionTaken = true
      }

      else if (lowerMessage.includes('how are you') || lowerMessage.includes('how do you do')) {
        response = `🤖 I'm doing great, thank you for asking! I'm here and ready to help you with all your shopping needs.\n\nI can assist you with:\n• Finding products\n• Managing your cart\n• Tracking orders\n• Getting recommendations\n\nHow can I help you today?`
        contextUpdate = { currentTopic: 'wellbeing', lastAction: 'how_are_you' }
        actionTaken = true
      }

      else if (lowerMessage.includes('recommend') || lowerMessage.includes('suggestion')) {
        const recommendations = await generateRecommendations()
        response = `🎯 Here are some personalized recommendations for you:\n\n${recommendations.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Search for specific items\n• Browse categories`
        contextUpdate = { currentTopic: 'recommendations', lastAction: 'get_recommendations' }
        actionTaken = true
      }

      else if (lowerMessage.includes('trending') || lowerMessage.includes('popular')) {
        const trendingProducts = await getTrendingProducts()
        response = `🔥 Here are the trending products right now:\n\n${trendingProducts.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks\n• Browse by category`
        contextUpdate = { currentTopic: 'trending', lastAction: 'view_trending' }
        actionTaken = true
      }

      else if (lowerMessage.includes('brand') && (lowerMessage.includes('search') || lowerMessage.includes('find') || lowerMessage.includes('show'))) {
        response = `🏷️ Search by Brand\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• Asus, Acer, MSI\n• And many more!\n\nWhich brand are you looking for?`
        contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand' }
        actionTaken = true
      }

      else if (lowerMessage.includes('view') && lowerMessage.includes('products')) {
        response = `📦 Navigate to Products Page\n\nI'm taking you to the products page where you can:\n• Browse all products\n• Filter by category\n• Sort by price, rating, popularity\n• Search for specific items\n• Add items to cart or wishlist\n• View product details\n\nNavigating now...`
        productsActions()
        contextUpdate = { currentTopic: 'view_products', lastAction: 'view_products' }
        actionTaken = true
      }

      else if (lowerMessage.includes('track') && (lowerMessage.includes('order') || lowerMessage.includes('delivery'))) {
        const orderId = extractOrderId(userMessage)
        if (orderId) {
          const orderStatus = await getOrderStatus(orderId)
          if (orderStatus) {
            response = `📦 Real-time Order #${orderStatus.orderId.slice(-6)} Status:\n\n📊 Order Details:\n• Status: ${orderStatus.status}\n• Description: ${orderStatus.statusDescription}\n• Amount: ₹${orderStatus.amount}\n• Payment: ${orderStatus.paymentMethod}\n• Transaction ID: ${orderStatus.transactionId}\n\n🚚 Delivery Info:\n• Last Updated: ${orderStatus.lastUpdated}\n• Estimated Delivery: ${orderStatus.estimatedDelivery}\n• Tracking Number: ${orderStatus.trackingNumber || 'Not available'}\n• Address: ${orderStatus.deliveryAddress}\n\n${orderStatus.canCancel ? '❌ Can Cancel: Yes' : ''}\n${orderStatus.canReturn ? '🔄 Can Return: Yes' : ''}\n${orderStatus.canTrack ? '📍 Can Track: Yes' : ''}\n\nWould you like to:\n• Get detailed order info\n• Cancel order\n• Contact support\n• Track other orders\n• View all orders`
          } else {
            response = `❌ Order #${orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products\n• View recent orders`
          }
        } else {
          response = `📦 Please provide your order ID!\n\nExamples:\n• "Track order 123456"\n• "Check status of order ABC123"\n• "Where is my order 789"\n\nWhat's your order ID?`
        }
        contextUpdate = { currentTopic: 'order_tracking', lastAction: 'track_order' }
        actionTaken = true
      }

      else if (lowerMessage.includes('stock') || lowerMessage.includes('available') || lowerMessage.includes('inventory')) {
        const productName = extractProductName(userMessage)
        if (productName) {
          const results = await searchProducts(productName)
          const product = results.find(p => p.name.toLowerCase().includes(productName.toLowerCase()))
          if (product) {
            const inventory = await checkInventory(product._id)
            if (inventory) {
              response = `📦 Real-time Inventory Check for "${product.name}":\n\n📊 Stock Information:\n• Available: ${inventory.stock} units\n• Status: ${inventory.status}\n• Seller: ${inventory.seller}\n• Price: ₹${inventory.price}\n• Category: ${inventory.category}\n• Last Updated: ${inventory.lastUpdated}\n\n${inventory.lowStock ? `⚠️ ${inventory.lowStock}` : ''}\n\nWould you like to:\n• Add to cart\n• Add to wishlist\n• Check similar products\n• Get price alerts\n• View product details`
            } else {
              response = `❌ Unable to check inventory for "${product.name}". Please try again.`
            }
          } else {
            response = `❌ Product "${productName}" not found. Would you like to:\n• Search for similar products\n• Browse categories\n• Show trending items`
          }
        } else {
          response = `📦 Please tell me which product you want to check!\n\nExamples:\n• "Check stock for iPhone"\n• "Is Samsung available"\n• "Inventory for laptop"\n\nWhat product would you like to check?`
        }
        contextUpdate = { currentTopic: 'inventory_check', lastAction: 'check_inventory' }
        actionTaken = true
      }

      else if (lowerMessage.includes('deals') || lowerMessage.includes('offers') || lowerMessage.includes('discount')) {
        const deals = getDealsAndOffers()
        response = `🎉 Here are the best deals and offers:\n\n${deals.slice(0, 5).map(deal =>
          `• ${deal.name} - ${deal.discount}% OFF - ₹${deal.price}\n`
        ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more deals\n• Get price alerts\n• Check your wishlist`
        contextUpdate = { currentTopic: 'deals', lastAction: 'view_deals' }
        actionTaken = true
      }

      else if (lowerMessage.includes('pay') || lowerMessage.includes('checkout') || lowerMessage.includes('purchase')) {
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          const paymentMethod = extractPaymentMethod(userMessage) || 'Credit Card'
          const orderItems = cartSummary.items.map(item => ({
            productId: item.productId,
            name: item.name,
            quantity: item.qty,
            price: item.price
          }))

          response = `💳 Real-time Payment Processing\n\n📊 Order Summary:\n• Total Items: ${cartSummary.count}\n• Total Amount: ₹${cartSummary.total}\n• Payment Method: ${paymentMethod}\n\n🛒 Items in Cart:\n${cartSummary.items.map(item =>
            `• ${item.name} - Qty: ${item.qty} - ₹${item.price * item.qty}\n`
          ).join('')}\n\nWould you like to:\n• Proceed with payment\n• Change payment method\n• Add more items\n• Apply discount code\n• Review order details`

          contextUpdate = {
            currentTopic: 'payment_processing',
            lastAction: 'initiate_payment',
            pendingAction: {
              type: 'process_payment',
              amount: cartSummary.total,
              method: paymentMethod,
              orderItems: orderItems
            }
          }
        } else {
          response = `🛒 Your cart is empty!\n\nWould you like to:\n• Browse products\n• Search for items\n• View recommendations\n• Check trending items`
        }
        actionTaken = true
      }

      else {
        
        const lowerMessage = userMessage.toLowerCase()

        if (lowerMessage.includes('fashion') || lowerMessage.includes('clothing') || lowerMessage.includes('dress')) {
          response = `👗 Fashion & Clothing!\n\nI can help you find the perfect fashion items:\n\n• Casual wear and formal attire\n• Shoes, bags, and accessories\n• Seasonal collections\n• Trending styles\n• Size and fit guidance\n\nWould you like me to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized fashion picks`
          contextUpdate = { currentTopic: 'fashion', lastAction: 'fashion_inquiry' }
        }
        else if (lowerMessage.includes('electronics') || lowerMessage.includes('phone') || lowerMessage.includes('laptop')) {
          response = `📱 Electronics & Tech!\n\nI can help you find the latest electronics:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\nWould you like me to:\n• Show trending electronics\n• Search for specific devices\n• Compare products\n• Get tech recommendations`
          contextUpdate = { currentTopic: 'electronics', lastAction: 'electronics_inquiry' }
        }
        else if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
          response = `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\nWould you like me to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
          contextUpdate = { currentTopic: 'pricing', lastAction: 'price_inquiry' }
        }
        else if (lowerMessage.includes('help') || lowerMessage.includes('support') || lowerMessage.includes('assist')) {
          response = `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 **Search & Discovery**\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 **Shopping Experience**\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 **Payment & Orders**\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 **Customer Support**\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\nWhat specific help do you need?`
          contextUpdate = { currentTopic: 'help', lastAction: 'help_request' }
        }
        else {
          
          let baseResponse = ""

          if (responseType === 'specific' && confidence > 0.8) {
            
            baseResponse = generateContextualResponse(userMessage, intent, sentiment, entities)
          } else if (responseType === 'contextual' && confidence > 0.5) {
            
            baseResponse = generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
          } else {
            
            const keywordResult = processIntelligentKeywords(userMessage)
            if (keywordResult) {
              baseResponse = keywordResult.response
              contextUpdate = keywordResult.contextUpdate || { currentTopic: 'general', lastAction: 'keyword_response' }
            } else {
              
              baseResponse = generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
              contextUpdate = { currentTopic: 'general', lastAction: 'ai_response' }
            }
          }

          let enhancedResponse = baseResponse

          if (personality === 'formal') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'formal') + "\n\n" + enhancedResponse
          } else if (personality === 'casual') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'casual') + "\n\n" + enhancedResponse
          } else if (personality === 'friendly') {
            enhancedResponse = getRandomResponse(responseLibraries.personality, 'friendly') + "\n\n" + enhancedResponse
          }

          if (emotions.length > 0) {
            const primaryEmotion = emotions[0]
            const emotionResponse = getRandomResponse(responseLibraries.emotions, primaryEmotion)
            enhancedResponse = emotionResponse + "\n\n" + enhancedResponse
          }

          if (urgency === 'high') {
            const urgencyResponse = getRandomResponse(responseLibraries.urgency, 'high')
            enhancedResponse = urgencyResponse + "\n\n" + enhancedResponse
          }

          if (context === 'firstTime') {
            const contextResponse = getRandomResponse(responseLibraries.context, 'firstTime')
            enhancedResponse = contextResponse + "\n\n" + enhancedResponse
          }

          if (suggestions.length > 0) {
            enhancedResponse += "\n\n💡 Quick suggestions:\n" + suggestions.map(suggestion => `• ${suggestion}`).join('\n')
          }

          response = enhancedResponse
          actionTaken = true
        }
      }

      if (actionTaken) {
        setConversationContext(prev => ({
          ...prev,
          ...contextUpdate,
          conversationFlow: [...prev.conversationFlow, { user: userMessage, ai: response }]
        }))

        updateConversationMemory(userMessage, response, contextUpdate)
      }

      setMessages(prev => prev.filter(msg => !msg.isTyping))

      const aiMessage = {
        id: Date.now(),
        message: response,
        type: "ai",
        timestamp: new Date(),
      }

      setMessages(prev => [...prev, aiMessage])

      if (voiceEnabled) {
        speakMessage(response)
      }

      setTimeout(() => {
        scrollToBottom()
      }, 200)

    } catch (error) {

      let errorResponse = ''
      if (error.message.includes('toLowerCase')) {
        errorResponse = `❌ I had trouble understanding your request. Please try:\n\n• "Add iPhone to cart"\n• "Add 2 laptops"\n• "Add shoes quantity 3"\n\nMake sure to specify a product name!`
      } else if (error.message.includes('fetch')) {
        errorResponse = `❌ Connection issue. Please check:\n\n• Your internet connection\n• Try refreshing the page\n• Contact support if the issue persists`
      } else {
        errorResponse = `❌ I encountered an error while processing your request.\n\nError: ${error.message}\n\nPlease try:\n• Refreshing the page\n• Using different keywords\n• Contacting support if the issue persists\n\nI'm here to help you with:\n• Product searches\n• Cart management\n• Order tracking\n• General assistance`
      }

      const errorMessage = {
        id: Date.now(),
        message: errorResponse,
        type: "ai",
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, errorMessage])

      setTimeout(() => {
        scrollToBottom()
      }, 200)
    } finally {
      setIsProcessing(false)
      setCurrentTask(null)
    }
  }

  const startListening = () => {
    if (recognitionRef.current && !isListening) {
      recognitionRef.current.start()
    }
  }

  const stopListening = () => {
    if (recognitionRef.current && isListening) {
      recognitionRef.current.stop()
    }
  }

  const speakMessage = (text) => {
    if (window.speechSynthesis && voiceEnabled) {
      setIsSpeaking(true)
      const utterance = new SpeechSynthesisUtterance(text)
      utterance.rate = 0.9
      utterance.pitch = 1
      utterance.volume = 0.8

      utterance.onend = () => {
        setIsSpeaking(false)
      }

      window.speechSynthesis.speak(utterance)
    }
  }

  const stopSpeaking = () => {
    if (window.speechSynthesis) {
      window.speechSynthesis.cancel()
      setIsSpeaking(false)
    }
  }

  const handleQuickAction = async (action) => {
    let message = ""
    let contextUpdate = {}
    let actionTaken = false

    try {
      
      const mainAction = quickActions.find(qa => qa.action === action)
      if (mainAction && mainAction.subActions) {
        
        setCurrentSubActions(mainAction.subActions)
        setSubActionHistory(prev => [...prev, { action: action, label: mainAction.label }])

        message = `🎯 ${mainAction.label}\n\nWhat would you like to do?\n\nI can help you with:\n${mainAction.subActions.slice(0, -1).map(sub =>
          `• ${sub.label}\n`
        ).join('')}\n• ${mainAction.subActions[mainAction.subActions.length - 1].label}`

        contextUpdate = { currentTopic: action, lastAction: action, pendingAction: null }
        actionTaken = true
      } else if (action === 'back_to_main') {
        
        setCurrentSubActions(null)
        setSubActionHistory([])

        message = "I'm here to help! How can I assist you today?"
        contextUpdate = { currentTopic: null, lastAction: null, pendingAction: null }
        actionTaken = true
      } else {
        
        switch (action) {
          case "search_by_name":
            message = `🔍 Search by Name\n\nJust tell me the product name you're looking for!\n\nExamples:\n• "iPhone"\n• "laptop"\n• "shoes"\n• "headphones"\n\nWhat product would you like to search for?`
            contextUpdate = { currentTopic: 'search_by_name', lastAction: 'search_by_name', pendingAction: { type: 'search_by_name' } }
            break

          case "search_by_category":
            const availableCategories = await getAvailableCategories()
            const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
            message = `📦 Search by Category\n\nAvailable categories:\n${categoryList}\n\nWhich category interests you?`
            contextUpdate = { currentTopic: 'search_by_category', lastAction: 'search_by_category', pendingAction: { type: 'search_by_category', userMessage: '' } }
            break

          case "search_by_price":
            message = `💰 Search by Price\n\nTell me your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n\nWhat's your budget range?`
            contextUpdate = { currentTopic: 'search_by_price', lastAction: 'search_by_price', pendingAction: { type: 'search_by_price', userMessage: '' } }
            break

          case "search_by_brand":
            message = `🏷️ Search by Brand\n\nPopular brands:\n• Apple, Samsung, Sony\n• Nike, Adidas, Puma\n• Dell, HP, Lenovo\n• And many more!\n\nWhich brand are you looking for?`
            contextUpdate = { currentTopic: 'search_by_brand', lastAction: 'search_by_brand', pendingAction: { type: 'search_by_brand' } }
            break

          case "advanced_search":
            message = `🔧 Advanced Search\n\nI can help you search with multiple filters:\n\n• Category + Price Range\n• Brand + Rating\n• Availability + Features\n• And more combinations!\n\nWhat filters would you like to apply?`
            contextUpdate = { currentTopic: 'advanced_search', lastAction: 'advanced_search', pendingAction: { type: 'advanced_search' } }
            break

          case "trending_products":
            const trendingProducts = await getTrendingProducts()
            if (trendingProducts.length > 0) {
              message = `🔥 Trending Products\n\nHere are the most popular products right now:\n\n${trendingProducts.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks`
            } else {
              message = `🔥 Trending Products\n\nCurrently no trending products available.\n\nWould you like to:\n• Browse all products\n• Search for specific items\n• Get recommendations`
            }
            contextUpdate = { currentTopic: 'trending_products', lastAction: 'view_trending' }
            break

          case "view_cart":
            const cartSummary = getCartSummary()
            if (cartSummary.count > 0) {
              message = `🛒 Your Cart\n\nYou have ${cartSummary.count} items:\n\n${cartSummary.items.map(item =>
                `• ${item.name} - Qty: ${item.quantity} - ₹${item.price * item.quantity}\n`
              ).join('')}\n\nTotal: ₹${cartSummary.total}\n\nI can help you:\n• Update quantities\n• Remove items\n• Add more products\n• Proceed to checkout`
            } else {
              message = `🛒 Your cart is empty.\n\nWould you like me to:\n• Show trending products\n• Search for items\n• Show recommendations\n• Browse categories`
            }
            contextUpdate = { currentTopic: 'view_cart', lastAction: 'view_cart' }
            break

          case "navigate_to_cart":
            const cartSummaryForNav = getCartSummary()
            if (cartSummaryForNav.count > 0) {
              message = `🛒 Navigate to Cart Page\n\nYour cart has ${cartSummaryForNav.count} items (Total: ₹${cartSummaryForNav.total})\n\nI'm taking you to the cart page where you can:\n• Add/remove items\n• Update quantities\n• Clear cart\n• Proceed to checkout\n\nNavigating now...`
              cartActions()
            } else {
              message = `🛒 Navigate to Cart Page\n\nYour cart is empty.\n\nI'm taking you to the cart page where you can:\n• Browse products\n• Add items to cart\n• View recommendations\n\nNavigating now...`
              cartActions()
            }
            contextUpdate = { currentTopic: 'cart', lastAction: 'navigate_to_cart' }
            break

          case "checkout":
            const checkoutCart = getCartSummary()
            if (checkoutCart.count > 0) {
              message = `💳 Proceed to Checkout\n\nCheckout Summary:\n• Items: ${checkoutCart.count}\n• Total: ₹${checkoutCart.total}\n\nI can help you:\n• Review your cart\n• Apply discount codes\n• Choose payment method\n• Complete purchase\n\nWould you like to proceed?`
            } else {
              message = `Your cart is empty. Would you like to:\n• Browse products\n• Search for items\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'checkout', lastAction: 'checkout', pendingAction: { type: 'checkout' } }
            break

          case "view_wishlist":
            const wishlistSummaryForView = getWishlistSummary()
            if (wishlistSummaryForView.count > 0) {
              message = `💖 Your Wishlist\n\nYou have ${wishlistSummaryForView.count} items:\n\n${wishlistSummaryForView.items.map(item =>
                `• ${item.name} - ₹${item.price} - ${item.category}\n`
              ).join('')}\n\nI can help you:\n• Add items to cart\n• Remove items\n• Share wishlist\n• Get price alerts`
            } else {
              message = `💖 Your wishlist is empty.\n\nWould you like to:\n• Browse products\n• Search for items\n• Get recommendations\n• View trending items`
            }
            contextUpdate = { currentTopic: 'view_wishlist', lastAction: 'view_wishlist' }
            break

          case "navigate_to_wishlist":
            const wishlistSummaryForNav = getWishlistSummary()
            if (wishlistSummaryForNav.count > 0) {
              message = `💖 Navigate to Wishlist Page\n\nYour wishlist has ${wishlistSummaryForNav.count} items\n\nI'm taking you to the wishlist page where you can:\n• Add/remove items\n• Move items to cart\n• Share wishlist\n• Set price alerts\n\nNavigating now...`
              wishlistActions()
            } else {
              message = `💖 Navigate to Wishlist Page\n\nYour wishlist is empty.\n\nI'm taking you to the wishlist page where you can:\n• Browse products\n• Add items to wishlist\n• View recommendations\n\nNavigating now...`
              wishlistActions()
            }
            contextUpdate = { currentTopic: 'wishlist', lastAction: 'navigate_to_wishlist' }
            break

          case "share_wishlist":
            const shareWishlist = getWishlistSummary()
            if (shareWishlist.count > 0) {
              message = `📤 Share Wishlist\n\nYour wishlist has ${shareWishlist.count} items:\n\n${shareWishlist.items.map(item =>
                `• ${item.name} - ₹${item.price}\n`
              ).join('')}\n\nI can help you:\n• Generate share link\n• Send via email\n• Share on social media\n• Create gift registry`
            } else {
              message = `Your wishlist is empty. Would you like to:\n• Add some products\n• Browse categories\n• Search for items`
            }
            contextUpdate = { currentTopic: 'share_wishlist', lastAction: 'share_wishlist' }
            break

          case "price_alerts":
            const priceWishlist = getWishlistSummary()
            if (priceWishlist.count > 0) {
              message = `🔔 Price Alerts\n\nI can set up price alerts for your wishlist items:\n\n${priceWishlist.items.map(item =>
                `• ${item.name} - Current: ₹${item.price}\n`
              ).join('')}\n\nWould you like to:\n• Set price drop alerts\n• Track price changes\n• Get notified of deals\n• Compare prices`
            } else {
              message = `Your wishlist is empty. Would you like to:\n• Add products to track\n• Browse trending items\n• Search for products`
            }
            contextUpdate = { currentTopic: 'price_alerts', lastAction: 'price_alerts' }
            break

          case "view_orders":
            const orderSummary = getOrderSummary()
            if (orderSummary.count > 0) {
              message = `📦 Your Orders\n\nYou have ${orderSummary.count} orders:\n\n${orderSummary.items.map(order =>
                `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
              ).join('')}\n\nI can help you:\n• Track specific orders\n• Check delivery status\n• Cancel orders\n• Return items`
            } else {
              message = `📦 You don't have any orders yet.\n\nWould you like to:\n• Browse products\n• Add items to cart\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'view_orders', lastAction: 'view_orders' }
            break

          case "track_specific_order":
            const ordersToTrack = getOrderSummary()
            if (ordersToTrack.count > 0) {
              message = `🔍 Track Specific Order\n\nYour recent orders:\n\n${ordersToTrack.items.map(order =>
                `• Order #${order._id.slice(-6)} - ${order.status} - ₹${order.amount}\n`
              ).join('')}\n\nWhich order would you like to track?\n\nJust tell me the order number!`
            } else {
              message = `You don't have any orders to track. Would you like to:\n• Browse products\n• Add items to cart\n• View recommendations`
            }
            contextUpdate = { currentTopic: 'track_specific_order', lastAction: 'track_specific_order', pendingAction: { type: 'track_specific_order' } }
            break

          case "navigate_to_orders":
            const orderSummaryForNav = getOrderSummary()
            if (orderSummaryForNav.count > 0) {
              message = `📦 Navigate to Orders Page\n\nYou have ${orderSummaryForNav.count} orders\n\nI'm taking you to the orders page where you can:\n• View order details\n• Track deliveries\n• Cancel orders\n• Return items\n• Check status\n\nNavigating now...`
              orderActions()
            } else {
              message = `📦 Navigate to Orders Page\n\nYou don't have any orders yet.\n\nI'm taking you to the orders page where you can:\n• View order history\n• Track future orders\n• Manage returns\n\nNavigating now...`
              orderActions()
            }
            contextUpdate = { currentTopic: 'orders', lastAction: 'navigate_to_orders' }
            break

          case "order_status":
            message = `📊 Check Order Status\n\nI can help you check the status of any order!\n\nJust tell me:\n• Order number\n• Or describe your order\n\nWhat order would you like to check?`
            contextUpdate = { currentTopic: 'order_status', lastAction: 'order_status', pendingAction: { type: 'order_status' } }
            break

          case "payment_methods":
            message = `💳 Payment Methods\n\nWe accept:\n\n• Credit/Debit Cards\n• UPI (Google Pay, PhonePe, etc.)\n• Net Banking\n• Digital Wallets\n• EMI Options\n• Gift Cards\n\nAll transactions are secure with SSL encryption!\n\nWhich payment method would you like to know more about?`
            contextUpdate = { currentTopic: 'payment_methods', lastAction: 'payment_methods' }
            break

          case "payment_issues":
            message = `⚠️ Payment Issues\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nWhat payment issue are you experiencing?`
            contextUpdate = { currentTopic: 'payment_issues', lastAction: 'payment_issues', pendingAction: { type: 'payment_issues' } }
            break

          case "refund_status":
            message = `💰 Refund Status\n\nI can help you check your refund status!\n\nJust tell me:\n• Order number\n• Or describe your return\n\nWhat refund would you like to check?`
            contextUpdate = { currentTopic: 'refund_status', lastAction: 'refund_status', pendingAction: { type: 'refund_status' } }
            break

          case "billing_help":
            message = `📄 Billing Help\n\nI can assist with:\n\n• Invoice generation\n• Tax calculations\n• Billing address\n• Payment receipts\n• Corporate billing\n• Bulk orders\n\nWhat billing help do you need?`
            contextUpdate = { currentTopic: 'billing_help', lastAction: 'billing_help' }
            break

          case "security_info":
            message = `🔒 Security Information\n\nYour security is our priority:\n\n• SSL encrypted transactions\n• PCI DSS compliant\n• Secure payment gateways\n• Data protection\n• Privacy policy\n• Fraud protection\n\nAll your data is safe with us!`
            contextUpdate = { currentTopic: 'security_info', lastAction: 'security_info' }
            break

          case "personalized_recommendations":
            const personalizedRecs = await generateRecommendations()
            if (personalizedRecs.length > 0) {
              message = `⭐ Personalized Recommendations\n\nBased on your preferences:\n\n${personalizedRecs.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more recommendations\n• Get recommendations by category`
            } else {
              message = `⭐ Personalized Recommendations\n\nI don't have enough data for personalized recommendations yet.\n\nWould you like to:\n• Browse trending products\n• Search for items\n• View all products`
            }
            contextUpdate = { currentTopic: 'personalized_recommendations', lastAction: 'personalized_recommendations' }
            break

          case "trending_recommendations":
            const trendingRecs = await getTrendingProducts()
            if (trendingRecs.length > 0) {
              message = `🔥 Trending Recommendations\n\nMost popular right now:\n\n${trendingRecs.slice(0, 5).map(product =>
                `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.rating || product.ratings || 'N/A'}\n`
              ).join('')}\n\nWould you like to:\n• Add any to cart\n• See more trending items\n• Get personalized picks`
            } else {
              message = `🔥 Trending Recommendations\n\nCurrently no trending products available.\n\nWould you like to:\n• Browse all products\n• Search for specific items\n• Get personalized picks`
            }
            contextUpdate = { currentTopic: 'trending_recommendations', lastAction: 'trending_recommendations' }
            break

          case "category_recommendations":
            message = `📦 Recommendations by Category\n\nTell me which category you're interested in:\n\n• Electronics\n• Fashion\n• Home & Garden\n• Sports\n• Books\n• Beauty\n• And more!\n\nWhich category would you like recommendations for?`
            contextUpdate = { currentTopic: 'category_recommendations', lastAction: 'category_recommendations', pendingAction: { type: 'category_recommendations' } }
            break

          case "price_recommendations":
            message = `💰 Recommendations by Price\n\nTell me your budget range:\n\n• Under ₹1000\n• ₹1000-5000\n• ₹5000-10000\n• Above ₹10000\n\nWhat's your budget for recommendations?`
            contextUpdate = { currentTopic: 'price_recommendations', lastAction: 'price_recommendations', pendingAction: { type: 'price_recommendations' } }
            break

          case "similar_products":
            message = `🔄 Similar Products\n\nI can find similar products for you!\n\nJust tell me:\n• Product name\n• Or describe what you're looking for\n\nWhat product would you like similar items for?`
            contextUpdate = { currentTopic: 'similar_products', lastAction: 'similar_products', pendingAction: { type: 'similar_products' } }
            break

          case "contact_support":
            message = `🎧 Contact Support\n\nI can help you connect with our support team:\n\n• Live Chat: Available 24/7\n• Email: support@mkcart.com\n• Phone: +91-XXXXXXXXXX\n• Response Time: Within 2 hours\n\nWhat support do you need?`
            contextUpdate = { currentTopic: 'contact_support', lastAction: 'contact_support' }
            break

          case "faq":
            message = `❓ FAQ\n\nCommon questions:\n\n• How to track orders?\n• How to return items?\n• Payment methods accepted?\n• Delivery time?\n• Refund policy?\n• Account issues?\n\nWhat would you like to know?`
            contextUpdate = { currentTopic: 'faq', lastAction: 'faq' }
            break

          case "live_chat":
            message = `💬 Live Chat\n\nOur live chat is available 24/7!\n\n• Instant responses\n• Real-time assistance\n• File sharing\n• Screen sharing\n• Multi-language support\n\nWould you like to start a live chat?`
            contextUpdate = { currentTopic: 'live_chat', lastAction: 'live_chat' }
            break

          case "email_support":
            message = `📧 Email Support\n\nYou can email us at:\n\n• General: support@mkcart.com\n• Orders: orders@mkcart.com\n• Technical: tech@mkcart.com\n• Billing: billing@mkcart.com\n\nResponse time: Within 2 hours\n\nWhat would you like to email about?`
            contextUpdate = { currentTopic: 'email_support', lastAction: 'email_support' }
            break

          case "technical_help":
            message = `🔧 Technical Help\n\nI can help with technical issues:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nWhat technical issue are you experiencing?`
            contextUpdate = { currentTopic: 'technical_help', lastAction: 'technical_help', pendingAction: { type: 'technical_help' } }
            break

          case "view_products":
            message = `📦 Navigate to Products Page\n\nI'm taking you to the products page where you can:\n• Browse all products\n• Filter by category\n• Sort by price, rating, popularity\n• Search for specific items\n• Add items to cart or wishlist\n• View product details\n\nNavigating now...`
           
            productsActions()

            contextUpdate = { currentTopic: 'view_products', lastAction: 'view_products' }
            break

          default:
            message = `I understand you want to ${action}. Let me help you with that!\n\nWhat specific information or action do you need?`
            contextUpdate = { currentTopic: action, lastAction: action }
        }
        actionTaken = true
      }

      if (actionTaken) {
        
        const aiMessage = {
          id: Date.now() + 1,
          type: "ai",
          message: message,
          timestamp: new Date(),
        }

        setMessages(prev => [...prev, aiMessage])
        setConversationContext(prev => ({ ...prev, ...contextUpdate }))

        if (voiceEnabled) {
          speakMessage(message)
        }

        setTimeout(() => {
          scrollToBottom()
        }, 200)
      }
    } catch (error) {
      
      const errorMessage = {
        id: Date.now() + 1,
        type: "ai",
        message: "Sorry, I encountered an error. Please try again or contact support if the problem persists.",
        timestamp: new Date(),
      }
      setMessages(prev => [...prev, errorMessage])

      setTimeout(() => {
        scrollToBottom()
      }, 200)
    }
  }

  const handleSuggestionClick = (suggestion) => {
    handleSendMessage(suggestion)
  }

  const handleQuickReply = (reply) => {
    handleSendMessage(reply)
  }

  const copyMessage = (message) => {
    navigator.clipboard.writeText(message)
    
  }

  const shareMessage = (message) => {
    if (navigator.share) {
      navigator.share({
        title: "MKCart AI Assistant",
        text: message,
      })
    }
  }

  const rateMessage = (messageId, rating) => {
    setMessages((prev) => prev.map((msg) => (msg.id === messageId ? { ...msg, rating: rating } : msg)))
  }

  const handleFileUpload = (event) => {
    const file = event.target.files[0]
    if (file) {
      const fileMessage = {
        id: Date.now(),
        type: "user",
        message: `Uploaded file: ${file.name}`,
        timestamp: new Date(),
        file: file,
        fileType: file.type,
      }
      setMessages((prev) => [...prev, fileMessage])

      setTimeout(() => {
        const aiResponse = {
          id: Date.now() + 1,
          type: "ai",
          message: "I've received your file. Let me analyze it and provide you with relevant information.",
          timestamp: new Date(),
        }
        setMessages((prev) => [...prev, aiResponse])
      }, 1000)
    }
  }

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && !e.shiftKey) {
      e.preventDefault()
      handleSendMessage()
    }
  }

  const openChat = () => {
    setIsOpen(true)
    setIsFullScreen(true) 
    setShowTooltip(false) 
  }

  const closeChat = () => {
    setIsOpen(false)
    setIsFullScreen(true) 
  }

  const clearChat = () => {
    setMessages([
      {
        id: Date.now(),
        type: "ai",
        message: "Chat cleared! How can I help you today?",
        timestamp: new Date(),
      },
    ])
    setConversationContext({
      currentTopic: null,
      lastAction: null,
      userPreferences: {},
      searchHistory: [],
      currentFilters: {},
      pendingAction: null,
      conversationFlow: []
    })
  }

  useEffect(() => {
    scrollToBottom()
  }, [messages])

  const handleMouseEnter = () => {
    setShowTooltip(true)
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
  }

  const handleMouseLeave = () => {
    if (tooltipTimeoutRef.current) {
      clearTimeout(tooltipTimeoutRef.current)
    }
    tooltipTimeoutRef.current = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      setShowTooltip(false)
    }, 3000)

    return () => {
      clearTimeout(timer)
      if (tooltipTimeoutRef.current) {
        clearTimeout(tooltipTimeoutRef.current)
      }
    }
  }, [])

  const advancedSearch = async (filters) => {
    try {
      const searchParams = new URLSearchParams({
        keyword: filters.keyword || '',
        category: filters.category || '',
        minPrice: filters.minPrice || '',
        maxPrice: filters.maxPrice || '',
        brand: filters.brand || '',
        rating: filters.rating || '',
        availability: filters.availability || ''
      })

      const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)
      const data = await response.json()

      if (data.success) {
        setCurrentSearchResults(data.products)
        setSearchHistory(prev => [...prev, { query: filters.keyword, results: data.products.length, timestamp: new Date() }])
        return data.products
      }
      return []
    } catch (error) {
      
      return []
    }
  }

  const navigateToPage = (path, message) => {
    window.location.href = path
    return {
      success: true,
      message: message
    }
  }

  const cartActions = () => navigateToPage('/cart', "Navigating to your cart page where you can manage your items.")
  const wishlistActions = () => navigateToPage('/wishlist', "Navigating to your wishlist page where you can manage your saved items.")
  const orderActions = () => navigateToPage('/orders', "Navigating to your orders page where you can manage your orders.")
  const productsActions = () => navigateToPage('/productlist', "Navigating to the products page where you can browse all products.")

  const fetchOrderData = async (orderId) => {
    try {
      const orderResponse = await fetch(`${getFullApiUrl()}/user/orders/${orderId}`)
      const orderData = await orderResponse.json()

      let order
      if (orderData.success && orderData.order) {
        order = orderData.order
      } else {
        order = ordersData?.find(order => order._id === orderId || order._id.includes(orderId))
      }
      return order
    } catch (error) {
     
      return null
    }
  }

  const getOrderDetails = async (orderId) => {
    const order = await fetchOrderData(orderId)
    if (order) {
      return {
        _id: order._id,
        orderId: order.orderId || order._id,
        status: order.status || 'Processing',
        amount: order.amount || 0,
        items: order.orderItems || [],
        paymentMethod: order.paymentMethod || 'Not specified',
        transactionId: order.transactionId || '',
        orderDate: order.createdAt || new Date(),
        estimatedDelivery: order.estimatedDelivery || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString(),
        deliveryAddress: order.deliveryAddress || 'User Address',
        trackingNumber: order.trackingNumber || '',
        lastUpdated: new Date().toLocaleDateString()
      }
    }
    return null
  }

  const getOrderStatus = async (orderId) => {
    const order = await fetchOrderData(orderId)
    if (order) {
      const status = order.status || 'Processing'
      const statusDetails = {
        'Confirmed': 'Order confirmed and being prepared',
        'Processing': 'Order is being processed',
        'Shipped': 'Order has been shipped',
        'In Transit': 'Order is in transit',
        'Delivered': 'Order has been delivered',
        'Cancelled': 'Order has been cancelled',
        'Returned': 'Order has been returned'
      }

      return {
        orderId: order.orderId || order._id,
        status: status,
        statusDescription: statusDetails[status] || 'Order status unknown',
        lastUpdated: new Date().toLocaleDateString(),
        estimatedDelivery: order.estimatedDelivery || new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString(),
        trackingNumber: order.trackingNumber || '',
        deliveryAddress: order.deliveryAddress || 'User Address',
        amount: order.amount || 0,
        paymentMethod: order.paymentMethod || 'Not specified',
        transactionId: order.transactionId || '',
        canCancel: ['Confirmed', 'Processing'].includes(status),
        canReturn: status === 'Delivered',
        canTrack: ['Shipped', 'In Transit'].includes(status)
      }
    }
    return null
  }

  const processPayment = async (amount, method, orderItems = []) => {
    try {
      
      await new Promise(resolve => setTimeout(resolve, 2000))

      const paymentResult = {
        success: Math.random() > 0.1, 
        transactionId: `TXN${Date.now()}`,
        amount: amount,
        method: method,
        timestamp: new Date(),
        orderId: `ORD${Date.now()}`,
        status: 'Processing'
      }

      if (paymentResult.success) {
        
        const orderData = {
          orderItems: orderItems,
          amount: amount,
          paymentMethod: method,
          status: 'Confirmed',
          transactionId: paymentResult.transactionId,
          orderId: paymentResult.orderId,
          deliveryAddress: 'User Address', 
          estimatedDelivery: new Date(Date.now() + 7 * 24 * 60 * 60 * 1000).toLocaleDateString()
        }

        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          
          setCurrentCartItems([])
        }
      }

      return paymentResult
    } catch (error) {
      
      return { success: false, error: 'Payment failed' }
    }
  }

  const getPersonalizedRecommendations = () => {
    if (!productsData?.products) return []

    const cartItems = getCartSummary().items
    const wishlistItems = getWishlistSummary().items
    const userItems = [...cartItems, ...wishlistItems]
    const userCategories = [...new Set(userItems.map(item => item.category).filter(Boolean))]
    const userBrands = [...new Set(userItems.map(item => item.brand).filter(Boolean))]

    return [...productsData.products]
      .filter(product =>
        userCategories.includes(product.category) ||
        userBrands.includes(product.brand)
      )
      .sort((a, b) => (b.rating || 0) - (a.rating || 0))
      .slice(0, 8)
  }

const getTrendingProducts = async () => {
  try {
    
    const searchParams = new URLSearchParams({
      keyword: '', 
      rating: '4', 
      availability: 'in stock' 
    })

    const response = await fetch(`${getFullApiUrl()}/products?${searchParams}`)

    if (!response.ok) {
      throw new Error(`API request failed: ${response.status}`)
    }

    const data = await response.json()

    if (data.success && data.products && Array.isArray(data.products)) {
      
      return data.products
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }

    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    if (availableProducts && Array.isArray(availableProducts)) {
      return [...availableProducts]
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }

    return []
  } catch (error) {

    const availableProducts = productsData?.products || fallbackProductsData?.products || []
    if (availableProducts && Array.isArray(availableProducts)) {
      return [...availableProducts]
        .sort((a, b) => (b.rating || b.ratings || 0) - (a.rating || a.ratings || 0))
        .slice(0, 5)
    }
    return []
  }
}

  const getCategoryProducts = async (category) => {
    try {
      
      const response = await fetch(`${getFullApiUrl()}/products?category=${encodeURIComponent(category)}`)
      const data = await response.json()

      if (data.success && data.products) {
        
        let categoryProducts
        if (category.toLowerCase() === 'men') {
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          categoryProducts = data.products.filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
        return categoryProducts
      }

      if (productsData?.products) {
        
        if (category.toLowerCase() === 'men') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
      }

      return []
    } catch (error) {

      if (productsData?.products) {
        
        if (category.toLowerCase() === 'men') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'men'
          )
        } else if (category.toLowerCase() === 'women') {
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase() === 'women'
          )
        } else {
          
          return (productsData?.products || []).filter(product =>
            product.category?.toLowerCase().includes(category.toLowerCase())
          )
        }
      }
      return []
    }
  }

  const getAvailableCategories = async () => {
    try {
      
      const response = await fetch(`${getFullApiUrl()}/products`)
      const data = await response.json()

      if (data.success && data.products) {
        
        const categories = [...new Set(data.products.map(product => product.category).filter(Boolean))]
        return categories.sort()
      }

      return [
        'Mobile Phones',
        'Accessories',
        'Laptops',
        'Headphones',
        'Shoes',
        'Electronics',
        'Men',
        'Women',
        'Toys',
        'Musical Instruments'
      ]
    } catch (error) {
      
      return [
        'Mobile Phones',
        'Accessories',
        'Laptops',
        'Headphones',
        'Shoes',
        'Electronics',
        'Men',
        'Women',
        'Toys',
        'Musical Instruments'
      ]
    }
  }

  const getDealsAndOffers = () => {
    if (!productsData?.products) return []

    return [...productsData.products]
      .filter(product => product.discount > 0)
      .sort((a, b) => (b.discount || 0) - (a.discount || 0))
      .slice(0, 5)
  }

  const getUserInsights = () => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const orderSummary = getOrderSummary()

    const favoriteCategory = cartSummary.items.length > 0
      ? cartSummary.items.reduce((acc, item) => {
        acc[item.category] = (acc[item.category] || 0) + 1
        return acc
      }, {})
      : {}

    const topCategory = Object.entries(favoriteCategory)
      .sort(([, a], [, b]) => b - a)[0]?.[0] || 'No preference'

    return {
      totalSpent: orderSummary.items.reduce((sum, order) => sum + (order.amount || 0), 0),
      averageOrderValue: orderSummary.count > 0 ? orderSummary.items.reduce((sum, order) => sum + (order.amount || 0), 0) / orderSummary.count : 0,
      favoriteCategory: topCategory,
      cartTotal: cartSummary.total,
      wishlistCount: wishlistSummary.count,
      orderCount: orderSummary.count
    }
  }

  const trackPriceChanges = (productId) => {
    const productsArray = productsData?.products || []
  const product = productsArray.find(p => p._id === productId)
    const wishlistItem = getWishlistSummary().items.find(w => w.productId === productId)

    if (product && wishlistItem) {
      const priceChange = product.price - wishlistItem.price
      const percentageChange = (priceChange / wishlistItem.price) * 100

      return {
        productName: product.name,
        oldPrice: wishlistItem.price,
        newPrice: product.price,
        priceChange,
        percentageChange,
        isDecrease: priceChange < 0
      }
    }
    return null
  }

  const checkInventory = async (productId) => {
    try {
      
      const productResponse = await fetch(`${getFullApiUrl()}/product/${productId}`)
      const productData = await productResponse.json()

      let product
      if (productData.success && productData.product) {
        product = productData.product
      } else {
        
        product = productsData?.products?.find(p => p._id === productId)
      }

      if (product) {
        return {
          productId: product._id,
          name: product.name,
          stock: product.stock || 0,
          available: product.stock > 0,
          seller: product.seller || '',
          category: product.category || '',
          price: product.price || 0,
          lastUpdated: new Date().toLocaleDateString(),
          status: product.stock > 0 ? 'In Stock' : 'Out of Stock',
          lowStock: product.stock > 0 && product.stock <= 5 ? 'Low Stock Alert' : null,
          availability: (product.stock || 0) > 10 ? 'In Stock' : (product.stock || 0) > 0 ? 'Low Stock' : 'Out of Stock'
        }
      }
      return null
    } catch (error) {
      
      return null
    }
  }

  const calculateCartAmount = (items) => {
    return items.reduce((sum, item) => {
      const quantity = item.quantity || item.qty || 1
      const price = item.price || 0
      return sum + (price * quantity)
    }, 0)
  }

  const handlePendingAction = async (action) => {
    switch (action.type) {
      case 'add_to_cart':
        
        let product = currentSearchResults.find(p => p.name.toLowerCase() === action.productName.toLowerCase())

        if (!product) {
          product = currentSearchResults.find(p => p.name.toLowerCase().includes(action.productName.toLowerCase()))
        }

        if (!product) {
          product = currentSearchResults.find(p => action.productName.toLowerCase().includes(p.name.toLowerCase()))
        }

        if (product) {
          return `🛒 To add ${action.quantity || 1} "${product.name}" to your cart, please navigate to the product page and use the "Add to Cart" button.\n\nPrice: ₹${product.price}\n\nI can help you:\n• Navigate to cart page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}". Would you like me to search for similar products?`

      case 'remove_from_cart':
        const removeCartItems = getCartSummary().items
        let cartItem = removeCartItems.find(item => item.name.toLowerCase() === action.productName.toLowerCase())

        if (!cartItem) {
          cartItem = removeCartItems.find(item => item.name.toLowerCase().includes(action.productName.toLowerCase()))
        }

        if (!cartItem) {
          cartItem = removeCartItems.find(item => action.productName.toLowerCase().includes(item.name.toLowerCase()))
        }

        if (cartItem) {
          return `🛒 To remove "${cartItem.name}" from your cart, please navigate to the cart page where you can manage your items.\n\nI can help you:\n• Navigate to cart page\n• Search for products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}" in your cart. Would you like me to show your current cart items?`

      case 'add_to_wishlist':
        const wishlistProduct = currentSearchResults.find(p => p.name.toLowerCase().includes(action.productName.toLowerCase()))
        if (wishlistProduct) {
          return `💖 To add "${wishlistProduct.name}" to your wishlist, please navigate to the product page and use the "Add to Wishlist" button.\n\nPrice: ₹${wishlistProduct.price}\nCategory: ${wishlistProduct.category}\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}". Would you like me to search for similar products?`

      case 'remove_from_wishlist':
        const wishlistItem = getWishlistSummary().items.find(item => item.name.toLowerCase().includes(action.productName.toLowerCase()))
        if (wishlistItem) {
          return `💖 To remove "${wishlistItem.name}" from your wishlist, please navigate to the wishlist page where you can manage your saved items.\n\nI can help you:\n• Navigate to wishlist page\n• Search for more products\n• Show recommendations`
        }
        return `I couldn't find "${action.productName}" in your wishlist. Would you like me to show your current wishlist items?`

      case 'search_with_filters':
        const results = await advancedSearch(action.filters)
        return `🔍 Search Results with Filters\n\nI found ${results.length} products matching your criteria:\n\n${results.products.slice(0, 5).map(product =>
          `• ${product.name} - ₹${product.price} - ${product.category}\n`
        ).join('')}\n\nWould you like me to:\n• Show more results\n• Apply different filters\n• Add items to cart\n• Get recommendations`

      case 'checkout':
        const cartSummary = getCartSummary()
        if (cartSummary.count > 0) {
          return `🛒 Checkout Summary\n\nTotal Items: ${cartSummary.count}\nTotal Amount: ₹${cartSummary.total}\n\nI can help you:\n• Review your cart\n• Apply discounts\n• Choose payment method\n• Complete purchase\n• Save for later`
        } else {
          return `Your cart is empty. Would you like me to:\n• Show trending products\n• Search for items\n• Show recommendations`
        }

      case 'cancel_order':
        if (action.orderId) {
          
          return `✅ Order #${action.orderId.slice(-6)} has been cancelled successfully!\n\nRefund will be processed within 5-7 business days.\n\nWould you like to:\n• Check other orders\n• Browse products\n• Contact support`
        }
        return `Order cancellation completed. Would you like to:\n• Check your order history\n• Browse products\n• Contact support`

      case 'clear_cart':
        return `🛒 To clear your cart, please navigate to the cart page where you can remove all items.\n\nI can help you:\n• Navigate to cart page\n• Browse products\n• Search for items\n• View recommendations`

      case 'track_order':
        if (action.orderId) {
          const orderDetails = getOrderDetails(action.orderId)
          if (orderDetails) {
            return `📦 Order #${action.orderId.slice(-6)} Details:\n\nStatus: ${orderDetails.status}\nAmount: ₹${orderDetails.amount}\nItems: ${orderDetails.items.length}\n\nWould you like to:\n• Track delivery\n• Cancel order\n• Return items\n• Contact support`
          } else {
            return `❌ Order #${action.orderId.slice(-6)} not found.\n\nWould you like to:\n• Check your order history\n• Contact support\n• Browse products`
          }
        }
        return `Please provide your order number to track it.`

      case 'payment_issue':
        return `⚠️ Payment Issue Support\n\nI can help you resolve payment problems:\n\n• Transaction failed\n• Payment not reflected\n• Refund not received\n• Card declined\n• UPI issues\n• EMI problems\n\nPlease describe your specific issue, and I'll guide you through the resolution process.`

      case 'search_by_price':
        
        const pricePatterns = [
          
          { pattern: /(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:under|below|less than|up to)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:above|over|more than|greater than)\s+(\d+)/i, type: 'above' },
          
          { pattern: /(\d+)\s+to\s+(\d+)/i, type: 'range' },
          
          { pattern: /between\s+(\d+)\s+and\s+(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price range|cost)\s+(\d+)\s*-\s*(\d+)/i, type: 'range' },
          
          { pattern: /(?:budget|price)\s+(?:under|below|less than)\s+(\d+)/i, type: 'under' },
          
          { pattern: /(?:budget|price)\s+(?:above|over|more than)\s+(\d+)/i, type: 'above' }
        ]

        let minPrice = 0
        let maxPrice = 0
        let priceRangeFound = false

        for (const { pattern, type } of pricePatterns) {
          const match = action.userMessage.match(pattern)
          if (match) {
            priceRangeFound = true

            if (type === 'range') {
              minPrice = parseInt(match[1])
              maxPrice = parseInt(match[2])
            } else if (type === 'under') {
              minPrice = 0
              maxPrice = parseInt(match[1])
            } else if (type === 'above') {
              minPrice = parseInt(match[1])
              maxPrice = Infinity
            }
            break
          }
        }

        if (priceRangeFound) {
          const results = await searchProducts('', { minPrice, maxPrice })

          const filteredResults = (results.products || []).filter(product => {
            const price = parseFloat(product.price) || 0
            if (maxPrice === Infinity) {
              return price >= minPrice
            } else {
              return price >= minPrice && price <= maxPrice
            }
          })

          if (filteredResults.length > 0) {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            return `💰 Products in your price range (${rangeText}):\n\n${(Array.isArray(filteredResults) ? filteredResults : (filteredResults?.products || [])).slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nFound ${filteredResults.length} products matching your criteria.\n\nWould you like to:\n• Add any to cart\n• See more products\n• Adjust price range\n• Get recommendations`
          } else {
            const rangeText = maxPrice === Infinity
              ? `₹${minPrice}+`
              : minPrice === 0
                ? `Under ₹${maxPrice}`
                : `₹${minPrice} - ₹${maxPrice}`

            return `💰 No products found in your price range (${rangeText}).\n\nWould you like to:\n• Try a different price range\n• Browse all products\n• Show trending items\n• Get personalized recommendations`
          }
        }

        return `💰 Please specify your price range!\n\nExamples:\n• "Under 1000"\n• "1000-5000"\n• "5000-10000"\n• "Above 10000"\n• "Between 1000 and 2000"\n\nWhat's your budget range?`

      case 'product_availability':
        
        const productName = action.productName || action.userMessage.replace(/(?:check|availability|stock|available|in stock|out of stock)/gi, '').trim()
        if (productName) {
          const results = await searchProducts(productName)
          if (results.products && results.products.length > 0) {
            const product = results[0]
            const availability = await checkInventory(product._id)

            if (availability) {
              return `📦 Stock Availability for "${product.name}":\n\n• Status: ${availability.status}\n• Stock Level: ${availability.stock} units\n• Seller: ${availability.seller}\n• Category: ${availability.category}\n• Price: ₹${availability.price}\n• Last Updated: ${availability.lastUpdated}\n${availability.lowStock ? `• ⚠️ ${availability.lowStock}\n` : ''}\n\nWould you like to:\n• Add to cart\n• Check similar products\n• Get price alerts\n• View full details`
            } else {
              return `❌ Sorry, I couldn't check the availability for "${product.name}".\n\nWould you like to:\n• Search for similar products\n• Browse the category\n• Get recommendations`
            }
          } else {
            return `❌ Product "${productName}" not found.\n\nWould you like to:\n• Search for similar products\n• Browse categories\n• Get recommendations`
          }
        }

        return `📦 Please specify which product you'd like me to check for availability!\n\nExamples:\n• "Check iPhone stock"\n• "Is laptop available"\n• "Shoe availability"\n\nWhat product should I check?`

      case 'search_by_category':
        
        const category = action.userMessage?.trim() || ''
        if (category) {
          const categoryProducts = await getCategoryProducts(category)

          if (categoryProducts.length > 0) {
            return `📦 Great choice! Here are ${categoryProducts.length} products in the ${category} category:\n\n${categoryProducts.slice(0, 5).map(product =>
              `• ${product.name} - ₹${product.price} - ${product.category} - ⭐${product.ratings || 'N/A'} - Stock: ${product.stock}\n`
            ).join('')}\n\nI can help you:\n• Add any to cart\n• See more ${category} products\n• Filter by price range\n• Sort by popularity\n• Get personalized picks\n• Browse other categories`
          } else {
            const availableCategories = await getAvailableCategories()
            const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
            return `📦 No products found in the ${category} category.\n\nAvailable categories:\n${categoryList}\n\nWould you like to:\n• Try a different category\n• Browse all products\n• Show trending items\n• Get recommendations`
          }
        }

        const availableCategories = await getAvailableCategories()
        const categoryList = availableCategories.map(cat => `• ${cat}`).join('\n')
        return `📦 Please specify which category you'd like to browse!\n\nAvailable categories:\n${categoryList}\n\nExamples:\n• "Electronics"\n• "Fashion"\n• "Toys"\n• "Sports"\n\nWhat category interests you?`

      case 'technical_issue':
        return `🔧 Technical Support\n\nI can help you with:\n\n• Website/app problems\n• Login issues\n• Payment errors\n• Order problems\n• Account issues\n• Performance problems\n\nPlease describe your specific technical issue, and I'll guide you through the resolution process.`

      default:
        return "I'm not sure what action to take. Could you please clarify?"
    }
  }

  const [conversationMemory, setConversationMemory] = useState([])
  const [aiPersonality, setAiPersonality] = useState({
    name: 'MKCart Assistant',
    expertise: ['e-commerce', 'shopping', 'product recommendations', 'customer service'],
    tone: 'helpful and knowledgeable',
    capabilities: ['search', 'recommendations', 'order management', 'payment assistance']
  })

  const analyzeUserIntent = (message) => {
    const lowerMessage = message.toLowerCase()

    const intents = {
      search: /search|find|look for|browse|explore|discover/i,
      purchase: /buy|purchase|order|checkout|pay|add to cart/i,
      information: /what|how|when|where|why|tell me|explain|describe/i,
      comparison: /compare|vs|versus|difference|better|best/i,
      recommendation: /recommend|suggest|advise|what should|help me choose/i,
      complaint: /problem|issue|error|wrong|broken|not working/i,
      gratitude: /thank|thanks|appreciate|grateful/i,
      greeting: /hello|hi|hey|good morning|good afternoon|good evening/i,
      farewell: /bye|goodbye|see you|farewell/i,
      urgency: /urgent|asap|quickly|fast|immediately/i
    }

    for (const [intent, pattern] of Object.entries(intents)) {
      if (pattern.test(lowerMessage)) {
        return intent
      }
    }

    return 'general'
  }

  const analyzeSentiment = (message) => {
    const lowerMessage = message.toLowerCase()

    const positiveWords = ['good', 'great', 'excellent', 'amazing', 'wonderful', 'perfect', 'love', 'like', 'happy', 'satisfied']
    const negativeWords = ['bad', 'terrible', 'awful', 'hate', 'dislike', 'angry', 'frustrated', 'disappointed', 'upset']

    let positiveCount = 0
    let negativeCount = 0

    positiveWords.forEach(word => {
      if (lowerMessage.includes(word)) positiveCount++
    })

    negativeWords.forEach(word => {
      if (lowerMessage.includes(word)) negativeCount++
    })

    if (positiveCount > negativeCount) return 'positive'
    if (negativeCount > positiveCount) return 'negative'
    return 'neutral'
  }

  const extractEntities = (message) => {
    const entities = {
      products: [],
      categories: [],
      prices: [],
      quantities: [],
      brands: [],
      actions: []
    }

    const productPatterns = [
      /iPhone|iPad|MacBook|Samsung|Nike|Adidas|Sony|Dell|HP|Lenovo/gi,
      /laptop|phone|shoes|shirt|pants|headphones|camera|watch/gi
    ]

    productPatterns.forEach(pattern => {
      const matches = message.match(pattern)
      if (matches) {
        entities.products.push(...matches)
      }
    })

    const categoryPatterns = [
      /electronics|fashion|sports|books|beauty|home|automotive|toys/gi
    ]

    categoryPatterns.forEach(pattern => {
      const matches = message.match(pattern)
      if (matches) {
        entities.categories.push(...matches)
      }
    })

    const priceMatches = message.match(/₹?\d+(?:,\d+)*(?:\.\d{2})?/g)
    if (priceMatches) {
      entities.prices.push(...priceMatches)
    }

    const quantityMatches = message.match(/\d+\s*(?:piece|item|unit|quantity|qty)/gi)
    if (quantityMatches) {
      entities.quantities.push(...quantityMatches)
    }

    return entities
  }

  const responseLibraries = {
    greetings: {
      morning: [
        "Good morning! ☀️ I'm your MKCart AI assistant, ready to help you with your shopping needs. How can I assist you today?",
        "Rise and shine! 🌅 Welcome to MKCart. I'm here to make your shopping experience delightful. What can I help you find?",
        "Good morning! 🌞 I hope you're having a wonderful start to your day. I'm ready to help you discover amazing products.",
        "Morning! ☀️ Your personal shopping assistant is here and ready to serve. What's on your shopping list today?"
      ],
      afternoon: [
        "Good afternoon! 🌤️ Welcome to MKCart. I'm your AI shopping companion, ready to help you find exactly what you need.",
        "Afternoon! 🌅 I hope your day is going great. I'm here to assist you with all your shopping questions and needs.",
        "Good afternoon! 🌤️ Your MKCart assistant is ready to help you discover amazing products and deals.",
        "Hello there! 🌅 I'm your shopping buddy for the afternoon. What can I help you find today?"
      ],
      evening: [
        "Good evening! 🌙 Welcome to MKCart. I'm here to help you with your evening shopping needs.",
        "Evening! 🌆 I hope you've had a great day. I'm ready to assist you with finding the perfect products.",
        "Good evening! 🌙 Your MKCart assistant is here to help you wind down with some great shopping.",
        "Hello! 🌆 Evening shopping is my specialty. What can I help you discover today?"
      ],
      general: [
        "Hello! 👋 I'm your MKCart AI assistant, your personal shopping companion. How can I help you today?",
        "Hi there! 🛍️ Welcome to MKCart. I'm here to make your shopping experience amazing. What can I assist you with?",
        "Greetings! 🎉 I'm your AI shopping assistant, ready to help you find the perfect products. What's on your mind?",
        "Hey! 👋 Your MKCart assistant is here and ready to help. What would you like to explore today?"
      ]
    },

    gratitude: {
      positive: [
        "You're absolutely welcome! 😊 It's my pleasure to help you have the best shopping experience possible.",
        "Thank you for choosing MKCart! 🙏 I'm here whenever you need assistance with your shopping journey.",
        "You're very welcome! 💫 I love helping customers find exactly what they're looking for.",
        "It's my pleasure! 🌟 I'm committed to making your shopping experience smooth and enjoyable.",
        "Anytime! 😄 I'm your shopping assistant, and I'm here to help you succeed."
      ],
      neutral: [
        "You're welcome! I'm here to help with all your shopping needs.",
        "No problem at all! Let me know if you need anything else.",
        "Glad I could help! Feel free to ask if you have more questions.",
        "You're welcome! I'm always here when you need assistance."
      ]
    },

    farewell: [
      "Goodbye! 👋 Thank you for shopping with MKCart. Have a wonderful day!",
      "See you later! 🛍️ I'll be here when you return. Happy shopping!",
      "Take care! 😊 I hope you found everything you were looking for.",
      "Farewell! 🌟 Thank you for choosing MKCart. Come back anytime!",
      "Bye for now! 👋 I'm always here to help with your next shopping adventure."
    ],

    confusion: [
      "I'm not quite sure I understood that. Could you please rephrase or tell me more specifically what you're looking for?",
      "Let me make sure I understand correctly. Could you clarify what you'd like help with?",
      "I want to help you best, but I need a bit more clarity. What exactly are you looking for?",
      "I'm here to help, but I need to understand better. Could you explain what you need?"
    ],

    recommendations: {
      general: [
        "Based on what I know about your preferences, here are some products you might love:",
        "I think you'll really enjoy these recommendations I've picked just for you:",
        "Here are some amazing products that match your style and preferences:",
        "I've curated these recommendations especially for you:"
      ],
      trending: [
        "These are the hottest products everyone's talking about right now:",
        "Here are the trending items that are flying off our virtual shelves:",
        "These products are trending and getting amazing reviews:",
        "Check out what's popular and in-demand right now:"
      ],
      personalized: [
        "Based on your shopping history and preferences, I think you'll love:",
        "I've analyzed your style and here are some perfect matches:",
        "These recommendations are tailored specifically to your taste:",
        "Here are some products that align perfectly with your preferences:"
      ]
    },

    search: {
      product: [
        "I'll help you find the perfect {product}. Let me search our extensive collection for you.",
        "Searching for {product}... I'll show you the best options available.",
        "Let me find the best {product} options for you from our curated selection.",
        "I'm on it! Searching for {product} across all our categories."
      ],
      category: [
        "Great choice! Let me show you the best {category} products we have.",
        "I'll browse through our {category} collection to find you the perfect items.",
        "Let me explore our {category} section for you.",
        "I'm searching our {category} inventory for the best options."
      ]
    },

    help: {
      general: [
        "I'm here to help! I can assist you with searching products, managing your cart, tracking orders, and much more.",
        "I can help you find products, compare prices, track orders, manage your wishlist, and answer any shopping questions.",
        "I'm your shopping assistant! I can search, recommend, help with orders, and make your shopping experience better.",
        "I'm here to make your shopping easier! I can search, compare, track, and help with any shopping needs."
      ],
      specific: [
        "I can help you with that! Just tell me more about what you're looking for.",
        "Absolutely! I'm here to assist you with that. What specific details can you provide?",
        "I'd love to help! Let me know more about what you need assistance with.",
        "I'm ready to help! Please share more details so I can assist you better."
      ]
    },

    emotions: {
      excited: [
        "That's fantastic! 🎉 I'm excited to help you with that!",
        "Wonderful! ✨ I can't wait to assist you with this!",
        "Amazing! 🌟 Let's make this happen together!",
        "Excellent choice! 🚀 I'm here to help you succeed!"
      ],
      frustrated: [
        "I understand this can be frustrating. Let me help you resolve this quickly.",
        "I'm here to help make this easier for you. Let's work through this together.",
        "I can see this is bothering you. Let me assist you in finding a solution.",
        "Don't worry, I'm here to help you get this sorted out."
      ],
      confused: [
        "No worries! Let me break this down for you in a simpler way.",
        "I understand this might be confusing. Let me explain it clearly.",
        "Let me help you understand this better. I'll guide you through it step by step.",
        "I'm here to clarify things for you. What specific part would you like me to explain?"
      ],
      satisfied: [
        "I'm so glad I could help! 😊 Is there anything else you'd like assistance with?",
        "Perfect! I'm happy we could resolve this together. What's next?",
        "Excellent! I'm here whenever you need more help.",
        "Great! I'm always ready to assist you with your next shopping adventure."
      ]
    },

    urgency: {
      high: [
        "I understand this is urgent! Let me help you quickly.",
        "I'll prioritize this for you right away.",
        "Let me get this sorted out immediately for you.",
        "I'm on it! This will be handled as a priority."
      ],
      medium: [
        "I'll help you with this promptly.",
        "Let me assist you with this right away.",
        "I'll get this done for you quickly.",
        "I'm here to help you resolve this efficiently."
      ],
      low: [
        "I'll help you with this at your convenience.",
        "Take your time, I'm here to assist you.",
        "I'll guide you through this step by step.",
        "I'm here whenever you're ready to proceed."
      ]
    },

    personality: {
      formal: [
        "I understand your request. Allow me to assist you with that matter.",
        "I appreciate your inquiry. Let me provide you with the necessary information.",
        "Thank you for your question. I'll be happy to help you with this.",
        "I acknowledge your request. Let me address this for you."
      ],
      casual: [
        "Hey! I got you covered on that!",
        "No problem at all! Let me help you out.",
        "Sure thing! I'm here to make this easy for you.",
        "Absolutely! Let's get this sorted together."
      ],
      friendly: [
        "Of course! I'd love to help you with that! 😊",
        "You bet! I'm here to make your day easier!",
        "Absolutely! Let's make this happen together!",
        "Sure thing! I'm excited to help you out!"
      ]
    },

    context: {
      firstTime: [
        "Welcome to MKCart! I'm here to make your first shopping experience amazing!",
        "First time here? Let me show you around and help you get started!",
        "Welcome! I'm your personal shopping assistant. Let me help you discover our amazing products!",
        "New to MKCart? I'm here to guide you through everything we have to offer!"
      ],
      returning: [
        "Welcome back! I'm glad to see you again!",
        "Great to have you back! How can I help you today?",
        "Welcome back! I'm here to continue helping you with your shopping needs!",
        "It's wonderful to see you again! What can I assist you with today?"
      ],
      frequent: [
        "Welcome back, valued customer! I'm here to help you with your shopping!",
        "Great to see you again! I'm ready to assist you with your shopping needs!",
        "Welcome back! I'm here to make your shopping experience even better!",
        "It's always a pleasure to help you! What can I do for you today?"
      ]
    },

    payment: {
      methods: [
        "We accept multiple payment methods for your convenience:\n\n💳 Credit/Debit Cards (Visa, MasterCard, American Express)\n📱 UPI (Google Pay, PhonePe, Paytm)\n🏦 Net Banking (All major banks)\n📲 Digital Wallets (Paytm, Amazon Pay)\n💳 EMI Options (3, 6, 9, 12 months)\n💰 Cash on Delivery\n\nAll payments are secured with bank-level encryption!",
        "Here are our secure payment options:\n\n💳 Cards: Visa, MasterCard, Amex\n📱 UPI: Instant transfers\n🏦 Net Banking: Direct bank transfers\n📲 Wallets: Paytm, Amazon Pay, Google Pay\n💳 EMI: No-cost EMI available\n💰 COD: Pay when you receive\n\nYour payment security is our top priority!",
        "Choose from our wide range of payment methods:\n\n💳 Credit/Debit Cards\n📱 UPI Payments\n🏦 Internet Banking\n📲 Mobile Wallets\n💳 Easy EMI Plans\n💰 Cash on Delivery\n\nAll transactions are 100% secure and encrypted!"
      ],
      security: [
        "Your payment security is guaranteed with:\n\n🔒 SSL Encryption (256-bit)\n🛡️ PCI DSS Compliance\n🔐 3D Secure Authentication\n🛡️ Fraud Protection\n🔒 Secure Payment Gateway\n\nWe never store your payment details!",
        "We use industry-leading security measures:\n\n🔒 Bank-level encryption\n🛡️ PCI DSS certified\n🔐 Two-factor authentication\n🛡️ Real-time fraud detection\n🔒 Secure payment processing\n\nYour financial information is completely safe!",
        "Rest assured with our security features:\n\n🔒 Military-grade encryption\n🛡️ Payment card industry standards\n🔐 Secure authentication\n🛡️ Anti-fraud systems\n🔒 Protected transactions\n\nWe prioritize your payment safety!"
      ],
      issues: [
        "I understand payment issues can be frustrating. Let me help you:\n\n🔍 Check payment status\n💳 Verify card details\n📱 Confirm UPI ID\n🏦 Validate bank information\n📞 Contact payment support\n\nWhat specific payment issue are you facing?",
        "Let's resolve your payment problem together:\n\n🔍 Review transaction details\n💳 Check card validity\n📱 Verify UPI credentials\n🏦 Confirm bank details\n📞 Get expert assistance\n\nPlease share more details about the issue.",
        "I'm here to help with your payment concern:\n\n🔍 Investigate the problem\n💳 Validate payment method\n📱 Check UPI status\n🏦 Verify bank information\n📞 Connect with support team\n\nWhat exactly happened with your payment?"
      ],
      emi: [
        "EMI options available for your convenience:\n\n💳 3 months EMI - No extra cost\n💳 6 months EMI - 0% interest\n💳 9 months EMI - Low processing fee\n💳 12 months EMI - Competitive rates\n\nEligible on orders above ₹1,000!",
        "Make your purchase easier with EMI:\n\n💳 3, 6, 9, 12 month plans\n💳 No-cost EMI available\n💳 Instant approval\n💳 All major banks accepted\n💳 No hidden charges\n\nCheck eligibility at checkout!",
        "Flexible EMI plans for you:\n\n💳 Multiple tenure options\n💳 Zero interest on select plans\n💳 Quick approval process\n💳 Wide bank coverage\n💳 Transparent pricing\n\nSplit your payment into easy installments!"
      ]
    },

    product: {
      details: [
        "Here are the complete product details:\n\n📦 Brand: {brand}\n💰 Price: {price}\n⭐ Rating: {rating}/5 ({reviews} reviews)\n📏 Dimensions: {dimension}\n⚖️ Weight: {weight}\n🏭 Material: {material}\n🛡️ Warranty: {warranty}\n\nKey Features:\n{features}\n\nWould you like to know more about any specific aspect?",
        "Product specifications for you:\n\n🏷️ Brand: {brand}\n💵 Price: {price}\n⭐ Customer Rating: {rating}⭐\n📐 Size: {dimension}\n⚖️ Weight: {weight}\n🏭 Build Material: {material}\n🛡️ Warranty Period: {warranty}\n\nHighlighted Features:\n{features}\n\nNeed any clarification on these details?",
        "Complete product information:\n\n🏷️ Manufacturer: {brand}\n💰 Cost: {price}\n⭐ User Rating: {rating}/5\n📏 Measurements: {dimension}\n⚖️ Product Weight: {weight}\n🏭 Construction: {material}\n🛡️ Guarantee: {warranty}\n\nSpecial Features:\n{features}\n\nWhat would you like to know more about?"
      ],
      comparison: [
        "Let me compare these products for you:\n\n📊 Price Comparison:\n• Product A: ₹{priceA}\n• Product B: ₹{priceB}\n\n⭐ Rating Comparison:\n• Product A: {ratingA}⭐\n• Product B: {ratingB}⭐\n\n🔍 Feature Comparison:\n• Product A: {featuresA}\n• Product B: {featuresB}\n\nWhich aspects are most important to you?",
        "Here's a detailed comparison:\n\n💰 Price Analysis:\n• Option 1: ₹{priceA}\n• Option 2: ₹{priceB}\n\n⭐ Customer Ratings:\n• Option 1: {ratingA}⭐\n• Option 2: {ratingB}⭐\n\n✨ Key Differences:\n• Option 1: {featuresA}\n• Option 2: {featuresB}\n\nWhat factors matter most in your decision?",
        "Product comparison breakdown:\n\n💵 Cost Comparison:\n• Item A: ₹{priceA}\n• Item B: ₹{priceB}\n\n⭐ Quality Ratings:\n• Item A: {ratingA}⭐\n• Item B: {ratingB}⭐\n\n🔍 Feature Analysis:\n• Item A: {featuresA}\n• Item B: {featuresB}\n\nWhich product better fits your needs?"
      ],
      availability: [
        "Stock status for this product:\n\n✅ In Stock: {quantity} units available\n🚚 Delivery: {deliveryTime}\n📍 Location: {location}\n🔄 Restock: {restockDate}\n\nWould you like me to check availability in other locations?",
        "Current availability information:\n\n✅ Available: {quantity} pieces in stock\n🚚 Shipping: {deliveryTime}\n📍 Warehouse: {location}\n🔄 Next Stock: {restockDate}\n\nShould I check alternative locations for you?",
        "Product availability details:\n\n✅ Stock: {quantity} units ready\n🚚 Delivery Time: {deliveryTime}\n📍 Storage: {location}\n🔄 Replenishment: {restockDate}\n\nWould you like me to search nearby warehouses?"
      ]
    },

    recommendations: {
      personalized: [
        "Based on your preferences, here are personalized recommendations:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nThese match your style and budget perfectly!",
        "Curated just for you:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nSelected based on your shopping history!",
        "Personal picks for you:\n\n⭐ {product1.name} - {product1.price} ({product1.rating}⭐)\n🔥 {product2.name} - {product2.price} ({product2.rating}⭐)\n💎 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nTailored to your taste and preferences!"
      ],
      trending: [
        "Hot trending products right now:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nEveryone's talking about these!",
        "Currently trending items:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nFlying off our shelves!",
        "Trending products this week:\n\n🔥 {product1.name} - {product1.price} ({product1.rating}⭐)\n⚡ {product2.name} - {product2.price} ({product2.rating}⭐)\n🚀 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nHighly popular choices!"
      ],
      category: [
        "Best picks in {category}:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nTop-rated in this category!",
        "Leading {category} products:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nCustomer favorites!",
        "Premium {category} selection:\n\n🏆 {product1.name} - {product1.price} ({product1.rating}⭐)\n🥈 {product2.name} - {product2.price} ({product2.rating}⭐)\n🥉 {product3.name} - {product3.price} ({product3.rating}⭐)\n\nHighest quality options!"
      ]
    },

    search: {
      results: [
        "🔍 Search Results for '{query}':\n\nFound {count} products matching your search\n\n{products}\n\n💡 Tips:\n• Use filters to narrow results\n• Sort by price, rating, or popularity\n• Save items to wishlist for later\n• Compare similar products\n\nWould you like to refine your search?",
        "📋 Search Results for '{query}':\n\n{count} products found\n\n{products}\n\n✨ Suggestions:\n• Apply price range filters\n• Sort by customer ratings\n• Check product reviews\n• Add favorites to wishlist\n\nNeed help finding something specific?",
        "🎯 Search Results for '{query}':\n\n{count} matching products\n\n{products}\n\n🔧 Options:\n• Filter by category or brand\n• Sort by newest arrivals\n• View detailed specifications\n• Read customer reviews\n\nLooking for something else?"
      ],
      noResults: [
        "😔 No products found for '{query}'\n\n💡 Suggestions:\n• Check spelling and try again\n• Try different keywords\n• Browse similar categories\n• Use broader search terms\n• Check our trending products\n\nWould you like me to suggest alternatives?",
        "🔍 No results for '{query}'\n\n✨ Try these alternatives:\n• Use simpler search terms\n• Check for typos\n• Browse related categories\n• Look at popular items\n• Try synonyms\n\nLet me help you find what you're looking for!",
        "📭 No products match '{query}'\n\n🎯 Suggestions:\n• Double-check your spelling\n• Try related keywords\n• Explore similar categories\n• Check trending products\n• Use category filters\n\nI can help you discover great alternatives!"
      ],
      suggestions: [
        "💡 Search Suggestions:\n\n• Try: '{suggestion1}', '{suggestion2}', '{suggestion3}'\n• Popular searches: '{popular1}', '{popular2}'\n• Related categories: '{category1}', '{category2}'\n\nWould you like to try one of these searches?",
        "🔍 Did you mean:\n\n• '{suggestion1}' (most popular)\n• '{suggestion2}' (trending)\n• '{suggestion3}' (similar)\n• Popular: '{popular1}', '{popular2}'\n• Categories: '{category1}', '{category2}'\n\nWhich would you like to explore?",
        "✨ Search Alternatives:\n\n• Similar terms: '{suggestion1}', '{suggestion2}'\n• Trending searches: '{popular1}', '{popular2}'\n• Related categories: '{category1}', '{category2}'\n• Popular products in this area\n\nLet me know which interests you!"
      ],
      filters: [
        "🔧 Search Filters Available:\n\n💰 Price Range: ₹100 - ₹50,000+\n⭐ Rating: 1-5 stars\n🏷️ Brand: All major brands\n📦 Category: All categories\n🚚 Delivery: Free/Express\n\nApply filters to find exactly what you need!",
        "⚙️ Filter Options:\n\n💰 Price: Set your budget range\n⭐ Rating: Filter by customer ratings\n🏷️ Brand: Choose specific brands\n📦 Category: Select product categories\n🚚 Shipping: Free delivery options\n\nCustomize your search for better results!",
        "🎛️ Search Filters:\n\n💰 Price Range: Customize budget\n⭐ Customer Rating: 1-5 stars\n🏷️ Brand Selection: All available brands\n📦 Category Filter: All product types\n🚚 Delivery Options: Free/Paid shipping\n\nUse filters to narrow down your search!"
      ]
    },

    tracking: {
      found: [
        "📦 Order Tracking Results:\n\nOrder: #{orderNumber}\nStatus: {status}\nEstimated Delivery: {deliveryDate}\nCurrent Location: {location}\n\n📋 Order Details:\n{items}\n\n💰 Total: {total}\n🚚 Shipping: {shipping}\n\nWould you like to track another order?",
        "🚚 Order Status Update:\n\nOrder Number: #{orderNumber}\nCurrent Status: {status}\nExpected Delivery: {deliveryDate}\nLast Update: {location}\n\n📦 Items Ordered:\n{items}\n\n💵 Order Total: {total}\n📮 Shipping Method: {shipping}\n\nNeed help with this order?",
        "📋 Order Information:\n\nOrder ID: #{orderNumber}\nStatus: {status}\nDelivery Date: {deliveryDate}\nCurrent Location: {location}\n\n🛍️ Products:\n{items}\n\n💰 Total Amount: {total}\n🚚 Delivery: {shipping}\n\nAny questions about this order?"
      ],
      notFound: [
        "🔍 Order #{orderNumber} not found\n\nPossible reasons:\n• Order number might be incorrect\n• Order might be from a different account\n• Order might be older than 2 years\n• Check spelling and try again\n\nNeed help finding your order?",
        "📭 Order #{orderNumber} not located\n\n💡 Suggestions:\n• Verify the order number\n• Check if you're logged into the right account\n• Orders older than 2 years may not be available\n• Contact support for assistance\n\nWould you like me to help you search?",
        "❌ Order #{orderNumber} not found\n\n🔍 Troubleshooting:\n• Double-check the order number\n• Ensure you're using the correct account\n• Recent orders are more likely to be found\n• Older orders may have limited information\n\nLet me help you locate your order!"
      ],
      multiple: [
        "📦 Multiple Orders Found:\n\n{orders}\n\n💡 Tips:\n• Click on any order for detailed tracking\n• Orders are sorted by date (newest first)\n• Track multiple orders simultaneously\n• Get delivery notifications\n\nWhich order would you like to track in detail?",
        "📋 Your Recent Orders:\n\n{orders}\n\n✨ Features:\n• Real-time tracking updates\n• Delivery notifications\n• Order history access\n• Return/refund status\n\nSelect an order for detailed information!",
        "🚚 Order Summary:\n\n{orders}\n\n🔧 Options:\n• View detailed tracking\n• Check delivery status\n• Monitor shipping progress\n• Access order history\n\nChoose an order to get more details!"
      ]
    },

    cart: {
      items: [
        "🛒 Your Shopping Cart:\n\n{items}\n\n💰 Subtotal: {subtotal}\n🚚 Shipping: {shipping}\n💳 Tax: {tax}\n💵 Total: {total}\n\n✨ Cart Features:\n• Save for later\n• Update quantities\n• Remove items\n• Apply coupon codes\n• Proceed to checkout\n\nReady to complete your purchase?",
        "📦 Cart Contents:\n\n{items}\n\n💳 Price Breakdown:\n• Subtotal: {subtotal}\n• Shipping: {shipping}\n• Tax: {tax}\n• Total: {total}\n\n🔧 Cart Options:\n• Modify quantities\n• Remove products\n• Save to wishlist\n• Add coupon\n• Checkout now\n\nWhat would you like to do?",
        "🛍️ Your Cart Summary:\n\n{items}\n\n💰 Cost Summary:\n• Items Total: {subtotal}\n• Delivery Fee: {shipping}\n• Taxes: {tax}\n• Grand Total: {total}\n\n⚙️ Available Actions:\n• Edit quantities\n• Delete items\n• Move to wishlist\n• Apply discounts\n• Place order\n\nReady to proceed?"
      ],
      empty: [
        "🛒 Your cart is empty\n\n💡 Suggestions:\n• Browse our trending products\n• Check out personalized recommendations\n• Explore new arrivals\n• View your wishlist items\n• Discover daily deals\n\nLet me help you find something amazing!",
        "📭 Shopping cart is empty\n\n✨ What's new:\n• Latest product arrivals\n• Trending items this week\n• Personalized picks for you\n• Special offers and deals\n• Customer favorites\n\nWould you like to explore our collection?",
        "🛍️ No items in your cart\n\n🎯 Discover:\n• Hot selling products\n• Recommended for you\n• New arrivals\n• Limited time offers\n• Best sellers\n\nReady to start shopping? Let me show you some great options!"
      ],
      recommendations: [
        "💡 Cart Recommendations:\n\nBased on your cart, you might also like:\n\n{recommendations}\n\n🔥 Add these to save more:\n• Bundle deals available\n• Free shipping on orders above ₹999\n• Extra discounts on multiple items\n\nWould you like to add any of these?",
        "✨ Suggested Additions:\n\nPerfect with your current items:\n\n{recommendations}\n\n💎 Benefits:\n• Complete your look\n• Save with bundles\n• Free delivery eligible\n• Extra savings available\n\nInterested in any of these?",
        "🎯 Recommended for You:\n\nGreat additions to your cart:\n\n{recommendations}\n\n🚀 Advantages:\n• Enhance your purchase\n• Bundle savings\n• Free shipping threshold\n• Additional discounts\n\nWant to add any of these items?"
      ]
    },

    wishlist: {
      items: [
        "❤️ Your Wishlist:\n\n{items}\n\n💡 Wishlist Features:\n• Move items to cart\n• Remove from wishlist\n• Share wishlist\n• Get price drop alerts\n• Compare items\n\nWould you like to move any items to your cart?",
        "📋 Wishlist Contents:\n\n{items}\n\n✨ Options Available:\n• Add to cart\n• Remove items\n• Share with friends\n• Price notifications\n• Item comparison\n\nReady to purchase any of these?",
        "💝 Your Saved Items:\n\n{items}\n\n🔧 Wishlist Tools:\n• Purchase items\n• Delete from list\n• Share wishlist\n• Price alerts\n• Compare products\n\nWhich items would you like to buy?"
      ],
      empty: [
        "❤️ Your wishlist is empty\n\n💡 Start building your wishlist:\n• Browse trending products\n• Save items you love\n• Get price drop notifications\n• Share with friends\n• Compare products\n\nLet me show you some amazing products!",
        "📭 No items in wishlist\n\n✨ Benefits of wishlisting:\n• Save items for later\n• Price drop alerts\n• Easy comparison\n• Share with family\n• Quick access\n\nWould you like to explore and save some items?",
        "💝 Wishlist is empty\n\n🎯 Why create a wishlist:\n• Never lose track of items\n• Get notified of sales\n• Compare prices easily\n• Share with loved ones\n• Quick reordering\n\nReady to discover and save some favorites?"
      ],
      priceAlerts: [
        "💰 Price Drop Alert!\n\nThese items in your wishlist have price drops:\n\n{priceDrops}\n\n⚡ Limited time offers\n🔥 Don't miss out on savings\n💳 Secure payment options\n\nWould you like to purchase any of these?",
        "📉 Price Reduced!\n\nGreat news! Prices dropped on:\n\n{priceDrops}\n\n🎯 Special offers available\n🚀 Quick checkout process\n💎 Premium customer service\n\nReady to grab these deals?",
        "💸 Savings Alert!\n\nPrice reductions on your wishlist:\n\n{priceDrops}\n\n🔥 Limited time only\n⚡ Fast delivery available\n💳 Multiple payment options\n\nDon't wait - these deals won't last!"
      ]
    },

    support: {
      general: [
        "I'm here to help with any questions or issues:\n\n📞 Live Chat: Available 24/7\n📧 Email: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Response Time: Within 2 hours\n\nWhat can I assist you with today?",
        "Customer support at your service:\n\n📞 Chat Support: 24/7 available\n📧 Email Support: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Quick Response: Under 2 hours\n\nHow can I help you today?",
        "Need help? I'm here for you:\n\n📞 24/7 Live Chat\n📧 Email: support@mkcart.com\n📱 WhatsApp: +91-98765-43210\n🕒 Fast Response: 2 hours max\n\nWhat's your concern today?"
      ],
      order: [
        "Order support assistance:\n\n📦 Track your order\n🔄 Check order status\n❌ Cancel order\n🔄 Return/Refund\n📞 Order support\n\nPlease provide your order number for quick assistance.",
        "I can help with your order:\n\n📦 Order tracking\n🔄 Status updates\n❌ Order cancellation\n🔄 Returns & refunds\n📞 Direct support\n\nShare your order number for immediate help.",
        "Order-related help available:\n\n📦 Track delivery\n🔄 Check status\n❌ Cancel if needed\n🔄 Return process\n📞 Get support\n\nYour order number will help me assist you faster."
      ],
      technical: [
        "Technical support is here to help:\n\n🔧 Website issues\n📱 App problems\n💳 Payment errors\n🔐 Account issues\n📞 Tech support\n\nDescribe the technical problem you're facing.",
        "Technical assistance available:\n\n🔧 Site problems\n📱 App issues\n💳 Payment troubles\n🔐 Account problems\n📞 Expert help\n\nPlease explain the technical issue you're experiencing.",
        "I can help with technical issues:\n\n🔧 Website problems\n📱 App difficulties\n💳 Payment issues\n🔐 Account troubles\n📞 Technical support\n\nWhat technical problem are you encountering?"
      ],
      refund: [
        "Refund and return assistance:\n\n🔄 Return policy: 30 days\n💰 Refund time: 5-7 days\n📦 Free return shipping\n📞 Refund support\n\nI'll guide you through the return process.",
        "Return and refund help:\n\n🔄 30-day return window\n💰 5-7 day refund time\n📦 No-cost returns\n📞 Refund assistance\n\nLet me help you with the return process.",
        "Refund support available:\n\n🔄 30-day returns\n💰 Quick refunds (5-7 days)\n📦 Free return shipping\n📞 Refund help\n\nI'll assist you with the return and refund process."
      ]
    }
  }

  const getRandomResponse = (library, category = null) => {
    if (category && library[category]) {
      const responses = library[category]
      return responses[Math.floor(Math.random() * responses.length)]
    } else if (Array.isArray(library)) {
      return library[Math.floor(Math.random() * library.length)]
    }
    return "I'm here to help! How can I assist you today?"
  }

  const comprehensiveNLU = (userMessage) => {
    const lowerMessage = userMessage.toLowerCase()
    const analysis = {
      intent: null,
      sentiment: null,
      entities: {},
      emotions: [],
      urgency: 'low',
      personality: 'friendly',
      context: 'general',
      confidence: 0,
      suggestions: [],
      responseType: 'general'
    }

    const intentPatterns = {
      search: {
        patterns: [
          /search|find|look for|where can i get|i need|i want|show me|display|browse/i,
          /buy|purchase|get|acquire|obtain/i,
          /product|item|thing|stuff/i
        ],
        confidence: 0.9
      },
      recommendation: {
        patterns: [
          /recommend|suggest|advise|what should|help me choose|best|top|popular/i,
          /similar|like this|same as|alternative/i
        ],
        confidence: 0.85
      },
      cart: {
        patterns: [
          /cart|basket|add to cart|remove from cart|checkout|buy now/i,
          /quantity|how many|update|change/i
        ],
        confidence: 0.9
      },
      wishlist: {
        patterns: [
          /wishlist|favorites|save|wish|favorite|saved items/i,
          /save for later|remember this/i
        ],
        confidence: 0.85
      },
      order: {
        patterns: [
          /order|track|delivery|shipping|status|tracking|package|parcel/i,
          /when will|where is|arrive|delivered/i
        ],
        confidence: 0.9
      },
      complaint: {
        patterns: [
          /problem|issue|error|wrong|broken|not working|complaint/i,
          /refund|return|cancel|disappointed|angry/i
        ],
        confidence: 0.8
      },
      gratitude: {
        patterns: [
          /thank|thanks|appreciate|grateful|awesome|great job/i
        ],
        confidence: 0.95
      },
      greeting: {
        patterns: [
          /hello|hi|hey|good morning|good afternoon|good evening|greetings/i
        ],
        confidence: 0.95
      },
      farewell: {
        patterns: [
          /bye|goodbye|see you|farewell|take care|later/i
        ],
        confidence: 0.9
      },
      help: {
        patterns: [
          /help|support|assist|how do i|what can you|capabilities/i
        ],
        confidence: 0.85
      }
    }

    let maxConfidence = 0
    for (const [intent, data] of Object.entries(intentPatterns)) {
      const matches = data.patterns.filter(pattern => pattern.test(userMessage))
      if (matches.length > 0) {
        const confidence = data.confidence * (matches.length / data.patterns.length)
        if (confidence > maxConfidence) {
          maxConfidence = confidence
          analysis.intent = intent
        }
      }
    }
    analysis.confidence = maxConfidence

    const sentimentWords = {
      positive: [
        'good', 'great', 'excellent', 'amazing', 'wonderful', 'perfect', 'love', 'like', 'happy', 'satisfied',
        'awesome', 'fantastic', 'brilliant', 'outstanding', 'superb', 'terrific', 'fabulous', 'incredible'
      ],
      negative: [
        'bad', 'terrible', 'awful', 'hate', 'dislike', 'angry', 'frustrated', 'disappointed', 'upset',
        'horrible', 'dreadful', 'miserable', 'annoyed', 'irritated', 'mad', 'furious', 'livid'
      ],
      neutral: [
        'okay', 'fine', 'alright', 'normal', 'usual', 'standard', 'regular', 'typical'
      ]
    }

    let positiveScore = 0
    let negativeScore = 0
    let neutralScore = 0

    Object.entries(sentimentWords).forEach(([sentiment, words]) => {
      words.forEach(word => {
        const regex = new RegExp(`\\b${word}\\b`, 'gi')
        const matches = userMessage.match(regex)
        if (matches) {
          if (sentiment === 'positive') positiveScore += matches.length
          else if (sentiment === 'negative') negativeScore += matches.length
          else neutralScore += matches.length
        }
      })
    })

    if (positiveScore > negativeScore && positiveScore > neutralScore) {
      analysis.sentiment = 'positive'
    } else if (negativeScore > positiveScore && negativeScore > neutralScore) {
      analysis.sentiment = 'negative'
    } else {
      analysis.sentiment = 'neutral'
    }

    const emotionPatterns = {
      excited: [/excited|thrilled|can't wait|eager|enthusiastic/i],
      frustrated: [/frustrated|annoyed|irritated|fed up|tired of/i],
      confused: [/confused|don't understand|unclear|not sure|puzzled/i],
      satisfied: [/satisfied|happy|pleased|content|fulfilled/i],
      worried: [/worried|concerned|anxious|nervous|stressed/i]
    }

    Object.entries(emotionPatterns).forEach(([emotion, patterns]) => {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.emotions.push(emotion)
      }
    })

    const urgencyPatterns = {
      high: [/urgent|asap|immediately|right now|quickly|emergency/i],
      medium: [/soon|shortly|promptly|efficiently/i],
      low: [/whenever|no rush|take your time|convenient/i]
    }

    for (const [level, patterns] of Object.entries(urgencyPatterns)) {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.urgency = level
        break
      }
    }

    const personalityPatterns = {
      formal: [/please|kindly|would you|could you|may i/i],
      casual: [/hey|yo|what's up|cool|awesome/i],
      friendly: [/thanks|appreciate|love|great|wonderful/i]
    }

    for (const [style, patterns] of Object.entries(personalityPatterns)) {
      if (patterns.some(pattern => pattern.test(userMessage))) {
        analysis.personality = style
        break
      }
    }

    if (conversationMemory.length === 0) {
      analysis.context = 'firstTime'
    } else if (conversationMemory.length > 10) {
      analysis.context = 'frequent'
    } else {
      analysis.context = 'returning'
    }

    analysis.entities = extractEntities(userMessage)

    if (analysis.intent === 'search' && analysis.entities.products.length > 0) {
      analysis.suggestions.push('Compare similar products', 'Check reviews', 'Find deals')
    } else if (analysis.intent === 'cart') {
      analysis.suggestions.push('View cart', 'Proceed to checkout', 'Add more items')
    } else if (analysis.intent === 'recommendation') {
      analysis.suggestions.push('Personalized picks', 'Trending items', 'Category browse')
    }

    if (analysis.confidence > 0.8) {
      analysis.responseType = 'specific'
    } else if (analysis.confidence > 0.5) {
      analysis.responseType = 'contextual'
    } else {
      analysis.responseType = 'general'
    }

    return analysis
  }

  const generateRandomData = {
    
    products: () => {
      const products = [
        { name: "Wireless Bluetooth Headphones", price: "₹1,299", category: "Electronics", rating: 4.5, reviews: 1247, brand: "Sony", features: ["Noise Cancellation", "40hr Battery", "Quick Charge"] },
        { name: "Premium Cotton T-Shirt", price: "₹599", category: "Fashion", rating: 4.3, reviews: 892, brand: "Nike", features: ["100% Cotton", "Breathable", "Multiple Colors"] },
        { name: "Smart Fitness Watch", price: "₹2,499", category: "Electronics", rating: 4.7, reviews: 2156, brand: "Fitbit", features: ["Heart Rate Monitor", "GPS", "Water Resistant"] },
        { name: "Organic Face Cream", price: "₹899", category: "Beauty", rating: 4.4, reviews: 567, brand: "The Body Shop", features: ["Natural Ingredients", "Anti-aging", "Suitable for all skin types"] },
        { name: "Stainless Steel Water Bottle", price: "₹399", category: "Home", rating: 4.6, reviews: 1234, brand: "Hydro Flask", features: ["24hr Cold", "12hr Hot", "BPA Free"] },
        { name: "Gaming Mouse", price: "₹1,799", category: "Electronics", rating: 4.8, reviews: 1890, brand: "Logitech", features: ["RGB Lighting", "Programmable Buttons", "High DPI"] },
        { name: "Yoga Mat", price: "₹299", category: "Sports", rating: 4.2, reviews: 445, brand: "Lululemon", features: ["Non-slip", "Eco-friendly", "6mm Thick"] },
        { name: "LED Desk Lamp", price: "₹699", category: "Home", rating: 4.5, reviews: 678, brand: "Philips", features: ["Adjustable Brightness", "Color Temperature", "Touch Control"] },
        { name: "Wireless Charger", price: "₹1,199", category: "Electronics", rating: 4.6, reviews: 945, brand: "Samsung", features: ["Fast Charging", "Universal Compatibility", "LED Indicator"] },
        { name: "Running Shoes", price: "₹3,999", category: "Sports", rating: 4.9, reviews: 2341, brand: "Adidas", features: ["Cushioned Sole", "Breathable Mesh", "Lightweight"] }
      ]
      return products[Math.floor(Math.random() * products.length)]
    },

    deals: () => {
      const deals = [
        { type: "Flash Sale", discount: "50% OFF", category: "Electronics", validUntil: "2 hours", code: "FLASH50" },
        { type: "Weekend Special", discount: "30% OFF", category: "Fashion", validUntil: "Sunday", code: "WEEKEND30" },
        { type: "New User Offer", discount: "₹500 OFF", category: "All Products", validUntil: "24 hours", code: "NEW500" },
        { type: "Bundle Deal", discount: "Buy 2 Get 1 Free", category: "Beauty", validUntil: "3 days", code: "BUNDLE3" },
        { type: "Clearance Sale", discount: "Up to 70% OFF", category: "Home", validUntil: "1 week", code: "CLEAR70" },
        { type: "Student Discount", discount: "20% OFF", category: "All Products", validUntil: "Always", code: "STUDENT20" },
        { type: "First Order", discount: "₹200 OFF", category: "All Products", validUntil: "First Purchase", code: "FIRST200" },
        { type: "Loyalty Reward", discount: "15% OFF", category: "All Products", validUntil: "7 days", code: "LOYAL15" }
      ]
      return deals[Math.floor(Math.random() * deals.length)]
    },

    trends: () => {
      const trends = [
        "Sustainable Fashion",
        "Smart Home Devices",
        "Fitness & Wellness",
        "Organic Beauty Products",
        "Gaming Accessories",
        "Kitchen Gadgets",
        "Travel Essentials",
        "Pet Care Products",
        "Work From Home Setup",
        "Outdoor Adventure Gear",
        "Digital Art Supplies",
        "Plant Care Essentials"
      ]
      return trends[Math.floor(Math.random() * trends.length)]
    },

    reviews: () => {
      const reviews = [
        { text: "Amazing quality! Highly recommended.", rating: 5, author: "Priya S.", verified: true },
        { text: "Great value for money. Will buy again!", rating: 4, author: "Rahul M.", verified: true },
        { text: "Fast delivery and excellent product.", rating: 5, author: "Anjali K.", verified: true },
        { text: "Good product but could be better.", rating: 3, author: "Vikram P.", verified: false },
        { text: "Perfect for my needs. Love it!", rating: 5, author: "Sneha R.", verified: true },
        { text: "Exceeded my expectations!", rating: 5, author: "Arjun K.", verified: true },
        { text: "Good quality for the price.", rating: 4, author: "Meera P.", verified: true },
        { text: "Fast shipping and great packaging.", rating: 5, author: "Karan S.", verified: true }
      ]
      return reviews[Math.floor(Math.random() * reviews.length)]
    },

    shipping: () => {
      const options = [
        { method: "Standard Delivery", time: "3-5 business days", cost: "₹99", tracking: true },
        { method: "Express Delivery", time: "1-2 business days", cost: "₹199", tracking: true },
        { method: "Same Day Delivery", time: "Today", cost: "₹299", tracking: true },
        { method: "Free Delivery", time: "5-7 business days", cost: "Free", tracking: true },
        { method: "Premium Delivery", time: "Next Day", cost: "₹399", tracking: true }
      ]
      return options[Math.floor(Math.random() * options.length)]
    },

    payments: () => {
      const methods = [
        { name: "Credit/Debit Card", icon: "💳", security: "SSL Encrypted", processing: "Instant" },
        { name: "UPI", icon: "📱", security: "Bank Level", processing: "Instant" },
        { name: "Net Banking", icon: "🏦", security: "Bank Level", processing: "Instant" },
        { name: "Digital Wallets", icon: "📲", security: "SSL Encrypted", processing: "Instant" },
        { name: "EMI", icon: "💳", security: "SSL Encrypted", processing: "Instant" },
        { name: "Cash on Delivery", icon: "💰", security: "Pay on Delivery", processing: "On Delivery" }
      ]
      return methods[Math.floor(Math.random() * methods.length)]
    },

    categories: () => {
      const categories = [
        { name: "Electronics", icon: "📱", count: "15,000+ products", trending: true },
        { name: "Fashion", icon: "👗", count: "25,000+ products", trending: true },
        { name: "Home & Garden", icon: "🏠", count: "12,000+ products", trending: false },
        { name: "Sports & Fitness", icon: "🏃‍♂️", count: "8,000+ products", trending: true },
        { name: "Beauty & Personal Care", icon: "💄", count: "10,000+ products", trending: true },
        { name: "Books & Media", icon: "📚", count: "20,000+ products", trending: false },
        { name: "Toys & Games", icon: "🎮", count: "6,000+ products", trending: false },
        { name: "Automotive", icon: "🚗", count: "4,000+ products", trending: false }
      ]
      return categories[Math.floor(Math.random() * categories.length)]
    },

    support: () => {
      const topics = [
        { issue: "Order Tracking", priority: "High", response: "I can help you track your order. Please provide your order number." },
        { issue: "Payment Issues", priority: "High", response: "I understand payment problems can be frustrating. Let me help you resolve this." },
        { issue: "Returns & Refunds", priority: "Medium", response: "I'll guide you through our return and refund process." },
        { issue: "Product Quality", priority: "Medium", response: "I'm here to help with any product quality concerns." },
        { issue: "Delivery Problems", priority: "High", response: "I can help you resolve delivery issues quickly." },
        { issue: "Account Issues", priority: "Medium", response: "Let me help you with your account-related questions." }
      ]
      return topics[Math.floor(Math.random() * topics.length)]
    },

    specifications: () => {
      const specs = [
        { dimension: "10 x 5 x 2 cm", weight: "150g", material: "Premium Plastic", warranty: "1 Year" },
        { dimension: "15 x 8 x 3 cm", weight: "250g", material: "Aluminum", warranty: "2 Years" },
        { dimension: "20 x 12 x 4 cm", weight: "400g", material: "Stainless Steel", warranty: "3 Years" },
        { dimension: "8 x 6 x 1.5 cm", weight: "100g", material: "Silicone", warranty: "6 Months" },
        { dimension: "25 x 18 x 5 cm", weight: "600g", material: "Wood", warranty: "1 Year" }
      ]
      return specs[Math.floor(Math.random() * specs.length)]
    }
  }

  const learnFromUserBehavior = (userMessage, intent, sentiment, entities) => {
    
    if (entities.categories.length > 0) {
      setUserPreferences(prev => ({
        ...prev,
        favoriteCategories: [...new Set([...prev.favoriteCategories, ...entities.categories])]
      }))
    }

    if (entities.brands.length > 0) {
      setUserPreferences(prev => ({
        ...prev,
        preferredBrands: [...new Set([...prev.preferredBrands, ...entities.brands])]
      }))
    }

    if (sentiment === 'positive') {
      setAiPersonality(prev => ({
        ...prev,
        tone: 'enthusiastic and helpful'
      }))
    } else if (sentiment === 'negative') {
      setAiPersonality(prev => ({
        ...prev,
        tone: 'empathetic and supportive'
      }))
    }
  }

  const generateAdaptiveSuggestions = () => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const userInsights = getUserInsights()

    const suggestions = []

    if (cartSummary.count > 0) {
      suggestions.push('View your cart', 'Proceed to checkout', 'Add more items')
    } else {
      suggestions.push('Browse trending products', 'Search for items', 'Get recommendations')
    }

    if (wishlistSummary.count > 0) {
      suggestions.push('View your wishlist', 'Add wishlist items to cart')
    }

    if (userPreferences.favoriteCategories.length > 0) {
      suggestions.push(`Browse ${userPreferences.favoriteCategories[0]} products`)
    }

    const hour = new Date().getHours()
    if (hour < 12) {
      suggestions.push('Start your day with great deals')
    } else if (hour < 17) {
      suggestions.push('Afternoon shopping session')
    } else {
      suggestions.push('Evening shopping deals')
    }

    return suggestions.slice(0, 5)
  }

  const generatePersonalizedGreeting = () => {
    const timeOfDay = new Date().getHours()
    const userInsights = getUserInsights()
    const cartSummary = getCartSummary()

    let greeting = ''

    if (timeOfDay < 12) {
      greeting = getRandomResponse(responseLibraries.greetings, 'morning')
    } else if (timeOfDay < 17) {
      greeting = getRandomResponse(responseLibraries.greetings, 'afternoon')
    } else {
      greeting = getRandomResponse(responseLibraries.greetings, 'evening')
    }

    let personalization = ''

    if (userInsights.favoriteCategory !== 'No preference') {
      personalization = `I noticed you love ${userInsights.favoriteCategory} products! `
    }

    if (cartSummary.count > 0) {
      personalization += `You have ${cartSummary.count} items in your cart ready for checkout. `
    }

    return `${greeting}! ${personalization}I'm here to help you with all your shopping needs.`
  }

  const analyzeConversationPattern = () => {
    if (conversationMemory.length < 3) return null

    const recentMessages = conversationMemory.slice(-5)
    const intents = recentMessages.map(msg => msg.intent)
    const sentiments = recentMessages.map(msg => msg.sentiment)

    const patterns = {
      frequentSearch: intents.filter(i => i === 'search').length > 2,
      priceConscious: recentMessages.some(msg => msg.entities.prices.length > 0),
      brandLoyal: recentMessages.some(msg => msg.entities.brands.length > 0),
      comparisonFocused: intents.filter(i => i === 'comparison').length > 1,
      issueProne: intents.filter(i => i === 'complaint').length > 0
    }

    return patterns
  }

  const generateContextualResponse = (userMessage, intent, sentiment, entities) => {
    const lowerMessage = userMessage.toLowerCase()

    learnFromUserBehavior(userMessage, intent, sentiment, entities)

    const patterns = analyzeConversationPattern()

    if (intent === 'greeting') {
      return generatePersonalizedGreeting()
    }

    if (intent === 'gratitude') {
      return getRandomResponse(responseLibraries.gratitude, sentiment === 'positive' ? 'positive' : 'neutral')
    }

    if (intent === 'farewell') {
      return getRandomResponse(responseLibraries.farewell)
    }

    if (intent === 'search') {
      if (entities.products.length > 0) {
        const product = entities.products[0]
        let response = getRandomResponse(responseLibraries.search, 'product').replace('{product}', product)

        if (patterns?.priceConscious) {
          response += `\n\n💰 I'll also show you the best prices and any current deals.`
        }

        if (patterns?.comparisonFocused) {
          response += `\n\n📊 I can also help you compare ${product} with similar products.`
        }

        response += `\n\nI can also help you:\n• Compare similar products\n• Check availability and pricing\n• Read customer reviews\n• Find related accessories\n\nWhat specific features are you looking for in ${product}?`
        return response
      }

      if (entities.categories.length > 0) {
        const category = entities.categories[0]
        return getRandomResponse(responseLibraries.search, 'category').replace('{category}', category) +
          `\n\nI can help you:\n• Filter by price range\n• Sort by popularity or rating\n• Find trending items\n• Get personalized picks\n\nWhat's your budget for ${category} items?`
      }

      return getRandomResponse(responseLibraries.help, 'general') +
        `\n\nI can search by:\n• Product name or brand\n• Category (electronics, fashion, etc.)\n• Price range\n• Features or specifications\n\nJust tell me what you're interested in!`
    }

    if (intent === 'recommendation') {
      const userInsights = getUserInsights()
      const adaptiveSuggestions = generateAdaptiveSuggestions()

      if (userInsights.favoriteCategory !== 'No preference') {
        const randomProduct = generateRandomData.products()
        const randomDeal = generateRandomData.deals()

        return getRandomResponse(responseLibraries.recommendations, 'personalized') +
          `\n\n⭐ ${randomProduct.name} - ${randomProduct.price} (${randomProduct.rating}⭐)\n🔥 ${randomDeal.type}: ${randomDeal.discount} on ${randomDeal.category}\n\nI can also suggest:\n• Trending items in your favorite categories\n• Best deals and discounts\n• New arrivals you might like\n• Products similar to your recent purchases\n\nWould you like to see more recommendations?`
      }

      const randomProduct = generateRandomData.products()
      const trendingTopic = generateRandomData.trends()

      return getRandomResponse(responseLibraries.recommendations, 'trending') +
        `\n\n🔥 Trending: ${trendingTopic}\n⭐ ${randomProduct.name} - ${randomProduct.price} (${randomProduct.rating}⭐)\n\nI can also suggest:\n• Show trending products\n• Recommend based on popular categories\n• Find deals and discounts\n• Suggest based on your interests\n\nWhat type of products are you interested in?`
    }

    if (intent === 'complaint') {
      let response = `I understand you're experiencing an issue, and I'm here to help resolve it quickly.\n\n🔧 Let me assist you with:\n\n• Order problems\n• Payment issues\n• Website/app problems\n• Product concerns\n• Delivery issues\n\n`

      if (sentiment === 'negative') {
        response += `I apologize for any inconvenience. Please describe the specific problem you're facing, and I'll guide you through the resolution process.`
      } else {
        response += `Please describe the specific problem you're facing, and I'll guide you through the resolution process.`
      }

      return response
    }

    if (intent === 'comparison') {
      if (entities.products.length >= 2) {
        const product1 = entities.products[0]
        const product2 = entities.products[1]
        return `I'll help you compare ${product1} and ${product2}!\n\n📊 Comparison Analysis:\n\nI can compare:\n• Price and value\n• Features and specifications\n• Customer reviews and ratings\n• Availability and delivery\n• Warranty and support\n\nWould you like me to show you a detailed comparison?`
      }

      return `I'd be happy to help you compare products! Please tell me which products you'd like to compare, and I'll provide a detailed analysis.\n\nYou can compare:\n• Similar products\n• Different brands\n• Different price ranges\n• Different categories`
    }

    if (lowerMessage.includes('fashion') || lowerMessage.includes('clothing') || lowerMessage.includes('dress')) {
      const randomProduct = generateRandomData.products()
      return `👗 Fashion & Style!\n\nI can help you discover amazing fashion items:\n\n• Trendy clothing and accessories\n• Shoes, bags, and jewelry\n• Seasonal collections\n• Size and fit guidance\n• Style recommendations\n\n🔥 Trending: ${randomProduct.name} - ${randomProduct.price}\n\nWould you like me to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized style picks`
    }

    if (lowerMessage.includes('electronics') || lowerMessage.includes('phone') || lowerMessage.includes('laptop')) {
      const randomProduct = generateRandomData.products()
      return `📱 Electronics & Tech!\n\nI can help you find the latest gadgets:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\n🔥 Hot Deal: ${randomProduct.name} - ${randomProduct.price}\n\nWould you like me to:\n• Show trending electronics\n• Search for specific devices\n• Compare tech products\n• Get tech recommendations`
    }

    if (lowerMessage.includes('price') || lowerMessage.includes('cost') || lowerMessage.includes('expensive')) {
      const randomDeal = generateRandomData.deals()
      return `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\n🔥 Special Offer: ${randomDeal.type} - ${randomDeal.discount}\n\nWould you like me to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
    }

    if (lowerMessage.includes('delivery') || lowerMessage.includes('shipping') || lowerMessage.includes('when')) {
      const shippingOption = generateRandomData.shipping()
      return `🚚 Delivery & Shipping Info!\n\n${shippingOption.method}: ${shippingOption.time}\nCost: ${shippingOption.cost}\n\nI can help you with:\n• Track your order\n• Check delivery status\n• Change delivery address\n• Schedule delivery\n• Express shipping options\n\nWould you like to check your order status?`
    }

    if (lowerMessage.includes('review') || lowerMessage.includes('rating') || lowerMessage.includes('feedback')) {
      const randomReview = generateRandomData.reviews()
      return `⭐ Reviews & Ratings!\n\nHere's what customers are saying:\n\n"${randomReview.text}" - ${randomReview.author} (${randomReview.rating}⭐)\n\nI can help you with:\n• Read product reviews\n• Check ratings\n• Compare customer feedback\n• Find highly-rated products\n• Write your own review\n\nWould you like to see more reviews?`
    }

    if (lowerMessage.includes('deal') || lowerMessage.includes('offer') || lowerMessage.includes('discount')) {
      const randomDeal = generateRandomData.deals()
      const randomProduct = generateRandomData.products()
      return `🎉 Deals & Offers!\n\n🔥 ${randomDeal.type}: ${randomDeal.discount} on ${randomDeal.category}\n⏰ Valid until: ${randomDeal.validUntil}\n\nFeatured Deal: ${randomProduct.name} - ${randomProduct.price}\n\nI can help you with:\n• Find more deals\n• Apply discount codes\n• Flash sales\n• Bundle offers\n• Loyalty rewards\n\nWould you like to see all current offers?`
    }

    return generateIntelligentDefaultResponse(userMessage, intent, sentiment, entities)
  }

  const generateIntelligentDefaultResponse = (userMessage, intent, sentiment, entities) => {
    const cartSummary = getCartSummary()
    const wishlistSummary = getWishlistSummary()
    const orderSummary = getOrderSummary()

    const userInsights = getUserInsights()
    const randomProduct = generateRandomData.products()
    const randomDeal = generateRandomData.deals()
    const trendingTopic = generateRandomData.trends()

    let response = getRandomResponse(responseLibraries.help, 'specific') + '\n\n'

    if (cartSummary.count > 0) {
      response += `🛒 I notice you have ${cartSummary.count} items in your cart (₹${cartSummary.total}).\n`
    }

    if (wishlistSummary.count > 0) {
      response += `💖 You have ${wishlistSummary.count} items in your wishlist.\n`
    }

    if (orderSummary.count > 0) {
      response += `📦 You have ${orderSummary.count} recent orders.\n`
    }

    if (userInsights.favoriteCategory !== 'No preference') {
      response += `\n⭐ Since you love ${userInsights.favoriteCategory}, check out: ${randomProduct.name} - ${randomProduct.price}\n`
    }

    response += `\n🔥 Trending: ${trendingTopic}\n🎉 Special: ${randomDeal.type} - ${randomDeal.discount}\n\n`

    response += `I can help you with:\n\n`

    if (entities.products.length > 0) {
      response += `• Search for ${entities.products[0]}\n`
      response += `• Compare ${entities.products[0]} with similar products\n`
      response += `• Check availability and pricing\n`
    }

    if (entities.categories.length > 0) {
      response += `• Browse ${entities.categories[0]} products\n`
      response += `• Find deals in ${entities.categories[0]}\n`
    }

    response += `• Manage your cart and wishlist\n`
    response += `• Track orders and payments\n`
    response += `• Get personalized recommendations\n`
    response += `• Find deals and offers\n`
    response += `• Resolve any issues\n`

    response += `\nWhat would you like to do?`

    return response
  }

  const updateConversationMemory = (userMessage, aiResponse, context) => {
    const memoryEntry = {
      timestamp: new Date(),
      userMessage,
      aiResponse,
      context,
      intent: analyzeUserIntent(userMessage),
      sentiment: analyzeSentiment(userMessage),
      entities: extractEntities(userMessage)
    }

    setConversationMemory(prev => {
      const updated = [...prev, memoryEntry]
      
      return updated.slice(-10)
    })
  }

  const formatAIResponse = (response) => {
    
    let formattedResponse = response

    formattedResponse = formattedResponse.replace(/🛒 Shopping:/g, '<div class="ai-section-header">🛒 Shopping</div>')
    formattedResponse = formattedResponse.replace(/📊 Your Account:/g, '<div class="ai-section-header">📊 Your Account</div>')
    formattedResponse = formattedResponse.replace(/📊 Account:/g, '<div class="ai-section-header">📊 Account</div>')
    formattedResponse = formattedResponse.replace(/🔍 Search:/g, '<div class="ai-section-header">🔍 Search</div>')
    formattedResponse = formattedResponse.replace(/🔍 Quick Actions:/g, '<div class="ai-section-header">🔍 Quick Actions</div>')
    formattedResponse = formattedResponse.replace(/💬 Support:/g, '<div class="ai-section-header">💬 Support</div>')
    formattedResponse = formattedResponse.replace(/⭐ Personalized Recommendations:/g, '<div class="ai-section-header">⭐ Personalized Recommendations</div>')
    formattedResponse = formattedResponse.replace(/📊 Comparison Analysis:/g, '<div class="ai-section-header">📊 Comparison Analysis</div>')
    formattedResponse = formattedResponse.replace(/🔧 Let me assist you with:/g, '<div class="ai-section-header">🔧 Let me assist you with</div>')

    formattedResponse = formattedResponse.replace(/I can help you with:/g, '<div class="ai-subsection-header">I can help you with:</div>')
    formattedResponse = formattedResponse.replace(/I can also help you:/g, '<div class="ai-subsection-header">I can also help you:</div>')
    formattedResponse = formattedResponse.replace(/I can also suggest:/g, '<div class="ai-subsection-header">I can also suggest:</div>')
    formattedResponse = formattedResponse.replace(/I can compare:/g, '<div class="ai-subsection-header">I can compare:</div>')
    formattedResponse = formattedResponse.replace(/You can compare:/g, '<div class="ai-subsection-header">You can compare:</div>')
    formattedResponse = formattedResponse.replace(/Would you like to:/g, '<div class="ai-subsection-header">Would you like to:</div>')
    formattedResponse = formattedResponse.replace(/What would you like to do?/g, '<div class="ai-subsection-header">What would you like to do?</div>')

    formattedResponse = formattedResponse.replace(/Cart: (\d+) items \(₹([\d,]+)\)/g, '<span class="ai-text-accent">Cart: $1 items (₹$2)</span>')
    formattedResponse = formattedResponse.replace(/Wishlist: (\d+) items/g, '<span class="ai-text-accent">Wishlist: $1 items</span>')
    formattedResponse = formattedResponse.replace(/Orders: (\d+) orders/g, '<span class="ai-text-accent">Orders: $1 orders</span>')

    formattedResponse = formattedResponse.replace(/✅/g, '<span class="ai-text-success">✅</span>')
    formattedResponse = formattedResponse.replace(/❌/g, '<span class="ai-text-error">❌</span>')
    formattedResponse = formattedResponse.replace(/⚠️/g, '<span class="ai-text-warning">⚠️</span>')

    formattedResponse = formattedResponse.replace(/\n\n/g, '<div class="ai-message-spacing"></div>')
    formattedResponse = formattedResponse.replace(/\n/g, '<br>')

    return formattedResponse
  }

  const extractProductName = (message) => {
    
    if (!message || typeof message !== 'string') {
      return ''
    }

    const lowerMessage = message.toLowerCase()

    const cleanedMessage = lowerMessage
      .replace(/(add|remove|delete|update|change|to|cart|wishlist|quantity|qty|number|count|from|in|the|a|an)/g, '')
      .replace(/\s+/g, ' ')
      .trim()

    if (!cleanedMessage) {
      const words = message.split(' ')
      const productWords = words.filter(word =>
        word.length > 2 &&
        !['the', 'and', 'or', 'but', 'for', 'with', 'from', 'to', 'in', 'on', 'at', 'by', 'add', 'remove', 'update', 'change', 'cart', 'wishlist', 'quantity', 'qty'].includes(word.toLowerCase())
      )
      return productWords.join(' ') || message
    }

    return cleanedMessage || message
  }

  const extractCategory = (message) => {
    
    const categoryMap = {
      'electronics': ['electronics', 'electronic', 'tech', 'technology', 'gadgets', 'devices', 'phone', 'laptop', 'computer', 'smartphone', 'tablet'],
      'fashion': ['fashion', 'clothing', 'apparel', 'wear', 'dress', 'style', 'outfit', 'shirt', 'pants', 'shoes', 'accessories'],
      'home': ['home', 'house', 'kitchen', 'furniture', 'decor', 'garden', 'outdoor', 'living', 'bedroom', 'bathroom'],
      'sports': ['sports', 'fitness', 'exercise', 'athletic', 'gym', 'workout', 'running', 'training', 'equipment'],
      'books': ['books', 'book', 'reading', 'literature', 'novel', 'textbook', 'magazine', 'journal'],
      'beauty': ['beauty', 'cosmetics', 'makeup', 'skincare', 'personal care', 'perfume', 'cosmetic'],
      'automotive': ['automotive', 'car', 'vehicle', 'auto', 'automobile', 'motorcycle', 'bike'],
      'toys': ['toys', 'toy', 'games', 'play', 'children', 'kids', 'game', 'entertainment']
    }

    const lowerMessage = message.toLowerCase()

    for (const [category, variations] of Object.entries(categoryMap)) {
      if (variations.some(v => lowerMessage.includes(v))) {
        return category
      }
    }

    for (const [category, variations] of Object.entries(categoryMap)) {
      for (const variation of variations) {
        if (lowerMessage.includes(variation)) {
          return category
        }
      }
    }

    return message.trim()
  }

  const extractBrand = (message) => {
   
    const brands = [
      'samsung', 'apple', 'nike', 'adidas', 'sony', 'dell', 'hp', 'lenovo', 'lg', 'panasonic', 'canon', 'nikon', 'puma', 'reebok', 'under armour',
      'asus', 'acer', 'msi', 'gigabyte', 'corsair', 'logitech', 'razer', 'steelseries', 'hyperx', 'jbl', 'bose', 'beats', 'skullcandy', 'sennheiser',
      'philips', 'sharp', 'toshiba', 'hitachi', 'mitsubishi', 'fujitsu', 'vaio', 'alienware', 'roccat', 'cooler master', 'thermaltake', 'antec',
      'new balance', 'converse', 'vans', 'timberland', 'dr martens', 'clarks', 'crocs', 'skechers', 'reebok', 'fila', 'umbro', 'kappa', 'lotto',
      'motorola', 'oneplus', 'xiaomi', 'oppo', 'vivo', 'realme', 'honor', 'huawei', 'google', 'blackberry', 'htc', 'nokia', 'lg', 'zte',
      'gopro', 'dji', 'fujifilm', 'olympus', 'pentax', 'leica', 'sigma', 'tamron', 'tokina', 'rokinon', 'samyang', 'laowa', 'venus optics',
      'coca cola', 'pepsi', 'nestle', 'unilever', 'procter & gamble', 'johnson & johnson', 'colgate', 'unilever', 'nestle', 'kraft', 'kellogg',
      'ikea', 'walmart', 'target', 'costco', 'best buy', 'home depot', 'lowes', 'macy', 'nordstrom', 'gap', 'h&m', 'zara', 'uniqlo', 'forever 21'
    ]
    
    const lowerMessage = message.toLowerCase().trim()

    for (const brand of brands) {
      if (lowerMessage === brand || lowerMessage.includes(brand)) {
        return brand
      }
    }

    const brandPatterns = [
      /(?:brand|make|manufacturer|company)\s+(?:is\s+)?([a-zA-Z0-9\s&]+)/i,
      /(?:looking\s+for|search\s+for|find)\s+([a-zA-Z0-9\s&]+)\s+(?:brand|products?)/i,
      /([a-zA-Z0-9\s&]+)\s+(?:brand|products?|items?)/i
    ]
    
    for (const pattern of brandPatterns) {
      const match = lowerMessage.match(pattern)
      if (match && match[1]) {
        const extractedBrand = match[1].trim()
        if (extractedBrand.length > 1 && extractedBrand.length < 50) {
          return extractedBrand
        }
      }
    }

    return lowerMessage.replace(/^(search|find|look|show|get|i want|i need|give me)\s+/i, '').trim()
  }

  const extractQuantity = (message) => {
    
    const quantityPatterns = [
      
      /(\d+)\s*(piece|item|unit|quantity|qty|number|count)/i,
      
      /add\s+(\d+)\s+(?:of|pieces?|items?|units?)/i,
      
      /quantity\s+(\d+)/i,
      
      /to\s+(\d+)/i,
      
      /(\d+)\s+quantity/i,
      
      /add\s+(\d+)\s+[a-zA-Z]/i
    ]

    for (const pattern of quantityPatterns) {
      const match = message.match(pattern)
      if (match) {
        const quantity = parseInt(match[1])
        if (quantity > 0 && quantity <= 100) {
          return quantity
        }
      }
    }

    const numbers = message.match(/(\d+)/g)
    if (numbers && numbers.length > 0) {
      
      const validQuantities = numbers.filter(num => {
        const numInt = parseInt(num)
        return numInt <= 100 && numInt > 0
      })
      if (validQuantities.length > 0) {
        return parseInt(validQuantities[0])
      }
    }

    return 1 
  }

  const extractOrderId = (message) => {
    
    const orderMatch = message.match(/(?:order|order id|order number|track order)\s*(?:#|number)?\s*([a-zA-Z0-9]+)/i)
    if (orderMatch) {
      return orderMatch[1]
    }

    const idMatch = message.match(/([a-zA-Z0-9]{6,})/)
    if (idMatch) {
      return idMatch[1]
    }

    return message.trim()
  }

  const extractPaymentMethod = (message) => {
    const paymentMethods = ['credit card', 'debit card', 'paypal', 'cash', 'bank transfer', 'upi', 'gpay', 'phonepe', 'amazon pay']
    const lowerMessage = message.toLowerCase()

    for (const method of paymentMethods) {
      if (lowerMessage.includes(method)) {
        return method
      }
    }

    return 'credit card' 
  }

  const extractIssueType = (message) => {
    const issues = {
      'order': ['order', 'delivery', 'shipping', 'tracking'],
      'payment': ['payment', 'billing', 'charge', 'refund', 'money'],
      'product': ['product', 'item', 'quality', 'defective', 'broken'],
      'website': ['website', 'app', 'login', 'account', 'technical'],
      'delivery': ['delivery', 'shipping', 'address', 'location']
    }

    const lowerMessage = message.toLowerCase()

    for (const [issueType, keywords] of Object.entries(issues)) {
      for (const keyword of keywords) {
        if (lowerMessage.includes(keyword)) {
          return issueType
        }
      }
    }

    return 'general' 
  }

  const processIntelligentKeywords = (userMessage) => {
    const lowerMessage = userMessage.toLowerCase()

    const keywordMap = {
      
      'fashion': {
        keywords: ['fashion', 'clothing', 'dress', 'shirt', 'pants', 'shoes', 'accessories', 'style', 'outfit', 'wear', 'apparel'],
        response: `👗 Fashion & Style!\n\nI can help you discover amazing fashion items:\n\n• Trendy clothing and accessories\n• Shoes, bags, and jewelry\n• Seasonal collections\n• Size and fit guidance\n• Style recommendations\n\nWould you like to:\n• Show trending fashion items\n• Search for specific clothing\n• Browse fashion categories\n• Get personalized style picks`
      },

      'electronics': {
        keywords: ['electronics', 'phone', 'laptop', 'computer', 'smartphone', 'tablet', 'gadget', 'tech', 'technology', 'device', 'mobile'],
        response: `📱 Electronics & Tech!\n\nI can help you find the latest gadgets:\n\n• Smartphones and tablets\n• Laptops and computers\n• Audio and video equipment\n• Gaming devices\n• Smart home products\n\nWould you like to:\n• Show trending electronics\n• Search for specific devices\n• Compare tech products\n• Get tech recommendations`
      },

      'home': {
        keywords: ['home', 'house', 'kitchen', 'furniture', 'decor', 'garden', 'outdoor', 'living', 'bedroom', 'bathroom', 'appliance'],
        response: `🏠 Home & Garden!\n\nI can help you find perfect home items:\n\n• Furniture and decor\n• Kitchen appliances\n• Garden tools and plants\n• Home improvement\n• Smart home devices\n\nWould you like to:\n• Show trending home products\n• Search for specific items\n• Browse home categories\n• Get home recommendations`
      },

      'sports': {
        keywords: ['sports', 'fitness', 'exercise', 'gym', 'workout', 'running', 'training', 'athletic', 'equipment', 'sportswear'],
        response: `🏃‍♂️ Sports & Fitness!\n\nI can help you find sports equipment:\n\n• Workout gear and clothing\n• Sports equipment\n• Fitness accessories\n• Athletic shoes\n• Training gear\n\nWould you like to:\n• Show trending sports items\n• Search for specific equipment\n• Browse sports categories\n• Get fitness recommendations`
      },

      'books': {
        keywords: ['books', 'book', 'reading', 'education', 'study', 'textbook', 'novel', 'literature', 'learning', 'academic'],
        response: `📚 Books & Education!\n\nI can help you find great books:\n\n• Fiction and non-fiction\n• Textbooks and academic\n• Self-help and business\n• Children's books\n• Digital books\n\nWould you like to:\n• Show trending books\n• Search for specific titles\n• Browse book categories\n• Get reading recommendations`
      },

      'beauty': {
        keywords: ['beauty', 'cosmetics', 'makeup', 'skincare', 'personal care', 'perfume', 'cosmetic', 'beauty product'],
        response: `💄 Beauty & Personal Care!\n\nI can help you find beauty products:\n\n• Makeup and cosmetics\n• Skincare products\n• Fragrances and perfumes\n• Hair care products\n• Personal hygiene\n\nWould you like to:\n• Show trending beauty items\n• Search for specific products\n• Browse beauty categories\n• Get beauty recommendations`
      },

      'automotive': {
        keywords: ['car', 'vehicle', 'auto', 'automotive', 'automobile', 'motorcycle', 'bike', 'accessories', 'parts'],
        response: `🚗 Automotive!\n\nI can help you find automotive products:\n\n• Car accessories and parts\n• Motorcycle gear\n• Vehicle maintenance\n• Auto electronics\n• Safety equipment\n\nWould you like to:\n• Show trending auto items\n• Search for specific parts\n• Browse automotive categories\n• Get auto recommendations`
      },

      'toys': {
        keywords: ['toys', 'toy', 'games', 'game', 'play', 'children', 'kids', 'entertainment', 'fun'],
        response: `🎮 Toys & Games!\n\nI can help you find fun products:\n\n• Children's toys\n• Board games and puzzles\n• Video games\n• Educational toys\n• Outdoor play equipment\n\nWould you like to:\n• Show trending toys\n• Search for specific games\n• Browse toy categories\n• Get game recommendations`
      },

      'pricing': {
        keywords: ['price', 'cost', 'expensive', 'cheap', 'budget', 'affordable', 'deal', 'discount', 'sale', 'offer'],
        response: () => {
          const randomDeal = generateRandomData.deals()
          return `💰 Price & Budget Help!\n\nI can help you with pricing:\n\n• Search by price range\n• Find deals and discounts\n• Compare prices\n• Set price alerts\n• Budget-friendly options\n\n🔥 Current Offer: ${randomDeal.type} - ${randomDeal.discount}\nUse Code: ${randomDeal.code}\n\nWould you like to:\n• Show products under ₹1000\n• Find deals and offers\n• Compare similar products\n• Set price drop alerts`
        }
      },

      'payment': {
        keywords: ['payment', 'pay', 'card', 'upi', 'emi', 'cash', 'wallet', 'bank', 'credit', 'debit', 'money', 'transaction', 'billing'],
        response: () => {
          const paymentMethod = generateRandomData.payments()
          return getRandomResponse(responseLibraries.payment, 'methods') +
            `\n\n${paymentMethod.icon} ${paymentMethod.name}\n🔒 ${paymentMethod.security}\n⚡ ${paymentMethod.processing}\n\nWould you like to:\n• Learn about payment security\n• Get EMI options\n• Resolve payment issues\n• Check payment status`
        }
      },

      'product_details': {
        keywords: ['details', 'specifications', 'specs', 'features', 'information', 'description', 'what is', 'tell me about', 'product info'],
        response: () => {
          const product = generateRandomData.products()
          const specs = generateRandomData.specifications()
          const review = generateRandomData.reviews()

          let response = getRandomResponse(responseLibraries.product, 'details')
            .replace('{brand}', product.brand)
            .replace('{price}', product.price)
            .replace('{rating}', product.rating)
            .replace('{reviews}', product.reviews)
            .replace('{dimension}', specs.dimension)
            .replace('{weight}', specs.weight)
            .replace('{material}', specs.material)
            .replace('{warranty}', specs.warranty)
            .replace('{features}', product.features.map(f => `• ${f}`).join('\n'))

          response += `\n\n💬 Customer Review:\n"${review.text}" - ${review.author} (${review.rating}⭐)`

          return response
        }
      },

      'recommendations': {
        keywords: ['recommend', 'suggestion', 'advise', 'what should', 'help me choose', 'best', 'top', 'popular', 'trending'],
        response: () => {
          const product1 = generateRandomData.products()
          const product2 = generateRandomData.products()
          const product3 = generateRandomData.products()
          const category = generateRandomData.categories()

          let response = getRandomResponse(responseLibraries.recommendations, 'personalized')
            .replace('{product1.name}', product1.name)
            .replace('{product1.price}', product1.price)
            .replace('{product1.rating}', product1.rating)
            .replace('{product2.name}', product2.name)
            .replace('{product2.price}', product2.price)
            .replace('{product2.rating}', product2.rating)
            .replace('{product3.name}', product3.name)
            .replace('{product3.price}', product3.price)
            .replace('{product3.rating}', product3.rating)

          response += `\n\n${category.icon} Trending in ${category.name}: ${category.count} products available!`

          return response
        }
      },

      'customer_support': {
        keywords: ['support', 'help', 'assist', 'problem', 'issue', 'trouble', 'complaint', 'contact', 'service', 'customer care'],
        response: () => {
          const supportTopic = generateRandomData.support()
          return getRandomResponse(responseLibraries.support, 'general') +
            `\n\n🔧 ${supportTopic.issue} (${supportTopic.priority} Priority)\n${supportTopic.response}\n\nWould you like to:\n• Get order support\n• Technical assistance\n• Return/refund help\n• Contact live agent`
        }
      },

      'help': {
        keywords: ['help', 'support', 'assist', 'problem', 'issue', 'trouble', 'question', 'how', 'what', 'why'],
        response: () => {
          const category = generateRandomData.categories()
          return `🆘 I'm here to help!\n\nI can assist you with:\n\n🔍 Search & Discovery\n• Find products by name, category, brand\n• Advanced search with filters\n• Trending and popular items\n\n🛒 Shopping Experience\n• Add items to cart\n• Manage your wishlist\n• Track orders and deliveries\n\n💳 Payment & Orders\n• Payment methods and security\n• Order tracking and status\n• Returns and refunds\n\n🎧 Customer Support\n• Live chat and email support\n• FAQ and troubleshooting\n• Technical assistance\n\n${category.icon} Popular Category: ${category.name} (${category.count})\n\nWhat specific help do you need?`
        }
      },

      'cart': {
        keywords: ['cart', 'shopping cart', 'basket', 'add to cart', 'remove from cart', 'checkout', 'buy', 'purchase'],
        response: `🛒 Cart Management!\n\nI can help you with your cart:\n\n• View your current cart\n• Add items to cart\n• Remove items from cart\n• Update quantities\n• Proceed to checkout\n\nWould you like to:\n• View your cart\n• Add items to cart\n• Remove items\n• Checkout now`
      },

      'wishlist': {
        keywords: ['wishlist', 'favorites', 'save', 'wish', 'favorite', 'saved items'],
        response: `💖 Wishlist Management!\n\nI can help you with your wishlist:\n\n• View your wishlist\n• Add items to wishlist\n• Remove items from wishlist\n• Share your wishlist\n• Get price alerts\n\nWould you like to:\n• View your wishlist\n• Add items to wishlist\n• Remove items\n• Share wishlist`
      },

      'orders': {
        keywords: ['order', 'track', 'delivery', 'shipping', 'status', 'tracking', 'package', 'parcel'],
        response: `📦 Order Tracking!\n\nI can help you track your orders:\n\n• View all your orders\n• Track specific order\n• Check delivery status\n• Cancel orders\n• Return items\n\nWould you like to:\n• View your orders\n• Track specific order\n• Check delivery status\n• Cancel order`
      },

      'recommendations': {
        keywords: ['recommend', 'suggestion', 'advise', 'what should', 'help me choose', 'best', 'top', 'popular'],
        response: `⭐ Recommendations!\n\nI can provide smart recommendations:\n\n• Personalized picks\n• Trending products\n• Category recommendations\n• Price-based suggestions\n• Similar products\n\nWould you like to:\n• Get personalized picks\n• See trending items\n• Browse by category\n• Find similar products`
      }
    }

    for (const [category, data] of Object.entries(keywordMap)) {
      if (data.keywords.some(keyword => lowerMessage.includes(keyword))) {
        return {
          response: typeof data.response === 'function' ? data.response() : data.response,
          contextUpdate: { currentTopic: category, lastAction: `${category}_inquiry` }
        }
      }
    }

    if (lowerMessage.includes('what can you do') || lowerMessage.includes('your capabilities') || lowerMessage.includes('what do you do')) {
      const category = generateRandomData.categories()
      const deal = generateRandomData.deals()
      return {
        response: `I'm your AI shopping assistant! Here's what I can do:\n\n🛍️ Shopping:\n• Search products by name, category, or brand\n• Compare products and prices\n• Find deals and discounts\n• Manage your cart and wishlist\n\n📦 Orders:\n• Track your orders\n• Check delivery status\n• Manage returns and cancellations\n\n💡 Recommendations:\n• Personalized product suggestions\n• Trending items\n• Price alerts\n• Style recommendations\n\n💬 Support:\n• Answer questions\n• Resolve issues\n• Provide guidance\n\n${category.icon} Popular: ${category.name} (${category.count})\n🔥 Current: ${deal.type} - ${deal.discount}\n\nI'm here to make your shopping experience amazing! What would you like to do?`,
        contextUpdate: { currentTopic: 'capabilities', lastAction: 'capabilities_inquiry' }
      }
    }

    if (lowerMessage.includes('emi') || lowerMessage.includes('installment')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'emi'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'emi_inquiry' }
      }
    }

    if (lowerMessage.includes('security') || lowerMessage.includes('safe') || lowerMessage.includes('secure')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'security'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'security_inquiry' }
      }
    }

    if (lowerMessage.includes('payment problem') || lowerMessage.includes('payment issue') || lowerMessage.includes('payment error')) {
      return {
        response: getRandomResponse(responseLibraries.payment, 'issues'),
        contextUpdate: { currentTopic: 'payment', lastAction: 'payment_issue' }
      }
    }

    if (lowerMessage.includes('compare') || lowerMessage.includes('vs') || lowerMessage.includes('difference')) {
      const product1 = generateRandomData.products()
      const product2 = generateRandomData.products()
      let response = getRandomResponse(responseLibraries.product, 'comparison')
        .replace('{priceA}', product1.price)
        .replace('{priceB}', product2.price)
        .replace('{ratingA}', product1.rating)
        .replace('{ratingB}', product2.rating)
        .replace('{featuresA}', product1.features.slice(0, 2).join(', '))
        .replace('{featuresB}', product2.features.slice(0, 2).join(', '))

      return {
        response: response,
        contextUpdate: { currentTopic: 'product', lastAction: 'comparison_inquiry' }
      }
    }

    if (lowerMessage.includes('stock') || lowerMessage.includes('available') || lowerMessage.includes('in stock')) {
      const product = generateRandomData.products()
      const shipping = generateRandomData.shipping()
      let response = getRandomResponse(responseLibraries.product, 'availability')
        .replace('{quantity}', Math.floor(Math.random() * 50) + 10)
        .replace('{deliveryTime}', shipping.time)
        .replace('{location}', 'Mumbai Warehouse')
        .replace('{restockDate}', 'Next week')

      return {
        response: response,
        contextUpdate: { currentTopic: 'product', lastAction: 'availability_inquiry' }
      }
    }

    if (lowerMessage.includes('order problem') || lowerMessage.includes('order issue') || lowerMessage.includes('delivery problem')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'order'),
        contextUpdate: { currentTopic: 'support', lastAction: 'order_issue' }
      }
    }

    if (lowerMessage.includes('technical') || lowerMessage.includes('website problem') || lowerMessage.includes('app issue')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'technical'),
        contextUpdate: { currentTopic: 'support', lastAction: 'technical_issue' }
      }
    }

    if (lowerMessage.includes('refund') || lowerMessage.includes('return') || lowerMessage.includes('money back')) {
      return {
        response: getRandomResponse(responseLibraries.support, 'refund'),
        contextUpdate: { currentTopic: 'support', lastAction: 'refund_inquiry' }
      }
    }

    if (lowerMessage.includes('how are you') || lowerMessage.includes('how do you feel')) {
      return {
        response: "I'm doing great, thank you for asking! 😊 I'm always excited to help you with your shopping needs. How can I assist you today?",
        contextUpdate: { currentTopic: 'wellbeing', lastAction: 'wellbeing_inquiry' }
      }
    }

    if (lowerMessage.includes('joke') || lowerMessage.includes('funny') || lowerMessage.includes('humor')) {
      const jokes = [
        "Why did the shopping cart go to therapy? Because it had too many issues to carry! 😄",
        "What do you call a shopping assistant who's always late? A procrasti-buyer! 🛍️",
        "Why did the customer bring a ladder to the store? To reach the high-end products! 📈",
        "What's a shopper's favorite type of music? Sale music! 🎵"
      ]
      return {
        response: jokes[Math.floor(Math.random() * jokes.length)],
        contextUpdate: { currentTopic: 'humor', lastAction: 'humor_request' }
      }
    }

    if (lowerMessage.includes('weather') || lowerMessage.includes('temperature')) {
      return {
        response: "I'm focused on shopping, but I can help you find weather-appropriate clothing and accessories! 🌤️ Would you like me to show you seasonal items?",
        contextUpdate: { currentTopic: 'weather', lastAction: 'weather_inquiry' }
      }
    }

    if (lowerMessage.includes('time') || lowerMessage.includes('clock')) {
      const now = new Date()
      const timeString = now.toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit',
        hour12: true
      })
      return {
        response: `It's currently ${timeString}. Perfect time for some shopping! 🛍️ What can I help you find?`,
        contextUpdate: { currentTopic: 'time', lastAction: 'time_inquiry' }
      }
    }

    return null 
  }

  const getSubActions = (actionType) => {
    const mainAction = quickActions.find(qa => qa.action === actionType)
    return mainAction ? mainAction.subActions || [] : []
  }

  return (
    <>
      {}
      <AnimatePresence>
        {!isOpen && (
          <motion.div
            className="ai-chat-toggle-container"
            style={style}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
          >
            <motion.button
              className="ai-chat-toggle-btn"
              onClick={openChat}
              onMouseEnter={handleMouseEnter}
              onMouseLeave={handleMouseLeave}
              whileHover={{ scale: 1.1, rotate: 5 }}
              whileTap={{ scale: 0.9 }}
            >
              <motion.div
                className="ai-avatar"
                animate={{
                  rotate: [0, 360],
                  scale: [1, 1.1, 1],
                }}
                transition={{
                  rotate: { duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" },
                  scale: { duration: 2, repeat: Number.POSITIVE_INFINITY, ease: "easeInOut" },
                }}
              >
                <Bot size={24} />
              </motion.div>

              {}
              {[...Array(6)].map((_, i) => (
                <motion.div
                  key={i}
                  className="ai-particle"
                  style={{
                    position: "absolute",
                    width: "4px",
                    height: "4px",
                    background: "linear-gradient(45deg, #667eea, #764ba2)",
                    borderRadius: "50%",
                    left: "50%",
                    top: "50%",
                  }}
                  animate={{
                    x: [0, Math.cos((i * 60) * Math.PI / 180) * 30],
                    y: [0, Math.sin((i * 60) * Math.PI / 180) * 30],
                    rotate: [0, 360],
                    scale: [0, 1, 0],
                    opacity: [0, 1, 0],
                  }}
                  transition={{
                    duration: 2.5,
                    repeat: Number.POSITIVE_INFINITY,
                    delay: i * 0.3,
                  }}
                />
              ))}

              {}
              <AnimatePresence>
                {showTooltip && (
                  <motion.div
                    className="ai-welcome-tooltip"
                    initial={{ opacity: 0, x: 20, scale: 0.8 }}
                    animate={{ opacity: 1, x: 0, scale: 1 }}
                    exit={{ opacity: 0, x: 20, scale: 0.8 }}
                    transition={{ duration: 0.3 }}
                  >
                    <div className="tooltip-content">
                      <Zap size={16} />
                      <span>AI Assistant ready to help!</span>
                    </div>
                    <div className="tooltip-arrow" />
                  </motion.div>
                )}
              </AnimatePresence>
            </motion.button>
          </motion.div>
        )}
      </AnimatePresence>

      {}
      <AnimatePresence>
        {isOpen && (
          <motion.div
            className={`ai-chat-window ${isFullScreen ? 'fullscreen' : ''}`}
            style={style}
            initial={{ scale: 0, opacity: 0 }}
            animate={{ scale: 1, opacity: 1 }}
            exit={{ scale: 0, opacity: 0 }}
            transition={{ duration: 0.3, ease: "easeOut" }}
          >
            {}
            <div className="ai-chat-header">
              <div className="ai-header-content">
                <div className="ai-agent-info">
                  <div className="ai-agent-avatar">
                    <motion.div
                      animate={{ rotate: [0, 360] }}
                      transition={{ duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" }}
                    >
                      <Bot size={24} />
                    </motion.div>
                    <div className="ai-status-indicator online" />
                  </div>

                  <div className="ai-agent-details">
                    <h4 className="ai-agent-name">MKCart AI Assistant</h4>
                    <p className="ai-agent-role">
                      {isTyping ? "Thinking..." : isListening ? "Listening..." : "Online & Ready"}
                    </p>
                  </div>
                </div>

                <div className="ai-header-actions">
                  <motion.button
                    className="ai-header-btn"
                    onClick={() => setVoiceEnabled(!voiceEnabled)}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                    data-active={voiceEnabled}
                  >
                    {voiceEnabled ? <Volume2 size={16} /> : <VolumeX size={16} />}
                  </motion.button>

                  <motion.button
                    className="ai-header-btn"
                    onClick={clearChat}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <RotateCcw size={16} />
                  </motion.button>

                  <motion.button
                    className="ai-header-btn"
                    onClick={closeChat}
                    whileHover={{ scale: 1.1 }}
                    whileTap={{ scale: 0.9 }}
                  >
                    <X size={16} />
                  </motion.button>
                </div>
              </div>
            </div>

            {}
            <div className="ai-chat-messages">
              {messages.map((message) => (
                <div key={message.id} className={`ai-message ${message.type}`}>
                  <div className="ai-message-avatar">
                    {message.type === "ai" ? (
                      <motion.div
                        animate={{ rotate: [0, 360] }}
                        transition={{ duration: 20, repeat: Number.POSITIVE_INFINITY, ease: "linear" }}
                      >
                        <Bot size={20} />
                      </motion.div>
                    ) : (
                      <User size={20} />
                    )}
                  </div>

                  <div className="ai-message-bubble">
                    <div className="ai-message-content" dangerouslySetInnerHTML={{ __html: message.type === 'ai' ? formatAIResponse(message.message) : message.message.replace(/\n/g, '<br>') }} />
                    <div className="ai-message-actions">
                      <motion.button
                        className="ai-message-action"
                        onClick={() => copyMessage(message)}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        <Copy size={14} />
                      </motion.button>
                      <motion.button
                        className="ai-message-action"
                        onClick={() => shareMessage(message)}
                        whileHover={{ scale: 1.1 }}
                        whileTap={{ scale: 0.9 }}
                      >
                        <Share2 size={14} />
                      </motion.button>
                      {message.type === "ai" && (
                        <>
                          <motion.button
                            className="ai-message-action"
                            onClick={() => rateMessage(message.id, "up")}
                            whileHover={{ scale: 1.1 }}
                            whileTap={{ scale: 0.9 }}
                          >
                            <ThumbsUp size={14} />
                          </motion.button>
                          <motion.button
                            className="ai-message-action"
                            onClick={() => rateMessage(message.id, "down")}
                            whileHover={{ scale: 1.1 }}
                            whileTap={{ scale: 0.9 }}
                          >
                            <ThumbsDown size={14} />
                          </motion.button>
                        </>
                      )}
                    </div>
                  </div>
                </div>
              ))}

              {}
              {isTyping && (
                <div className="ai-processing-indicator">
                  <div className="ai-processing-spinner" />
                  <div className="ai-processing-text">{currentTask}</div>
                </div>
              )}

              {}
              <div ref={messagesEndRef} />

            </div>

            {}
            <div className="ai-quick-actions">
              <div className="ai-quick-actions-grid">
                {currentSubActions ? (
                  
                  <>
                    {}
                    {subActionHistory.length > 0 && (
                      <div className="ai-sub-action-breadcrumb">
                        {subActionHistory.map((item, index) => (
                          <span key={index} className="ai-breadcrumb-item">
                            {item.label}
                            {index < subActionHistory.length - 1 && <span className="ai-breadcrumb-separator"> → </span>}
                          </span>
                        ))}
                      </div>
                    )}

                    {}
                    {currentSubActions.map((subAction) => (
                      <motion.button
                        key={subAction.action}
                        className="ai-quick-action-btn"
                        onClick={() => handleQuickAction(subAction.action)}
                        whileHover={{ scale: 1.05 }}
                        whileTap={{ scale: 0.95 }}
                        disabled={isTyping}
                        style={{
                          background: `linear-gradient(135deg, ${subAction.color}20, ${subAction.color}10)`,
                          border: `1px solid ${subAction.color}30`
                        }}
                      >
                        <div className="ai-quick-action-icon">
                          <subAction.icon size={16} />
                        </div>
                        <span className="ai-quick-action-text">{subAction.label}</span>
                      </motion.button>
                    ))}
                  </>
                ) : (
                  quickActions.map((actionObj) => (
                    <motion.button
                      key={actionObj.action}
                      className="ai-quick-action-btn"
                      onClick={() => handleQuickAction(actionObj.action)}
                      whileHover={{ scale: 1.05 }}
                      whileTap={{ scale: 0.95 }}
                      disabled={isTyping}
                      style={{
                        background: `linear-gradient(135deg, ${actionObj.color}20, ${actionObj.color}10)`,
                        border: `1px solid ${actionObj.color}30`
                      }}
                    >
                      <div className="ai-quick-action-icon">
                        <actionObj.icon size={16} />
                      </div>
                      <span className="ai-quick-action-text">{actionObj.label}</span>
                    </motion.button>
                  ))
                )}
              </div>
            </div>

            {}
            <div className="ai-chat-input-container">
              <div className="ai-input-wrapper">
                <motion.button
                  className="ai-input-action-btn"
                  onClick={handleFileUpload}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                >
                  <Paperclip size={16} />
                </motion.button>

                <motion.button
                  className="ai-input-action-btn"
                  onClick={isListening ? stopListening : startListening}
                  whileHover={{ scale: 1.1 }}
                  whileTap={{ scale: 0.9 }}
                  data-active={isListening}
                >
                  {isListening ? <MicOff size={16} /> : <Mic size={16} />}
                </motion.button>

                <textarea
                  className="ai-chat-input"
                  value={inputMessage}
                  onChange={(e) => setInputMessage(e.target.value)}
                  onKeyPress={handleKeyPress}
                  placeholder="Type your message here..."
                  disabled={isTyping}
                  rows={1}
                />

                <motion.button
                  className="ai-send-btn"
                  onClick={handleSendMessage}
                  disabled={!inputMessage.trim() || isTyping}
                  whileHover={{ scale: 1.05 }}
                  whileTap={{ scale: 0.95 }}
                >
                  <Send size={16} />
                </motion.button>
              </div>
            </div>
          </motion.div>
        )}
      </AnimatePresence>
    </>
  )
}

export default AIChatAssistant