// import { useRef, useState, useCallback, useEffect } from 'react'

// // ** MUI Components
// import {
//   Box,
//   Button,
//   IconButton,
//   Typography,
//   Card,
//   CardContent,
//   Alert,
//   CircularProgress,
//   LinearProgress
// } from '@mui/material'

// // ** MediaPipe Imports
// import { FaceDetector, FaceLandmarker, FilesetResolver } from '@mediapipe/tasks-vision'

// interface PhotoCaptureWithMediaPipeProps {
//   onCapture: (photoFile: File) => void
//   onClose: () => void
// }

// // Helper to convert canvas to File
// const canvasToFile = (canvas: HTMLCanvasElement, fileName: string = 'face_photo.jpg'): File => {
//   return new Promise<File>((resolve) => {
//     canvas.toBlob((blob) => {
//       if (blob) {
//         const file = new File([blob], fileName, { type: 'image/jpeg' })
//         resolve(file)
//       }
//     }, 'image/jpeg', 0.9)
//   })
// }

// const PhotoCaptureWithMediaPipe: React.FC<PhotoCaptureWithMediaPipeProps> = ({ onCapture, onClose }) => {
//   const videoRef = useRef<HTMLVideoElement>(null)
//   const canvasRef = useRef<HTMLCanvasElement>(null)
//   const overlayCanvasRef = useRef<HTMLCanvasElement>(null)
//   const [stream, setStream] = useState<MediaStream | null>(null)
//   const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user')
//   const [error, setError] = useState<string>('')
//   const [loading, setLoading] = useState(true)
//   const [capturedPhoto, setCapturedPhoto] = useState<string | null>(null)
//   const [capturedFile, setCapturedFile] = useState<File | null>(null)
//   const [isDetecting, setIsDetecting] = useState(false)
//   const [faceDetected, setFaceDetected] = useState(false)
//   const [faceLandmarks, setFaceLandmarks] = useState<any>(null)
//   const [detectionStatus, setDetectionStatus] = useState<string>('Initializing...')
//   const [faceLandmarker, setFaceLandmarker] = useState<any>(null)
//   const [isMediaPipeReady, setIsMediaPipeReady] = useState(false)
//   const [isModelLoading, setIsModelLoading] = useState(true)
//   const [livenessScore, setLivenessScore] = useState<number | null>(null)
//   const [isLive, setIsLive] = useState(false)

//   // Initialize MediaPipe
//   useEffect(() => {
//     const initializeMediaPipe = async () => {
//       try {
//         setIsModelLoading(true)
//         setDetectionStatus('Loading face detection model...')
        
//         const vision = await FilesetResolver.forVisionTasks(
//           'https://cdn.jsdelivr.net/npm/@mediapipe/tasks-vision@0.10.0/wasm'
//         )
        
//         const faceLandmarker = await FaceLandmarker.createFromOptions(vision, {
//           baseOptions: {
//             modelAssetPath: 'https://storage.googleapis.com/mediapipe-models/face_landmarker/face_landmarker/float16/1/face_landmarker.task',
//             delegate: 'GPU'
//           },
//           outputFaceBlendshapes: true,
//           runningMode: 'VIDEO',
//           numFaces: 1
//         })
        
//         setFaceLandmarker(faceLandmarker)
//         setIsMediaPipeReady(true)
//         setIsModelLoading(false)
//         setDetectionStatus('Ready for face detection')
//         console.log('✅ MediaPipe Face Landmarker initialized')
//       } catch (error) {
//         console.error('Failed to initialize MediaPipe:', error)
//         setError('Failed to load face detection model. Please try again.')
//         setIsModelLoading(false)
//       }
//     }

//     initializeMediaPipe()
    
//     return () => {
//       if (faceLandmarker) {
//         faceLandmarker.close()
//       }
//     }
//   }, [])

//   const startCamera = useCallback(async () => {
//     setLoading(true)
//     setError('')
    
//     try {
//       if (stream) {
//         stream.getTracks().forEach(track => track.stop())
//       }
      
//       const mediaStream = await navigator.mediaDevices.getUserMedia({
//         video: { 
//           facingMode: { exact: facingMode },
//           width: { ideal: 640 },
//           height: { ideal: 480 }
//         }
//       })
      
//       setStream(mediaStream)
//       if (videoRef.current) {
//         videoRef.current.srcObject = mediaStream
//         videoRef.current.onloadedmetadata = () => {
//           videoRef.current?.play()
//           setLoading(false)
//         }
//       }
//     } catch (err) {
//       try {
//         const mediaStream = await navigator.mediaDevices.getUserMedia({
//           video: { width: { ideal: 640 }, height: { ideal: 480 } }
//         })
//         setStream(mediaStream)
//         if (videoRef.current) {
//           videoRef.current.srcObject = mediaStream
//           videoRef.current.onloadedmetadata = () => {
//             videoRef.current?.play()
//             setLoading(false)
//           }
//         }
//       } catch (fallbackErr) {
//         setError('Unable to access camera. Please check permissions.')
//         console.error('Camera error:', fallbackErr)
//         setLoading(false)
//       }
//     }
//   }, [facingMode])

//   useEffect(() => {
//     startCamera()
    
//     return () => {
//       if (stream) {
//         stream.getTracks().forEach(track => track.stop())
//       }
//     }
//   }, [startCamera])

//   // Face detection loop
//   useEffect(() => {
//     if (!videoRef.current || !isMediaPipeReady || !faceLandmarker || loading) {
//       return
//     }

