import React, { useState, useRef, useCallback, useEffect } from 'react';
import { ProcessedImage, ProcessingOptions, ImageFormat, WatermarkPosition, GalleryLayout } from '../types.ts';
import { formatSize, processImage, readFileAsDataURL } from '../utils/imageProcessor.ts';

interface ImageToolProps {
  title: string;
  description: string;
  mode: 'compress' | 'resize' | 'watermark' | 'gallery';
}

interface Preset {
  name: string;
  width?: number;
  height?: number;
  category: string;
}

const PRESETS: Preset[] = [
  { name: 'Custom', width: undefined, height: undefined, category: 'Manual' },
  { name: 'Instagram Square', width: 1080, height: 1080, category: 'Social Media' },
  { name: 'Instagram Portrait', width: 1080, height: 1350, category: 'Social Media' },
  { name: 'Instagram Story', width: 1080, height: 1920, category: 'Social Media' },
  { name: 'Facebook Post', width: 1200, height: 630, category: 'Social Media' },
  { name: 'Facebook Cover', width: 851, height: 315, category: 'Social Media' },
  { name: 'YouTube Thumbnail', width: 1280, height: 720, category: 'Social Media' },
  { name: 'YouTube Cover', width: 2560, height: 1440, category: 'Social Media' },
  { name: 'X (Twitter) Post', width: 1200, height: 675, category: 'Social Media' },
  { name: 'LinkedIn Post', width: 1200, height: 627, category: 'Social Media' },
  { name: 'Full HD (1080p)', width: 1920, height: 1080, category: 'Display' },
  { name: '4K Ultra HD', width: 3840, height: 2160, category: 'Display' },
];

const AdsterraNativeBanner: React.FC<{ mode: string }> = ({ mode }) => {
  const containerId = "container-af35530bd36f08c72364701a55854a2a";
  const scriptUrl = "https://cutterbewilderedvile.com/af35530bd36f08c72364701a55854a2a/invoke.js";

  useEffect(() => {
    const injectAd = () => {
      const container = document.getElementById(containerId);
      if (!container) return;
      container.innerHTML = '';
      const oldScripts = document.querySelectorAll(`script[src*="cutterbewilderedvile.com"]`);
      oldScripts.forEach(s => s.remove());
      const script = document.createElement('script');
      script.async = true;
      script.dataset.cfasync = "false";
      script.src = scriptUrl;
      container.appendChild(script);
    };

    const timer = setTimeout(() => {
        if ('requestIdleCallback' in window) {
            requestIdleCallback(injectAd);
        } else {
            injectAd();
        }
    }, 1000);

    return () => {
      clearTimeout(timer);
      const container = document.getElementById(containerId);
      if (container) container.innerHTML = '';
    };
  }, [mode]);

  return (
    <div id={containerId} className="w-full flex items-center justify-center min-h-[160px] bg-slate-50/50 rounded-lg overflow-hidden">
      <div className="animate-pulse text-[10px] text-slate-300 uppercase tracking-widest font-black text-center">
        Ad Center
      </div>
    </div>
  );
};

