'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 className="fixed inset-0 z-50 bg-slate-950 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-slate-500 font-bold">Powered by Gemini 2.0 Flash</p>
            </div>
        </div>
        <button onClick={() => { stopLiveCamera(); onCancel(); }} className="p-2 hover:bg-slate-900 rounded-full transition-colors">
          <X size={24} />
        </button>
      </div>

      {!image && !isLive ? (
        <div className="flex-1 flex flex-col gap-6 min-h-0">
          <div className="flex bg-slate-900/50 p-1.5 rounded-2xl border border-slate-800/50 shrink-0">
            <button 
              onClick={() => setMode('item')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold transition-all ${mode === 'item' ? 'bg-primary text-white shadow-lg' : 'text-slate-500 hover:text-slate-300'}`}
            >
              <Package size={18} />
              <span className="text-xs">Discovery Mode</span>
            </button>
            <button 
              onClick={() => setMode('box')}
              className={`flex-1 flex items-center justify-center gap-2 py-3 rounded-xl font-bold transition-all ${mode === 'box' ? 'bg-primary text-white shadow-lg' : 'text-slate-500 hover:text-slate-300'}`}
            >
              <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-slate-900/30 overflow-hidden px-4">
            <div className="w-20 h-20 bg-slate-900 rounded-3xl flex items-center justify-center mb-6 shadow-inner text-primary">
               <Camera size={32} />
            </div>
            <p className="text-slate-300 mb-2 text-center font-bold">
               {mode === 'box' ? 'Deep Box Analysis' : 'Multi-Item Extraction'}
            </p>
            <p className="text-xs text-slate-500 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}
              className="flex flex-col items-center justify-center gap-2 bg-primary text-white rounded-3xl font-bold shadow-2xl shadow-primary/20 active:scale-95 transition-all"
            >
              <Camera size={24} />
              <span className="text-sm">Scan Camera</span>
            </button>
            <button 
              onClick={() => fileInputRef.current?.click()}
              className="flex flex-col items-center justify-center gap-2 bg-slate-900 text-slate-200 border border-slate-800 rounded-3xl font-bold active:scale-95 transition-all"
            >
              <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 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-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 backdrop-blur-md px-4 py-1.5 rounded-full border border-white/10">
               <span className="text-xs font-black text-white uppercase tracking-widest 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}
              className="px-6 py-4 bg-slate-900 border border-slate-800 text-slate-400 rounded-2xl font-bold transition-all active:scale-95"
            >
              Cancel
            </button>
            <button 
              onClick={captureSnapshot}
              className="flex-1 py-4 bg-white text-slate-950 rounded-2xl font-black text-lg shadow-xl shadow-white/10 flex items-center justify-center gap-3 active:scale-95 hover:bg-slate-200"
            >
              <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-slate-950" />
              </div>
              Capture Image
            </button>
          </div>
        </div>
      ) : extractedItems.length === 0 ? (
        <div 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-slate-900">
            <img src={image || undefined} className="w-full h-full object-contain" alt="Captured label" />
            <div className="absolute inset-0 bg-gradient-to-t from-black/60 via-transparent to-transparent pointer-events-none" />
            
            {uploading && (
              <div className="absolute inset-0 bg-slate-950/60 backdrop-blur-sm 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}
              className="px-6 py-4 bg-slate-900 border border-slate-800 text-slate-400 rounded-2xl font-bold transition-all active:scale-95 disabled:opacity-50"
            >
              Retake
            </button>
            <button 
              onClick={processImage} 
              disabled={uploading}
              className="flex-1 py-4 bg-primary text-white rounded-2xl font-black text-lg shadow-xl shadow-primary/30 flex items-center justify-center gap-3 active:scale-95 disabled:opacity-50 hover:bg-blue-500"
            >
              {uploading ? "Analyzing..." : "Extract Data"}
              {!uploading && <Check size={20} />}
            </button>
          </div>
        </div>
      ) : editingIndex !== null ? (
        <div className="flex-1 flex flex-col gap-6 overflow-hidden">
          <div className="flex items-center justify-between">
              <span className="text-xs text-slate-500 font-bold uppercase tracking-wider">Item Details ({editingIndex + 1}/{extractedItems.length})</span>
              <button 
                onClick={() => setEditingIndex(null)}
                className="text-xs text-primary font-bold px-3 py-1 bg-primary/10 rounded-full"
              >
                Back to List
              </button>
          </div>
          
          <div className="flex-1 overflow-y-auto space-y-2 pr-1 scrollbar-hide">
            <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-700 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 className="bg-slate-900/80 py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                 <label className="text-xs text-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200"
                  placeholder="e.g. storage"
                />
                <datalist id="onboarding-categories">
                   {categories.map(c => (
                    <option key={c.id} value={c.name} />
                  ))}
                </datalist>
              </div>
              <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200"
                  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-slate-900/80 py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200"
                  placeholder="e.g. Aqua"
                />
              </div>
              <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-300 py-0"
                placeholder="Product description..."
              />
            </div>

            <div className="grid grid-cols-2 gap-3">
               <div className="bg-slate-900/80 py-3 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200"
                  placeholder="e.g. LC/UPC"
                />
              </div>
              <div className="bg-slate-900/80 px-4 rounded-[1.2rem] border border-slate-800 focus-within:border-primary/50 transition-colors group">
                <label className="text-xs text-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200"
                  placeholder="e.g. 5m / 10G"
                />
              </div>
            </div>

            <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200 py-0 scrollbar-hide"
                placeholder="Heuristic string for local matching..."
              />
            </div>

            <div className="grid grid-cols-2 gap-2">
              <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors tracking-tight uppercase">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-slate-200 uppercase"
                  placeholder="ID code..."
                />
              </div>
              <div className="bg-slate-900/80 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-slate-500 font-bold mb-0.5 block group-focus-within:text-primary transition-colors uppercase 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-slate-200"
                />
              </div>
            </div>
          </div>

          <div className="flex flex-col gap-3 shrink-0">
             <button 
              onClick={() => confirmSingleItem(editingIndex)}
              className="py-5 bg-primary text-white rounded-[1.8rem] font-black text-lg shadow-2xl shadow-primary/20 active:scale-95 transition-all hover:bg-blue-500"
            >
              Add to Catalog
            </button>
          </div>
        </div>
      ) : (
        <div className="flex-1 flex flex-col gap-6 overflow-hidden">
          <div className="flex items-center justify-between">
              <h3 className="text-sm font-black text-slate-400 uppercase tracking-widest">Discovery Dashboard</h3>
              <span 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}
                className="bg-slate-900/50 border border-slate-800 rounded-3xl p-5 flex items-center justify-between group hover:border-primary/40 transition-all active:scale-[0.98]"
              >
                <div 
                  className="flex-1 min-w-0 cursor-pointer"
                  onClick={() => setEditingIndex(idx)}
                >
                  <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-slate-100 truncate">{item.Item || item.name || "Unknown Item"}</h4>
                  </div>
                  <div className="flex gap-2">
                    <span className="text-xs font-black uppercase px-2 py-0.5 bg-slate-800 text-slate-400 rounded-md tracking-wider">
                      {item.Type || item.type || "Generic"}
                    </span>
                    <span className="text-xs font-black uppercase px-2 py-0.5 bg-slate-800 text-slate-500 rounded-md tracking-wider">
                      {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);
                    }}
                    className="p-3 text-slate-600 hover:text-red-500 transition-colors"
                   >
                     <X size={20} />
                   </button>
                   <button 
                    onClick={() => setEditingIndex(idx)}
                    className="p-3 bg-primary/10 text-primary rounded-2xl hover:bg-primary/20 transition-all"
                   >
                     <ChevronDown size={20} className="-rotate-90" />
                   </button>
                </div>
              </div>
            ))}
          </div>

          <div className="flex flex-col gap-3 shrink-0">
             <button 
              onClick={confirmAllItems}
              className="py-5 bg-white text-slate-950 rounded-[1.8rem] font-black text-lg shadow-2xl shadow-white/10 active:scale-95 transition-all hover:bg-slate-200"
            >
              Add {extractedItems.length} items to catalog
            </button>
            <button 
              onClick={() => {
                setExtractedItems([]);
                setImage(null);
              }}
              className="py-3 text-xs text-slate-600 font-bold hover:text-slate-400 tracking-widest uppercase"
            >
              Discard Discovery
            </button>
          </div>
        </div>
      )}
    </div>
  );
}
