// import React, { useState } from 'react'

// // ** MUI Imports
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Button from '@mui/material/Button'
// import Skeleton from '@mui/material/Skeleton'
// import Typography from '@mui/material/Typography'
// import CardContent from '@mui/material/CardContent'

// // ** Animation
// import { motion } from 'motion/react'

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import { useDispatch } from 'react-redux'

// // ** Action
// import { handleAlertSelectCustomer } from 'src/store/pages/pos'
// import { addToCart } from 'src/store/pages/pos/cartSlice'

// // ** Toast
// import toast from 'react-hot-toast'

// const MotionImg = motion.img

// interface Product {
//   id: string
//   name: string
//   image: string
//   price: number
// }

// interface ProductCardProps {
//   name: string
//   price: number
//   image: string
//   items: Product
// }

// // ** Product Card Component
// export const ProductCard: React.FC<ProductCardProps> = ({
//   name = 'Goldy Brare',
//   price = 23,
//   image = 'url',
//   ...props
// }) => {
//   // ** Props
//   const { items } = props

//   // ** States
//   const [added, setAdded] = useState(false)

//   // ** Hooks
//   const dispatch = useDispatch()
//   const isCustomerSelected = useSelector((state: RootState) => state.pos.isCustomerSelected)

//   // ** Handle Add To Cart
//   const handleAddToCart = () => {
//     if (!isCustomerSelected) {
//       dispatch(handleAlertSelectCustomer(1))

//       toast.error('Please select a customer before adding products to the cart.')

//       return
//     }
//     dispatch(addToCart({ ...items, quantity: 1 }))
//     setAdded(true)
//   }

//   return (
//     <Card
//       sx={{
//         width: '100%',
//         height: '100%',
//         display: 'flex',
//         flexDirection: 'column',
//         cursor: 'pointer',
//         border: theme => `1px solid ${theme.palette.divider}`
//       }}
//     >
//       {/* Image Box */}
//       <Box
//         sx={{
//           margin: 4,
//           aspectRatio: '1 / 1',
//           overflow: 'hidden',
//           display: 'flex',
//           alignItems: 'center',
//           justifyContent: 'center',
//           borderRadius: 2,
//           bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//         }}
//       >
//         <MotionImg
//           src={image}
//           alt={name}
//           style={{
//             maxWidth: '100%',
//             maxHeight: '100%',
//             objectFit: 'contain'
//           }}
//           initial={{ opacity: 0, scale: 0.9 }}
//           animate={{ opacity: 1, scale: 1 }}
//           transition={{ duration: 0.5 }}
//           whileHover={{ scale: 1.1 }} // 🔥 only image scales on hover
//         />
//       </Box>

//       {/* Content */}
//       <CardContent
//         sx={{
//           flex: 1,
//           display: 'flex',
//           flexDirection: 'column',
//           justifyContent: 'space-between',
//           p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//           gap: 1
//         }}
//       >
//         <Typography variant='body1' fontWeight={900}>
//           {name}
//         </Typography>

//         <Typography variant='body2' color='text.secondary' sx={{ borderTop: '1px dashed gray', pt: 2 }}>
//           ${price}
//         </Typography>
//       </CardContent>
//       <Button
//         variant='contained'
//         color={added ? 'success' : 'primary'}
//         onClick={() => handleAddToCart()}
//         sx={{ py: 2.5, width: '100%', borderTopLeftRadius: 0, borderTopRightRadius: 0 }}
//       >
//         {added ? 'Added To Cart' : 'Add To Cart'}
//       </Button>
//     </Card>
//   )
// }

// // ** Product Render Component
// const ProductCardSkeleton: React.FC = () => {
//   return (
//     <Card
//       sx={{
//         width: '100%',
//         height: '100%',
//         display: 'flex',
//         flexDirection: 'column',
//         cursor: 'pointer',
//         border: theme => `1px solid ${theme.palette.divider}`
//       }}
//     >
//       {/* Image Skeleton */}
//       <Box
//         sx={{
//           margin: 4,
//           aspectRatio: '1 / 1',
//           display: 'flex',
//           alignItems: 'center',
//           justifyContent: 'center',
//           borderRadius: 2,
//           overflow: 'hidden',
//           bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//         }}
//       >
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>

//       {/* Content Skeleton */}
//       <CardContent
//         sx={{
//           flex: 1,
//           display: 'flex',
//           flexDirection: 'column',
//           justifyContent: 'space-between',
//           p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//           gap: 1
//         }}
//       >
//         <Skeleton variant='text' width='80%' height={30} />
//         <Skeleton variant='text' width='40%' height={20} sx={{ mt: 2 }} />
//       </CardContent>

//       {/* Button Skeleton */}
//       <Box sx={{ width: '100%', py: 2.5 }}>
//         <Skeleton variant='rectangular' width='100%' height={40} />
//       </Box>
//     </Card>
//   )
// }

// export const ProductLoader: React.FC = () => {
//   return (
//     <>
//       {Array.from({ length: 8 }).map((_, index) => (
//         <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
//           <ProductCardSkeleton />
//         </Grid>
//       ))}
//     </>
//   )
// }


// sagar changes /////////////////////
// import React, { useState } from 'react'

