Files
webb/src/components/tools/DynamicToolWorkspace.tsx
T

1106 lines
50 KiB
TypeScript
Raw Normal View History

'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<File | null>(null);
const [primaryPreview, setPrimaryPreview] = useState<string | null>(null);
const [secondaryFile, setSecondaryFile] = useState<File | null>(null);
const [secondaryPreview, setSecondaryPreview] = useState<string | null>(null);
const [promptText, setPromptText] = useState<string>('');
const [aspectRatio, setAspectRatio] = useState<string>('1:1');
// Thumbnails Selection
const initialThumbnailId = tool.thumbnails?.[0]?.id;
const [selectedThumbnail, setSelectedThumbnail] = useState<ThumbnailItem | undefined>(
tool.thumbnails?.find((t) => t.id === initialThumbnailId) || tool.thumbnails?.[0]
);
// Masking State
const [hasMaskDrawn, setHasMaskDrawn] = useState(false);
const getMaskBlobRef = useRef<(() => Promise<Blob | null>) | null>(null);
// Cropper State & Export Ref
const getCroppedBlobRef = useRef<(() => Promise<Blob | null>) | null>(null);
const [isCropFull, setIsCropFull] = useState(true);
// Inference Execution State
const [status, setStatus] = useState<'idle' | 'processing' | 'success' | 'error' | 'limit'>('idle');
const [resultUrl, setResultUrl] = useState<string | null>(null);
const [errorMessage, setErrorMessage] = useState<string>('');
const [remainingTries, setRemainingTries] = useState<number>(tool.tryIt?.limits?.perDay || 5);
const fileInputRef = useRef<HTMLInputElement>(null);
const secondaryFileInputRef = useRef<HTMLInputElement>(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) {
formData.append(imageParamName, fileToSend, 'photo.jpg');
} else if (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);
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 (
<div className="min-h-screen bg-paper pb-20">
{/* Studio Clean Top Bar (Old duplicate buttons & pills removed) */}
<div className="sticky top-0 z-40 bg-paper-hi/95 backdrop-blur-md border-b border-rule shadow-2xs">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 h-16 flex items-center justify-between gap-4">
{/* Left: Clean Back to Overview */}
<button
type="button"
onClick={() => setViewMode('landing')}
className="inline-flex items-center gap-2 px-3.5 py-2 rounded-xl text-xs font-sans font-semibold text-slate-700 bg-slate-100 hover:bg-slate-200 transition-colors cursor-pointer"
>
<ArrowLeft className="w-4 h-4" />
<span>Back to Overview</span>
</button>
{/* Right: Direct Download when Result is Ready */}
<div className="flex items-center gap-3">
{status === 'success' && resultUrl && (
<a
href={resultUrl}
download={`${tool.slug}-result.png`}
className="inline-flex items-center gap-2 px-5 py-2 rounded-full bg-slate-900 text-white text-xs font-semibold shadow-xs hover:bg-slate-800 transition-colors cursor-pointer"
>
<Download className="w-3.5 h-3.5 text-accent" />
<span>Download Result</span>
</a>
)}
</div>
</div>
</div>
{/* Studio Workspace Canvas */}
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-6 space-y-6">
{/* Prominent, Visually Large Tool Heading & Subtitle */}
<div className="space-y-2">
<div className="flex items-center gap-2 text-xs font-sans text-slate-500">
<Link href="/tools" className="hover:text-slate-900 hover:underline">Tools</Link>
<span>/</span>
<span className="text-slate-700 font-medium">{toolName}</span>
</div>
<h1 className="text-3xl sm:text-5xl font-display font-extrabold text-slate-900 tracking-tight">
{toolName}
</h1>
<p className="text-sm sm:text-base text-slate-600 font-sans max-w-3xl leading-relaxed">
{toolSummary}
</p>
</div>
{/* Error Banner */}
{errorMessage && (
<div className="p-3.5 rounded-xl bg-red-500/10 border border-red-500/20 text-red-600 text-xs font-sans flex items-center gap-2">
<AlertCircle className="w-4 h-4 shrink-0" />
<span>{errorMessage}</span>
</div>
)}
{/* Archetype Studio Layout */}
<div className="studio-sheet p-5 sm:p-6 rounded-3xl bg-paper-hi border border-rule shadow-sheet space-y-6">
{/* POST-EDIT RESULT COMPARISON VIEW (If inference succeeded) */}
{status === 'success' && resultUrl ? (
<div className="space-y-6">
<div className="flex items-center justify-between pb-3 border-b border-rule">
<div>
<h3 className="text-lg font-display font-bold text-ink">
Transformation Complete
</h3>
<p className="text-xs text-muted font-body">
Drag the center slider to inspect before and after details.
</p>
</div>
<button
type="button"
onClick={() => setStatus('idle')}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-body font-semibold text-accent bg-accent/10 hover:bg-accent/20 transition-colors cursor-pointer"
>
<RefreshCw className="w-3 h-3" />
<span>Re-edit / Adjust</span>
</button>
</div>
<div className="aspect-[4/3] sm:aspect-[16/10] max-h-[580px] w-full rounded-2xl overflow-hidden bg-paper-2 border border-rule">
<CardBeforeAfterSlider
beforeUrl={primaryPreview || primaryExample.before}
afterUrl={resultUrl}
title={toolName}
aspectRatio="aspect-auto h-full"
beforeLabel="ORIGINAL"
afterLabel="RESULT"
/>
</div>
{/* POST-EDIT ACTION BAR */}
<div className="pt-6 border-t border-rule">
<div className="flex flex-col sm:flex-row items-center justify-between gap-4">
<div className="flex items-center gap-2.5 w-full sm:w-auto order-2 sm:order-1">
<button
type="button"
onClick={() => setStatus('idle')}
className="flex-1 sm:flex-none inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl bg-paper-2 hover:bg-paper text-ink font-body text-xs sm:text-sm font-semibold border border-rule transition-colors cursor-pointer shadow-2xs"
>
<RefreshCw className="w-4 h-4 text-accent" />
<span>Re-edit / Adjust</span>
</button>
<button
type="button"
onClick={handleResetStudio}
className="flex-1 sm:flex-none inline-flex items-center justify-center gap-2 px-6 py-3.5 rounded-2xl bg-paper-2 hover:bg-paper text-ink font-body text-xs sm:text-sm font-semibold border border-rule transition-colors cursor-pointer shadow-2xs"
>
<UploadCloud className="w-4 h-4 text-muted" />
<span>Try Another Photo</span>
</button>
</div>
<a
href={resultUrl}
download={`${tool.slug}-result.png`}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-12 py-4 rounded-2xl sm:rounded-full bg-ink hover:bg-slate-900 text-paper-hi font-display font-bold text-sm sm:text-base shadow-xl hover:scale-[1.02] active:scale-98 transition-all cursor-pointer order-1 sm:order-2"
>
<Download className="w-5 h-5 text-accent" />
<span>Download Result (HD PNG)</span>
</a>
</div>
</div>
</div>
) : (
/* PRE-EDIT WORKSPACE (Interactive Editing by Page Type) */
<div className="space-y-6">
{/* 1. MASKING STUDIO (Inpainting & Brush Editor) */}
{pageType === 'masking' && primaryPreview && (
<div className="space-y-4">
<div className="flex items-center justify-between pb-2 border-b border-rule">
<span className="text-xs font-semibold text-ink font-body">
Inpainting & Object Masking Studio
</span>
<span className="text-[11px] text-muted font-body">
Paint over areas to remove or replace
</span>
</div>
<MaskCanvasEditor
imageUrl={primaryPreview}
config={tool.maskingConfig}
locale={locale}
isProcessing={status === 'processing'}
toolName={toolName}
onMaskChange={setHasMaskDrawn}
onExportReady={(fn) => {
getMaskBlobRef.current = fn;
}}
/>
</div>
)}
{/* 2. DEFAULT PHOTO CROPPER STUDIO (For image-only and image-thumbnail) */}
{(pageType === 'image-only' || pageType === 'image-thumbnail') && primaryPreview && (
<div className="space-y-4">
<div className="relative">
<ImageCropper
imageUrl={primaryPreview}
onCropChange={(crop, isFull) => {
setIsCropFull(isFull);
}}
onExportReady={(fn) => {
getCroppedBlobRef.current = fn;
}}
disabled={status === 'processing'}
/>
{status === 'processing' && (
<div className="absolute inset-0 z-30 rounded-2xl overflow-hidden">
<ProcessingOverlay toolName={toolName} />
</div>
)}
</div>
</div>
)}
{/* 3. TEXT-TO-IMAGE STUDIO */}
{pageType === 'text-to-image' && (
<div className="space-y-5">
<label className="block text-xs font-semibold text-ink font-body">
Prompt Description
</label>
<div className="relative">
<textarea
rows={4}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={
resolveLocalised(tool.textToImageConfig?.placeholder, locale) ||
'Describe what you want to create in vivid detail (e.g. A futuristic cybernetic portrait with neon rim lighting in 4K resolution)...'
}
className="w-full p-4 rounded-2xl border border-rule bg-paper text-ink text-sm font-body placeholder:text-muted focus:outline-none focus:border-accent focus:ring-2 focus:ring-accent/20"
/>
{status === 'processing' && (
<div className="absolute inset-0 rounded-2xl overflow-hidden">
<ProcessingOverlay toolName={toolName} />
</div>
)}
</div>
{/* Aspect Ratios Selector */}
<div className="space-y-2">
<span className="text-xs font-semibold text-ink font-body">Aspect Ratio</span>
<div className="flex items-center gap-2">
{['1:1', '16:9', '9:16', '4:3'].map((ratio) => (
<button
key={ratio}
type="button"
onClick={() => setAspectRatio(ratio)}
className={`px-3 py-1.5 rounded-xl text-xs font-body font-semibold transition-colors cursor-pointer ${
aspectRatio === ratio
? 'bg-ink text-paper-hi shadow-xs'
: 'bg-paper-2 text-ink-2 hover:bg-paper'
}`}
>
{ratio}
</button>
))}
</div>
</div>
</div>
)}
{/* 4. TWO-IMAGES STUDIO */}
{pageType === 'two-images' && (
<div className="relative">
<div className="grid grid-cols-1 md:grid-cols-2 gap-6">
{/* Primary Image Slot */}
<div className="space-y-2">
<span className="text-xs font-semibold text-ink font-body">
{resolveLocalised(tool.twoImagesConfig?.firstImageLabel, locale) || 'Primary Photo'}
</span>
<div className="aspect-[4/3] rounded-2xl overflow-hidden bg-paper-2 border border-rule relative">
{primaryPreview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={primaryPreview} alt="Primary" className="w-full h-full object-contain" />
) : (
<div className="w-full h-full flex flex-col items-center justify-center p-4 text-muted text-xs">
<UploadCloud className="w-6 h-6 mb-2 text-accent" />
<span>Upload primary photo</span>
</div>
)}
</div>
</div>
{/* Secondary Image Slot */}
<div className="space-y-2">
<span className="text-xs font-semibold text-ink font-body">
{resolveLocalised(tool.twoImagesConfig?.secondImageLabel, locale) || 'Reference / Style Photo'}
</span>
<div className="aspect-[4/3] rounded-2xl overflow-hidden bg-paper-2 border border-rule relative">
{secondaryPreview ? (
// eslint-disable-next-line @next/next/no-img-element
<img src={secondaryPreview} alt="Secondary" className="w-full h-full object-contain" />
) : (
<label className="w-full h-full flex flex-col items-center justify-center p-4 text-muted text-xs cursor-pointer hover:bg-paper transition-colors">
<UploadCloud className="w-6 h-6 mb-2 text-accent" />
<span>Click to upload reference photo</span>
<input
ref={secondaryFileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
if (e.target.files?.[0]) handleSecondaryFileSelect(e.target.files[0]);
}}
/>
</label>
)}
</div>
</div>
</div>
{status === 'processing' && (
<ProcessingOverlay toolName={toolName} />
)}
</div>
)}
{/* In-Studio Style Preset Thumbnails (if available) */}
{tool.thumbnails && tool.thumbnails.length > 0 && (
<div className="pt-4 border-t border-rule">
<ThumbnailsSection
thumbnails={tool.thumbnails}
selectedId={selectedThumbnail?.id}
onSelect={(item) => setSelectedThumbnail(item)}
locale={locale}
variant="compact-bar"
/>
</div>
)}
{/* ================================================================= */}
{/* STUDIO MAIN ACTION BAR: CLEARLY VISIBLE PRIMARY BUTTON WITH REMAINING COUNT */}
{/* DIRECTLY BELOW THE PHOTO UPLOAD CANVAS */}
{/* ================================================================= */}
<div className="pt-6 border-t border-rule">
<div className="flex flex-col sm:flex-row items-center justify-between gap-4">
{/* Left: Reset / Try Another Photo */}
<div className="flex items-center gap-2.5 w-full sm:w-auto order-2 sm:order-1">
<button
type="button"
onClick={handleResetStudio}
className="inline-flex items-center justify-center gap-2 px-5 py-3.5 rounded-2xl bg-paper-2 hover:bg-paper text-ink font-body text-xs sm:text-sm font-semibold border border-rule transition-colors cursor-pointer shadow-2xs"
>
<RotateCcw className="w-4 h-4 text-slate-500" />
<span>Try Another Photo</span>
</button>
</div>
{/* Right: Massive High-Visibility Main Process Button with Dynamic Server-backed Quota Icon */}
<div className="w-full sm:w-auto order-1 sm:order-2">
<button
type="button"
onClick={handleExecute}
disabled={status === 'processing' || remainingTries <= 0}
className="w-full sm:w-auto inline-flex items-center justify-center gap-3 px-8 sm:px-10 py-4 rounded-2xl sm:rounded-full bg-accent hover:bg-accent-hi text-white font-display font-extrabold text-sm sm:text-base shadow-xl shadow-accent/25 hover:shadow-accent/40 hover:scale-[1.02] active:scale-98 transition-all cursor-pointer disabled:opacity-50 disabled:hover:scale-100"
>
{status === 'processing' ? (
<>
<Loader2 className="w-5 h-5 animate-spin" />
<span>Processing Neural Model...</span>
</>
) : (
<>
<Sparkles className="w-5 h-5 text-amber-300 animate-pulse" />
<span>
{pageType === 'masking'
? 'Inpaint & Remove Objects'
: pageType === 'text-to-image'
? 'Generate AI Artwork'
: pageType === 'two-images'
? 'Fuse Facial Identities'
: pageType === 'image-thumbnail' && selectedThumbnail
? `Apply ${resolveLocalised(selectedThumbnail.label, locale)} Look`
: 'Process & Enhance Photo'}
</span>
{/* Dynamic Icon Badge Showing Remaining Tries */}
<span className="inline-flex items-center gap-1.5 px-2.5 py-1 rounded-full bg-white/20 text-white font-mono text-xs font-bold shadow-2xs backdrop-blur-xs ml-1">
<Zap className="w-3.5 h-3.5 text-amber-300" />
<span>{remainingTries} left</span>
</span>
<ArrowRight className="w-4 h-4 ml-0.5" />
</>
)}
</button>
</div>
</div>
</div>
</div>
)}
</div>
</div>
</div>
);
}
// =========================================================================
// VIEW 2: TOOL LANDING OVERVIEW PAGE (Initial State)
// =========================================================================
return (
<div className="min-h-screen bg-paper">
{/* ================= HERO SECTION ================= */}
<section className="relative pt-6 sm:pt-10 pb-12 sm:pb-16 bg-paper border-b border-rule overflow-hidden">
{/* Ambient Radial Spotlight */}
<div
className="pointer-events-none absolute top-0 left-1/2 -translate-x-1/2 w-[900px] h-[400px] [background:radial-gradient(ellipse_at_top,color-mix(in_oklab,var(--color-accent)_12%,transparent)_0%,transparent_70%)]"
aria-hidden="true"
/>
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 relative z-10">
{/* Breadcrumb row */}
<div className="flex items-center gap-2 text-xs font-sans text-slate-500 mb-5 tracking-wide">
<Link href="/" className="hover:text-slate-900 hover:underline">Home</Link>
<span>/</span>
<Link href="/tools" className="hover:text-slate-900 hover:underline">Tools</Link>
<span>/</span>
<span className="text-accent font-semibold">{toolName}</span>
</div>
{/* Header Title & Summary (Larger, visually striking typography) */}
<div className="max-w-5xl mb-8 sm:mb-12 space-y-4 sm:space-y-5">
<h1 className="text-4xl sm:text-6xl lg:text-7xl font-display font-extrabold text-slate-900 tracking-tight leading-[1.08]">
<AnimatedShinyText>{toolName}</AnimatedShinyText>
</h1>
<p className="text-base sm:text-xl text-slate-600 font-sans max-w-4xl leading-relaxed">
{toolSummary}
</p>
</div>
{/* Studio Workspace: Upload Box on Left, Specimen on Right */}
<div className="grid grid-cols-1 lg:grid-cols-12 gap-8 lg:gap-10 items-start">
{/* Upload Box: Configured Dynamically by pageType */}
<div id="studio-upload-box" className="lg:col-span-6 bg-paper-hi border border-rule rounded-3xl p-6 sm:p-8 shadow-sheet relative overflow-hidden">
<BorderBeam size={120} duration={10} borderWidth={1.5} colorFrom="var(--color-accent)" colorTo="var(--color-accent-hi)" />
<div className="border-b border-rule pb-3.5 mb-6 flex items-center justify-between">
<span className="text-sm font-bold font-sans text-slate-900">
{pageType === 'text-to-image' ? 'Generate AI Image' : 'Select Photo to Edit'}
</span>
</div>
{/* Dynamic Upload Input by Type */}
<div className="space-y-6">
{/* Style Thumbnail Selector on Landing Card (Before-Upload / Both) */}
{tool.thumbnails && tool.thumbnails.length > 0 && tool.thumbnailPlacement !== 'after-upload' && (
<div className="space-y-3 pb-4 border-b border-rule/60">
<div className="flex items-center justify-between text-xs sm:text-sm font-sans">
<span className="font-semibold text-slate-900">1. Select Effect Style</span>
{selectedThumbnail && (
<span className="text-accent font-semibold">
{resolveLocalised(selectedThumbnail.label, locale)}
</span>
)}
</div>
<div className="flex items-center gap-2.5 overflow-x-auto pb-1 scrollbar-none">
{tool.thumbnails.map((t) => {
const isSelected = selectedThumbnail?.id === t.id;
return (
<button
key={t.id}
type="button"
onClick={() => setSelectedThumbnail(t)}
className={`shrink-0 flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs font-sans transition-all cursor-pointer ${
isSelected
? 'bg-slate-900 text-white shadow-xs font-semibold'
: 'bg-slate-100 text-slate-700 hover:bg-slate-200'
}`}
>
{(t.thumbnail || t.preview) && (
// eslint-disable-next-line @next/next/no-img-element
<img src={t.thumbnail || t.preview} alt="" className="w-5 h-5 rounded-full object-cover" />
)}
<span>{resolveLocalised(t.label, locale)}</span>
</button>
);
})}
</div>
</div>
)}
{/* 1. Standard Single Upload Dropzone */}
{pageType !== 'two-images' && pageType !== 'text-to-image' && (
<div className="space-y-5">
<input
ref={fileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => {
if (e.target.files?.[0]) handlePrimaryFileSelect(e.target.files[0]);
}}
/>
{/* Prominent High-Visibility Drag & Drop Zone */}
<div
onClick={() => fileInputRef.current?.click()}
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
if (e.dataTransfer.files?.[0]) handlePrimaryFileSelect(e.dataTransfer.files[0]);
}}
className="w-full min-h-[320px] p-8 sm:p-12 rounded-2xl border-2 border-dashed border-accent/40 hover:border-accent bg-accent/5 hover:bg-accent/10 transition-all cursor-pointer flex flex-col items-center justify-center text-center space-y-4 group shadow-inner"
>
<div className="w-16 h-16 sm:w-20 sm:h-20 rounded-2xl bg-white shadow-md flex items-center justify-center group-hover:scale-110 transition-transform">
<UploadCloud className="w-8 h-8 sm:w-10 sm:h-10 text-accent" />
</div>
<div className="space-y-1">
<span className="text-base sm:text-lg font-bold text-slate-900 block font-sans">
Click to upload or drag photo here
</span>
<p className="text-xs sm:text-sm text-slate-500 font-sans">
Supports JPEG, PNG, and WebP (up to {tool.tryIt?.limits?.maxMB || 12}MB)
</p>
</div>
<button
type="button"
onClick={(e) => {
e.stopPropagation();
fileInputRef.current?.click();
}}
className="w-full sm:w-auto px-8 py-3.5 rounded-xl bg-slate-900 hover:bg-slate-800 text-white font-sans font-semibold text-xs sm:text-sm shadow-md transition-colors"
>
Select from Device
</button>
</div>
{/* Sample Presets */}
<div className="pt-2 flex items-center justify-between text-xs text-slate-500 font-sans">
<span>No photo ready?</span>
<button
type="button"
onClick={() => handleLoadSample(primaryExample.before)}
className="text-accent font-semibold hover:underline cursor-pointer"
>
Try with sample photo →
</button>
</div>
</div>
)}
{/* 2. Two-Images Archetype Upload */}
{pageType === 'two-images' && (
<div className="space-y-5">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Image 1 Dropzone */}
<div
onClick={() => fileInputRef.current?.click()}
className="p-5 rounded-2xl border-2 border-dashed border-rule hover:border-accent bg-paper hover:bg-accent/5 transition-all cursor-pointer flex flex-col items-center justify-center text-center space-y-2 min-h-[160px]"
>
<input
ref={fileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
if (e.target.files?.[0]) handlePrimaryFileSelect(e.target.files[0]);
}}
/>
<UploadCloud className="w-6 h-6 text-accent" />
<span className="text-xs font-bold text-ink font-body">
{resolveLocalised(tool.twoImagesConfig?.firstImageLabel, locale) || '1. Source Face'}
</span>
<span className="text-[10px] text-muted font-body">Click to choose</span>
</div>
{/* Image 2 Dropzone */}
<div
onClick={() => secondaryFileInputRef.current?.click()}
className="p-5 rounded-2xl border-2 border-dashed border-rule hover:border-accent bg-paper hover:bg-accent/5 transition-all cursor-pointer flex flex-col items-center justify-center text-center space-y-2 min-h-[160px]"
>
<input
ref={secondaryFileInputRef}
type="file"
accept="image/*"
className="hidden"
onChange={(e) => {
if (e.target.files?.[0]) handleSecondaryFileSelect(e.target.files[0]);
}}
/>
<UploadCloud className="w-6 h-6 text-accent" />
<span className="text-xs font-bold text-ink font-body">
{resolveLocalised(tool.twoImagesConfig?.secondImageLabel, locale) || '2. Target Body/Photo'}
</span>
<span className="text-[10px] text-muted font-body">Click to choose</span>
</div>
</div>
<button
type="button"
onClick={() => {
setViewMode('studio');
if (typeof window !== 'undefined') {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}}
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi text-white font-display font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
>
<Sparkles className="w-4 h-4 text-amber-300" />
<span>Open Fusion Studio</span>
</button>
</div>
)}
{/* 3. Text-to-Image Archetype Input */}
{pageType === 'text-to-image' && (
<div className="space-y-4">
<textarea
rows={3}
value={promptText}
onChange={(e) => setPromptText(e.target.value)}
placeholder={
resolveLocalised(tool.textToImageConfig?.placeholder, locale) ||
'Describe what you want to create in detail...'
}
className="w-full p-4 rounded-2xl border border-rule bg-paper text-ink text-sm font-body placeholder:text-muted focus:outline-none focus:border-accent focus:ring-2 focus:ring-accent/20"
/>
{/* Sample Prompts */}
{tool.textToImageConfig?.samplePrompts && (
<div className="flex flex-wrap gap-1.5 pt-1">
{tool.textToImageConfig.samplePrompts.slice(0, 3).map((sp, idx) => (
<button
key={idx}
type="button"
onClick={() => setPromptText(resolveLocalised(sp, locale))}
className="px-2.5 py-1 rounded-lg bg-paper-2 hover:bg-paper border border-rule text-[11px] text-muted hover:text-ink font-body transition-colors cursor-pointer text-left line-clamp-1"
>
&ldquo;{resolveLocalised(sp, locale)}&rdquo;
</button>
))}
</div>
)}
<button
type="button"
onClick={() => {
if (promptText.trim()) {
setViewMode('studio');
if (typeof window !== 'undefined') {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
}}
disabled={!promptText.trim()}
className="w-full py-4 rounded-2xl bg-accent hover:bg-accent-hi disabled:opacity-50 text-white font-display font-bold text-sm shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2.5"
>
<Sparkles className="w-4 h-4 text-amber-300" />
<span>Open Creation Studio</span>
</button>
</div>
)}
</div>
</div>
{/* Specimen View: Interactive Before/After Slider */}
<div className="lg:col-span-6">
<div className="studio-sheet p-6 sm:p-8 rounded-3xl shadow-sheet">
<div className="mb-4 flex items-center justify-between text-xs sm:text-sm font-sans">
<span className="font-bold text-slate-900">Transformation specimen</span>
<span className="text-xs text-slate-500">Drag slider to inspect details</span>
</div>
<div className="aspect-[4/3] rounded-2xl overflow-hidden bg-paper-2 border border-rule shadow-inner">
<CardBeforeAfterSlider
beforeUrl={primaryExample.before}
afterUrl={primaryExample.after}
title={toolName}
aspectRatio="aspect-auto h-full"
beforeLabel="ORIGINAL"
afterLabel="ENHANCED"
/>
</div>
</div>
</div>
</div>
</div>
</section>
{/* ================= OPTIONAL THUMBNAILS SECTION (If enabled in JSON) ================= */}
{tool.showThumbnailsSection && tool.thumbnails && tool.thumbnails.length > 0 && (
<ThumbnailsSection
thumbnails={tool.thumbnails}
selectedId={selectedThumbnail?.id}
onSelect={(item) => {
setSelectedThumbnail(item);
if (primaryFile || primaryPreview || pageType === 'text-to-image') {
setViewMode('studio');
if (typeof window !== 'undefined') window.scrollTo({ top: 0, behavior: 'smooth' });
} else {
if (typeof window !== 'undefined') {
const el = document.getElementById('studio-upload-box');
if (el) el.scrollIntoView({ behavior: 'smooth', block: 'center' });
else window.scrollTo({ top: 0, behavior: 'smooth' });
}
}
}}
locale={locale}
title={resolveLocalised(tool.name, locale)}
/>
)}
{/* ================= ALTERNATING FEATURES ZIG-ZAG SECTION ================= */}
{tool.content?.alternatingFeatures && tool.content.alternatingFeatures.length > 0 && (
<AlternatingFeaturesSection
features={tool.content.alternatingFeatures}
locale={locale}
sectionTitle={`Why Choose ${toolName}`}
sectionSubtitle="State-of-the-art neural architecture tuned for natural photographic accuracy."
/>
)}
{/* ================= HOW IT WORKS STEPS ================= */}
{tool.content?.steps && tool.content.steps.length > 0 && (
<section className="py-10 sm:py-14 border-t border-rule bg-paper">
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 sm:space-y-8">
<div className="text-center max-w-2xl mx-auto space-y-1.5">
<span className="text-xs font-semibold text-accent uppercase tracking-wider font-sans">
Step-by-step
</span>
<h2 className="text-2xl sm:text-3xl font-display font-bold text-ink">
How It Works
</h2>
</div>
<div className="grid grid-cols-1 md:grid-cols-3 gap-5 sm:gap-6">
{tool.content.steps.map((step, idx) => (
<div
key={idx}
className="studio-sheet p-5 rounded-2xl bg-paper-hi border border-rule shadow-xs space-y-2.5"
>
<div className="w-9 h-9 rounded-xl bg-slate-900 text-white flex items-center justify-center font-display font-bold text-xs">
0{idx + 1}
</div>
<h3 className="text-sm sm:text-base font-display font-bold text-ink">
{resolveLocalised(step.title, locale)}
</h3>
<p className="text-xs text-ink-2 font-sans leading-relaxed">
{resolveLocalised(step.desc, locale)}
</p>
</div>
))}
</div>
</div>
</section>
)}
{/* ================= FAQS ACCORDION ================= */}
{tool.content?.faqs && tool.content.faqs.length > 0 && (
<section className="py-10 sm:py-14 border-t border-rule bg-paper-2">
<div className="max-w-5xl mx-auto px-4 sm:px-6 lg:px-8 space-y-6 sm:space-y-8">
<div className="text-center space-y-1.5">
<h2 className="text-2xl sm:text-3xl font-display font-bold text-ink">
Frequently Asked Questions
</h2>
<p className="text-xs text-ink-2 font-sans">
Everything you need to know about inference, privacy, and output resolutions.
</p>
</div>
<div className="space-y-3">
{tool.content.faqs.map((faq, idx) => (
<div
key={idx}
className="p-4 sm:p-5 rounded-xl bg-paper-hi border border-rule shadow-2xs space-y-1.5"
>
<h4 className="text-sm font-display font-bold text-ink">
{faq.q}
</h4>
<p className="text-xs text-ink-2 font-sans leading-relaxed">
{faq.a}
</p>
</div>
))}
</div>
</div>
</section>
)}
{/* ================= NATIVE APP HANDOFF CTA ================= */}
<section className="py-10 sm:py-12 border-t border-rule bg-paper">
<div className="max-w-6xl mx-auto px-4 sm:px-6 lg:px-8">
<div className="studio-sheet p-6 sm:p-8 rounded-2xl bg-paper-hi border border-rule shadow-sheet flex flex-col sm:flex-row items-center justify-between gap-6">
<div className="space-y-1.5 max-w-xl text-center sm:text-left">
<h3 className="text-lg sm:text-xl font-display font-bold text-ink">
Need Batch Processing or 4K Lossless Export?
</h3>
<p className="text-xs text-ink-2 font-sans leading-relaxed">
Open {toolName} in {homeApp ? resolveLocalised(homeApp.name, locale) : 'our native apps'} with GPU acceleration and RAW format export.
</p>
</div>
<Link
href="/apps"
className="shrink-0 inline-flex items-center gap-2 px-5 py-2.5 rounded-full bg-slate-900 hover:bg-slate-800 text-white text-xs font-semibold shadow-md transition-colors"
>
<span>Explore Mobile Apps Suite</span>
</Link>
</div>
</div>
</section>
</div>
);
}