//     let animationId: number
//     let frameCount = 0
    
//     const detectFace = () => {
//       const video = videoRef.current
//       const overlayCanvas = overlayCanvasRef.current
      
//       if (!video || !overlayCanvas || video.readyState < 2) {
//         animationId = requestAnimationFrame(detectFace)
//         return
//       }
      
//       try {
//         const startTimeMs = performance.now()
//         const detections = faceLandmarker.detectForVideo(video, startTimeMs)
        
//         const ctx = overlayCanvas.getContext('2d')
//         if (!ctx) {
//           animationId = requestAnimationFrame(detectFace)
//           return
//         }
        
//         // Clear overlay
//         ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height)
        
//         if (detections.faceLandmarks && detections.faceLandmarks.length > 0) {
//           setFaceDetected(true)
//           setFaceLandmarks(detections.faceLandmarks[0])
//           setDetectionStatus('Face detected ✓')
          
//           // Draw face landmarks with different colors for different regions
//           const landmarks = detections.faceLandmarks[0]
          
//           // Draw face mesh connections
//           ctx.strokeStyle = 'rgba(0, 255, 0, 0.3)'
//           ctx.lineWidth = 1
          
//           // Draw landmarks as points
//           landmarks.forEach((landmark: any) => {
//             const x = landmark.x * overlayCanvas.width
//             const y = landmark.y * overlayCanvas.height
            
//             // Different colors for different face regions
//             let color = 'rgba(0, 255, 0, 0.8)'
            
//             // Eyes (regions 33-133 for left eye, 362-263 for right eye)
//             const index = landmarks.indexOf(landmark)
//             if (index >= 33 && index <= 133) {
//               color = 'rgba(255, 255, 0, 0.8)'
//             } else if (index >= 362 && index <= 263) {
//               color = 'rgba(255, 200, 0, 0.8)'
//             } else if (index >= 0 && index <= 16) {
//               color = 'rgba(0, 255, 255, 0.8)' // Jawline
//             } else if (index >= 61 && index <= 291) {
//               color = 'rgba(255, 0, 255, 0.8)' // Mouth
//             }
            
//             ctx.beginPath()
//             ctx.arc(x, y, 2, 0, 2 * Math.PI)
//             ctx.fillStyle = color
//             ctx.fill()
//           })
          
//           // Draw bounding box around face
//           const xCoords = landmarks.map((l: any) => l.x * overlayCanvas.width)
//           const yCoords = landmarks.map((l: any) => l.y * overlayCanvas.height)
//           const minX = Math.min(...xCoords)
//           const maxX = Math.max(...xCoords)
//           const minY = Math.min(...yCoords)
//           const maxY = Math.max(...yCoords)
          
//           ctx.strokeStyle = 'rgba(0, 255, 0, 0.8)'
//           ctx.lineWidth = 2
//           ctx.strokeRect(minX - 10, minY - 10, maxX - minX + 20, maxY - minY + 20)
          
//           // Draw liveness indicator
//           ctx.fillStyle = 'rgba(0, 255, 0, 0.2)'
//           ctx.fillRect(10, 10, 15, 15)
//           ctx.fillStyle = '#00ff00'
//           ctx.font = '14px Arial'
//           ctx.fillText('Live ✓', 30, 23)
          
//           // Add liveness check - simple blink detection
//           // Calculate eye aspect ratio for blink detection
//           const leftEye = landmarks.slice(33, 133)
//           const rightEye = landmarks.slice(362, 263)
          
//           const leftEyeAspectRatio = calculateEyeAspectRatio(leftEye)
//           const rightEyeAspectRatio = calculateEyeAspectRatio(rightEye)
//           const avgEyeAspectRatio = (leftEyeAspectRatio + rightEyeAspectRatio) / 2
          
//           // Update liveness score based on eye aspect ratio and movement
//           setLivenessScore(Math.min(100, Math.round(avgEyeAspectRatio * 100)))
          
//           if (avgEyeAspectRatio < 0.2) {
//             setDetectionStatus('Blink detected! ✓')
//             setIsLive(true)
//           } else {
//             setIsLive(true)
//           }
          
//         } else {
//           setFaceDetected(false)
//           setDetectionStatus('No face detected. Please look at the camera.')
//           setLivenessScore(null)
          
//           // Draw indicator on canvas
//           ctx.fillStyle = 'rgba(255, 0, 0, 0.2)'
//           ctx.fillRect(10, 10, 15, 15)
//           ctx.fillStyle = '#ff0000'
//           ctx.font = '14px Arial'
//           ctx.fillText('No Face Detected', 30, 23)
//         }
        
//       } catch (error) {
//         console.warn('Face detection error:', error)
//       }
      
//       animationId = requestAnimationFrame(detectFace)
//     }
    
//     // Start detection with a small delay to ensure video is ready
//     setTimeout(() => {
//       detectFace()
//     }, 1000)
    
//     return () => {
//       if (animationId) {
//         cancelAnimationFrame(animationId)
//       }
//     }
//   }, [videoRef, isMediaPipeReady, faceLandmarker, loading])

//   // Helper function to calculate eye aspect ratio
//   const calculateEyeAspectRatio = (eyeLandmarks: any[]) => {
//     if (eyeLandmarks.length < 6) return 0.3
    
//     // Use standard eye landmark indices for EAR calculation
//     const p1 = eyeLandmarks[1]  // Corner of eye
//     const p2 = eyeLandmarks[5]  // Other corner
//     const p3 = eyeLandmarks[2]  // Upper eyelid
//     const p5 = eyeLandmarks[4]  // Lower eyelid
    
