'use client'; import React, { useState, useRef, useCallback, useEffect } from 'react'; import Link from 'next/link'; import { UploadCloud, Sparkles, ArrowLeft, Download, RotateCcw, Loader2, AlertCircle, ArrowRight, RefreshCw, FolderOpen, Zap, Crop } from 'lucide-react'; import { ToolItem, AppItem, VariantSpec, ThumbnailItem, resolveLocalised, ToolPageType } from '@/types'; import { CardBeforeAfterSlider } from '@/components/ui/CardBeforeAfterSlider'; import { MaskCanvasEditor } from './MaskCanvasEditor'; import { ThumbnailsSection } from './ThumbnailsSection'; import { AlternatingFeaturesSection } from './AlternatingFeaturesSection'; import { ProcessingOverlay } from './ProcessingOverlay'; import { ImageCropper } from './ImageCropper'; import { AnimatedShinyText } from '@/components/magicui/animated-shiny-text'; import { BorderBeam } from '@/components/magicui/border-beam'; interface DynamicToolWorkspaceProps { tool: ToolItem; homeApp?: AppItem | null; variants?: VariantSpec[]; locale?: string; } export function DynamicToolWorkspace({ tool, homeApp, variants = [], locale = 'en', }: DynamicToolWorkspaceProps) { // Determine tool archetype from JSON (fallback intelligently based on category/id) const pageType: ToolPageType = tool.pageType || ( tool.id.includes('lama') || tool.id.includes('eraser') || tool.id.includes('inpaint') ? 'masking' : tool.thumbnails && tool.thumbnails.length > 0 ? 'image-thumbnail' : tool.id.includes('text') || tool.id.includes('prompt') ? 'text-to-image' : tool.id.includes('swap') || tool.id.includes('blend') ? 'two-images' : 'image-only' ); // View Mode: 'landing' (tool overview & upload) vs 'studio' (editing workspace) const [viewMode, setViewMode] = useState<'landing' | 'studio'>('landing'); // Input States const [primaryFile, setPrimaryFile] = useState(null); const [primaryPreview, setPrimaryPreview] = useState(null); const [secondaryFile, setSecondaryFile] = useState(null); const [secondaryPreview, setSecondaryPreview] = useState(null); const [promptText, setPromptText] = useState(''); const [aspectRatio, setAspectRatio] = useState('1:1'); // Thumbnails Selection const initialThumbnailId = tool.thumbnails?.[0]?.id; const [selectedThumbnail, setSelectedThumbnail] = useState( tool.thumbnails?.find((t) => t.id === initialThumbnailId) || tool.thumbnails?.[0] ); // Masking State const [hasMaskDrawn, setHasMaskDrawn] = useState(false); const getMaskBlobRef = useRef<(() => Promise) | null>(null); // Cropper State & Export Ref const getCroppedBlobRef = useRef<(() => Promise) | null>(null); const [isCropFull, setIsCropFull] = useState(true); // Inference Execution State const [status, setStatus] = useState<'idle' | 'processing' | 'success' | 'error' | 'limit'>('idle'); const [resultUrl, setResultUrl] = useState(null); const [comparisonBeforeUrl, setComparisonBeforeUrl] = useState(null); const [errorMessage, setErrorMessage] = useState(''); const [remainingTries, setRemainingTries] = useState(tool.tryIt?.limits?.perDay || 5); const fileInputRef = useRef(null); const secondaryFileInputRef = useRef(null); // Fetch verified user quota from server dynamically (immune to inspect tool manipulation) const fetchUserQuota = useCallback(async () => { try { const res = await fetch('/api/user-quota', { cache: 'no-store' }); if (res.ok) { const data = await res.json(); if (typeof data.remainingToday === 'number') { setRemainingTries(data.remainingToday); } } } catch { // Keep existing state } }, []); useEffect(() => { fetchUserQuota(); }, [fetchUserQuota]); // Examples from JSON const primaryExample = tool.content?.examples?.[0] || { before: 'https://images.unsplash.com/photo-1534528741775-53994a69daeb?w=800&auto=format&fit=crop&q=80', after: 'https://images.unsplash.com/photo-1517841905240-472988babdf9?w=800&auto=format&fit=crop&q=80', caption: 'Interactive neural specimen', }; // Sample quick-load presets const samplePresets = [ { label: 'Sample portrait', url: primaryExample.before, resultUrl: primaryExample.after, }, ]; // File Handlers const handlePrimaryFileSelect = (file: File) => { const validTypes = ['image/jpeg', 'image/png', 'image/webp']; if (!validTypes.includes(file.type)) { setErrorMessage('Please upload a valid JPG, PNG, or WebP photo.'); return; } const maxBytes = (tool.tryIt?.limits?.maxMB || 12) * 1024 * 1024; if (file.size > maxBytes) { setErrorMessage(`File exceeds max size of ${tool.tryIt?.limits?.maxMB || 12}MB.`); return; } setPrimaryFile(file); const objectUrl = URL.createObjectURL(file); setPrimaryPreview(objectUrl); setResultUrl(null); setErrorMessage(''); setStatus('idle'); setViewMode('studio'); // Transition straight into the editing workspace! if (typeof window !== 'undefined') { window.scrollTo({ top: 0, behavior: 'smooth' }); } }; const handleSecondaryFileSelect = (file: File) => { const validTypes = ['image/jpeg', 'image/png', 'image/webp']; if (!validTypes.includes(file.type)) { setErrorMessage('Please upload a valid JPG, PNG, or WebP photo.'); return; } setSecondaryFile(file); setSecondaryPreview(URL.createObjectURL(file)); }; const handleLoadSample = (sampleUrl: string) => { setPrimaryPreview(sampleUrl); setPrimaryFile(null); setResultUrl(null); setErrorMessage(''); setStatus('idle'); setViewMode('studio'); if (typeof window !== 'undefined') { window.scrollTo({ top: 0, behavior: 'smooth' }); } }; // Execute Request dynamically according to pageType const handleExecute = async () => { if (remainingTries <= 0) { setStatus('limit'); setErrorMessage('You have reached the free operations limit for today. Try again tomorrow or get the mobile app.'); return; } setStatus('processing'); setErrorMessage(''); try { const formData = new FormData(); // 1. Primary Image (for image-based archetypes) if (pageType !== 'text-to-image') { const imageParamName = tool.maskingConfig?.imageParamName || tool.twoImagesConfig?.firstImageParam || 'image'; let fileToSend: Blob | File | null = primaryFile; // If user cropped the image via ImageCropper if (getCroppedBlobRef.current) { try { const croppedBlob = await getCroppedBlobRef.current(); if (croppedBlob) { fileToSend = croppedBlob; } } catch (e) { console.error('Failed to export cropped blob, using original:', e); } } if (fileToSend) { const compUrl = URL.createObjectURL(fileToSend); setComparisonBeforeUrl(compUrl); formData.append(imageParamName, fileToSend, 'photo.jpg'); } else if (primaryPreview) { setComparisonBeforeUrl(primaryPreview); const res = await fetch(primaryPreview); const blob = await res.blob(); formData.append(imageParamName, blob, 'sample.jpg'); } else { setStatus('error'); setErrorMessage('Please upload or select an image first.'); return; } } // 2. Secondary Image (for two-images archetype) if (pageType === 'two-images') { const secondParamName = tool.twoImagesConfig?.secondImageParam || 'reference_image'; if (secondaryFile) { formData.append(secondParamName, secondaryFile); } else if (secondaryPreview) { const res = await fetch(secondaryPreview); const blob = await res.blob(); formData.append(secondParamName, blob, 'secondary.jpg'); } else { setStatus('error'); setErrorMessage('Please upload the second reference image.'); return; } } // 3. Mask Image (for masking archetype) if (pageType === 'masking') { const maskParamName = tool.maskingConfig?.maskParamName || 'mask'; if (getMaskBlobRef.current) { const maskBlob = await getMaskBlobRef.current(); if (maskBlob) { formData.append(maskParamName, maskBlob, 'mask.png'); } } } // 4. Prompt Text (for text-to-image) if (pageType === 'text-to-image') { const promptParam = tool.textToImageConfig?.promptParam || 'prompt'; if (!promptText.trim()) { setStatus('error'); setErrorMessage('Please enter a description or prompt to generate.'); return; } formData.append(promptParam, promptText.trim()); formData.append('aspect_ratio', aspectRatio); } // 5. Selected Thumbnail / Style Preset if (selectedThumbnail) { formData.append('style', selectedThumbnail.value); formData.append('variant', selectedThumbnail.value); } const res = await fetch(`/api/try/${tool.id}`, { method: 'POST', body: formData, }); if (res.status === 429) { setStatus('limit'); setRemainingTries(0); return; } if (!res.ok) { const errData = await res.json().catch(() => ({})); setStatus('error'); setErrorMessage(errData?.error?.message || 'Processing failed. Please try another input.'); return; } const blob = await res.blob(); const outputUrl = URL.createObjectURL(blob); setResultUrl(outputUrl); setStatus('success'); // Update verified remaining count from server response headers or server quota const remainingHeader = res.headers.get('X-Remaining-Tries'); if (remainingHeader !== null && !isNaN(parseInt(remainingHeader, 10))) { setRemainingTries(parseInt(remainingHeader, 10)); } else { fetchUserQuota(); } } catch { setStatus('error'); setErrorMessage('Network error during model inference.'); } }; const handleResetStudio = () => { setPrimaryFile(null); setPrimaryPreview(null); setSecondaryFile(null); setSecondaryPreview(null); setResultUrl(null); setComparisonBeforeUrl(null); setStatus('idle'); setErrorMessage(''); if (fileInputRef.current) fileInputRef.current.value = ''; if (secondaryFileInputRef.current) secondaryFileInputRef.current.value = ''; setViewMode('landing'); }; const toolName = resolveLocalised(tool.name, locale); const toolSummary = resolveLocalised(tool.summary, locale); // ========================================================================= // VIEW 1: DEDICATED EDITING STUDIO PAGE (Post-Upload / Pre-Edit / Post-Edit) // ========================================================================= if (viewMode === 'studio') { return (
{/* Studio Clean Top Bar (Old duplicate buttons & pills removed) */}
{/* Left: Clean Back to Overview */} {/* Right: Direct Download when Result is Ready */}
{status === 'success' && resultUrl && ( Download Result )}
{/* Studio Workspace Canvas */}
{/* Prominent, Visually Large Tool Heading & Subtitle */}
Tools / {toolName}

{toolName}

{toolSummary}

{/* Error Banner */} {errorMessage && (
{errorMessage}
)} {/* Archetype Studio Layout */}
{/* POST-EDIT RESULT COMPARISON VIEW (If inference succeeded) */} {status === 'success' && resultUrl ? (

Transformation Complete

Drag the center slider to inspect before and after details.

{/* POST-EDIT ACTION BAR */}
Download Result (HD PNG)
) : ( /* PRE-EDIT WORKSPACE (Interactive Editing by Page Type) */
{/* 1. MASKING STUDIO (Inpainting & Brush Editor) */} {pageType === 'masking' && primaryPreview && (
Inpainting & Object Masking Studio Paint over areas to remove or replace
{ getMaskBlobRef.current = fn; }} />
)} {/* 2. DEFAULT PHOTO CROPPER STUDIO (For image-only and image-thumbnail) */} {(pageType === 'image-only' || pageType === 'image-thumbnail') && primaryPreview && (
{ setIsCropFull(isFull); }} onExportReady={(fn) => { getCroppedBlobRef.current = fn; }} disabled={status === 'processing'} /> {status === 'processing' && (
)}
)} {/* 3. TEXT-TO-IMAGE STUDIO */} {pageType === 'text-to-image' && (