'use client'; import { useParams as useNextParams, useRouter as useNextRouter } from 'next/navigation'; import { useState, useEffect, useRef, useCallback } from 'react'; import { motion, AnimatePresence } from 'framer-motion'; import { useReviewSession, useLayout, useVerifyLayout, } from '@/hooks/useStatementAPI'; import { useToast } from '@/components/ui/use-toast'; import { Button } from '@/components/ui/button'; import { api } from '@/lib/api'; import { LoadingState, ErrorState } from '@/components/shared'; import { useBeFreeStore } from '@/store/befree-store'; import { Columns, Plus, Trash2, FileText, RefreshCw, HelpCircle, AlertCircle, ArrowRight, ChevronLeft, ChevronRight, ZoomIn, ZoomOut, Maximize2, } from 'lucide-react'; interface ColumnLayout { name: string; header_label: string; x_min: number; x_max: number; col_type: string; confidence: number; } // ─── Color tokens per column type ──────────────────────────────────────────── const colConfig: Record = { date: { bg: 'rgba(22,163,74,0.10)', border: '#16a34a', text: '#15803d', pill: '#dcfce7' }, description: { bg: 'rgba(37,99,235,0.10)', border: '#2563eb', text: '#1d4ed8', pill: '#dbeafe' }, debit: { bg: 'rgba(220,38,38,0.10)', border: '#dc2626', text: '#b91c1c', pill: '#fee2e2' }, credit: { bg: 'rgba(5,150,105,0.10)', border: '#059669', text: '#047857', pill: '#d1fae5' }, balance: { bg: 'rgba(217,119,6,0.10)', border: '#d97706', text: '#b45309', pill: '#fef3c7' }, amount: { bg: 'rgba(124,58,237,0.10)', border: '#7c3aed', text: '#6d28d9', pill: '#ede9fe' }, other: { bg: 'rgba(100,116,139,0.10)', border: '#64748b', text: '#475569', pill: '#f1f5f9' }, }; const getColConfig = (name: string) => colConfig[name] ?? colConfig.other; function FieldLabel({ children }: { children: React.ReactNode }) { return ( ); } // ─── Dual-handle range slider for x_min / x_max ────────────────────────────── function BoundarySlider({ xMin, xMax, pageWidth, color, onChange, }: { xMin: number; xMax: number; pageWidth: number; color: string; onChange: (xMin: number, xMax: number) => void; }) { const trackRef = useRef(null); const dragging = useRef<'min' | 'max' | null>(null); const pct = (v: number) => Math.max(0, Math.min(100, (v / pageWidth) * 100)); const fromPct = (p: number) => Math.round(Math.max(0, Math.min(pageWidth, (p / 100) * pageWidth))); const getEventPct = (e: MouseEvent | TouchEvent) => { if (!trackRef.current) return 0; const rect = trackRef.current.getBoundingClientRect(); const clientX = 'touches' in e ? e.touches[0].clientX : e.clientX; return Math.max(0, Math.min(100, ((clientX - rect.left) / rect.width) * 100)); }; const startDrag = (handle: 'min' | 'max') => (e: React.MouseEvent | React.TouchEvent) => { e.preventDefault(); dragging.current = handle; const onMove = (ev: MouseEvent | TouchEvent) => { if (!dragging.current) return; const p = getEventPct(ev); const val = fromPct(p); if (dragging.current === 'min') { onChange(Math.min(val, xMax - 1), xMax); } else { onChange(xMin, Math.max(val, xMin + 1)); } }; const onUp = () => { dragging.current = null; window.removeEventListener('mousemove', onMove); window.removeEventListener('mouseup', onUp); window.removeEventListener('touchmove', onMove); window.removeEventListener('touchend', onUp); }; window.addEventListener('mousemove', onMove); window.addEventListener('mouseup', onUp); window.addEventListener('touchmove', onMove, { passive: false }); window.addEventListener('touchend', onUp); }; const leftPct = pct(xMin); const rightPct = pct(xMax); return (
{/* Track */}
{/* Rail */}
{/* Active fill */}
{/* Min handle */}
{/* Max handle */}
{/* Numeric readout */}
{xMin} pt ──────── {xMax} pt
); } // ─── Page navigator ─────────────────────────────────────────────────────────── function PageNavigator({ page, totalPages, onChange, }: { page: number; totalPages: number; onChange: (p: number) => void; }) { const [editing, setEditing] = useState(false); const [draft, setDraft] = useState(String(page)); const clamp = (v: number) => Math.max(1, Math.min(totalPages, v)); const commit = () => { const n = parseInt(draft, 10); onChange(isNaN(n) ? page : clamp(n)); setEditing(false); }; return (
{editing ? ( setDraft(e.target.value)} onBlur={commit} onKeyDown={(e) => { if (e.key === 'Enter') commit(); if (e.key === 'Escape') setEditing(false); }} className="w-10 text-center text-xs border border-indigo-400 rounded-lg py-1 focus:outline-none focus:ring-2 focus:ring-indigo-300 font-mono text-slate-800" /> ) : ( )}
); } // ─── Main Feature ───────────────────────────────────────────────────────────── export function LayoutReviewFeature() { const params = useNextParams(); const router = useNextRouter(); const statementId = params.statementId as string; const { toast } = useToast(); const { data: sessionData, isLoading: isSessionLoading } = useReviewSession(statementId); const { data: layoutData, isLoading: isLayoutLoading, refetch: refetchLayout, isError, } = useLayout(statementId); const verifyMutation = useVerifyLayout(statementId); const totalPdfPages = useBeFreeStore((s) => s.totalPdfPages); const setTotalPdfPages = useBeFreeStore((s) => s.setTotalPdfPages); const [columns, setColumns] = useState([]); const [headerPage, setHeaderPage] = useState(1); const [isVerifying, setIsVerifying] = useState(false); const [imageSrc, setImageSrc] = useState(null); const [imageLoading, setImageLoading] = useState(true); const [imageError, setImageError] = useState(false); // zoom: 1 = fit-to-container (default), >1 = user zoomed in const [zoom, setZoom] = useState(1); const imgContainerRef = useRef(null); const initializedRef = useRef(false); const pageWidth = layoutData?.page_width || 612; const pageHeight = layoutData?.page_height || 792; const totalPages = totalPdfPages > 1 ? totalPdfPages : 1; // ── Probe page count via GET ────────────────────────────────────────────── useEffect(() => { if (!statementId) return; if (totalPdfPages > 1) return; let cancelled = false; const probeExists = async (page: number): Promise => { try { const res = await api.head(`/api/v1/statements/${statementId}/page-image/${page}`); return res.status === 200; } catch { return false; } }; const discoverPageCount = async () => { let hi = 1; while (!cancelled && (await probeExists(hi))) { hi *= 2; } if (cancelled) return; let lo = Math.max(1, hi / 2); while (!cancelled && lo < hi - 1) { const mid = Math.floor((lo + hi) / 2); if (await probeExists(mid)) { lo = mid; } else { hi = mid; } } if (!cancelled) { const discovered = lo; if (discovered > 1) setTotalPdfPages(discovered); } }; discoverPageCount(); return () => { cancelled = true; }; // eslint-disable-next-line react-hooks/exhaustive-deps }, [statementId]); // ── Seed columns from layoutData ────────────────────────────────────────── useEffect(() => { if (!layoutData) return; setColumns( (layoutData.columns || []).map((c: any) => ({ name: c.name || 'other', header_label: c.header_label || '', x_min: Math.round(c.x_min ?? 0), x_max: Math.round(c.x_max ?? 0), col_type: c.col_type || 'text', confidence: c.confidence ?? 1.0, })) ); setHeaderPage((layoutData.page_num ?? 0) + 1); if (layoutData.total_pages) setTotalPdfPages(layoutData.total_pages); initializedRef.current = true; }, [layoutData]); const handleRedetect = useCallback(() => { initializedRef.current = false; refetchLayout(); }, [refetchLayout]); // ── Fetch page image ─────────────────────────────────────────────────────── useEffect(() => { if (!statementId || !headerPage) return; let cancelled = false; const fetchImage = async () => { setImageLoading(true); setImageError(false); try { const res = await api.get( `/api/v1/statements/${statementId}/page-image/${headerPage}`, { responseType: 'blob' } ); const objectUrl = URL.createObjectURL(res.data); if (!cancelled) { setImageSrc((prev) => { if (prev) URL.revokeObjectURL(prev); return objectUrl; }); setZoom(1); } } catch (err) { console.error('Page image fetch failed:', err); if (!cancelled) setImageError(true); } finally { if (!cancelled) setImageLoading(false); } }; fetchImage(); return () => { cancelled = true; }; }, [statementId, headerPage]); useEffect(() => { return () => { setImageSrc((prev) => { if (prev) URL.revokeObjectURL(prev); return null; }); }; }, []); // ── Guards ──────────────────────────────────────────────────────────────── if (isSessionLoading || isLayoutLoading) { return ; } if (isError || !layoutData) { return ( ); } // ── Column helpers ──────────────────────────────────────────────────────── const handleAddColumn = () => { setColumns((prev) => [ ...prev, { name: 'other', header_label: 'New Column', x_min: 0, x_max: 100, col_type: 'text', confidence: 1.0 }, ]); }; const handleRemoveColumn = (index: number) => { setColumns((prev) => prev.filter((_, i) => i !== index)); }; const handleColumnChange = (index: number, fields: Partial) => { setColumns((prev) => { const next = [...prev]; next[index] = { ...next[index], ...fields }; return next; }); }; // ── Verify ──────────────────────────────────────────────────────────────── const handleVerify = async () => { if (columns.length === 0) { toast({ title: 'Validation Error', description: 'Configure at least one column.', variant: 'destructive' }); return; } if (columns.some((c) => c.x_min >= c.x_max)) { toast({ title: 'Invalid Boundaries', description: 'Each column must have x_min < x_max.', variant: 'destructive' }); return; } try { setIsVerifying(true); await verifyMutation.mutateAsync({ columns: columns.map((c) => ({ name: c.name, header_label: c.header_label, x_min: Number(c.x_min), x_max: Number(c.x_max), col_type: c.col_type, confidence: c.confidence, })), header_page: Number(headerPage) - 1, }); toast({ title: 'Re-extraction started', description: 'Processing with updated column layout…', variant: 'success' }); router.push(`/processing/${statementId}`); } catch (err: any) { setIsVerifying(false); toast({ title: 'Re-extraction Failed', description: err?.message || 'Could not start re-extraction.', variant: 'destructive' }); } }; const zoomStep = 0.25; const minZoom = 0.5; const maxZoom = 3; // ── Render ───────────────────────────────────────────────────────────────── return (
{/* ── Header ─────────────────────────────────────────────────────────── */}