//     // Calculate Euclidean distances
//     const dist1 = Math.sqrt(
//       Math.pow(p3.x - p5.x, 2) + 
//       Math.pow(p3.y - p5.y, 2) + 
//       Math.pow(p3.z - p5.z, 2)
//     )
//     const dist2 = Math.sqrt(
//       Math.pow(p1.x - p2.x, 2) + 
//       Math.pow(p1.y - p2.y, 2) + 
//       Math.pow(p1.z - p2.z, 2)
//     )
    
//     return dist2 > 0 ? dist1 / dist2 : 0.3
//   }

//   const capturePhoto = async () => {
//     const video = videoRef.current
//     const canvas = canvasRef.current
    
//     if (!video || !canvas) return
    
//     // Check if face is detected before capturing
//     if (!faceDetected) {
//       setError('No face detected. Please position your face in the frame.')
//       return
//     }
    
//     setIsDetecting(true)
    
//     try {
//       // Set canvas dimensions to match video
//       canvas.width = video.videoWidth
//       canvas.height = video.videoHeight
      
//       const context = canvas.getContext('2d')
//       if (!context) {
//         throw new Error('Could not get canvas context')
//       }
      
//       // Draw the video frame
//       context.drawImage(video, 0, 0, canvas.width, canvas.height)
      
//       // Draw face landmarks on the captured image for verification
//       if (faceLandmarks) {
//         context.strokeStyle = 'rgba(0, 255, 0, 0.5)'
//         context.lineWidth = 2
        
//         // Draw landmarks
//         faceLandmarks.forEach((landmark: any) => {
//           const x = landmark.x * canvas.width
//           const y = landmark.y * canvas.height
//           context.beginPath()
//           context.arc(x, y, 2, 0, 2 * Math.PI)
//           context.fillStyle = 'rgba(0, 255, 0, 0.8)'
//           context.fill()
//         })
//       }
      
//       // Convert to File
//       const file = await canvasToFile(canvas, 'face_verification.jpg')
      
//       // Create preview URL
//       const imageData = canvas.toDataURL('image/jpeg', 0.9)
      
//       setCapturedPhoto(imageData)
//       setCapturedFile(file)
//       setIsDetecting(false)
      
//     } catch (error) {
//       console.error('Error capturing photo:', error)
//       setError('Failed to capture photo. Please try again.')
//       setIsDetecting(false)
//     }
//   }

//   const retakePhoto = () => {
//     setCapturedPhoto(null)
//     setCapturedFile(null)
//     setError('')
//   }

//   const confirmPhoto = () => {
//     if (capturedFile) {
//       onCapture(capturedFile)
//     }
//   }

//   const switchCamera = () => {
//     setFacingMode(prev => prev === 'user' ? 'environment' : 'user')
//     setCapturedPhoto(null)
//     setCapturedFile(null)
//     setError('')
//   }

//   const getLivenessColor = () => {
//     if (livenessScore === null) return 'grey'
//     if (livenessScore > 60) return 'success'
//     if (livenessScore > 30) return 'warning'
//     return 'error'
//   }

//   if (error) {
//     return (
//       <Card>
//         <CardContent>
//           <Alert severity="error" sx={{ mb: 2 }}>
//             {error}
//           </Alert>
//           <Button variant="contained" onClick={onClose} fullWidth>
//             Close
//           </Button>
//         </CardContent>
//       </Card>
//     )
//   }

//   return (
//     <Card sx={{ position: 'relative' }}>
//       <IconButton
//         sx={{ position: 'absolute', top: 8, right: 8, zIndex: 1, bgcolor: 'background.paper' }}
//         onClick={onClose}
//       >
//         ✕
//       </IconButton>
      
//       <CardContent>
//         <Typography variant="h6" gutterBottom align="center">
//           Face Verification
//         </Typography>
//         <Typography variant="body2" color="text.secondary" align="center" sx={{ mb: 2 }}>
//           Position your face in the center of the frame
//         </Typography>
        
//         {isModelLoading && (
//           <Box sx={{ mb: 2 }}>
//             <Typography variant="body2" align="center" sx={{ mb: 1 }}>
//               Loading face detection model...
//             </Typography>
//             <LinearProgress />
//           </Box>
//         )}
        
//         <Box sx={{ position: 'relative', mb: 2 }}>
//           {!capturedPhoto ? (
//             <>
//               <Box
//                 sx={{
//                   position: 'relative',
//                   borderRadius: 2,
//                   overflow: 'hidden',
//                   bgcolor: 'black',
//                   aspectRatio: '4/3',
//                   display: 'flex',
//                   alignItems: 'center',
//                   justifyContent: 'center'
//                 }}
//               >
//                 {loading && (
//                   <Box sx={{ position: 'absolute', color: 'white' }}>
//                     <CircularProgress color="inherit" />
//                     <Typography sx={{ mt: 2, color: 'white' }}>
//                       Starting camera...
//                     </Typography>
//                   </Box>
//                 )}
//                 <video
//                   ref={videoRef}
//                   autoPlay
//                   playsInline
//                   style={{
//                     width: '100%',
//                     height: '100%',
//                     objectFit: 'cover',
//                     display: loading ? 'none' : 'block'
//                   }}
//                 />
//                 <canvas
//                   ref={overlayCanvasRef}
//                   style={{
//                     position: 'absolute',
//                     top: 0,
//                     left: 0,
//                     width: '100%',
//                     height: '100%',
//                     pointerEvents: 'none'
//                   }}
//                   width={640}
//                   height={480}
//                 />
//                 <Box
//                   sx={{
//                     position: 'absolute',
//                     top: 0,
//                     left: 0,
//                     right: 0,
//                     bottom: 0,
//                     border: `2px solid ${faceDetected ? 'rgba(0,255,0,0.5)' : 'rgba(255,255,255,0.5)'}`,
//                     borderRadius: '50%',
//                     width: '200px',
//                     height: '200px',
//                     margin: 'auto',
//                     pointerEvents: 'none',
//                     transition: 'border-color 0.3s ease'
//                   }}
//                 />
                