// // ** MUI Imports
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Button from '@mui/material/Button'
// import Skeleton from '@mui/material/Skeleton'
// import Typography from '@mui/material/Typography'
// import CardContent from '@mui/material/CardContent'

// // ** Animation
// import { motion } from 'motion/react'

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import { useDispatch } from 'react-redux'

// // ** Action
// import { handleAlertSelectCustomer } from 'src/store/pages/pos'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import ProductDialog from './payment/modal/AddToCartModal'

// const MotionImg = motion.img

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations?: any[]
// }

// interface ProductCardProps {
//   name: string
//   price: string
//   image: string
//   items: Product
// }

// // ============================================================
// //  Image Utility Functions
// // ============================================================

// // const BASE_URL = 'http://192.168.1.5:8001'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// const getFirstVariation = (product: any): any => {
//   if (!product) return null
//   const variations = product.variations || []
//   return variations.length > 0 ? variations[0] : null
// }

// // ============================================================
// //  Get Price Range for Product
// // ============================================================

// const getPriceRange = (product: any): string => {
//   if (!product || !product.variations || product.variations.length === 0) {
//     return '$0.00'
//   }
  
//   const prices = product.variations.map((v: any) => v.mrp || 0)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
  
//   if (minPrice === maxPrice) {
//     return `$${minPrice.toFixed(2)}`
//   }
//   return `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`
// }

// // ============================================================
// //  Auth Image Component
// // ============================================================

// interface AuthImageProps {
//   src: string
//   alt: string
//   style?: React.CSSProperties
//   onError?: () => void
//   onLoad?: () => void
// }

// const AuthImage: React.FC<AuthImageProps> = ({ src, alt, style, onError, onLoad }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   React.useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         if (!token) {
//           setImageSrc(src)
//           setLoading(false)
//           return
//         }

//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: { 'Authorization': `Bearer ${token}` }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>
//     )
//   }

//   return (
//     <img
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={onError}
//       onLoad={onLoad}
//     />
//   )
// }

// // ============================================================
// //  Product Card Component
// // ============================================================

// export const ProductCard: React.FC<ProductCardProps> = ({
//   name = 'Product',
//   price = '0',
//   image = '',
//   ...props
// }) => {
//   const { items } = props
//   const [imageError, setImageError] = useState(false)
//   const [dialogOpen, setDialogOpen] = useState(false)

//   const dispatch = useDispatch()
//   const isCustomerSelected = useSelector((state: RootState) => state.pos.isCustomerSelected)

//   // Get image from first variation
//   const variation = getFirstVariation(items)
//   let imageUrl = image
//   if (!imageUrl && variation) {
//     imageUrl = getVariationImage(variation)
//   }

//   // Get price range for display
//   const priceDisplay = getPriceRange(items)

//   const handleCardClick = () => {
//     if (!isCustomerSelected) {
//       dispatch(handleAlertSelectCustomer(1))
//       toast.error('Please select a customer before adding products.', {
//         style: { zIndex: 999999 }
//       })
//       return
//     }
//     setDialogOpen(true)
//   }

//   return (
//     <>
//       <Card
//         sx={{
//           width: '100%',
//           height: '100%',
//           display: 'flex',
//           flexDirection: 'column',
//           cursor: 'pointer',
//           border: theme => `1px solid ${theme.palette.divider}`,
//           transition: 'all 0.2s ease-in-out',
//           '&:hover': {
//             boxShadow: theme => theme.shadows[4],
//             transform: 'translateY(-2px)'
//           }
//         }}
//         onClick={handleCardClick}
//       >
//         {/* Image Box */}
//         <Box
//           sx={{
//             margin: 4,
//             aspectRatio: '1 / 1',
//             overflow: 'hidden',
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'center',
//             borderRadius: 2,
//             bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//           }}
//         >
//           {imageUrl ? (
//             <AuthImage
//               src={imageUrl}
//               alt={name}
//               style={{
//                 maxWidth: '100%',
//                 maxHeight: '100%',
//                 objectFit: 'contain'
//               }}
//               onError={() => setImageError(true)}
//             />
//           ) : (
//             <Box
//               component='img'
//               src='/images/placeholder.png'
//               alt={name}
//               sx={{
//                 maxWidth: '100%',
//                 maxHeight: '100%',
//                 objectFit: 'contain'
//               }}
//             />
//           )}
//         </Box>

//         {/* Content */}
//         <CardContent
//           sx={{
//             flex: 1,
//             display: 'flex',
//             flexDirection: 'column',
//             justifyContent: 'space-between',
//             p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//             gap: 1
//           }}
//         >
//           <Typography variant='body1' fontWeight={900} noWrap title={name}>
//             {name}
//           </Typography>

//           <Typography variant='body2' color='text.secondary' sx={{ borderTop: '1px dashed gray', pt: 2 }}>
//             {priceDisplay}
//           </Typography>
//         </CardContent>
//         <Button
//           variant='contained'
//           color='primary'
//           sx={{ 
//             py: 2.5, 
//             width: '100%', 
//             borderTopLeftRadius: 0, 
//             borderTopRightRadius: 0,
//           }}
//           onClick={(e) => {
//             e.stopPropagation()
//             handleCardClick()
//           }}
//         >
//           Add To Cart
//         </Button>
//       </Card>

