'use client';

import React, { useState } 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 { useAIExtraction } from '@/hooks/useAIExtraction';
import { ImageAdjustmentModal } from './ImageAdjustmentModal';

interface AIOnboardingProps {
  onCancel: () => void;
  onComplete: (itemData: any) => void;
  categories: any[];
  inventory: any[];
}

export default function AIOnboarding({ onCancel, onComplete, categories, inventory }: AIOnboardingProps) {
  const [showImageAdjustment, setShowImageAdjustment] = useState(false);
  const [adjustingItemIndex, setAdjustingItemIndex] = useState<number | null>(null);
  const [pendingItemData, setPendingItemData] = useState<any>(null);

  const {
    image,
    setImage,
    uploading,
    extractedItems,
    setExtractedItems,
    editingIndex,
    setEditingIndex,
    mode,
    setMode,
    isLive,
    videoRef,
    canvasRef,
    fileInputRef,
    existingTypes,
    existingBoxes,
    startLiveCamera,
    stopLiveCamera,
    captureSnapshot,
    processImage,
    confirmSingleItem: hookConfirmSingleItem,
    confirmAllItems: hookConfirmAllItems,
    updateEditingItem,
    handleFileChange
  } = useAIExtraction(inventory, onComplete);

  const confirmSingleItem = (index: number) => {
    if (!extractedItems[index]) return;

    const data = extractedItems[index];
    const skipPhoto = data._skipPhoto === true;

    if (skipPhoto || !image) {
      hookConfirmSingleItem(index);
      return;
    }

    setPendingItemData({ index, data, skipPhoto });
    setAdjustingItemIndex(index);
    setShowImageAdjustment(true);
  };

  const handleImageAdjustmentConfirm = async (adjustments: { rotation: number; cropBounds: { x: number; y: number; width: number; height: number } } | null) => {
    if (!pendingItemData) return;

    const { index } = pendingItemData;

    if (adjustments && extractedItems[index]) {
      // Override AI-detected values with user adjustments
      const updatedItems = [...extractedItems];
      updatedItems[index] = {
        ...updatedItems[index],
        image_processing: {
          ...updatedItems[index].image_processing,
          rotation_degrees: adjustments.rotation,
          crop_bounds: {
            x: Math.round(adjustments.cropBounds.x),
            y: Math.round(adjustments.cropBounds.y),
            width: Math.round(adjustments.cropBounds.width),
            height: Math.round(adjustments.cropBounds.height)
          },
          user_adjusted: true
        }
      };
      setExtractedItems(updatedItems);
    }

    // Now call the hook's confirm with the updated data
    hookConfirmSingleItem(index);
    setShowImageAdjustment(false);
    setAdjustingItemIndex(null);
    setPendingItemData(null);
  };

  const handleImageAdjustmentCancel = () => {
    setShowImageAdjustment(false);
    setAdjustingItemIndex(null);
    setPendingItemData(null);
  };

  const confirmAllItems = async () => {
    await hookConfirmAllItems();
    onCancel(); // Close modal after bulk completion
  };

  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-normal">AI Discovery</h2>
              <p className="text-xs text-muted font-normal">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-3 md:gap-4 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-normal 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-normal 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-normal">
               {mode === 'box' ? 'Deep Box Analysis' : 'Multi-Item Extraction'}
            </p>
            <p className="text-xs text-muted px-8 text-center leading-relaxed font-normal">
              {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-normal 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-normal 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-3 md:gap-4 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-normal 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-normal 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-normal 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-3 md:gap-4 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-normal 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-normal 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-normal 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-3 md:gap-4 overflow-hidden">
          <div data-testid="ai-onboarding-wizard" className="flex items-center justify-between">
              <span className="text-xs text-muted font-normal">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-normal 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>

          {/* Image Preview Section */}
          {image && (
            <div className="bg-surface/70 border border-slate-800/50 rounded-2xl overflow-hidden">
              <div className="relative h-40 md:h-48 bg-black/20 flex items-center justify-center">
                <img
                  src={image}
                  alt="Extracted label"
                  className="max-w-full max-h-full object-contain"
                />
              </div>
              <div className="p-3 space-y-2">
                <p className="text-xs text-muted font-normal">Extracted Photo</p>
                <div className="flex items-center gap-2">
                  <input
                    type="checkbox"
                    id="save-photo-check"
                    checked={!extractedItems[editingIndex]._skipPhoto}
                    onChange={(e) => updateEditingItem({ _skipPhoto: !e.target.checked })}
                    className="w-4 h-4 rounded border-slate-600 accent-primary cursor-pointer"
                  />
                  <label htmlFor="save-photo-check" className="text-xs text-slate-300 font-normal cursor-pointer">
                    Save this photo with the item
                  </label>
                </div>
              </div>
            </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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal 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-normal">
                {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-normal text-secondary truncate">{item.Item || item.name || "Unknown Item"}</h4>
                  </div>
                  <div className="flex gap-2">
                    <span className="text-xs font-normal px-2 py-0.5 bg-slate-800 text-secondary rounded-md">
                      {item.Type || item.type || "Generic"}
                    </span>
                    <span className="text-xs font-normal 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-normal 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-normal 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>
      )}

      {showImageAdjustment && image && (
        <ImageAdjustmentModal
          imageUrl={image}
          onConfirm={handleImageAdjustmentConfirm}
          onCancel={handleImageAdjustmentCancel}
        />
      )}
    </div>
  );
}
