// import React from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'

// // ** Redux Hook
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'

// // ** Components
// import { ProductCard, ProductLoader } from './ProductRender'

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

// const ProductArea = () => {
//   const { list, loading } = useSelector((state: RootState) => state.pos)

//   // ** Render Product
//   const renderProduct = list.map((item: Product) => (
//     <Grid item xs={12} sm={6} md={4} lg={3} key={item.id}>
//       <ProductCard name={item.name} price={item.price} image={item.image} items={item} />
//     </Grid>
//   ))

//   return (
//     <Grid container spacing={4}>
//       {loading ? <ProductLoader /> : renderProduct}
//     </Grid>
//   )
// }

// export default ProductArea


// sagar changes ////////////////////
// import React from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'

// // ** Redux Hook
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import axios from 'src/configs/axios'

// // ** Components
// import { ProductCard, ProductLoader } from './ProductRender'

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

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

// /**
//  * Get the full image URL from a relative path
//  */
// // const getFullImageUrl = (path: string): string => {
// //   if (!path) return '/images/placeholder.png'
  
// //   if (path.startsWith('http://') || path.startsWith('https://')) {
// //     return path
// //   }
  
// //   if (path.startsWith('blob:') || path.startsWith('data:')) {
// //     return path
// //   }
  
// //   const baseUrl = 'http://192.168.1.5:8001'
// //   const cleanPath = path.startsWith('/') ? path : `/${path}`
  
// //   return `${baseUrl}${cleanPath}`
// // }
// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''

//   if (
//     path.startsWith('http://') ||
//     path.startsWith('https://') ||
//     path.startsWith('blob:') ||
//     path.startsWith('data:')
//   ) {
//     return path
//   }

//   const cleanPath = path.startsWith('/') ? path : `/${path}`

//   return `${axios.defaults.baseURL}${cleanPath}`
// }


// /**
//  * Get the first image from a variation
//  */
// const getVariationImage = (variation: any): string => {
//   if (!variation) return '/images/placeholder.png'
  
//   const images = variation.variationImages || []
//   if (images.length === 0) return '/images/placeholder.png'
  
//   const imageObj = images[0]
//   const imageUrl = imageObj?.imageUrl || imageObj?.url || ''
  
//   if (!imageUrl) return '/images/placeholder.png'
  
//   return getFullImageUrl(imageUrl)
// }

// /**
//  * Get the first variation from a product
//  */
// const getFirstVariation = (product: any): any => {
//   if (!product) return null
//   const variations = product.variations || []
//   return variations.length > 0 ? variations[0] : null
// }

// const ProductArea = () => {
//   const { list, loading, searchTerm } = useSelector((state: RootState) => state.pos)

//   // Filter products based on search term
//   const filteredProducts = React.useMemo(() => {
//     if (!searchTerm) return list
//     return list.filter((product: Product) =>
//       product.name.toLowerCase().includes(searchTerm.toLowerCase())
//     )
//   }, [list, searchTerm])

//   // Render Product
//   const renderProduct = filteredProducts.map((item: Product) => {
//     const variation = getFirstVariation(item)
//     const price = variation?.mrp || 0
    
//     let imageUrl = '/images/placeholder.png'
//     if (variation) {
//       imageUrl = getVariationImage(variation)
//     }
    
//     return (
//       <Grid item xs={12} sm={6} md={4} lg={3} key={item.uid}>
//         <ProductCard
//           name={item.name}
//           price={price}
//           image={imageUrl}
//           items={item}
//         />
//       </Grid>
//     )
//   })

//   if (loading) {
//     return (
//       <Grid container spacing={4}>
//         <ProductLoader />
//       </Grid>
//     )
//   }

//   if (filteredProducts.length === 0) {
//     return (
//       <Box sx={{ 
//         display: 'flex', 
//         flexDirection: 'column', 
//         alignItems: 'center', 
//         justifyContent: 'center',
//         py: 8,
//         width: '100%'
//       }}>
//         <Typography variant='h6' color='text.secondary'>
//           {searchTerm ? 'No products found matching your search' : 'No products available'}
//         </Typography>
//         {searchTerm && (
//           <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
//             Try adjusting your search terms
//           </Typography>
//         )}
//       </Box>
//     )
//   }

//   return (
//     <Grid container spacing={4}>
//       {renderProduct}
//     </Grid>
//   )
// }

// export default ProductArea

// product issue solved 
// import React, { useMemo } from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'

// // ** Redux Hook
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import axios from 'src/configs/axios'

// // ** Components
// import { ProductCard, ProductLoader } from './ProductRender'

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

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''

//   if (
//     path.startsWith('http://') ||
//     path.startsWith('https://') ||
//     path.startsWith('blob:') ||
//     path.startsWith('data:')
//   ) {
//     return path
//   }

//   const cleanPath = path.startsWith('/') ? path : `/${path}`