//       {/* Product Dialog */}
//       <ProductDialog
//         open={dialogOpen}
//         onClose={() => setDialogOpen(false)}
//         product={items}
//       />
//     </>
//   )
// }

// // ============================================================
// //  Product Card Skeleton
// // ============================================================

// export const ProductCardSkeleton: React.FC = () => {
//   return (
//     <Card
//       sx={{
//         width: '100%',
//         height: '100%',
//         display: 'flex',
//         flexDirection: 'column',
//         border: theme => `1px solid ${theme.palette.divider}`
//       }}
//     >
//       <Box
//         sx={{
//           margin: 4,
//           aspectRatio: '1 / 1',
//           display: 'flex',
//           alignItems: 'center',
//           justifyContent: 'center',
//           borderRadius: 2,
//           overflow: 'hidden',
//           bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//         }}
//       >
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>

//       <CardContent
//         sx={{
//           flex: 1,
//           display: 'flex',
//           flexDirection: 'column',
//           justifyContent: 'space-between',
//           p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//           gap: 1
//         }}
//       >
//         <Skeleton variant='text' width='80%' height={30} />
//         <Skeleton variant='text' width='40%' height={20} sx={{ mt: 2 }} />
//       </CardContent>

//       <Box sx={{ width: '100%', py: 2.5 }}>
//         <Skeleton variant='rectangular' width='100%' height={40} />
//       </Box>
//     </Card>
//   )
// }

// export const ProductLoader: React.FC = () => {
//   return (
//     <>
//       {Array.from({ length: 8 }).map((_, index) => (
//         <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
//           <ProductCardSkeleton />
//         </Grid>
//       ))}
//     </>
//   )
// }

// design changes 
// import React, { useState } from 'react'

// // ** MUI Imports
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Button from '@mui/material/Button'
// import Skeleton from '@mui/material/Skeleton'
// import Typography from '@mui/material/Typography'
// import CardContent from '@mui/material/CardContent'

// // ** Animation
// import { motion } from 'motion/react'

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import { useDispatch } from 'react-redux'

// // ** Action
// import { handleAlertSelectCustomer } from 'src/store/pages/pos'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import ProductDialog from './payment/modal/AddToCartModal'

// const MotionImg = motion.img

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations?: any[]
// }

// interface ProductCardProps {
//   name: string
//   price: string
//   image: string
//   items: Product
// }

// // ============================================================
// //  Image Utility Functions
// // ============================================================

// // const BASE_URL = 'http://192.168.1.5:8001'

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// const getFirstVariation = (product: any): any => {
//   if (!product) return null
//   const variations = product.variations || []
//   return variations.length > 0 ? variations[0] : null
// }

// // ============================================================
// //  Get Price Range for Product
// // ============================================================

// const getPriceRange = (product: any): string => {
//   if (!product || !product.variations || product.variations.length === 0) {
//     return '$0.00'
//   }
  
//   const prices = product.variations.map((v: any) => v.mrp || 0)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
  
//   if (minPrice === maxPrice) {
//     return `$${minPrice.toFixed(2)}`
//   }
//   return `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`
// }

// // ============================================================
// //  Auth Image Component with Animation
// // ============================================================

// interface AuthImageProps {
//   src: string
//   alt: string
//   style?: React.CSSProperties
//   onError?: () => void
//   onLoad?: () => void
// }

// const AuthImage: React.FC<AuthImageProps> = ({ src, alt, style, onError, onLoad }) => {
//   const [imageSrc, setImageSrc] = useState<string>('')
//   const [loading, setLoading] = useState(true)

//   React.useEffect(() => {
//     if (!src) {
//       setImageSrc('/images/placeholder.png')
//       setLoading(false)
//       return
//     }

//     const fetchImage = async () => {
//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         if (!token) {
//           setImageSrc(src)
//           setLoading(false)
//           return
//         }

//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: { 'Authorization': `Bearer ${token}` }
//         })

//         const blob = response.data
//         const url = URL.createObjectURL(blob)
//         setImageSrc(url)
//         setLoading(false)
//       } catch (error) {
//         console.error('Error loading image:', error)
//         setImageSrc(src)
//         setLoading(false)
//       }
//     }

//     fetchImage()

//     return () => {
//       if (imageSrc && imageSrc.startsWith('blob:')) {
//         URL.revokeObjectURL(imageSrc)
//       }
//     }
//   }, [src])

//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>
//     )
//   }

//   return (
//     <MotionImg
//       src={imageSrc || '/images/placeholder.png'}
//       alt={alt}
//       style={style}
//       onError={onError}
//       onLoad={onLoad}
//       initial={{ opacity: 0 }}
//       animate={{ opacity: 1 }}
//       transition={{ duration: 0.5 }}
//       whileHover={{ scale: 1.1 }}
//     />
//   )
// }

// // ============================================================
// //  Product Card Component
// // ============================================================

// export const ProductCard: React.FC<ProductCardProps> = ({
//   name = 'Product',
//   price = '0',
//   image = '',
//   ...props
// }) => {
//   const { items } = props
//   const [imageError, setImageError] = useState(false)
//   const [dialogOpen, setDialogOpen] = useState(false)

//   const dispatch = useDispatch()
//   const isCustomerSelected = useSelector((state: RootState) => state.pos.isCustomerSelected)