const ImageTool: React.FC<ImageToolProps> = ({ title, description, mode }) => {
  const [images, setImages] = useState<ProcessedImage[]>([]);
  const [isProcessing, setIsProcessing] = useState(false);
  const [quality, setQuality] = useState(0.8);
  const [format, setFormat] = useState<ImageFormat>('image/jpeg');
  const [width, setWidth] = useState<number | undefined>(undefined);
  const [height, setHeight] = useState<number | undefined>(undefined);
  const [maintainAspect, setMaintainAspect] = useState(true);
  const [selectedPreset, setSelectedPreset] = useState<string>('Custom');
  
  const [watermarkDataUrl, setWatermarkDataUrl] = useState<string | undefined>(undefined);
  const [watermarkPosition, setWatermarkPosition] = useState<WatermarkPosition>('bottom-right');
  const [watermarkOpacity, setWatermarkOpacity] = useState(0.8);
  const [watermarkScale, setWatermarkScale] = useState(0.2);

  const [galleryLayout, setGalleryLayout] = useState<GalleryLayout>('masonry');
  const [isGalleryGenerated, setIsGalleryGenerated] = useState(false);
  const galleryRef = useRef<HTMLDivElement>(null);

  const fileInputRef = useRef<HTMLInputElement>(null);
  const folderInputRef = useRef<HTMLInputElement>(null);
  const logoInputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (images.length > 0) {
      setImages(prev => prev.map(img => ({ ...img, status: 'pending', progress: 0 })));
    }
    setIsGalleryGenerated(false);
  }, [mode]);

  const handleFiles = useCallback((files: FileList | null) => {
    if (!files) return;
    const newImages: ProcessedImage[] = Array.from(files)
      .filter(file => file.type.startsWith('image/'))
      .map(file => ({
        id: Math.random().toString(36).substr(2, 9),
        file,
        name: file.name,
        originalSize: file.size,
        dataUrl: URL.createObjectURL(file),
        status: 'pending',
        progress: 0,
        format: file.type as ImageFormat
      }));
    setImages(prev => [...prev, ...newImages]);
    // Reset gallery generated state when new images are added to ensure manual click
    setIsGalleryGenerated(false);
  }, []);

  const handleLogoUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
    const file = e.target.files?.[0];
    if (file) {
      const dataUrl = await readFileAsDataURL(file);
      setWatermarkDataUrl(dataUrl);
    }
  };

  const handlePresetChange = (presetName: string) => {
    setSelectedPreset(presetName);
    const preset = PRESETS.find(p => p.name === presetName);
    if (preset && preset.name !== 'Custom') {
      setWidth(preset.width);
      setHeight(preset.height);
    } else {
      setWidth(undefined);
      setHeight(undefined);
    }
  };

  const clearAll = () => {
    images.forEach(img => URL.revokeObjectURL(img.dataUrl));
    setImages([]);
    setIsGalleryGenerated(false);
    setWatermarkDataUrl(undefined);
  };

  const removeImage = (id: string) => {
    setImages(prev => prev.filter(img => img.id !== id));
    setIsGalleryGenerated(false);
  };

  const processAll = async () => {
    if (images.length === 0 || isProcessing) return;

    if (mode === 'gallery') {
      setIsProcessing(true);
      // For gallery, we just "generate" the view locally
      await new Promise(resolve => setTimeout(resolve, 800));
      setIsGalleryGenerated(true);
      setIsProcessing(false);
      return;
    }

    setIsProcessing(true);
    const updatedImages: ProcessedImage[] = images.map(img => ({ ...img, status: img.status === 'completed' ? 'pending' : img.status }));
    
    for (let i = 0; i < updatedImages.length; i++) {
      if (updatedImages[i].status === 'completed') continue;
      
      try {
        updatedImages[i].status = 'processing';
        setImages([...updatedImages]);
        const options: ProcessingOptions = {
          quality,
          format,
          width: mode === 'resize' ? width : undefined,
          height: mode === 'resize' ? height : undefined,
          maintainAspectRatio: maintainAspect,
          watermarkDataUrl: mode === 'watermark' ? watermarkDataUrl : undefined,
          watermarkPosition: mode === 'watermark' ? watermarkPosition : undefined,
          watermarkOpacity: mode === 'watermark' ? watermarkOpacity : undefined,
          watermarkScale: mode === 'watermark' ? watermarkScale : undefined
        };
        const result = await processImage(updatedImages[i].file, options);
        updatedImages[i].compressedSize = result.blob.size;
        updatedImages[i].status = 'completed';
        updatedImages[i].width = result.width;
        updatedImages[i].height = result.height;
        updatedImages[i].progress = 100;
        updatedImages[i].dataUrl = URL.createObjectURL(result.blob);
      } catch (error) {
        updatedImages[i].status = 'error';
      }
      setImages([...updatedImages]);
    }
    setIsProcessing(false);
  };

  // Auto-process effect: When images are added, automatically trigger processing
  // BUT: Disable auto-generation for gallery mode as requested.
  useEffect(() => {
    if (images.length > 0 && !isProcessing && mode !== 'gallery') {
      const hasUnprocessed = images.some(img => img.status === 'pending');
      if (hasUnprocessed) {
        processAll();
      }
    }
  }, [images.length, mode]);

  const downloadAll = async () => {
    const completedImages = images.filter(img => img.status === 'completed');
    if (completedImages.length === 0) return;
    
    const JSZip = (await import('https://esm.sh/jszip@3.10.1?bundle')).default;

    if (completedImages.length === 1) {
      const link = document.createElement('a');
      link.href = completedImages[0].dataUrl;
      link.download = `opti-${completedImages[0].name.split('.')[0]}.${format.split('/')[1]}`;
      link.click();
      return;
    }
    
    const zip = new JSZip();
    for (const img of completedImages) {
      const response = await fetch(img.dataUrl);
      const blob = await response.blob();
      zip.file(`opti-${img.name.split('.')[0]}.${format.split('/')[1]}`, blob);
    }
    const content = await zip.generateAsync({ type: 'blob' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(content);
    link.download = 'optimized-images.zip';
    link.click();
  };

  const downloadZipOfOriginals = async () => {
    if (images.length === 0) return;
    const JSZip = (await import('https://esm.sh/jszip@3.10.1?bundle')).default;
    const zip = new JSZip();
    for (const img of images) {
      zip.file(img.name, img.file);
    }
    const content = await zip.generateAsync({ type: 'blob' });
    const link = document.createElement('a');
    link.href = URL.createObjectURL(content);
    link.download = 'original-images.zip';
    link.click();
  };

  const downloadGalleryAsPDF = async () => {
    if (!galleryRef.current) return;
    const html2canvas = (await import('https://esm.sh/html2canvas@1.4.1')).default;
    const { jsPDF } = await import('https://esm.sh/jspdf@2.5.1');

    const canvas = await html2canvas(galleryRef.current, { useCORS: true, scale: 2 });
    const imgData = canvas.toDataURL('image/png');
    const pdf = new jsPDF({
      orientation: canvas.width > canvas.height ? 'landscape' : 'portrait',
      unit: 'px',
      format: [canvas.width, canvas.height]
    });
    pdf.addImage(imgData, 'PNG', 0, 0, canvas.width, canvas.height);
    pdf.save('gallery-export.pdf');
  };

  const downloadGalleryAsJPG = async () => {
    if (!galleryRef.current) return;
    const html2canvas = (await import('https://esm.sh/html2canvas@1.4.1')).default;
    const canvas = await html2canvas(galleryRef.current, { useCORS: true, scale: 2 });
    const link = document.createElement('a');
    link.href = canvas.toDataURL('image/jpeg', 0.9);
    link.download = 'gallery-snapshot.jpg';
    link.click();
  };

  if (mode === 'gallery') {
    return (
      <div className="space-y-8 bg-white p-6 sm:p-10 rounded-3xl border border-slate-100 shadow-sm max-w-6xl mx-auto">
        <div className="flex flex-col lg:flex-row gap-8">
          <div className="w-full lg:w-2/3 space-y-6">
            <div className="flex justify-between items-center border-b border-slate-100 pb-2 mb-8">
                <h2 className="text-xl sm:text-2xl font-black text-black tracking-tight uppercase">Gallery Generator</h2>
                <button onClick={clearAll} disabled={images.length === 0} className={`text-xs font-black uppercase tracking-widest transition-colors ${images.length > 0 ? 'text-red-500 hover:text-red-700' : 'text-slate-300 cursor-not-allowed'}`}>Clear All</button>
            </div>
            
            <div className="space-y-6">
              <div className="space-y-2">
                <label className="text-sm font-bold text-slate-500 uppercase tracking-wide block">Add Visual Content</label>
                <div className="flex flex-col sm:flex-row items-center gap-3">
                  <button onClick={() => fileInputRef.current?.click()} className="w-full sm:w-auto px-6 py-3 bg-slate-100 border border-slate-200 rounded-xl text-sm font-bold hover:bg-slate-200 transition-colors flex items-center justify-center gap-2">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
                    Select Images
                  </button>
                  <button onClick={() => folderInputRef.current?.click()} className="w-full sm:w-auto px-6 py-3 bg-slate-100 border border-slate-200 rounded-xl text-sm font-bold hover:bg-slate-200 transition-colors flex items-center justify-center gap-2">
                    <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
                    Upload Folder
                  </button>
                  <span className="text-slate-400 text-sm italic">{images.length > 0 ? `${images.length} files selected` : "No files selected"}</span>
                  <input type="file" multiple accept="image/*" className="hidden" ref={fileInputRef} onChange={(e) => handleFiles(e.target.files)} />
                  <input type="file" {...({ webkitdirectory: "", directory: "" } as any)} className="hidden" ref={folderInputRef} onChange={(e) => handleFiles(e.target.files)} />
                </div>
              </div>
              <div className="space-y-2">
                <label htmlFor="gallery-layout-select" className="text-sm font-bold text-slate-500 uppercase tracking-wide block">Layout Style</label>
                <select id="gallery-layout-select" value={galleryLayout} onChange={(e) => setGalleryLayout(e.target.value as GalleryLayout)} className="w-full sm:w-80 p-3 border border-slate-200 rounded-xl bg-white text-black font-bold focus:ring-2 focus:ring-slate-100 outline-none appearance-none cursor-pointer shadow-sm">
                  <option value="masonry">Masonry</option><option value="grid">Grid</option><option value="collage">Collage</option><option value="slideshow">Slideshow</option>
                </select>
              </div>
            </div>

            {/* Buttons are visible by default */}
            <div className="flex flex-wrap gap-3 pt-6">
              <button 
                onClick={processAll} 
                disabled={isProcessing || images.length === 0} 
                className="px-8 py-4 bg-black text-white rounded-xl text-base font-black hover:bg-slate-800 disabled:bg-slate-300 transition-all shadow-md uppercase"
              >
                {isProcessing ? 'Generating...' : 'Generate Gallery'}
              </button>
              <button 
                onClick={downloadZipOfOriginals} 
                disabled={images.length === 0}
                className="px-5 py-4 bg-slate-100 text-black rounded-xl text-sm font-black hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-all uppercase"
              >
                ZIP Archive
              </button>
              <button 
                onClick={downloadGalleryAsPDF} 
                disabled={!isGalleryGenerated}
                className="px-5 py-4 bg-slate-100 text-black rounded-xl text-sm font-black hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-all uppercase"
              >
                Export PDF
              </button>
              <button 
                onClick={downloadGalleryAsJPG} 
                disabled={!isGalleryGenerated}
                className="px-5 py-4 bg-slate-100 text-black rounded-xl text-sm font-black hover:bg-slate-200 disabled:opacity-50 disabled:cursor-not-allowed transition-all uppercase"
              >
                Snap JPG
              </button>
            </div>
          </div>
          <div className="w-full lg:w-1/3">
            <div className="bg-[#f8fafc] border border-slate-100 rounded-[2rem] p-6 h-full min-h-[300px] flex flex-col items-center relative overflow-hidden">
               <p className="text-[9px] uppercase tracking-[0.2em] text-[#94a3b8] font-black mb-6 relative z-10">Advertisement</p>
               <AdsterraNativeBanner mode={mode} />
            </div>
          </div>
        </div>

        {/* List of images currently in selection */}
        {images.length > 0 && (
          <div className="mt-8">
             <h3 className="text-xs font-black text-slate-400 uppercase tracking-widest mb-4">Selected Assets ({images.length})</h3>
             <div className="grid grid-cols-2 sm:grid-cols-4 md:grid-cols-6 gap-3">
                {images.map(img => (
                  <div key={img.id} className="relative group aspect-square rounded-lg overflow-hidden bg-slate-50 border border-slate-200">
                    <img src={img.dataUrl} alt={img.name} className="w-full h-full object-cover" />
                    <button onClick={() => removeImage(img.id)} className="absolute top-1 right-1 bg-white/90 text-red-500 rounded-full w-5 h-5 flex items-center justify-center font-bold text-xs opacity-0 group-hover:opacity-100 transition-opacity shadow-sm">×</button>
                  </div>
                ))}
             </div>
          </div>
        )}

        {isGalleryGenerated && (
          <div className="mt-12 border-t border-slate-100 pt-12">
             <div ref={galleryRef} className={`bg-white p-8 rounded-3xl border border-slate-200 shadow-sm ${
                  galleryLayout === 'masonry' ? 'columns-1 sm:columns-2 md:columns-3 gap-6 space-y-6' : 
                  galleryLayout === 'grid' ? 'grid grid-cols-2 md:grid-cols-4 gap-6' :
                  galleryLayout === 'collage' ? 'grid grid-cols-4 grid-rows-2 gap-6' : 
                  'flex flex-col items-center space-y-6'
                }`}>
                {images.map((img, idx) => (
                  <div key={img.id} className={`overflow-hidden rounded-2xl bg-slate-50 border border-slate-100 ${
                      galleryLayout === 'collage' && idx % 3 === 0 ? 'col-span-2 row-span-2' : ''
                    } ${galleryLayout === 'slideshow' ? 'w-full max-w-2xl aspect-video' : ''}`}>
                    <img src={img.dataUrl} alt={img.name} className={`w-full h-full ${galleryLayout === 'slideshow' ? 'object-contain' : 'object-cover'}`} />
                  </div>
                ))}
              </div>
          </div>
        )}
      </div>
    );
  }

  return (
    <div className="space-y-6 sm:space-y-8">
      <div className="text-center max-w-2xl mx-auto px-2">
        <h2 className="text-2xl sm:text-4xl font-extrabold text-black mb-3 sm:mb-4">{title}</h2>
        <p className="text-slate-600 text-sm sm:text-lg leading-relaxed">{description}</p>
      </div>
      <div className="grid grid-cols-1 lg:grid-cols-4 gap-6 sm:gap-8">
        <aside className="lg:col-span-1 space-y-5 sm:space-y-6 bg-slate-50 p-4 sm:p-6 rounded-2xl border border-slate-200 h-fit">
          <div className="flex justify-between items-center mb-2">
            <h3 className="font-bold text-xs sm:text-sm uppercase tracking-wider text-slate-500">Settings</h3>
            <button onClick={clearAll} disabled={images.length === 0} className={`text-[10px] font-black uppercase tracking-widest hover:underline ${images.length > 0 ? 'text-red-500' : 'text-slate-300 cursor-not-allowed'}`}>Clear All</button>
          </div>
          <div className="space-y-4">
            {(mode === 'compress' || mode === 'watermark') && (
              <div className="space-y-2">
                <label htmlFor="quality-range" className="text-sm font-medium flex justify-between text-black">Quality <span>{Math.round(quality * 100)}%</span></label>
                <input id="quality-range" type="range" min="0.1" max="1" step="0.05" value={quality} onChange={(e) => setQuality(parseFloat(e.target.value))} className="w-full h-1.5 bg-slate-200 rounded-lg appearance-none cursor-pointer accent-black" />
              </div>
            )}
            {mode === 'resize' && (
              <div className="space-y-4">
                <label htmlFor="preset-select" className="text-sm font-bold text-slate-700">Preset Size</label>
                <select id="preset-select" value={selectedPreset} onChange={(e) => handlePresetChange(e.target.value)} className="w-full p-2.5 border border-slate-300 rounded-xl bg-white text-black font-bold text-sm outline-none">
                  {Array.from(new Set(PRESETS.map(p => p.category))).map(cat => (
                    <optgroup key={cat} label={cat}>{PRESETS.filter(p => p.category === cat).map(p => (<option key={p.name} value={p.name}>{p.name}</option>))}</optgroup>
                  ))}
                </select>
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-1">
                    <label htmlFor="width-input" className="sr-only">Width</label>
                    <input id="width-input" type="number" placeholder="Width" value={width || ''} onChange={(e) => setWidth(parseInt(e.target.value) || undefined)} className="w-full p-2.5 border border-slate-300 rounded-xl text-sm outline-none font-bold" />
                  </div>
                  <div className="space-y-1">
                    <label htmlFor="height-input" className="sr-only">Height</label>
                    <input id="height-input" type="number" placeholder="Height" value={height || ''} onChange={(e) => setHeight(parseInt(e.target.value) || undefined)} className="w-full p-2.5 border border-slate-300 rounded-xl text-sm outline-none font-bold" />
                  </div>
                </div>
                <div className="flex items-center space-x-2">
                    <input type="checkbox" id="aspect" checked={maintainAspect} onChange={(e) => setMaintainAspect(e.target.checked)} className="accent-black" />
                    <label htmlFor="aspect" className="text-xs font-bold text-slate-600">Maintain Aspect Ratio</label>
                </div>
              </div>
            )}
            {mode === 'watermark' && (
                <div className="space-y-4 pt-4 border-t border-slate-200">
                    <label className="text-sm font-bold text-slate-700">Logo Watermark</label>
                    <div className="flex flex-col space-y-2">
                        <button onClick={() => logoInputRef.current?.click()} className="px-4 py-2 bg-white border border-slate-300 rounded-lg text-xs font-bold hover:bg-slate-50 transition-colors uppercase">
                            {watermarkDataUrl ? 'Change Logo' : 'Upload Logo'}
                        </button>
                        <input id="logo-upload" type="file" accept="image/*" className="hidden" ref={logoInputRef} onChange={handleLogoUpload} />
                        {watermarkDataUrl && <p className="text-[10px] text-green-600 font-bold">✓ Logo Uploaded</p>}
                    </div>
                    <div className="space-y-2">
                        <label htmlFor="wm-opacity-range" className="text-xs font-bold flex justify-between">Opacity <span>{Math.round(watermarkOpacity * 100)}%</span></label>
                        <input id="wm-opacity-range" type="range" min="0.1" max="1" step="0.05" value={watermarkOpacity} onChange={(e) => setWatermarkOpacity(parseFloat(e.target.value))} className="w-full h-1 bg-slate-200 rounded-lg accent-black" />
                    </div>
                    <div className="space-y-2">
                        <label htmlFor="wm-scale-range" className="text-xs font-bold flex justify-between">Scale <span>{Math.round(watermarkScale * 100)}%</span></label>
                        <input id="wm-scale-range" type="range" min="0.05" max="0.5" step="0.01" value={watermarkScale} onChange={(e) => setWatermarkScale(parseFloat(e.target.value))} className="w-full h-1 bg-slate-200 rounded-lg accent-black" />
                    </div>
                    <div className="space-y-2">
                        <label htmlFor="wm-position-select" className="text-xs font-bold">Position</label>
                        <select id="wm-position-select" value={watermarkPosition} onChange={(e) => setWatermarkPosition(e.target.value as WatermarkPosition)} className="w-full p-2 border border-slate-300 rounded-lg bg-white text-xs font-bold outline-none">
                            <option value="top-left">Top Left</option><option value="top-right">Top Right</option><option value="bottom-left">Bottom Left</option><option value="bottom-right">Bottom Right</option><option value="center">Center</option>
                        </select>
                    </div>
                </div>
            )}
            <div className="space-y-1">
              <label htmlFor="format-select" className="text-sm font-medium text-black">Output Format</label>
              <select id="format-select" value={format} onChange={(e) => setFormat(e.target.value as ImageFormat)} className="w-full p-2.5 border border-slate-300 rounded-xl bg-white text-sm outline-none font-bold">
                <option value="image/jpeg">JPG</option><option value="image/png">PNG</option><option value="image/webp">WebP</option><option value="image/avif">AVIF</option>
              </select>
            </div>
          </div>
          <div className="space-y-3 pt-4">
              <button 
                onClick={processAll} 
                disabled={images.length === 0 || isProcessing} 
                className="w-full py-3 bg-black text-white rounded-xl text-sm font-black hover:bg-slate-800 disabled:bg-slate-300 transition-all uppercase shadow-md"
              >
                {isProcessing ? 'Processing...' : `Start ${mode.charAt(0).toUpperCase() + mode.slice(1)} (${images.length})`}
              </button>
              <button 
                onClick={downloadAll} 
                disabled={!images.some(img => img.status === 'completed')}
                className="w-full py-3 border-2 border-black text-black rounded-xl text-sm font-black hover:bg-black hover:text-white disabled:opacity-30 disabled:border-slate-200 disabled:text-slate-300 disabled:cursor-not-allowed transition-all uppercase"
              >
                Download Results
              </button>
          </div>
          <div className="pt-6 border-t border-slate-200">
             <div className="min-h-[220px] w-full flex flex-col items-center justify-center p-2 bg-white rounded-2xl border border-slate-100 shadow-sm relative overflow-hidden">
                <p className="text-[9px] font-black uppercase tracking-widest text-[#94a3b8] mb-4">Advertisement</p>
                <AdsterraNativeBanner mode={mode} />
             </div>
          </div>
        </aside>
        <section className="lg:col-span-3 space-y-6">
          <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
            <button type="button" aria-label="Select individual images" className="border-2 border-dashed border-slate-300 rounded-2xl p-8 text-center hover:border-black transition-colors cursor-pointer bg-white group focus:outline-none focus:ring-2 focus:ring-black" onClick={() => fileInputRef.current?.click()}>
              <div className="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-3 group-hover:bg-black group-hover:text-white transition-colors">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 4v16m8-8H4"/></svg>
              </div>
              <p className="text-sm font-black uppercase tracking-tight text-slate-500">Select Images</p>
              <input type="file" multiple accept="image/*" className="hidden" ref={fileInputRef} onChange={(e) => handleFiles(e.target.files)} />
            </button>
            <button type="button" aria-label="Upload an entire folder of images" className="border-2 border-dashed border-slate-300 rounded-2xl p-8 text-center hover:border-black transition-colors cursor-pointer bg-white group focus:outline-none focus:ring-2 focus:ring-black" onClick={() => folderInputRef.current?.click()}>
              <div className="w-10 h-10 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-3 group-hover:bg-black group-hover:text-white transition-colors">
                <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24" aria-hidden="true"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M3 7v10a2 2 0 002 2h14a2 2 0 002-2V9a2 2 0 00-2-2h-6l-2-2H5a2 2 0 00-2 2z"/></svg>
              </div>
              <p className="text-sm font-black uppercase tracking-tight text-slate-500">Upload Folder</p>
              <input type="file" {...({ webkitdirectory: "", directory: "" } as any)} className="hidden" ref={folderInputRef} onChange={(e) => handleFiles(e.target.files)} />
            </button>
          </div>
          {images.length > 0 && (
            <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
              {images.map(img => (
                <div key={img.id} className="border border-slate-200 rounded-2xl p-3 flex items-center space-x-3 bg-white shadow-sm">
                  <img src={img.dataUrl} className="w-12 h-12 rounded-lg object-cover" alt={img.name} />
                  <div className="flex-grow min-w-0">
                    <h4 className="font-bold text-xs truncate text-black">{img.name}</h4>
                    <span className={`text-[10px] font-bold ${img.status === 'completed' ? 'text-green-600' : 'text-slate-500'}`}>
                        {formatSize(img.originalSize)} {img.status === 'completed' && `→ ${formatSize(img.compressedSize || 0)}`}
                        {img.status === 'processing' && ' - Processing...'}
                    </span>
                  </div>
                  <button onClick={() => removeImage(img.id)} className="text-slate-300 hover:text-red-500 font-bold text-xl transition-colors px-2" aria-label={`Remove ${img.name}`}>×</button>
                </div>
              ))}
            </div>
          )}
        </section>
      </div>
    </div>
  );
};

export default ImageTool;