'use client'; import { useState, useRef, useEffect } from 'react'; import { X, Camera, RotateCcw, Check } from 'lucide-react'; import clsx from 'clsx'; interface CameraModalProps { isOpen: boolean; onClose: () => void; onCapture: (file: File) => void; } export default function CameraModal({ isOpen, onClose, onCapture }: CameraModalProps) { const videoRef = useRef(null); const canvasRef = useRef(null); const [stream, setStream] = useState(null); const [capturedImage, setCapturedImage] = useState(null); const [error, setError] = useState(null); const [facingMode, setFacingMode] = useState<'user' | 'environment'>('environment'); useEffect(() => { if (isOpen) { startCamera(); } else { stopCamera(); setCapturedImage(null); } return () => stopCamera(); }, [isOpen, facingMode]); const startCamera = async () => { try { setError(null); const mediaStream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: facingMode, width: { ideal: 1280 }, height: { ideal: 720 } }, audio: false }); setStream(mediaStream); if (videoRef.current) { videoRef.current.srcObject = mediaStream; } } catch (err) { console.error('Camera error:', err); setError('Unable to access camera. Please check permissions.'); } }; const stopCamera = () => { if (stream) { stream.getTracks().forEach(track => track.stop()); setStream(null); } }; const switchCamera = () => { setFacingMode(prev => prev === 'user' ? 'environment' : 'user'); }; const capturePhoto = () => { if (videoRef.current && canvasRef.current) { const video = videoRef.current; const canvas = canvasRef.current; canvas.width = video.videoWidth; canvas.height = video.videoHeight; const ctx = canvas.getContext('2d'); if (ctx) { ctx.drawImage(video, 0, 0); const imageDataUrl = canvas.toDataURL('image/jpeg', 0.9); setCapturedImage(imageDataUrl); stopCamera(); } } }; const retake = () => { setCapturedImage(null); startCamera(); }; const confirmCapture = () => { if (capturedImage && canvasRef.current) { canvasRef.current.toBlob((blob) => { if (blob) { const file = new File([blob], `photo_${Date.now()}.jpg`, { type: 'image/jpeg' }); onCapture(file); onClose(); } }, 'image/jpeg', 0.9); } }; if (!isOpen) return null; return (
{/* Header */}

Take Photo

{/* Camera View */}
{error ? (

{error}

) : capturedImage ? ( Captured ) : (
{/* Controls */}
{!capturedImage ? ( <> {/* Switch Camera */} {/* Capture Button */} {/* Placeholder for symmetry */}
) : ( <> {/* Retake */} {/* Confirm */} )}
); }