Re-extract with Custom Layout

Adjust column boundaries then re-run extraction · {sessionData?.fileName || 'Loading…'}

{/* ── Workspace ──────────────────────────────────────────────────────── */}
{/* Full-screen verifying overlay */} {isVerifying && (

Re-extracting…

Processing with updated column boundaries

)} {/* ── LEFT: PDF viewer ─────────────────────────────────────────────── */}
{/* Viewer toolbar */}
{/* Page navigation */} setHeaderPage(p)} /> {/* Zoom controls */}
{/* Scrollable image area */}
1 ? 'grab' : 'default' }} > {imageLoading ? (
Rendering page…
) : imageError || !imageSrc ? (
Failed to load page image.
) : (
{`Page {/* Column overlays */} {columns.map((col, idx) => { const leftPct = Math.max(0, (col.x_min / pageWidth) * 100); const widthPct = Math.max(0.3, ((col.x_max - col.x_min) / pageWidth) * 100); const cfg = getColConfig(col.name); return (
{col.name}
); })}
)}
{/* ── RIGHT: Editor ─────────────────────────────────────────────────── */}
{/* Guide */}

Drag the handles on each column's range slider to adjust boundaries, then click Re-extract to re-run extraction with the updated layout. Column highlights on the page update in real-time.

{/* Columns */}

Column Ranges ({columns.length})

{columns.length === 0 && (
No columns yet — click Add Column to begin.
)}
{columns.map((col, idx) => { const cfg = getColConfig(col.name); const hasError = col.x_min >= col.x_max; return ( {/* Row 1: type + label + delete */}
Type
Header Label handleColumnChange(idx, { header_label: e.target.value })} className="w-full bg-white border border-slate-200 rounded-lg px-2.5 py-1.5 text-xs text-slate-800 focus:outline-none focus:ring-2 focus:ring-indigo-400 transition hover:border-slate-300" />
{/* Row 2: boundary slider */}
Column Boundaries (drag handles) {hasError && (

x_min must be less than x_max

)} handleColumnChange(idx, { x_min: xMin, x_max: xMax })} />
{/* Row 3: pill badge */}
{col.name}
); })}
); }