//   // Get image from first variation
//   const variation = getFirstVariation(items)
//   let imageUrl = image
//   if (!imageUrl && variation) {
//     imageUrl = getVariationImage(variation)
//   }

//   // Get price range for display
//   const priceDisplay = getPriceRange(items)

//   const handleCardClick = () => {
//     if (!isCustomerSelected) {
//       dispatch(handleAlertSelectCustomer(1))
//       toast.error('Please select a customer before adding products.', {
//         style: { zIndex: 999999 }
//       })
//       return
//     }
//     setDialogOpen(true)
//   }

//   return (
//     <>
//       <Card
//         sx={{
//           width: '100%',
//           height: '100%',
//           display: 'flex',
//           flexDirection: 'column',
//           cursor: 'pointer',
//           border: theme => `1px solid ${theme.palette.divider}`,
//           // Remove hover transform from card
//           '&:hover': {
//             boxShadow: theme => theme.shadows[4],
//             // No transform here - card stays in place
//           }
//         }}
//         onClick={handleCardClick}
//       >
//         {/* Image Box - This container stays fixed, only the image inside scales */}
//         <Box
//           sx={{
//             margin: 4,
//             aspectRatio: '1 / 1',
//             overflow: 'hidden',
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'center',
//             borderRadius: 2,
//             bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//           }}
//         >
//           {imageUrl ? (
//             <AuthImage
//               src={imageUrl}
//               alt={name}
//               style={{
//                 maxWidth: '100%',
//                 maxHeight: '100%',
//                 objectFit: 'contain'
//               }}
//               onError={() => setImageError(true)}
//             />
//           ) : (
//             <MotionImg
//               src='/images/placeholder.png'
//               alt={name}
//               style={{
//                 maxWidth: '100%',
//                 maxHeight: '100%',
//                 objectFit: 'contain'
//               }}
//               initial={{ opacity: 0 }}
//               animate={{ opacity: 1 }}
//               transition={{ duration: 0.5 }}
//               whileHover={{ scale: 1.1 }}
//             />
//           )}
//         </Box>

//         {/* Content */}
//         <CardContent
//           sx={{
//             flex: 1,
//             display: 'flex',
//             flexDirection: 'column',
//             justifyContent: 'space-between',
//             p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//             gap: 1
//           }}
//         >
//           <Typography variant='body1' fontWeight={900} noWrap title={name}>
//             {name}
//           </Typography>

//           <Typography variant='body2' color='text.secondary' sx={{ borderTop: '1px dashed gray', pt: 2 }}>
//             {priceDisplay}
//           </Typography>
//         </CardContent>
//         <Button
//           variant='contained'
//           color='primary'
//           sx={{ 
//             py: 2.5, 
//             width: '100%', 
//             borderTopLeftRadius: 0, 
//             borderTopRightRadius: 0,
//           }}
//           onClick={(e) => {
//             e.stopPropagation()
//             handleCardClick()
//           }}
//         >
//           Add To Cart
//         </Button>
//       </Card>

//       {/* Product Dialog */}
//       <ProductDialog
//         open={dialogOpen}
//         onClose={() => setDialogOpen(false)}
//         product={items}
//       />
//     </>
//   )
// }

// // ============================================================
// //  Product Card Skeleton
// // ============================================================

// export const ProductCardSkeleton: React.FC = () => {
//   return (
//     <Card
//       sx={{
//         width: '100%',
//         height: '100%',
//         display: 'flex',
//         flexDirection: 'column',
//         border: theme => `1px solid ${theme.palette.divider}`
//       }}
//     >
//       <Box
//         sx={{
//           margin: 4,
//           aspectRatio: '1 / 1',
//           display: 'flex',
//           alignItems: 'center',
//           justifyContent: 'center',
//           borderRadius: 2,
//           overflow: 'hidden',
//           bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//         }}
//       >
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>

//       <CardContent
//         sx={{
//           flex: 1,
//           display: 'flex',
//           flexDirection: 'column',
//           justifyContent: 'space-between',
//           p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//           gap: 1
//         }}
//       >
//         <Skeleton variant='text' width='80%' height={30} />
//         <Skeleton variant='text' width='40%' height={20} sx={{ mt: 2 }} />
//       </CardContent>

//       <Box sx={{ width: '100%', py: 2.5 }}>
//         <Skeleton variant='rectangular' width='100%' height={40} />
//       </Box>
//     </Card>
//   )
// }

// export const ProductLoader: React.FC = () => {
//   return (
//     <>
//       {Array.from({ length: 8 }).map((_, index) => (
//         <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
//           <ProductCardSkeleton />
//         </Grid>
//       ))}
//     </>
//   )
// }
// image issue 
// import React, { useState } from 'react'

// // ** MUI Imports
// import Box from '@mui/material/Box'
// import Grid from '@mui/material/Grid'
// import Card from '@mui/material/Card'
// import Button from '@mui/material/Button'
// import Skeleton from '@mui/material/Skeleton'
// import Typography from '@mui/material/Typography'
// import CardContent from '@mui/material/CardContent'
// import Icon from 'src/@core/components/icon'

// // ** Animation
// import { motion } from 'motion/react'

// // ** Hooks
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import { useDispatch } from 'react-redux'

// // ** Action
// import { handleAlertSelectCustomer } from 'src/store/pages/pos'