//   return `${axios.defaults.baseURL}${cleanPath}`
// }

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

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

// const ProductArea = () => {
//   const { list, loading, searchTerm } = useSelector((state: RootState) => state.pos)

//   // Filter products based on search term
//   const filteredProducts = useMemo(() => {
//     if (!searchTerm) return list
//     return list.filter((product: Product) =>
//       product.name.toLowerCase().includes(searchTerm.toLowerCase())
//     )
//   }, [list, searchTerm])

//   // Render Product
//   const renderProduct = filteredProducts.map((item: Product) => {
//     const variation = getFirstVariation(item)
//     const price = variation?.mrp || 0
    
//     let imageUrl = '/images/placeholder.png'
//     if (variation) {
//       imageUrl = getVariationImage(variation)
//     }
    
//     return (
//       <Grid item xs={12} sm={6} md={4} lg={3} key={item.uid}>
//         <ProductCard
//           name={item.name}
//           price={price}
//           image={imageUrl}
//           items={item}
//         />
//       </Grid>
//     )
//   })

//   if (loading) {
//     return (
//       <Grid container spacing={4}>
//         <ProductLoader />
//       </Grid>
//     )
//   }

//   if (filteredProducts.length === 0) {
//     return (
//       <Box sx={{ 
//         display: 'flex', 
//         flexDirection: 'column', 
//         alignItems: 'center', 
//         justifyContent: 'center',
//         py: 8,
//         width: '100%'
//       }}>
//         <Typography variant='h6' color='text.secondary'>
//           {searchTerm ? 'No products found matching your search' : 'No products available'}
//         </Typography>
//         {searchTerm && (
//           <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
//             Try adjusting your search terms
//           </Typography>
//         )}
//       </Box>
//     )
//   }

//   return (
//     <Grid container spacing={4}>
//       {renderProduct}
//     </Grid>
//   )
// }

// export default ProductArea

// image issue 
// import React, { useMemo, useState, useEffect } from 'react'

// // ** MUI Imports
// import Grid from '@mui/material/Grid'
// import Typography from '@mui/material/Typography'
// import Box from '@mui/material/Box'

// // ** Redux Hook
// import { useSelector } from 'react-redux'
// import { RootState } from 'src/store'
// import axios from 'src/configs/axios'

// // ** Components
// import { ProductCard, ProductLoader } from './ProductRender'

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

// // Image component with authentication - FIXED
// const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
//   const [imageSrc, setImageSrc] = useState<string | null>(null)
//   const [loading, setLoading] = useState(true)
//   const [error, setError] = useState(false)

//   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')
        
//         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]) // Only re-run when src changes

//   // Render loading state
//   if (loading) {
//     return (
//       <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
//         <div className="spinner-border text-primary" role="status">
//           <span className="visually-hidden">Loading...</span>
//         </div>
//       </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
//         }}
//       >
//         <span className="material-icons" style={{ fontSize: 24, color: '#9e9e9e' }}>photo_off</span>
//       </Box>
//     )
//   }

//   // Render image with error handling that doesn't trigger network requests
//   return (
//     <img
//       src={imageSrc}
//       alt={alt}
//       style={style}
//       onError={(e) => {
//         // Prevent infinite error loops
//         e.currentTarget.style.display = 'none'
//         setError(true)
//         setImageSrc(null)
//       }}
//     />
//   )
// }

// const getFullImageUrl = (path: string): string => {
//   if (!path) return ''

//   if (
//     path.startsWith('http://') ||
//     path.startsWith('https://') ||
//     path.startsWith('blob:') ||
//     path.startsWith('data:')
//   ) {
//     return path
//   }

//   const cleanPath = path.startsWith('/') ? path : `/${path}`

//   return `${axios.defaults.baseURL}${cleanPath}`
// }

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

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

// const ProductArea = () => {
//   const { list, loading, searchTerm } = useSelector((state: RootState) => state.pos)

//   // Filter products based on search term
//   const filteredProducts = useMemo(() => {
//     if (!searchTerm) return list
//     return list.filter((product: Product) =>
//       product.name.toLowerCase().includes(searchTerm.toLowerCase())
//     )
//   }, [list, searchTerm])

//   // Render Product
//   const renderProduct = filteredProducts.map((item: Product) => {
//     const variation = getFirstVariation(item)
//     const price = variation?.mrp || 0
    
//     let imageUrl = ''
//     if (variation) {
//       imageUrl = getVariationImage(variation)
//     }
    
//     return (
//       <Grid item xs={12} sm={6} md={4} lg={3} key={item.uid}>
//         <ProductCard
//           name={item.name}
//           price={price}
//           image={imageUrl}
//           items={item}
//         />
//       </Grid>
//     )
//   })

//   if (loading) {
//     return (
//       <Grid container spacing={4}>
//         <ProductLoader />
//       </Grid>
//     )
//   }

