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

1185 lines
56 KiB
TypeScript

'use client';
import React, { useState, useRef, useCallback } from 'react';
import Link from 'next/link';
import {
UploadCloud,
Sparkles,
ArrowLeft,
Download,
RotateCcw,
Loader2,
AlertCircle,
CheckCircle2,
Layers,
SlidersHorizontal,
ArrowRight,
Maximize2,
Wand2,
RefreshCw,
Image as ImageIcon,
Check,
ChevronRight,
Smartphone,
FolderOpen,
Zap,
ShieldCheck
} 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 { KineticText } from '@/components/magicui/kinetic-text';
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.id.includes('cartoon') || tool.id.includes('polaroid')
? '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);
// 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);
// 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, sampleResult?: 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 () => {
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';
if (primaryFile) {
formData.append(imageParamName, primaryFile);
} 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 (for image-thumbnail or any tool with thumbnails)
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');
setRemainingTries((prev) => Math.max(0, prev - 1));
} 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 Sticky Header */}
<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: Back to Overview & Tool Title */}
<div className="flex items-center gap-3">
<button
type="button"
onClick={() => setViewMode('landing')}
className="inline-flex items-center gap-1.5 px-3 py-1.5 rounded-xl text-xs font-body font-semibold text-ink-2 bg-paper-2 hover:bg-paper hover:text-ink transition-colors cursor-pointer"
>
<ArrowLeft className="w-3.5 h-3.5" />
<span>Overview</span>
</button>
<div className="h-4 w-px bg-rule hidden sm:block" />
<div className="flex items-center gap-2">
<span className="font-display font-bold text-ink text-sm sm:text-base">
{toolName}
</span>
<span className="px-2 py-0.5 rounded-full bg-accent/10 border border-accent/20 text-[10px] font-semibold text-accent uppercase tracking-wider font-body hidden md:inline-block">
{pageType} studio
</span>
</div>
</div>
{/* Right: Actions, Tries, Process Button */}
<div className="flex items-center gap-3">
<span className="text-xs text-muted font-body hidden sm:inline-block">
{remainingTries} free tries today
</span>
<button
type="button"
onClick={handleResetStudio}
className="p-2 rounded-xl text-ink-2 hover:bg-paper hover:text-ink transition-colors cursor-pointer"
title="Reset studio"
>
<RotateCcw className="w-4 h-4" />
</button>
{status === 'success' && resultUrl ? (
<a
href={resultUrl}
download={`${tool.slug}-result.png`}
className="inline-flex items-center gap-1.5 px-4 py-2 rounded-full bg-ink text-paper-hi text-xs font-semibold shadow-xs hover:bg-slate-900 transition-colors cursor-pointer"
>
<Download className="w-3.5 h-3.5" />
<span>Download Result</span>
</a>
) : (
<button
type="button"
onClick={handleExecute}
disabled={status === 'processing'}
className="inline-flex items-center gap-2 px-5 py-2 rounded-full bg-accent text-white text-xs font-semibold shadow-xs hover:bg-accent-hi transition-colors cursor-pointer disabled:opacity-50"
>
{status === 'processing' ? (
<>
<Loader2 className="w-3.5 h-3.5 animate-spin" />
<span>Processing...</span>
</>
) : (
<>
<Sparkles className="w-3.5 h-3.5" />
<span>Process Photo</span>
</>
)}
</button>
)}
</div>
</div>
</div>
{/* Studio Workspace Canvas */}
<div className="max-w-7xl mx-auto px-4 sm:px-6 lg:px-8 pt-5 space-y-5">
{/* 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-2xl bg-paper-hi border border-rule shadow-sheet space-y-5">
{/* 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: DIRECTLY BELOW THE RESULT SLIDER */}
<div className="pt-6 border-t border-rule space-y-4">
<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 (Auto-mask + Custom Mask Brush) */}
{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. IMAGE + THUMBNAIL STUDIO */}
{pageType === 'image-thumbnail' && primaryPreview && (
<div className="space-y-4">
<div className="aspect-[4/3] sm:aspect-[16/10] max-h-[520px] w-full rounded-2xl overflow-hidden bg-paper-2 border border-rule relative">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={primaryPreview}
alt="Uploaded preview"
className="w-full h-full object-contain"
/>
{status === 'processing' && (
<ProcessingOverlay toolName={toolName} />
)}
</div>
</div>
)}
{/* 3. IMAGE-ONLY STUDIO */}
{pageType === 'image-only' && primaryPreview && (
<div className="space-y-4">
<div className="aspect-[4/3] sm:aspect-[16/10] max-h-[520px] w-full rounded-2xl overflow-hidden bg-paper-2 border border-rule relative">
{/* eslint-disable-next-line @next/next/no-img-element */}
<img
src={primaryPreview}
alt="Uploaded preview"
className="w-full h-full object-contain"
/>
{status === 'processing' && (
<ProcessingOverlay toolName={toolName} />
)}
</div>
</div>
)}
{/* 4. 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>
)}
{/* 5. 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 (for image-thumbnail or masking with thumbnails) */}
{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 & SECONDARY BUTTONS */}
{/* DIRECTLY BELOW THE PHOTO UPLOAD CANVAS (USER MANDATE) */}
{/* ================================================================= */}
<div className="pt-6 border-t border-rule space-y-4">
<div className="flex flex-col sm:flex-row items-center justify-between gap-4">
{/* Left: Secondary actions (Change Photo, Reset, etc.) */}
<div className="flex items-center gap-2.5 w-full sm:w-auto order-2 sm:order-1">
{pageType !== 'text-to-image' && (
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="flex-1 sm:flex-none 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"
>
<FolderOpen className="w-4 h-4 text-accent" />
<span>Change Photo</span>
</button>
)}
<button
type="button"
onClick={handleResetStudio}
className="inline-flex items-center justify-center gap-1.5 px-4 py-3.5 rounded-2xl bg-paper-2 hover:bg-red-50 hover:text-red-600 hover:border-red-200 text-ink-2 font-body text-xs sm:text-sm font-medium border border-rule transition-colors cursor-pointer shadow-2xs"
>
<RotateCcw className="w-3.5 h-3.5" />
<span>Reset</span>
</button>
</div>
{/* Right: Massive High-Visibility Main Process Button */}
<div className="w-full sm:w-auto order-1 sm:order-2">
<button
type="button"
onClick={handleExecute}
disabled={status === 'processing'}
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-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>
<ArrowRight className="w-4 h-4" />
</>
)}
</button>
</div>
</div>
<div className="flex flex-wrap items-center justify-between text-[11px] text-muted font-body px-1 gap-2">
<span className="flex items-center gap-1 text-emerald-600 font-medium">
<CheckCircle2 className="w-3 h-3" />
<span>Volatile GPU memory execution · Zero server storage</span>
</span>
<span className="font-mono">{remainingTries} free daily operations remaining</span>
</div>
</div>
</div>
)}
</div>
{/* Quick Info Row */}
<div className="flex flex-wrap items-center justify-between gap-4 text-xs font-body text-muted px-2">
<div className="flex items-center gap-2 text-emerald-600">
<CheckCircle2 className="w-3.5 h-3.5" />
<span>In-browser volatile GPU RAM execution · Zero server storage</span>
</div>
<span>Unlimited batch & 4K exports available in {homeApp ? resolveLocalised(homeApp.name, locale) : 'the mobile app'}</span>
</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-8 pb-10 sm:pb-12 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-[800px] h-[350px] [background:radial-gradient(ellipse_at_top,color-mix(in_oklab,var(--color-accent)_10%,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-3">
<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 */}
<div className="max-w-5xl mb-6 sm:mb-8 space-y-2">
<div className="flex flex-wrap items-center gap-2 text-xs font-sans">
<div className="inline-flex items-center gap-1.5 px-3 py-0.5 rounded-full bg-paper-hi border border-rule text-slate-800 shadow-2xs font-medium">
<Sparkles className="w-3.5 h-3.5 text-accent" />
<span>Studio Vision Model</span>
</div>
<span className="px-2.5 py-0.5 rounded-full bg-emerald-500/10 border border-emerald-500/20 text-emerald-700 font-medium text-[11px]">
Volatile GPU RAM · Zero server retention
</span>
</div>
<h1 className="text-2xl sm:text-4xl font-display font-extrabold text-ink tracking-tight">
<AnimatedShinyText>{toolName}</AnimatedShinyText>
</h1>
<p className="text-sm sm:text-base text-ink-2 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-6 lg:gap-8 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-2xl p-5 sm:p-6 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-2.5 mb-4 flex items-center justify-between">
<span className="text-xs font-bold font-sans text-slate-900">
{pageType === 'text-to-image' ? 'Text prompt studio' : 'Interactive tool studio'}
</span>
<span className="text-[11px] text-slate-500 font-sans">Zero server retention</span>
</div>
{/* Dynamic Upload Input by Type */}
<div className="space-y-4">
{/* Style Thumbnail Selector on Landing Card (Before-Upload / Both) */}
{tool.thumbnails && tool.thumbnails.length > 0 && tool.thumbnailPlacement !== 'after-upload' && (
<div className="space-y-2 pb-2 border-b border-rule/60">
<div className="flex items-center justify-between text-xs 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 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 border text-xs font-sans font-semibold transition-all cursor-pointer ${
isSelected
? 'bg-accent/10 border-accent text-accent shadow-xs'
: 'bg-paper border-rule text-slate-800 hover:border-rule-2'
}`}
>
{(t.thumbnail || t.preview) && (
// eslint-disable-next-line @next/next/no-img-element
<img src={t.thumbnail || t.preview} alt="" className="w-4 h-4 rounded-full object-cover" />
)}
<span>{resolveLocalised(t.label, locale)}</span>
</button>
);
})}
</div>
</div>
)}
{/* Type 1, 2, 3: Single Drag & Drop Dropzone with Prominent Buttons Below */}
{pageType !== 'text-to-image' && pageType !== 'two-images' && (
<div className="space-y-3.5">
<div
onDragOver={(e) => e.preventDefault()}
onDrop={(e) => {
e.preventDefault();
if (e.dataTransfer.files?.[0]) handlePrimaryFileSelect(e.dataTransfer.files[0]);
}}
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-rule hover:border-accent rounded-2xl p-5 sm:p-6 text-center bg-paper/60 hover:bg-accent/5 transition-all cursor-pointer group"
>
<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]);
}}
/>
<div className="w-12 h-12 rounded-xl bg-paper-hi border border-rule flex items-center justify-center text-accent mx-auto mb-2.5 group-hover:scale-110 group-hover:border-accent transition-transform shadow-xs">
<UploadCloud className="w-6 h-6" />
</div>
<h4 className="text-sm sm:text-base font-display font-bold text-ink">
Drag and drop your image here
</h4>
<p className="text-xs text-muted font-sans mt-0.5 max-w-xs mx-auto">
Supports JPG, PNG, WebP up to 12MB. Zero server retention.
</p>
</div>
{/* PROMINENT ACTION BUTTONS DIRECTLY BELOW PHOTO UPLOAD */}
<div className="grid grid-cols-1 sm:grid-cols-2 gap-2.5 pt-1">
<button
type="button"
onClick={() => fileInputRef.current?.click()}
className="w-full inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-accent hover:bg-accent-hi text-white font-display font-bold text-xs sm:text-sm shadow-md hover:shadow-lg hover:scale-[1.01] active:scale-98 transition-all cursor-pointer group"
>
<FolderOpen className="w-4 h-4 text-white group-hover:scale-110 transition-transform" />
<span>Select Photo to Upload</span>
</button>
{samplePresets.length > 0 && (
<button
type="button"
onClick={() => handleLoadSample(samplePresets[0].url, samplePresets[0].resultUrl)}
className="w-full inline-flex items-center justify-center gap-2 px-5 py-3 rounded-xl bg-paper-hi hover:bg-paper-2 border border-rule hover:border-accent text-slate-800 font-sans text-xs sm:text-sm font-semibold shadow-2xs hover:shadow-xs active:scale-98 transition-all cursor-pointer group"
>
<Sparkles className="w-4 h-4 text-accent group-hover:rotate-12 transition-transform" />
<span>Try Demo Portrait</span>
</button>
)}
</div>
</div>
)}
{/* Type 5: Two-Images Dual Upload Dropzones */}
{pageType === 'two-images' && (
<div className="space-y-4">
<div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
{/* Box 1: Primary Image */}
<div
onClick={() => fileInputRef.current?.click()}
className="border-2 border-dashed border-rule hover:border-accent rounded-2xl p-5 text-center bg-paper/60 hover:bg-accent/5 transition-all cursor-pointer"
>
<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]);
}}
/>
<div className="w-10 h-10 rounded-xl bg-paper-hi border border-rule flex items-center justify-center text-accent mx-auto mb-2 shadow-xs">
<UploadCloud className="w-5 h-5" />
</div>
<h5 className="text-xs font-display font-bold text-ink">
{resolveLocalised(tool.twoImagesConfig?.firstImageLabel, locale) || '1. Primary Photo'}
</h5>
<p className="text-[11px] text-muted font-body mt-0.5">
{primaryFile ? primaryFile.name : 'Target face or subject'}
</p>
</div>
{/* Box 2: Reference Image */}
<div
onClick={() => secondaryFileInputRef.current?.click()}
className="border-2 border-dashed border-rule hover:border-accent rounded-2xl p-5 text-center bg-paper/60 hover:bg-accent/5 transition-all cursor-pointer"
>
<input
ref={secondaryFileInputRef}
type="file"
accept="image/jpeg,image/png,image/webp"
className="hidden"
onChange={(e) => {
if (e.target.files?.[0]) handleSecondaryFileSelect(e.target.files[0]);
}}
/>
<div className="w-10 h-10 rounded-xl bg-paper-hi border border-rule flex items-center justify-center text-accent mx-auto mb-2 shadow-xs">
<ImageIcon className="w-5 h-5" />
</div>
<h5 className="text-xs font-display font-bold text-ink">
{resolveLocalised(tool.twoImagesConfig?.secondImageLabel, locale) || '2. Reference Photo'}
</h5>
<p className="text-[11px] text-muted font-body mt-0.5">
{secondaryFile ? secondaryFile.name : 'Source identity to fuse'}
</p>
</div>
</div>
<button
type="button"
onClick={() => {
setViewMode('studio');
if (typeof window !== 'undefined') {
window.scrollTo({ top: 0, behavior: 'smooth' });
}
}}
className="w-full py-3 rounded-full bg-ink text-paper-hi text-xs sm:text-sm font-semibold shadow-xs hover:bg-slate-900 transition-colors cursor-pointer flex items-center justify-center gap-2"
>
<Sparkles className="w-4 h-4 text-accent" />
<span>Open in Dual-Image Studio</span>
</button>
</div>
)}
{/* Type 4: Text-to-image Landing 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 (e.g. A solitary astronaut standing on crystal sands under a violet nebula, cinematic rim lighting, 8k 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"
/>
{/* Quick Prompt Ideas */}
<div className="space-y-1.5">
<span className="text-[11px] font-semibold text-muted font-body">Quick prompt inspiration:</span>
<div className="flex flex-wrap items-center gap-1.5">
{[
'Cinematic 35mm portrait with golden hour rim light',
'Makoto Shinkai anime cityscape under starry skies',
'3D Disney character with luminous amber eyes',
'Hyperrealistic wildlife in lush emerald rain forest'
].map((samplePrompt) => (
<button
key={samplePrompt}
type="button"
onClick={() => setPromptText(samplePrompt)}
className="px-2.5 py-1 rounded-xl bg-paper-2 hover:bg-paper text-ink-2 hover:text-ink text-[11px] font-body border border-rule transition-colors cursor-pointer text-left truncate max-w-full"
>
+ {samplePrompt}
</button>
))}
</div>
</div>
<div className="flex items-center gap-2 pt-1">
<span className="text-xs text-muted font-body">Aspect:</span>
{['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>
<button
type="button"
onClick={() => {
if (promptText.trim()) {
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 text-sm font-display font-bold shadow-md hover:shadow-lg transition-all cursor-pointer flex items-center justify-center gap-2 group"
>
<Sparkles className="w-4 h-4 text-amber-300 group-hover:rotate-12 transition-transform" />
<span>Open in AI Generation Studio</span>
<ArrowRight className="w-4 h-4 text-white" />
</button>
</div>
)}
{/* Sample Presets to Try Instantly with 1 Click */}
{samplePresets.length > 0 && pageType !== 'text-to-image' && (
<div className="pt-2 border-t border-rule/60 flex items-center justify-between text-xs font-body">
<span className="text-muted">No photo handy?</span>
<button
type="button"
onClick={() => handleLoadSample(samplePresets[0].url, samplePresets[0].resultUrl)}
className="text-accent font-semibold hover:underline inline-flex items-center gap-1 cursor-pointer"
>
<span>Try sample portrait</span>
<ChevronRight className="w-3.5 h-3.5" />
</button>
</div>
)}
</div>
</div>
{/* Specimen View: Interactive Before/After Slider */}
<div className="lg:col-span-6">
<div className="studio-sheet p-4 sm:p-5 rounded-2xl">
<div className="mb-2.5 flex items-center justify-between text-xs text-muted font-sans">
<span className="font-semibold text-slate-900">Transformation specimen</span>
<span className="text-[11px] text-slate-500">Drag slider to inspect details</span>
</div>
<div className="aspect-[4/3] rounded-xl overflow-hidden bg-paper-2 border border-rule">
<CardBeforeAfterSlider
beforeUrl={primaryExample.before}
afterUrl={primaryExample.after}
title={toolName}
slug={tool.slug}
aspectRatio="aspect-[4/3]"
/>
</div>
<div className="mt-2.5 text-xs text-muted font-sans text-center">
Full 4K batch processing available in {homeApp ? resolveLocalised(homeApp.name, locale) : 'the mobile app'}.
</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="Explore Visual Styles & Presets"
subtitle="Click any preset thumbnail to select your effect before or during editing."
/>
)}
{/* ================= 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"
>
<Smartphone className="w-4 h-4 text-accent" />
<span>Explore Mobile Apps Suite</span>
</Link>
</div>
</div>
</section>
</div>
);
}