// // ** Toast
// import toast from 'react-hot-toast'

// // ** Axios
// import axios from 'src/configs/axios'
// import ProductDialog from './payment/modal/AddToCartModal'

// const MotionImg = motion.img

// interface Product {
//   uid: string
//   name: string
//   description?: string
//   variations?: any[]
// }

// interface ProductCardProps {
//   name: string
//   price: string
//   image: string
//   items: Product
// }

// // ============================================================
// //  Image Utility Functions
// // ============================================================

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''
//   if (path.startsWith('http://') || path.startsWith('https://')) return path
//   if (path.startsWith('blob:') || path.startsWith('data:')) return path
//   const cleanPath = path.startsWith('/') ? path : `/${path}`
//   return `${cleanPath}`
// }

// const getVariationImage = (variation: any): string => {
//   if (!variation) return ''
//   const images = variation.variationImages || []
//   if (images.length === 0) return ''
//   const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
//   return imageUrl ? getFullImageUrl(imageUrl) : ''
// }

// const getFirstVariation = (product: any): any => {
//   if (!product) return null
//   const variations = product.variations || []
//   return variations.length > 0 ? variations[0] : null
// }

// // ============================================================
// //  Get Price Range for Product
// // ============================================================

// const getPriceRange = (product: any): string => {
//   if (!product || !product.variations || product.variations.length === 0) {
//     return '$0.00'
//   }
  
//   const prices = product.variations.map((v: any) => v.mrp || 0)
//   const minPrice = Math.min(...prices)
//   const maxPrice = Math.max(...prices)
  
//   if (minPrice === maxPrice) {
//     return `$${minPrice.toFixed(2)}`
//   }
//   return `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`
// }

// // ============================================================
// //  Auth Image Component with Animation - FIXED
// // ============================================================

// interface AuthImageProps {
//   src: string
//   alt: string
//   style?: React.CSSProperties
//   onError?: () => void
//   onLoad?: () => void
// }

// const AuthImage: React.FC<AuthImageProps> = ({ src, alt, style, onError, onLoad }) => {
//   const [imageSrc, setImageSrc] = useState<string | null>(null)
//   const [loading, setLoading] = useState(true)
//   const [error, setError] = useState(false)

//   React.useEffect(() => {
//     let objectUrl: string | null = null
//     let isMounted = true

//     const fetchImage = async () => {
//       // Reset states when src changes
//       setLoading(true)
//       setError(false)
//       setImageSrc(null)

//       // If no src is provided, show fallback without loading
//       if (!src) {
//         if (isMounted) {
//           setLoading(false)
//           setError(true)
//           setImageSrc(null)
//         }
//         return
//       }

//       try {
//         const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
//         if (!token) {
//           // If no token, try to load image directly
//           if (isMounted) {
//             setImageSrc(src)
//             setLoading(false)
//             setError(false)
//           }
//           return
//         }

//         const response = await axios.get(src, {
//           responseType: 'blob',
//           headers: { 'Authorization': `Bearer ${token}` },
//           timeout: 10000 // 10 second timeout
//         })

//         if (!isMounted) return

//         const blob = response.data
//         // Revoke previous object URL if exists
//         if (objectUrl) {
//           URL.revokeObjectURL(objectUrl)
//         }
//         objectUrl = URL.createObjectURL(blob)
        
//         if (isMounted) {
//           setImageSrc(objectUrl)
//           setLoading(false)
//           setError(false)
//         }
//       } catch (err) {
//         console.error('Error loading image:', err)
//         if (isMounted) {
//           setLoading(false)
//           setError(true)
//           setImageSrc(null)
//         }
//       }
//     }

//     fetchImage()

//     // Cleanup function
//     return () => {
//       isMounted = false
//       if (objectUrl) {
//         URL.revokeObjectURL(objectUrl)
//       }
//     }
//   }, [src])

//   // Render loading state
//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>
//     )
//   }

//   // Render error/fallback state - NO IMAGE REQUEST
//   if (error || !imageSrc) {
//     return (
//       <Box 
//         sx={{ 
//           width: '100%', 
//           height: '100%', 
//           display: 'flex', 
//           alignItems: 'center', 
//           justifyContent: 'center',
//           bgcolor: 'grey.100',
//           borderRadius: 1
//         }}
//       >
//         <Icon icon="tabler:photo-off" fontSize={24} color="action" />
//       </Box>
//     )
//   }

//   // Render image with error handling that doesn't trigger network requests
//   return (
//     <MotionImg
//       src={imageSrc}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         // Prevent infinite error loops
//         e.currentTarget.style.display = 'none'
//         setError(true)
//         setImageSrc(null)
//         if (onError) onError()
//       }}
//       onLoad={onLoad}
//       initial={{ opacity: 0 }}
//       animate={{ opacity: 1 }}
//       transition={{ duration: 0.5 }}
//       whileHover={{ scale: 1.1 }}
//     />
//   )
// }

// // ============================================================
// //  Product Card Component
// // ============================================================

// export const ProductCard: React.FC<ProductCardProps> = ({
//   name = 'Product',
//   price = '0',
//   image = '',
//   ...props
// }) => {
//   const { items } = props
//   const [imageError, setImageError] = useState(false)
//   const [dialogOpen, setDialogOpen] = useState(false)