//   if (filteredProducts.length === 0) {
//     return (
//       <Box sx={{ 
//         display: 'flex', 
//         flexDirection: 'column', 
//         alignItems: 'center', 
//         justifyContent: 'center',
//         py: 8,
//         width: '100%'
//       }}>
//         <Typography variant='h6' color='text.secondary'>
//           {searchTerm ? 'No products found matching your search' : 'No products available'}
//         </Typography>
//         {searchTerm && (
//           <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
//             Try adjusting your search terms
//           </Typography>
//         )}
//       </Box>
//     )
//   }

//   return (
//     <Grid container spacing={4}>
//       {renderProduct}
//     </Grid>
//   )
// }

// export default ProductArea

// tyscript error 
import React, { useMemo, useState, useEffect } from 'react'

// ** MUI Imports
import Grid from '@mui/material/Grid'
import Typography from '@mui/material/Typography'
import Box from '@mui/material/Box'

// ** Redux Hook
import { useSelector } from 'react-redux'
import { RootState } from 'src/store'
import axios from 'src/configs/axios'

// ** Components
import { ProductCard, ProductLoader } from './ProductRender'

// ** Types - Use the same types as the Redux store
// Instead of redeclaring, use the store's types or use 'any' for compatibility

// Image component with authentication - FIXED
const AuthImageComponent: React.FC<{ src: string; alt: string; style?: React.CSSProperties }> = ({ src, alt, style }) => {
  const [imageSrc, setImageSrc] = useState<string | null>(null)
  const [loading, setLoading] = useState(true)
  const [error, setError] = useState(false)

  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')
        
        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]) // Only re-run when src changes

  // Render loading state
  if (loading) {
    return (
      <Box sx={{ width: '100%', height: '100%', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
        <div className="spinner-border text-primary" role="status">
          <span className="visually-hidden">Loading...</span>
        </div>
      </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
        }}
      >
        <span className="material-icons" style={{ fontSize: 24, color: '#9e9e9e' }}>photo_off</span>
      </Box>
    )
  }

  // Render image with error handling that doesn't trigger network requests
  return (
    <img
      src={imageSrc}
      alt={alt}
      style={style}
      onError={(e) => {
        // Prevent infinite error loops
        e.currentTarget.style.display = 'none'
        setError(true)
        setImageSrc(null)
      }}
    />
  )
}

const getFullImageUrl = (path: string): string => {
  if (!path) return ''

  if (
    path.startsWith('http://') ||
    path.startsWith('https://') ||
    path.startsWith('blob:') ||
    path.startsWith('data:')
  ) {
    return path
  }

  const cleanPath = path.startsWith('/') ? path : `/${path}`

  return `${axios.defaults.baseURL}${cleanPath}`
}

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

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

// ✅ Define a local type that matches what we actually use
interface LocalProduct {
  uid: string
  name: string
  description?: string
  productType?: string
  isInventoryManaged?: boolean
  variations?: any[]  // Use 'any[]' to avoid type conflicts with the store
  staffs?: any[]
  [key: string]: any  // Allow additional properties from the store
}

const ProductArea = () => {
  const { list, loading, searchTerm } = useSelector((state: RootState) => state.pos)

  // Filter products based on search term - Use 'any' type to avoid conflicts
  const filteredProducts = useMemo(() => {
    if (!searchTerm) return list
    return list.filter((product: any) =>
      product.name?.toLowerCase().includes(searchTerm.toLowerCase())
    )
  }, [list, searchTerm])

  // Render Product
  const renderProduct = filteredProducts.map((item: any) => {
    const variation = getFirstVariation(item)
    const price = variation?.mrp || 0
    
    let imageUrl = ''
    if (variation) {
      imageUrl = getVariationImage(variation)
    }
    
    return (
      <Grid item xs={12} sm={6} md={4} lg={3} key={item.uid}>
        <ProductCard
          name={item.name}
          price={price}
          image={imageUrl}
          items={item}
        />
      </Grid>
    )
  })

  if (loading) {
    return (
      <Grid container spacing={4}>
        <ProductLoader />
      </Grid>
    )
  }

  if (filteredProducts.length === 0) {
    return (
      <Box sx={{ 
        display: 'flex', 
        flexDirection: 'column', 
        alignItems: 'center', 
        justifyContent: 'center',
        py: 8,
        width: '100%'
      }}>
        <Typography variant='h6' color='text.secondary'>
          {searchTerm ? 'No products found matching your search' : 'No products available'}
        </Typography>
        {searchTerm && (
          <Typography variant='body2' color='text.secondary' sx={{ mt: 1 }}>
            Try adjusting your search terms
          </Typography>
        )}
      </Box>
    )
  }

  return (
    <Grid container spacing={4}>
      {renderProduct}
    </Grid>
  )
}

export default ProductArea