'use client'; import { useState, useRef, useCallback, useEffect } from 'react'; import { api } from '@/lib/api'; export default function Scanner({ onComplete }: { onComplete: () => void }) { const [mode, setMode] = useState<'idle' | 'camera' | 'processing' | 'result'>('idle'); const [result, setResult] = useState(null); const [error, setError] = useState(''); const videoRef = useRef(null); const canvasRef = useRef(null); const streamRef = useRef(null); const fileInputRef = useRef(null); const stopCamera = useCallback(() => { if (streamRef.current) { streamRef.current.getTracks().forEach(t => t.stop()); streamRef.current = null; } }, []); useEffect(() => { return () => stopCamera(); }, [stopCamera]); const startCamera = async () => { setError(''); try { const stream = await navigator.mediaDevices.getUserMedia({ video: { facingMode: 'environment', width: { ideal: 1920 }, height: { ideal: 1080 } } }); streamRef.current = stream; if (videoRef.current) { videoRef.current.srcObject = stream; await videoRef.current.play(); } setMode('camera'); } catch (err) { setError('Não foi possível acessar a câmera. Verifique as permissões.'); } }; const capturePhoto = () => { if (!videoRef.current || !canvasRef.current) return; const video = videoRef.current; const canvas = canvasRef.current; canvas.width = video.videoWidth; canvas.height = video.videoHeight; const ctx = canvas.getContext('2d')!; ctx.drawImage(video, 0, 0); const base64 = canvas.toDataURL('image/jpeg', 0.85); stopCamera(); processImage(base64); }; const handleFileUpload = (e: React.ChangeEvent) => { const file = e.target.files?.[0]; if (!file) return; const reader = new FileReader(); reader.onload = (ev) => { const base64 = ev.target?.result as string; processImage(base64); }; reader.readAsDataURL(file); }; const processImage = async (base64: string) => { setMode('processing'); setError(''); try { const res = await api.scanDocument(base64); setResult(res); setMode('result'); } catch (err: any) { setError(err.message); setMode('idle'); } }; const categoryColors: Record = { contrato: 'bg-blue-500/20 text-blue-400', nf: 'bg-green-500/20 text-green-400', receita: 'bg-pink-500/20 text-pink-400', rg: 'bg-yellow-500/20 text-yellow-400', cnh: 'bg-orange-500/20 text-orange-400', certidao: 'bg-purple-500/20 text-purple-400', boleto: 'bg-red-500/20 text-red-400', outro: 'bg-gray-500/20 text-gray-400', }; const categoryLabels: Record = { contrato: '📄 Contrato', nf: '🧾 Nota Fiscal', receita: '💊 Receita', rg: '🪪 RG', cnh: '🚗 CNH', certidao: '📋 Certidão', boleto: '💰 Boleto', outro: '📎 Outro', }; if (mode === 'camera') { return (