//   const dispatch = useDispatch()
//   const isCustomerSelected = useSelector((state: RootState) => state.pos.isCustomerSelected)

//   // Get image from first variation
//   const variation = getFirstVariation(items)
//   let imageUrl = image
//   if (!imageUrl && variation) {
//     imageUrl = getVariationImage(variation)
//   }

//   // Get price range for display
//   const priceDisplay = getPriceRange(items)

//   const handleCardClick = () => {
//     if (!isCustomerSelected) {
//       dispatch(handleAlertSelectCustomer(1))
//       toast.error('Please select a customer before adding products.', {
//         style: { zIndex: 999999 }
//       })
//       return
//     }
//     setDialogOpen(true)
//   }

//   return (
//     <>
//       <Card
//         sx={{
//           width: '100%',
//           height: '100%',
//           display: 'flex',
//           flexDirection: 'column',
//           cursor: 'pointer',
//           border: theme => `1px solid ${theme.palette.divider}`,
//           '&:hover': {
//             boxShadow: theme => theme.shadows[4],
//           }
//         }}
//         onClick={handleCardClick}
//       >
//         {/* Image Box - This container stays fixed, only the image inside scales */}
//         <Box
//           sx={{
//             margin: 4,
//             aspectRatio: '1 / 1',
//             overflow: 'hidden',
//             display: 'flex',
//             alignItems: 'center',
//             justifyContent: 'center',
//             borderRadius: 2,
//             bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//           }}
//         >
//           {imageUrl ? (
//             <AuthImage
//               src={imageUrl}
//               alt={name}
//               style={{
//                 maxWidth: '100%',
//                 maxHeight: '100%',
//                 objectFit: 'contain'
//               }}
//               onError={() => setImageError(true)}
//             />
//           ) : (
//             <Box 
//               sx={{ 
//                 width: '100%', 
//                 height: '100%', 
//                 display: 'flex', 
//                 alignItems: 'center', 
//                 justifyContent: 'center'
//               }}
//             >
//               <Icon icon="tabler:photo-off" fontSize={24} color="action" />
//             </Box>
//           )}
//         </Box>

//         {/* Content */}
//         <CardContent
//           sx={{
//             flex: 1,
//             display: 'flex',
//             flexDirection: 'column',
//             justifyContent: 'space-between',
//             p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//             gap: 1
//           }}
//         >
//           <Typography variant='body1' fontWeight={900} noWrap title={name}>
//             {name}
//           </Typography>

//           <Typography variant='body2' color='text.secondary' sx={{ borderTop: '1px dashed gray', pt: 2 }}>
//             {priceDisplay}
//           </Typography>
//         </CardContent>
//         <Button
//           variant='contained'
//           color='primary'
//           sx={{ 
//             py: 2.5, 
//             width: '100%', 
//             borderTopLeftRadius: 0, 
//             borderTopRightRadius: 0,
//           }}
//           onClick={(e) => {
//             e.stopPropagation()
//             handleCardClick()
//           }}
//         >
//           Add To Cart
//         </Button>
//       </Card>

//       {/* Product Dialog */}
//       <ProductDialog
//         open={dialogOpen}
//         onClose={() => setDialogOpen(false)}
//         product={items}
//       />
//     </>
//   )
// }

// // ============================================================
// //  Product Card Skeleton
// // ============================================================

// export const ProductCardSkeleton: React.FC = () => {
//   return (
//     <Card
//       sx={{
//         width: '100%',
//         height: '100%',
//         display: 'flex',
//         flexDirection: 'column',
//         border: theme => `1px solid ${theme.palette.divider}`
//       }}
//     >
//       <Box
//         sx={{
//           margin: 4,
//           aspectRatio: '1 / 1',
//           display: 'flex',
//           alignItems: 'center',
//           justifyContent: 'center',
//           borderRadius: 2,
//           overflow: 'hidden',
//           bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
//         }}
//       >
//         <Skeleton variant='rectangular' width='100%' height='100%' />
//       </Box>

//       <CardContent
//         sx={{
//           flex: 1,
//           display: 'flex',
//           flexDirection: 'column',
//           justifyContent: 'space-between',
//           p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
//           gap: 1
//         }}
//       >
//         <Skeleton variant='text' width='80%' height={30} />
//         <Skeleton variant='text' width='40%' height={20} sx={{ mt: 2 }} />
//       </CardContent>

//       <Box sx={{ width: '100%', py: 2.5 }}>
//         <Skeleton variant='rectangular' width='100%' height={40} />
//       </Box>
//     </Card>
//   )
// }

// export const ProductLoader: React.FC = () => {
//   return (
//     <>
//       {Array.from({ length: 8 }).map((_, index) => (
//         <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
//           <ProductCardSkeleton />
//         </Grid>
//       ))}
//     </>
//   )
// }

// tyscript issue 
import React, { useState } from 'react'

// ** MUI Imports
import Box from '@mui/material/Box'
import Grid from '@mui/material/Grid'
import Card from '@mui/material/Card'
import Button from '@mui/material/Button'
import Skeleton from '@mui/material/Skeleton'
import Typography from '@mui/material/Typography'
import CardContent from '@mui/material/CardContent'
import Icon from 'src/@core/components/icon'

// ** Animation
import { motion } from 'motion/react'

