Files
tfm_ainventory/frontend/components/AIOnboarding.tsx

648 lines
32 KiB
TypeScript

'use client';
import React, { useState, useRef, useEffect } from 'react';
import { toast } from 'react-hot-toast';
import { Camera, Check, RefreshCw, X, Image as ImageIcon, Sparkles, Hash, Layout, Layers, Package, ChevronDown } from 'lucide-react';
import { inventoryApi } from '@/lib/api';
interface AIOnboardingProps {
onCancel: () => void;
onComplete: (itemData: any) => void;
categories: any[];
inventory: any[];
}
export default function AIOnboarding({ onCancel, onComplete, categories, inventory }: AIOnboardingProps) {
const [image, setImage] = useState<string | null>(null);
const [uploading, setUploading] = useState(false);
const [extractedItems, setExtractedItems] = useState<any[]>([]);
const [editingIndex, setEditingIndex] = useState<number | null>(null);
const [mode, setMode] = useState<'item' | 'box'>('item');
const [isLive, setIsLive] = useState(false);
const videoRef = useRef<HTMLVideoElement>(null);
const canvasRef = useRef<HTMLCanvasElement>(null);
const streamRef = useRef<MediaStream | null>(null);
const startLiveCamera = async () => {
try {
setIsLive(true);
const stream = await navigator.mediaDevices.getUserMedia({
video: { facingMode: 'environment', width: { ideal: 1920 }, height: { ideal: 1080 } },
audio: false
});
if (videoRef.current) {
videoRef.current.srcObject = stream;
streamRef.current = stream;
}
} catch (err) {
console.error("Camera access error:", err);
toast.error("Could not access camera for live scan.");
setIsLive(false);
}
};
const stopLiveCamera = () => {
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
streamRef.current = null;
}
setIsLive(false);
};
const captureSnapshot = () => {
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, canvas.width, canvas.height);
const dataUrl = canvas.toDataURL('image/jpeg', 0.85);
setImage(dataUrl);
stopLiveCamera();
}
}
};
const processImage = async () => {
if (!image) return;
setUploading(true);
try {
const blob = await (await fetch(image)).blob();
const formData = new FormData();
formData.append('file', blob, 'label.jpg');
const data = await inventoryApi.analyzeLabel(formData, mode);
if (data.error) {
toast.error(`AI Error: ${data.error}`);
setUploading(false);
return;
}
let parsedData = data;
if (typeof data === 'string') {
try { parsedData = JSON.parse(data); } catch (e) {}
}
const d = parsedData;
// HYPER-ROBUST: Find ANY array in the response if it's not a direct array
let items: any[] = [];
if (Array.isArray(d)) {
items = d;
} else {
const potentialArrayKey = Object.keys(d).find(k => Array.isArray(d[k]));
if (potentialArrayKey) {
items = d[potentialArrayKey];
} else {
// Check for singular object (must have at least name or Item or PN)
const target = d.data || d;
if (target.name || target.Item || target.PartNr || target.part_number) {
items = [target];
}
}
}
if (!items || items.length === 0) {
toast.error("No relevant items detected. Try a closer photo.");
} else {
setExtractedItems(items);
if (items.length === 1) {
setEditingIndex(0);
toast.success("Item identified!");
} else {
toast.success(`Found ${items.length} items!`);
}
}
} catch (error) {
toast.error("Failed to process image with AI");
console.error(error);
} finally {
setUploading(false);
}
};
const confirmSingleItem = (index: number) => {
const data = extractedItems[index];
const newItem = {
name: String(data.Item || data.name || "New AI Item"),
category: String(data.Category || data.category || "Uncategorized"),
type: data.Type || data.type ? String(data.Type || data.type) : null,
part_number: data.PartNr || data.part_number ? String(data.PartNr || data.part_number) : null,
color: data.Color || data.color ? String(data.Color || data.color) : null,
description: String(data.Description || data.description || ""),
connector: data.Connector || data.connector ? String(data.Connector || data.connector) : null,
size: data.Size || data.size ? String(data.Size || data.size) : null,
ocr_text: data.OCR || data.ocr_text ? String(data.OCR || data.ocr_text) : null,
specs: String(data.specs || ""),
barcode: String(data.barcode || data.PartNr || data.part_number || `AI-${Date.now()}-${index}`),
quantity: parseFloat(String(data.quantity || 1)),
min_quantity: 1.0,
box_label: data.box_label ? String(data.box_label) : null,
labels_data: JSON.stringify(data)
};
onComplete(newItem);
if (extractedItems.length > 1) {
const remaining = [...extractedItems];
remaining.splice(index, 1);
setExtractedItems(remaining);
setEditingIndex(null);
} else {
setExtractedItems([]);
setEditingIndex(null);
}
};
const confirmAllItems = async () => {
// Clone items and process them sequentially
const itemsToProcess = [...extractedItems];
setUploading(true);
const toastId = toast.loading(`Adding ${itemsToProcess.length} items...`);
try {
for (let i = 0; i < itemsToProcess.length; i++) {
const data = itemsToProcess[i];
const newItem = {
name: String(data.Item || data.name || "New AI Item"),
category: String(data.Category || data.category || "Uncategorized"),
type: data.Type || data.type ? String(data.Type || data.type) : null,
part_number: data.PartNr || data.part_number ? String(data.PartNr || data.part_number) : null,
color: data.Color || data.color ? String(data.Color || data.color) : null,
description: String(data.Description || data.description || ""),
connector: data.Connector || data.connector ? String(data.Connector || data.connector) : null,
size: data.Size || data.size ? String(data.Size || data.size) : null,
ocr_text: data.OCR || data.ocr_text ? String(data.OCR || data.ocr_text) : null,
specs: String(data.specs || ""),
barcode: String(data.barcode || data.PartNr || data.part_number || `AI-${Date.now()}-${i}`),
quantity: parseFloat(String(data.quantity || 1)),
min_quantity: 1.0,
box_label: data.box_label ? String(data.box_label) : null,
labels_data: JSON.stringify(data)
};
// Wait for parent to process each one
await onComplete(newItem);
}
toast.success(`Successfully added ${itemsToProcess.length} items`, { id: toastId });
setExtractedItems([]);
onCancel(); // Close the modal after bulk completion
} catch (err) {
toast.error("Error during batch add", { id: toastId });
} finally {
setUploading(false);
}
};
const updateEditingItem = (fields: any) => {
if (editingIndex === null) return;
const newItems = [...extractedItems];
newItems[editingIndex] = { ...newItems[editingIndex], ...fields };
setExtractedItems(newItems);
};
// Extract unique item types for suggestions
const existingTypes = Array.from(new Set(inventory.map(i => i.type).filter(Boolean))).sort() as string[];
const existingBoxes = Array.from(new Set(inventory.map(i => i.box_label).filter(Boolean))).sort() as string[];
const fileInputRef = useRef<HTMLInputElement>(null);
const handleFileChange = (e: React.ChangeEvent<HTMLInputElement>) => {
const file = e.target.files?.[0];
if (file) {
const reader = new FileReader();
reader.onload = () => setImage(reader.result as string);
reader.readAsDataURL(file);
}
};
useEffect(() => {
// Cleanup on unmount
return () => {
if (streamRef.current) {
streamRef.current.getTracks().forEach(track => track.stop());
}
};
}, []);
return (
<div data-testid="ai-extraction-overlay" className="fixed inset-0 z-50 bg-background flex flex-col p-6 animate-in fade-in slide-in-from-bottom-5 duration-300">
<div className="flex justify-between items-center mb-6 shrink-0">
<div className="flex items-center gap-3">
<div className="p-2 bg-primary/20 rounded-xl">
<Sparkles className="text-primary w-5 h-5" />
</div>
<div>
<h2 className="text-lg font-bold">AI Discovery</h2>
<p className="text-xs text-muted font-bold">Powered by Gemini 2.0 Flash</p>
</div>
</div>
<button
onClick={() => { stopLiveCamera(); onCancel(); }}
aria-label="Close AI Discovery"
className="p-2 hover:bg-surface rounded-full cursor-pointer transition-colors focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
<X size={24} />
</button>
</div>
{!image && !isLive ? (
<div className="flex-1 flex flex-col gap-6 min-h-0">
<div data-testid="multi-item-toggle" className="flex bg-surface/70 p-1.5 rounded-2xl border border-slate-800/50 shrink-0">
<button
onClick={() => setMode('item')}
aria-label="Select Discovery Mode"
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold cursor-pointer transition-all focus:ring-2 focus:ring-primary focus:outline-none ${mode === 'item' ? 'bg-primary text-white shadow-lg' : 'text-muted hover:text-secondary'}`}
>
<Package size={18} />
<span className="text-xs">Discovery Mode</span>
</button>
<button
onClick={() => setMode('box')}
aria-label="Select Box Lookup mode"
className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold cursor-pointer transition-all focus:ring-2 focus:ring-primary focus:outline-none ${mode === 'box' ? 'bg-primary text-white shadow-lg' : 'text-muted hover:text-secondary'}`}
>
<Layers size={18} />
<span className="text-xs">Box Lookup</span>
</button>
</div>
<div className="flex-1 flex flex-col items-center justify-center border-2 border-dashed border-slate-800 rounded-[2.5rem] bg-surface/30 overflow-hidden px-4">
<div className="w-20 h-20 bg-surface rounded-3xl flex items-center justify-center mb-6 shadow-inner text-primary">
<Camera size={32} />
</div>
<p className="text-secondary mb-2 text-center font-bold">
{mode === 'box' ? 'Deep Box Analysis' : 'Multi-Item Extraction'}
</p>
<p className="text-xs text-muted px-8 text-center leading-relaxed font-bold">
{mode === 'box'
? 'Scan container labels to identify storage locations'
: 'Identify multiple technical items from a single photo or label'}
</p>
</div>
<div className="grid grid-cols-2 gap-4 h-28 shrink-0">
<button
onClick={startLiveCamera}
aria-label="Start camera scan"
className="flex flex-col items-center justify-center gap-2 bg-primary text-white rounded-3xl font-bold shadow-2xl shadow-primary/20 cursor-pointer active:scale-95 transition-all focus:ring-2 focus:ring-blue-400 focus:outline-none"
>
<Camera size={24} />
<span className="text-sm">Scan Camera</span>
</button>
<button
onClick={() => fileInputRef.current?.click()}
data-testid="manual-entry-tab"
aria-label="Upload photo from device"
className="flex flex-col items-center justify-center gap-2 bg-surface text-secondary border border-slate-800 rounded-3xl font-bold cursor-pointer active:scale-95 transition-all focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
<ImageIcon size={24} />
<span className="text-sm">Upload Photo</span>
</button>
</div>
<input type="file" ref={fileInputRef} onChange={handleFileChange} accept="image/*" className="hidden" />
</div>
) : isLive ? (
// LIVE VIEWFINDER MODE
<div data-testid="wizard-step wizard-step-capture" className="flex-1 flex flex-col gap-6 min-h-0 overflow-hidden">
<div data-testid="capture-camera" className="relative flex-1 min-h-0 rounded-[2.5rem] overflow-hidden border-4 border-slate-900 shadow-2xl bg-black">
<video
ref={videoRef}
autoPlay
playsInline
muted
className="w-full h-full object-cover"
/>
<canvas ref={canvasRef} className="hidden" />
<div className="absolute inset-0 border-[20px] border-black/20 pointer-events-none">
<div className="w-full h-full border border-primary/30 rounded-2xl relative">
{/* Corner Markers */}
<div className="absolute top-0 left-0 w-8 h-8 border-t-2 border-l-2 border-primary rounded-tl-xl" />
<div className="absolute top-0 right-0 w-8 h-8 border-t-2 border-r-2 border-primary rounded-tr-xl" />
<div className="absolute bottom-0 left-0 w-8 h-8 border-b-2 border-l-2 border-primary rounded-bl-xl" />
<div className="absolute bottom-0 right-0 w-8 h-8 border-b-2 border-r-2 border-primary rounded-br-xl" />
</div>
</div>
<div className="absolute top-6 left-1/2 -translate-x-1/2 bg-black/60 px-4 py-1.5 rounded-full border border-white/10">
<span className="text-xs font-black text-white flex items-center gap-2">
<div className="w-1.5 h-1.5 rounded-full bg-red-500 animate-pulse" />
Live Viewfinder
</span>
</div>
</div>
<div className="flex gap-4 shrink-0 pb-2">
<button
onClick={stopLiveCamera}
aria-label="Cancel camera scan"
className="px-6 py-4 bg-surface border border-slate-800 text-secondary rounded-2xl font-bold cursor-pointer transition-all active:scale-95 focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
Cancel
</button>
<button
onClick={captureSnapshot}
data-testid="capture-button"
aria-label="Capture image from camera"
className="flex-1 py-4 bg-white text-slate-950 rounded-2xl font-black text-lg shadow-xl shadow-white/10 cursor-pointer flex items-center justify-center gap-3 active:scale-95 hover:bg-slate-200 transition-all focus:ring-2 focus:ring-offset-2 focus:ring-offset-slate-950 focus:ring-white focus:outline-none"
>
<div className="w-5 h-5 rounded-full border-2 border-slate-950 flex items-center justify-center">
<div className="w-2.5 h-2.5 rounded-full bg-background" />
</div>
Capture Image
</button>
</div>
</div>
) : extractedItems.length === 0 ? (
<div data-testid="wizard-step" className="flex-1 flex flex-col gap-6 min-h-0 overflow-hidden">
<div className="relative flex-1 min-h-0 rounded-[2.5rem] overflow-hidden border-4 border-slate-900 shadow-2xl bg-surface">
<img src={image || undefined} className="w-full h-full object-contain" alt="Captured label" />
<div className="absolute inset-0 bg-black/30 pointer-events-none" />
{uploading && (
<div className="absolute inset-0 bg-background/60 flex flex-col items-center justify-center gap-4 z-10 transition-all">
<div className="relative">
<RefreshCw className="w-12 h-12 text-primary animate-spin" />
<Sparkles className="absolute -top-2 -right-2 text-amber-400 w-6 h-6 animate-pulse" />
</div>
<p className="text-white font-black tracking-tight text-sm">Gemini is processing...</p>
</div>
)}
</div>
<div className="flex gap-4 shrink-0 pb-2">
<button
onClick={() => setImage(null)}
disabled={uploading}
data-testid="retake-button"
aria-label="Retake photo"
className="px-6 py-4 bg-surface border border-slate-800 text-secondary rounded-2xl font-bold cursor-pointer transition-all active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed focus:ring-2 focus:ring-blue-500 focus:outline-none"
>
Retake
</button>
<button
onClick={processImage}
disabled={uploading}
aria-label="Extract data from image"
className="flex-1 py-4 bg-primary text-white rounded-2xl font-black text-lg shadow-xl shadow-primary/30 cursor-pointer flex items-center justify-center gap-3 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed hover:bg-blue-500 transition-all focus:ring-2 focus:ring-blue-400 focus:outline-none"
>
{uploading ? "Analyzing..." : "Extract Data"}
{!uploading && <Check size={20} />}
</button>
</div>
</div>
) : editingIndex !== null ? (
<div data-testid="extraction-results-form" className="flex-1 flex flex-col gap-6 overflow-hidden">
<div data-testid="ai-onboarding-wizard" className="flex items-center justify-between">
<span className="text-xs text-muted font-bold">Item Details (<span data-testid="current-step">{editingIndex + 1}</span>/<span data-testid="total-steps">{extractedItems.length}</span>)</span>
<button
onClick={() => setEditingIndex(null)}
aria-label="Back to item list"
className="text-xs text-primary font-bold px-3 py-1 bg-primary/10 rounded-full cursor-pointer transition-colors focus:ring-2 focus:ring-primary focus:outline-none"
>
Back to List
</button>
</div>
<div className="flex-1 overflow-y-auto space-y-2 pr-1 scrollbar-hide">
<div data-testid="extracted-name" className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Item Name</label>
<textarea
value={extractedItems[editingIndex].Item || extractedItems[editingIndex].name || ''}
onChange={(e) => updateEditingItem({ Item: e.target.value })}
className="bg-transparent w-full text-lg font-bold outline-none text-white placeholder:text-muted resize-none h-8 leading-tight selection:bg-primary/30 py-0"
placeholder="SSD, SFP, Cable..."
/>
</div>
<div className="grid grid-cols-2 gap-4">
<div data-testid="extracted-category" className="bg-surface py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Category</label>
<input
type="text"
list="onboarding-categories"
value={extractedItems[editingIndex].Category || extractedItems[editingIndex].category || ''}
onChange={(e) => updateEditingItem({ Category: e.target.value })}
className="bg-transparent w-full font-bold outline-none text-secondary"
placeholder="e.g. storage"
/>
<datalist id="onboarding-categories">
{categories.map(c => (
<option key={c.id} value={c.name} />
))}
</datalist>
</div>
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Item Type</label>
<input
value={extractedItems[editingIndex].Type || extractedItems[editingIndex].type || ''}
list="onboarding-types"
onChange={(e) => updateEditingItem({ Type: e.target.value })}
className="bg-transparent w-full text-sm font-bold outline-none text-secondary"
placeholder="e.g. spare parts"
/>
<datalist id="onboarding-types">
{existingTypes.map(t => <option key={t} value={t} />)}
</datalist>
</div>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="bg-surface py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Item Color</label>
<input
value={extractedItems[editingIndex].Color || extractedItems[editingIndex].color || ''}
onChange={(e) => updateEditingItem({ Color: e.target.value })}
className="bg-transparent w-full font-bold outline-none text-secondary"
placeholder="e.g. Aqua"
/>
</div>
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Box / Container</label>
<input
value={extractedItems[editingIndex].box_label || ''}
list="onboarding-boxes"
onChange={(e) => updateEditingItem({ box_label: e.target.value })}
className="bg-transparent w-full text-sm font-bold outline-none text-primary"
placeholder="e.g. Box 1"
/>
<datalist id="onboarding-boxes">
{existingBoxes.map(b => <option key={b} value={b} />)}
</datalist>
</div>
</div>
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Description</label>
<textarea
value={extractedItems[editingIndex].Description || extractedItems[editingIndex].description || ''}
onChange={(e) => updateEditingItem({ Description: e.target.value })}
className="bg-transparent w-full text-sm leading-tight outline-none resize-none h-8 text-secondary py-0"
placeholder="Product description..."
/>
</div>
<div className="grid grid-cols-2 gap-3">
<div className="bg-surface py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Connector</label>
<input
value={extractedItems[editingIndex].Connector || extractedItems[editingIndex].connector || ''}
onChange={(e) => updateEditingItem({ Connector: e.target.value })}
className="bg-transparent w-full font-bold outline-none text-secondary"
placeholder="e.g. LC/UPC"
/>
</div>
<div className="bg-surface px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Size / Length</label>
<input
value={extractedItems[editingIndex].Size || extractedItems[editingIndex].size || ''}
onChange={(e) => updateEditingItem({ Size: e.target.value })}
className="bg-transparent w-full text-sm font-bold outline-none text-secondary"
placeholder="e.g. 5m / 10G"
/>
</div>
</div>
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">OCR Matching Key</label>
<textarea
value={extractedItems[editingIndex].OCR || extractedItems[editingIndex].ocr_text || ''}
onChange={(e) => updateEditingItem({ OCR: e.target.value })}
className="bg-transparent w-full text-sm font-bold leading-tight outline-none resize-none h-10 text-secondary py-0 scrollbar-hide"
placeholder="Heuristic string for local matching..."
/>
</div>
<div className="grid grid-cols-2 gap-2">
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight">Part Number</label>
<input
value={extractedItems[editingIndex].PartNr || extractedItems[editingIndex].part_number || ''}
onChange={(e) => updateEditingItem({ PartNr: e.target.value })}
className="bg-transparent w-full font-mono text-sm font-bold outline-none text-secondary"
placeholder="ID code..."
/>
</div>
<div className="bg-surface py-2.5 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
<label className="text-xs text-muted font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tighter">Initial Qty</label>
<input
type="number"
value={extractedItems[editingIndex].quantity || 1}
onChange={(e) => updateEditingItem({ quantity: parseFloat(e.target.value) })}
className="bg-transparent w-full font-black text-base outline-none text-secondary"
/>
</div>
</div>
</div>
<div className="flex flex-col gap-3 shrink-0">
<button
onClick={() => confirmSingleItem(editingIndex)}
data-testid="confirm-extraction"
aria-label="Add item to catalog"
className="py-5 bg-primary text-white rounded-[1.8rem] font-black text-lg shadow-2xl shadow-primary/20 cursor-pointer active:scale-95 transition-all hover:bg-blue-500 focus:ring-2 focus:ring-blue-400 focus:outline-none"
>
Add to Catalog
</button>
</div>
</div>
) : (
<div data-testid="manual-entry-form" className="flex-1 flex flex-col gap-6 overflow-hidden">
<div className="flex items-center justify-between">
<h3 className="text-sm font-black text-secondary">Discovery Dashboard</h3>
<span data-testid="wizard-progress" className="text-xs bg-primary/20 text-primary px-3 py-1 rounded-full font-bold">
{extractedItems.length} items found
</span>
</div>
<div className="flex-1 overflow-y-auto space-y-3 pr-1 scrollbar-hide">
{extractedItems.map((item, idx) => (
<div
key={idx}
data-testid="extraction-item-row"
className="bg-surface/70 border border-slate-800 rounded-3xl p-5 flex items-center justify-between group hover:border-primary/40 transition-all active:scale-[0.98] focus-within:border-primary/60 focus-within:ring-2 focus-within:ring-primary/20"
>
<div
className="flex-1 min-w-0 cursor-pointer"
onClick={() => setEditingIndex(idx)}
role="button"
tabIndex={0}
onKeyDown={(e) => {
if (e.key === 'Enter' || e.key === ' ') {
e.preventDefault();
setEditingIndex(idx);
}
}}
aria-label={`Edit item: ${item.Item || item.name}`}
>
<div className="flex items-center gap-3 mb-2">
<div className="w-8 h-8 rounded-xl bg-primary/10 flex items-center justify-center text-primary">
<Package size={16} />
</div>
<h4 className="font-black text-secondary truncate">{item.Item || item.name || "Unknown Item"}</h4>
</div>
<div className="flex gap-2">
<span className="text-xs font-black px-2 py-0.5 bg-slate-800 text-secondary rounded-md">
{item.Type || item.type || "Generic"}
</span>
<span className="text-xs font-black px-2 py-0.5 bg-slate-800 text-muted rounded-md">
{item.PartNr || item.part_number || "No P/N"}
</span>
</div>
</div>
<div className="flex items-center gap-2">
<button
onClick={() => {
const newItems = [...extractedItems];
newItems.splice(idx, 1);
setExtractedItems(newItems);
}}
aria-label={`Delete item: ${item.Item || item.name}`}
className="p-3 text-secondary hover:text-red-500 cursor-pointer transition-colors focus:ring-2 focus:ring-red-500 focus:outline-none rounded-lg"
>
<X size={20} />
</button>
<button
onClick={() => setEditingIndex(idx)}
aria-label={`Edit item: ${item.Item || item.name}`}
className="p-3 bg-primary/10 text-primary rounded-2xl cursor-pointer hover:bg-primary/20 transition-all focus:ring-2 focus:ring-primary focus:outline-none"
>
<ChevronDown size={20} className="-rotate-90" />
</button>
</div>
</div>
))}
</div>
<div className="flex flex-col gap-3 shrink-0">
<button
onClick={confirmAllItems}
aria-label={`Add ${extractedItems.length} items to catalog`}
className="py-5 bg-white text-slate-950 rounded-[1.8rem] font-black text-lg shadow-2xl shadow-white/10 cursor-pointer active:scale-95 transition-all hover:bg-slate-200 focus:ring-2 focus:ring-offset-2 focus:ring-offset-slate-950 focus:ring-white focus:outline-none"
>
Add {extractedItems.length} items to catalog
</button>
<button
onClick={() => {
setExtractedItems([]);
setImage(null);
}}
data-testid="reject-extraction"
aria-label="Discard discovery session"
className="py-3 text-xs text-secondary font-bold cursor-pointer hover:text-secondary transition-colors focus:ring-2 focus:ring-slate-500 focus:outline-none rounded px-2"
>
Discard Discovery
</button>
</div>
</div>
)}
</div>
);
}