//                 {/* Status indicator */}
//                 <Box
//                   sx={{
//                     position: 'absolute',
//                     bottom: 16,
//                     left: 16,
//                     right: 16,
//                     display: 'flex',
//                     alignItems: 'center',
//                     justifyContent: 'space-between',
//                     bgcolor: 'rgba(0,0,0,0.6)',
//                     borderRadius: 1,
//                     p: 1
//                   }}
//                 >
//                   <Typography variant="caption" sx={{ color: 'white' }}>
//                     {detectionStatus}
//                   </Typography>
//                   {livenessScore !== null && (
//                     <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
//                       <Box
//                         sx={{
//                           width: 8,
//                           height: 8,
//                           borderRadius: '50%',
//                           bgcolor: getLivenessColor(),
//                           animation: isLive ? 'pulse 1s infinite' : 'none'
//                         }}
//                       />
//                       <Typography variant="caption" sx={{ color: 'white' }}>
//                         {livenessScore}%
//                       </Typography>
//                     </Box>
//                   )}
//                 </Box>
//               </Box>
              
//               <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 2, flexWrap: 'wrap' }}>
//                 <Button
//                   variant="contained"
//                   onClick={capturePhoto}
//                   disabled={loading || !isMediaPipeReady || isDetecting || !faceDetected}
//                 >
//                   {isDetecting ? <CircularProgress size={24} /> : '📷 Capture'}
//                 </Button>
//                 <Button
//                   variant="outlined"
//                   onClick={switchCamera}
//                   disabled={loading || isDetecting}
//                 >
//                   🔄 Switch Camera
//                 </Button>
//               </Box>
              
//               <Alert severity="info" sx={{ mt: 2 }}>
//                 <Typography variant="caption" component="div">
//                   • Ensure good lighting conditions<br />
//                   • Remove glasses, mask, or any face covering<br />
//                   • Look directly at the camera<br />
//                   {!faceDetected && '• Move closer to the camera if no face detected'}
//                 </Typography>
//               </Alert>
//             </>
//           ) : (
//             <>
//               <Box
//                 sx={{
//                   borderRadius: 2,
//                   overflow: 'hidden',
//                   aspectRatio: '4/3',
//                   bgcolor: 'black'
//                 }}
//               >
//                 <img
//                   src={capturedPhoto}
//                   alt="Captured"
//                   style={{ width: '100%', height: '100%', objectFit: 'cover' }}
//                 />
//               </Box>
              
//               <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 2 }}>
//                 <Button
//                   variant="outlined"
//                   onClick={retakePhoto}
//                 >
//                   🔄 Retake
//                 </Button>
//                 <Button
//                   variant="contained"
//                   color="success"
//                   onClick={confirmPhoto}
//                 >
//                   ✓ Confirm & Continue
//                 </Button>
//               </Box>
//             </>
//           )}
//         </Box>
        
//         <canvas ref={canvasRef} style={{ display: 'none' }} />
//       </CardContent>
      
//       {/* Add CSS for pulse animation */}
//       <style>
//         {`
//           @keyframes pulse {
//             0% { opacity: 1; }
//             50% { opacity: 0.3; }
//             100% { opacity: 1; }
//           }
//         `}
//       </style>
//     </Card>
//   )
// }

// export default PhotoCaptureWithMediaPipe

// new 
import { useRef, useState, useCallback, useEffect } from 'react'

// ** MUI Components
import {
  Box,
  Button,
  IconButton,
  Typography,
  Card,
  CardContent,
  Alert,
  CircularProgress,
  LinearProgress
} from '@mui/material'

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

interface PhotoCaptureWithMediaPipeProps {
  onCapture: (photoFile: File) => void
  onClose: () => void
}

// Helper to convert canvas to File with proper error handling
const canvasToFile = (canvas: HTMLCanvasElement, fileName = 'face_photo.jpg'): Promise<File> => {
  return new Promise((resolve, reject) => {
    if (!canvas) {
      reject(new Error('Canvas is null'))
      return
    }
    
    canvas.toBlob((blob) => {
      if (blob) {
        const file = new File([blob], fileName, { type: 'image/jpeg' })
        resolve(file)
      } else {
        reject(new Error('Failed to create blob from canvas'))
      }
    }, 'image/jpeg', 0.92)
  })
}

// Declare MediaPipe types for CDN
declare global {
  interface Window {
    FaceDetection: any
    FaceMesh: any
    Camera: any
    drawConnectors: any
    drawLandmarks: any
    FACEMESH_TESSELATION: any
    FACEMESH_CONTOURS: any
    FACEMESH_FACE_OVAL: any
    FACEMESH_IRISES: any
  }
}