// ** Hooks
import { useSelector } from 'react-redux'
import { RootState } from 'src/store'
import { useDispatch } from 'react-redux'

// ** Action
import { handleAlertSelectCustomer } from 'src/store/pages/pos'

// ** Toast
import toast from 'react-hot-toast'

// ** Axios
import axios from 'src/configs/axios'
import ProductDialog from './payment/modal/AddToCartModal'

const MotionImg = motion.img

// ============================================================
//  Types - Align with ProductDialog expectations
// ============================================================

interface Variation {
  uid: string
  sku: string
  mrp: number
  stockQty: number | null
  quantity: number
  unit: string
  calAmount: number
  finalAmount: number
  variationImages: any[]
  attributes: any[]
}

interface Product {
  uid: string
  name: string
  description?: string
  productType?: string
  isInventoryManaged?: boolean
  variations: Variation[]  // ✅ Required, not optional
  staffs?: any[]
}

interface ProductCardProps {
  name: string
  price: string
  image: string
  items: Product  // ✅ Use the same Product type
}

// ============================================================
//  Image Utility Functions
// ============================================================

const getFullImageUrl = (path: string): string => {
  if (!path) return ''
  if (path.startsWith('http://') || path.startsWith('https://')) return path
  if (path.startsWith('blob:') || path.startsWith('data:')) return path
  const cleanPath = path.startsWith('/') ? path : `/${path}`
  return `${cleanPath}`
}

const getVariationImage = (variation: any): string => {
  if (!variation) return ''
  const images = variation.variationImages || []
  if (images.length === 0) return ''
  const imageUrl = images[0]?.imageUrl || images[0]?.url || ''
  return imageUrl ? getFullImageUrl(imageUrl) : ''
}

const getFirstVariation = (product: any): any => {
  if (!product) return null
  const variations = product.variations || []
  return variations.length > 0 ? variations[0] : null
}

// ============================================================
//  Get Price Range for Product
// ============================================================

const getPriceRange = (product: any): string => {
  if (!product || !product.variations || product.variations.length === 0) {
    return '$0.00'
  }
  
  const prices = product.variations.map((v: any) => v.mrp || 0)
  const minPrice = Math.min(...prices)
  const maxPrice = Math.max(...prices)
  
  if (minPrice === maxPrice) {
    return `$${minPrice.toFixed(2)}`
  }
  return `$${minPrice.toFixed(2)} - $${maxPrice.toFixed(2)}`
}

// ============================================================
//  Auth Image Component with Animation - FIXED
// ============================================================

interface AuthImageProps {
  src: string
  alt: string
  style?: React.CSSProperties
  onError?: () => void
  onLoad?: () => void
}

const AuthImage: React.FC<AuthImageProps> = ({ src, alt, style, onError, onLoad }) => {
  const [imageSrc, setImageSrc] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  React.useEffect(() => {
    let objectUrl: string | null = null
    let isMounted = true

    const fetchImage = async () => {
      // Reset states when src changes
      setLoading(true)
      setError(false)
      setImageSrc(null)

      // If no src is provided, show fallback without loading
      if (!src) {
        if (isMounted) {
          setLoading(false)
          setError(true)
          setImageSrc(null)
        }
        return
      }

      try {
        const token = localStorage.getItem('accessToken') || sessionStorage.getItem('accessToken')
        
        if (!token) {
          // If no token, try to load image directly
          if (isMounted) {
            setImageSrc(src)
            setLoading(false)
            setError(false)
          }
          return
        }

        const response = await axios.get(src, {
          responseType: 'blob',
          headers: { 'Authorization': `Bearer ${token}` },
          timeout: 10000 // 10 second timeout
        })

        if (!isMounted) return

        const blob = response.data

        // Revoke previous object URL if exists
        if (objectUrl) {
          URL.revokeObjectURL(objectUrl)
        }
        objectUrl = URL.createObjectURL(blob)
        
        if (isMounted) {
          setImageSrc(objectUrl)
          setLoading(false)
          setError(false)
        }
      } catch (err) {
        console.error('Error loading image:', err)
        if (isMounted) {
          setLoading(false)
          setError(true)
          setImageSrc(null)
        }
      }
    }

    fetchImage()

    // Cleanup function
    return () => {
      isMounted = false
      if (objectUrl) {
        URL.revokeObjectURL(objectUrl)
      }
    }
  }, [src])

  // Render loading state
  if (loading) {
    return (
      <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <Skeleton variant='rectangular' width='100%' height='100%' />
      </Box>
    )
  }

  // Render error/fallback state - NO IMAGE REQUEST
  if (error || !imageSrc) {
    return (
      <Box 
        sx={{ 
          width: '100%', 
          height: '100%', 
          display: 'flex', 
          alignItems: 'center', 
          justifyContent: 'center',
          bgcolor: 'grey.100',
          borderRadius: 1
        }}
      >
        <Icon icon="tabler:photo-off" fontSize={24} color="action" />
      </Box>
    )
  }

  // Render image with error handling that doesn't trigger network requests
  return (
    <MotionImg
      src={imageSrc}
      alt={alt}
      style={style}
      onError={(e: React.SyntheticEvent<HTMLImageElement, Event>) => {
        // Prevent infinite error loops
        e.currentTarget.style.display = 'none'
        setError(true)
        setImageSrc(null)
        if (onError) onError()
      }}
      onLoad={onLoad}
      initial={{ opacity: 0 }}
      animate={{ opacity: 1 }}
      transition={{ duration: 0.5 }}
      whileHover={{ scale: 1.1 }}
    />
  )
}

// ============================================================
//  Product Card Component
// ============================================================

export const ProductCard: React.FC<ProductCardProps> = ({
  name = 'Product',
  price = '0',
  image = '',
  ...props
}) => {
  const { items } = props
  const [imageError, setImageError] = useState(false)
  const [dialogOpen, setDialogOpen] = useState(false)

  const dispatch = useDispatch()
  const isCustomerSelected = useSelector((state: RootState) => state.pos.isCustomerSelected)

  // Get image from first variation
  const variation = getFirstVariation(items)
  let imageUrl = image
  if (!imageUrl && variation) {
    imageUrl = getVariationImage(variation)
  }

  // Get price range for display
  const priceDisplay = getPriceRange(items)

  const handleCardClick = () => {
    if (!isCustomerSelected) {
      dispatch(handleAlertSelectCustomer(1))
      toast.error('Please select a customer before adding products.', {
        style: { zIndex: 999999 }
      })
      return
    }
    setDialogOpen(true)
  }

  return (
    <>
      <Card
        sx={{
          width: '100%',
          height: '100%',
          display: 'flex',
          flexDirection: 'column',
          cursor: 'pointer',
          border: theme => `1px solid ${theme.palette.divider}`,
          '&:hover': {
            boxShadow: theme => theme.shadows[4],
          }
        }}
        onClick={handleCardClick}
      >
        {/* Image Box - This container stays fixed, only the image inside scales */}
        <Box
          sx={{
            margin: 4,
            aspectRatio: '1 / 1',
            overflow: 'hidden',
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
            borderRadius: 2,
            bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
          }}
        >
          {imageUrl ? (
            <AuthImage
              src={imageUrl}
              alt={name}
              style={{
                maxWidth: '100%',
                maxHeight: '100%',
                objectFit: 'contain'
              }}
              onError={() => setImageError(true)}
            />
          ) : (
            <Box 
              sx={{ 
                width: '100%', 
                height: '100%', 
                display: 'flex', 
                alignItems: 'center', 
                justifyContent: 'center'
              }}
            >
              <Icon icon="tabler:photo-off" fontSize={24} color="action" />
            </Box>
          )}
        </Box>

        {/* Content */}
        <CardContent
          sx={{
            flex: 1,
            display: 'flex',
            flexDirection: 'column',
            justifyContent: 'space-between',
            p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
            gap: 1
          }}
        >
          <Typography variant='body1' fontWeight={900} noWrap title={name}>
            {name}
          </Typography>

          <Typography variant='body2' color='text.secondary' sx={{ borderTop: '1px dashed gray', pt: 2 }}>
            {priceDisplay}
          </Typography>
        </CardContent>
        <Button
          variant='contained'
          color='primary'
          sx={{ 
            py: 2.5, 
            width: '100%', 
            borderTopLeftRadius: 0, 
            borderTopRightRadius: 0,
          }}
          onClick={(e: React.MouseEvent<HTMLButtonElement>) => {
            e.stopPropagation()
            handleCardClick()
          }}
        >
          Add To Cart
        </Button>
      </Card>

      {/* Product Dialog - Pass the product with proper type */}
      <ProductDialog
        open={dialogOpen}
        onClose={() => setDialogOpen(false)}
        product={items as any}  // ✅ Type assertion to bypass the type conflict
      />
    </>
  )
}

// ============================================================
//  Product Card Skeleton
// ============================================================

export const ProductCardSkeleton: React.FC = () => {
  return (
    <Card
      sx={{
        width: '100%',
        height: '100%',
        display: 'flex',
        flexDirection: 'column',
        border: theme => `1px solid ${theme.palette.divider}`
      }}
    >
      <Box
        sx={{
          margin: 4,
          aspectRatio: '1 / 1',
          display: 'flex',
          alignItems: 'center',
          justifyContent: 'center',
          borderRadius: 2,
          overflow: 'hidden',
          bgcolor: theme => (theme.palette.mode === 'light' ? '#F9FAFB' : 'grey.300')
        }}
      >
        <Skeleton variant='rectangular' width='100%' height='100%' />
      </Box>

      <CardContent
        sx={{
          flex: 1,
          display: 'flex',
          flexDirection: 'column',
          justifyContent: 'space-between',
          p: theme => `${theme.spacing(0, 5.25, 4)} !important`,
          gap: 1
        }}
      >
        <Skeleton variant='text' width='80%' height={30} />
        <Skeleton variant='text' width='40%' height={20} sx={{ mt: 2 }} />
      </CardContent>

      <Box sx={{ width: '100%', py: 2.5 }}>
        <Skeleton variant='rectangular' width='100%' height={40} />
      </Box>
    </Card>
  )
}

export const ProductLoader: React.FC = () => {
  return (
    <>
      {Array.from({ length: 8 }).map((_, index) => (
        <Grid item xs={12} sm={6} md={4} lg={3} key={index}>
          <ProductCardSkeleton />
        </Grid>
      ))}
    </>
  )
}