const PhotoCaptureWithMediaPipe: React.FC<PhotoCaptureWithMediaPipeProps> = ({ onCapture, onClose }) => {
  const videoRef = useRef<HTMLVideoElement>(null)
  const canvasRef = useRef<HTMLCanvasElement>(null)
  const overlayCanvasRef = useRef<HTMLCanvasElement>(null)
  const [stream, setStream] = useState<MediaStream | null>(null)
  const [facingMode, setFacingMode] = useState<'user' | 'environment'>('user')
  const [error, setError] = useState<string>('')
  const [loading, setLoading] = useState(true)
  const [capturedPhoto, setCapturedPhoto] = useState<string | null>(null)
  const [capturedFile, setCapturedFile] = useState<File | null>(null)
  const [isDetecting, setIsDetecting] = useState(false)
  const [faceDetected, setFaceDetected] = useState(false)
  const [detectionStatus, setDetectionStatus] = useState<string>('Initializing...')
  const [isMediaPipeReady, setIsMediaPipeReady] = useState(false)
  const [isModelLoading, setIsModelLoading] = useState(true)
  const [livenessScore, setLivenessScore] = useState<number | null>(null)
  const [isLive, setIsLive] = useState(false)
  const [faceMesh, setFaceMesh] = useState<any>(null)
  const [camera, setCamera] = useState<any>(null)
  const [blinkCount, setBlinkCount] = useState(0)
  const [lastBlinkTime, setLastBlinkTime] = useState(0)
  const [isFaceMeshInitialized, setIsFaceMeshInitialized] = useState(false)
  const [isVideoReady, setIsVideoReady] = useState(false)
  const [isCapturing, setIsCapturing] = useState(false)

  // Load MediaPipe scripts from CDN
  useEffect(() => {
    const loadMediaPipeScripts = async () => {
      try {
        setIsModelLoading(true)
        setDetectionStatus('Loading MediaPipe scripts...')

        // Load Face Mesh script
        const faceMeshScript = document.createElement('script')
        faceMeshScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/face_mesh.js'
        faceMeshScript.crossOrigin = 'anonymous'
        document.head.appendChild(faceMeshScript)

        // Load Face Detection script
        const faceDetectionScript = document.createElement('script')
        faceDetectionScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/face_detection/face_detection.js'
        faceDetectionScript.crossOrigin = 'anonymous'
        document.head.appendChild(faceDetectionScript)

        // Load Camera Utils
        const cameraScript = document.createElement('script')
        cameraScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/camera_utils/camera_utils.js'
        cameraScript.crossOrigin = 'anonymous'
        document.head.appendChild(cameraScript)

        // Load Drawing Utils
        const drawingScript = document.createElement('script')
        drawingScript.src = 'https://cdn.jsdelivr.net/npm/@mediapipe/drawing_utils/drawing_utils.js'
        drawingScript.crossOrigin = 'anonymous'
        document.head.appendChild(drawingScript)

        // Wait for scripts to load
        await new Promise((resolve) => {
          const checkLoaded = () => {
            if (window.FaceMesh && window.FaceDetection && window.Camera) {
              resolve(true)
            } else {
              setTimeout(checkLoaded, 100)
            }
          }
          checkLoaded()
        })

        console.log('✅ MediaPipe scripts loaded')
        setIsMediaPipeReady(true)
        setIsModelLoading(false)
        setDetectionStatus('Ready for face detection')
        
        initializeFaceMesh()
      } catch (error) {
        console.error('Failed to load MediaPipe scripts:', error)
        setError('Failed to load face detection model. Please try again.')
        setIsModelLoading(false)
      }
    }

    loadMediaPipeScripts()

    return () => {
      // Cleanup
      if (camera) {
        try {
          camera.stop()
        } catch (e) {
          console.warn('Error stopping camera:', e)
        }
      }
      if (faceMesh) {
        try {
          faceMesh.close()
        } catch (e) {
          console.warn('Error closing face mesh:', e)
        }
      }
      if (stream) {
        stream.getTracks().forEach(track => track.stop())
      }
    }
  }, [])

  const initializeFaceMesh = () => {
    try {
      const FaceMesh = window.FaceMesh
      
      const faceMeshInstance = new FaceMesh({
        locateFile: (file: string) => {
          return `https://cdn.jsdelivr.net/npm/@mediapipe/face_mesh/${file}`
        }
      })

      faceMeshInstance.setOptions({
        maxNumFaces: 1,
        refineLandmarks: true,
        minDetectionConfidence: 0.5,
        minTrackingConfidence: 0.5
      })

      faceMeshInstance.onResults((results: any) => {
        handleFaceMeshResults(results)
      })

      setFaceMesh(faceMeshInstance)
      setIsFaceMeshInitialized(true)
      console.log('✅ FaceMesh initialized')
    } catch (error) {
      console.error('Failed to initialize face mesh:', error)
      setError('Failed to initialize face detection.')
    }
  }

  const handleFaceMeshResults = (results: any) => {
    const overlayCanvas = overlayCanvasRef.current
    if (!overlayCanvas) return

    const ctx = overlayCanvas.getContext('2d')
    if (!ctx) return

    // Clear overlay
    ctx.clearRect(0, 0, overlayCanvas.width, overlayCanvas.height)

    if (results.multiFaceLandmarks && results.multiFaceLandmarks.length > 0) {
      const landmarks = results.multiFaceLandmarks[0]
      setFaceDetected(true)
      setDetectionStatus('Face detected ✓')
      setIsLive(true)

      const width = overlayCanvas.width
      const height = overlayCanvas.height

      // Draw face mesh connections
      if (window.drawConnectors && window.FACEMESH_TESSELATION) {
        window.drawConnectors(ctx, landmarks, window.FACEMESH_TESSELATION, { 
          color: 'rgba(0, 255, 0, 0.15)', 
          lineWidth: 1 
        })
        window.drawConnectors(ctx, landmarks, window.FACEMESH_CONTOURS, { 
          color: 'rgba(0, 255, 0, 0.3)', 
          lineWidth: 1 
        })
      }

      // Draw landmarks with different colors
      landmarks.forEach((landmark: any, index: number) => {
        const x = landmark.x * width
        const y = landmark.y * height
        
        let color = 'rgba(0, 255, 0, 0.5)'
        
        // Eyes
        if (index >= 33 && index <= 133) {
          color = 'rgba(255, 255, 0, 0.7)'
        } else if (index >= 362 && index <= 263) {
          color = 'rgba(255, 200, 0, 0.7)'
        } else if (index >= 0 && index <= 16) {
          color = 'rgba(0, 255, 255, 0.7)'
        } else if (index >= 61 && index <= 291) {
          color = 'rgba(255, 0, 255, 0.7)'
        }
        
        ctx.beginPath()
        ctx.arc(x, y, 1.5, 0, 2 * Math.PI)
        ctx.fillStyle = color
        ctx.fill()
      })

      // Calculate eye aspect ratio for both eyes correctly
      const leftEyeIndices = [33, 133, 160, 159, 158, 144, 145, 153]
      const rightEyeIndices = [362, 263, 387, 386, 385, 373, 374, 380]
      
      const leftEye = leftEyeIndices.map(i => landmarks[i])
      const rightEye = rightEyeIndices.map(i => landmarks[i])
      
      const leftEAR = calculateEyeAspectRatio(leftEye)
      const rightEAR = calculateEyeAspectRatio(rightEye)
      const avgEAR = (leftEAR + rightEAR) / 2
      
      // Update liveness score
      const score = Math.min(100, Math.round(avgEAR * 100))
      setLivenessScore(score)
      
      // Detect blink (both eyes)
      if (avgEAR < 0.15) {
        const now = Date.now()
        if (now - lastBlinkTime > 500) {
          setBlinkCount(prev => prev + 1)
          setLastBlinkTime(now)
          setDetectionStatus(`Blink detected! ✓ (${blinkCount + 1} blinks)`)
        }
      }

      // Draw bounding box
      const xCoords = landmarks.map((l: any) => l.x * width)
      const yCoords = landmarks.map((l: any) => l.y * height)
      const minX = Math.min(...xCoords)
      const maxX = Math.max(...xCoords)
      const minY = Math.min(...yCoords)
      const maxY = Math.max(...yCoords)
      
      ctx.strokeStyle = 'rgba(0, 255, 0, 0.8)'
      ctx.lineWidth = 2
      ctx.strokeRect(minX - 10, minY - 10, maxX - minX + 20, maxY - minY + 20)

      // Draw status info
      ctx.fillStyle = 'rgba(0, 255, 0, 0.2)'
      ctx.fillRect(10, 10, 15, 15)
      ctx.fillStyle = '#00ff00'
      ctx.font = '14px Arial'
      ctx.fillText(`Live ✓ (${blinkCount} blinks)`, 30, 23)
      
      ctx.fillStyle = 'rgba(255,255,255,0.8)'
      ctx.fillText(`Liveness: ${score}%`, 30, 43)

    } else {
      setFaceDetected(false)
      setDetectionStatus('No face detected. Please look at the camera.')
      setLivenessScore(null)
      
      ctx.fillStyle = 'rgba(255, 0, 0, 0.2)'
      ctx.fillRect(10, 10, 15, 15)
      ctx.fillStyle = '#ff0000'
      ctx.font = '14px Arial'
      ctx.fillText('No Face Detected', 30, 23)
    }
  }

  const calculateEyeAspectRatio = (eyeLandmarks: any[]): number => {
    if (!eyeLandmarks || eyeLandmarks.length < 6) return 0.3
    
    try {
      const p1 = eyeLandmarks[1]
      const p2 = eyeLandmarks[5]
      const p3 = eyeLandmarks[2]
      const p5 = eyeLandmarks[4]
      
      const dist1 = Math.sqrt(
        Math.pow(p3.x - p5.x, 2) + 
        Math.pow(p3.y - p5.y, 2) + 
        Math.pow(p3.z - p5.z, 2)
      )
      const dist2 = Math.sqrt(
        Math.pow(p1.x - p2.x, 2) + 
        Math.pow(p1.y - p2.y, 2) + 
        Math.pow(p1.z - p2.z, 2)
      )
      
      return dist2 > 0 ? dist1 / dist2 : 0.3
    } catch (error) {
      return 0.3
    }
  }

  const startCamera = useCallback(async () => {
    setLoading(true)
    setError('')
    
    try {
      if (stream) {
        stream.getTracks().forEach(track => track.stop())
      }
      
      const mediaStream = await navigator.mediaDevices.getUserMedia({
        video: { 
          facingMode: { exact: facingMode },
          width: { ideal: 640 },
          height: { ideal: 480 }
        }
      })
      
      setStream(mediaStream)
      if (videoRef.current) {
        videoRef.current.srcObject = mediaStream
        videoRef.current.onloadedmetadata = () => {
          videoRef.current?.play()
          setIsVideoReady(true)
          setLoading(false)
        }
      }
    } catch (err) {
      try {
        const mediaStream = await navigator.mediaDevices.getUserMedia({
          video: { width: { ideal: 640 }, height: { ideal: 480 } }
        })
        setStream(mediaStream)
        if (videoRef.current) {
          videoRef.current.srcObject = mediaStream
          videoRef.current.onloadedmetadata = () => {
            videoRef.current?.play()
            setIsVideoReady(true)
            setLoading(false)
          }
        }
      } catch (fallbackErr) {
        setError('Unable to access camera. Please check permissions.')
        console.error('Camera error:', fallbackErr)
        setLoading(false)
      }
    }
  }, [facingMode])

  // Start face detection only when video and face mesh are ready
  useEffect(() => {
    if (!isVideoReady || !isFaceMeshInitialized || !faceMesh || !videoRef.current) {
      return
    }

    console.log('🔄 Starting face detection...')
    
    const startDetection = async () => {
      try {
        const Camera = window.Camera
        const cameraInstance = new Camera(videoRef.current, {
          onFrame: async () => {
            if (videoRef.current && faceMesh) {
              try {
                await faceMesh.send({ image: videoRef.current })
              } catch (err) {
                // Silently handle frame processing errors
              }
            }
          },
          width: 640,
          height: 480
        })
        await cameraInstance.start()
        setCamera(cameraInstance)
        console.log('✅ Face detection started')
      } catch (error) {
        console.error('Failed to start camera instance:', error)
      }
    }

    const timeoutId = setTimeout(startDetection, 500)
    
    return () => {
      clearTimeout(timeoutId)
    }
  }, [isVideoReady, isFaceMeshInitialized, faceMesh])

  // Initialize camera when MediaPipe is ready
  useEffect(() => {
    if (isMediaPipeReady && isFaceMeshInitialized) {
      startCamera()
    }
  }, [isMediaPipeReady, isFaceMeshInitialized, startCamera])

  useEffect(() => {
    const updateCanvasSize = () => {
      const video = videoRef.current
      const overlayCanvas = overlayCanvasRef.current
      if (video && overlayCanvas && video.videoWidth > 0 && video.videoHeight > 0) {
        overlayCanvas.width = video.videoWidth
        overlayCanvas.height = video.videoHeight
      }
    }

    const interval = setInterval(updateCanvasSize, 100)
    return () => clearInterval(interval)
  }, [])

  const capturePhoto = async () => {
    // Prevent multiple simultaneous captures
    if (isCapturing) return
    
    const video = videoRef.current
    const canvas = canvasRef.current
    
    // Validate video element
    if (!video) {
      setError('Camera not available. Please wait.')
      console.error('Video element is null')
      return
    }
    
    // Validate canvas element
    if (!canvas) {
      setError('Canvas not available. Please try again.')
      console.error('Canvas element is null')
      return
    }
    
    // Check if video is playing and has dimensions
    if (video.readyState < 2) {
      setError('Camera is not ready. Please wait.')
      console.error('Video not ready. ReadyState:', video.readyState)
      return
    }
    
    if (video.videoWidth === 0 || video.videoHeight === 0) {
      setError('Video dimensions not available. Please wait.')
      console.error('Video dimensions are zero:', video.videoWidth, video.videoHeight)
      return
    }
    
    if (!faceDetected) {
      setError('No face detected. Please position your face in the frame.')
      return
    }
    
    setIsCapturing(true)
    setIsDetecting(true)
    setError('')
    
    try {
      // Set canvas dimensions to match video
      canvas.width = video.videoWidth
      canvas.height = video.videoHeight
      
      console.log('📸 Capturing photo with dimensions:', canvas.width, 'x', canvas.height)
      
      const context = canvas.getContext('2d')
      if (!context) {
        throw new Error('Could not get canvas context')
      }
      
      // Draw the video frame onto the canvas
      context.drawImage(video, 0, 0, canvas.width, canvas.height)
      
      // Verify that something was drawn
      const imageData = context.getImageData(0, 0, canvas.width, canvas.height)
      if (imageData.data.every((val: number) => val === 0)) {
        throw new Error('Canvas is empty. Failed to capture image.')
      }
      
      // Convert to File
      const file = await canvasToFile(canvas, 'face_verification.jpg')
      
      // Create preview from canvas
      const previewDataUrl = canvas.toDataURL('image/jpeg', 0.92)
      
      setCapturedPhoto(previewDataUrl)
      setCapturedFile(file)
      
      toast.success('Face photo captured successfully!')
      
    } catch (error: any) {
      console.error('Error capturing photo:', error)
      setError(error.message || 'Failed to capture photo. Please try again.')
      toast.error(error.message || 'Failed to capture photo')
    } finally {
      setIsDetecting(false)
      setIsCapturing(false)
    }
  }

  const retakePhoto = () => {
    setCapturedPhoto(null)
    setCapturedFile(null)
    setError('')
  }

  const confirmPhoto = () => {
    if (capturedFile) {
      onCapture(capturedFile)
    }
  }

  const switchCamera = () => {
    setFacingMode(prev => prev === 'user' ? 'environment' : 'user')
    setCapturedPhoto(null)
    setCapturedFile(null)
    setError('')
    setIsVideoReady(false)
    setLoading(true)
    setIsCapturing(false)
  }

  const getLivenessColor = () => {
    if (livenessScore === null) return 'grey'
    if (livenessScore > 60) return 'success'
    if (livenessScore > 30) return 'warning'
    return 'error'
  }

  if (error) {
    return (
      <Card>
        <CardContent>
          <Alert severity="error" sx={{ mb: 2 }}>
            {error}
          </Alert>
          <Button variant="contained" onClick={onClose} fullWidth>
            Close
          </Button>
        </CardContent>
      </Card>
    )
  }

  return (
    <Card sx={{ position: 'relative' }}>
      <IconButton
        sx={{ position: 'absolute', top: 8, right: 8, zIndex: 1, bgcolor: 'background.paper' }}
        onClick={onClose}
      >
        ✕
      </IconButton>
      
      <CardContent>
        <Typography variant="h6" gutterBottom align="center">
          Face Verification
        </Typography>
        <Typography variant="body2" color="text.secondary" align="center" sx={{ mb: 2 }}>
          Position your face in the center of the frame
        </Typography>
        
        {isModelLoading && (
          <Box sx={{ mb: 2 }}>
            <Typography variant="body2" align="center" sx={{ mb: 1 }}>
              Loading face detection model...
            </Typography>
            <LinearProgress />
          </Box>
        )}
        
        <Box sx={{ position: 'relative', mb: 2 }}>
          {!capturedPhoto ? (
            <>
              <Box
                sx={{
                  position: 'relative',
                  borderRadius: 2,
                  overflow: 'hidden',
                  bgcolor: 'black',
                  aspectRatio: '4/3',
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center'
                }}
              >
                {loading && (
                  <Box sx={{ position: 'absolute', color: 'white' }}>
                    <CircularProgress color="inherit" />
                    <Typography sx={{ mt: 2, color: 'white' }}>
                      Starting camera...
                    </Typography>
                  </Box>
                )}
                <video
                  ref={videoRef}
                  autoPlay
                  playsInline
                  style={{
                    width: '100%',
                    height: '100%',
                    objectFit: 'cover',
                    display: loading ? 'none' : 'block'
                  }}
                />
                <canvas
                  ref={overlayCanvasRef}
                  style={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    width: '100%',
                    height: '100%',
                    pointerEvents: 'none'
                  }}
                  width={640}
                  height={480}
                />
                <Box
                  sx={{
                    position: 'absolute',
                    top: 0,
                    left: 0,
                    right: 0,
                    bottom: 0,
                    border: `2px solid ${faceDetected ? 'rgba(0,255,0,0.5)' : 'rgba(255,255,255,0.5)'}`,
                    borderRadius: '50%',
                    width: '200px',
                    height: '200px',
                    margin: 'auto',
                    pointerEvents: 'none',
                    transition: 'border-color 0.3s ease'
                  }}
                />
                
                <Box
                  sx={{
                    position: 'absolute',
                    bottom: 16,
                    left: 16,
                    right: 16,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'space-between',
                    bgcolor: 'rgba(0,0,0,0.6)',
                    borderRadius: 1,
                    p: 1
                  }}
                >
                  <Typography variant="caption" sx={{ color: 'white' }}>
                    {detectionStatus}
                  </Typography>
                  {livenessScore !== null && (
                    <Box sx={{ display: 'flex', alignItems: 'center', gap: 1 }}>
                      <Box
                        sx={{
                          width: 8,
                          height: 8,
                          borderRadius: '50%',
                          bgcolor: getLivenessColor(),
                          animation: isLive ? 'pulse 1s infinite' : 'none'
                        }}
                      />
                      <Typography variant="caption" sx={{ color: 'white' }}>
                        {livenessScore}%
                      </Typography>
                    </Box>
                  )}
                </Box>
              </Box>
              
              <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 2, flexWrap: 'wrap' }}>
                <Button
                  variant="contained"
                  onClick={capturePhoto}
                  disabled={loading || !isMediaPipeReady || isDetecting || !faceDetected || !isVideoReady || isCapturing}
                >
                  {isDetecting ? <CircularProgress size={24} /> : '📷 Capture'}
                </Button>
                <Button
                  variant="outlined"
                  onClick={switchCamera}
                  disabled={loading || isDetecting || isCapturing}
                >
                  🔄 Switch Camera
                </Button>
              </Box>
              
              <Alert severity="info" sx={{ mt: 2 }}>
                <Typography variant="caption" component="div">
                  • Ensure good lighting conditions<br />
                  • Remove glasses, mask, or any face covering<br />
                  • Look directly at the camera<br />
                  • Blink occasionally to prove liveness<br />
                  {!faceDetected && '• Move closer to the camera if no face detected'}
                </Typography>
              </Alert>
            </>
          ) : (
            <Box>
              <Box
                sx={{
                  borderRadius: 2,
                  overflow: 'hidden',
                  aspectRatio: '4/3',
                  bgcolor: 'black'
                }}
              >
                <img
                  src={capturedPhoto}
                  alt="Captured"
                  style={{ width: '100%', height: '100%', objectFit: 'cover' }}
                />
              </Box>
              
              <Box sx={{ display: 'flex', justifyContent: 'center', gap: 2, mt: 2 }}>
                <Button
                  variant="outlined"
                  onClick={retakePhoto}
                >
                  🔄 Retake
                </Button>
                <Button
                  variant="contained"
                  color="success"
                  onClick={confirmPhoto}
                >
                  ✓ Confirm & Continue
                </Button>
              </Box>
            </Box>
          )}
        </Box>
        
        {/* Hidden canvas for capturing clean photo without landmarks */}
        <canvas ref={canvasRef} style={{ display: 'none' }} />
      </CardContent>
      
      <style>
        {`
          @keyframes pulse {
            0% { opacity: 1; }
            50% { opacity: 0.3; }
            100% { opacity: 1; }
          }
        `}
      </style>
    </Card>
  )
}

export default PhotoCaptureWithMediaPipe