<?php
/**
 * Tpictures - Premium Cinematic Image Upload Portal
 * Developed by Olojede Treasure.
 * Enhanced for full interactivity, visual excellence, and robustness.
 */

if (session_status() === PHP_SESSION_NONE) {
    ini_set('session.use_strict_mode', 1);
    session_start();
}

// Allowed extensions and mime types for security
$allowed_extensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$allowed_mime_types = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];

// --- API Background Removal Endpoint (With Abuse Prevention) ---
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'remove_bg') {
    header('Content-Type: application/json');

    $maxRequestsPerDay = 5;
    $ipAddress = filter_var($_SERVER['REMOTE_ADDR'], FILTER_VALIDATE_IP) ?: '0.0.0.0';
    $rateLimitFile = sys_get_temp_dir() . '/tpictures_bg_removals.json';
    
    // 1. Abuse Prevention System (Concurrency-Safe Read)
    $tracker = [];
    if (file_exists($rateLimitFile)) {
        $fp = @fopen($rateLimitFile, 'r');
        if ($fp && flock($fp, LOCK_SH)) {
            $fileData = stream_get_contents($fp);
            flock($fp, LOCK_UN);
            fclose($fp);
            $tracker = $fileData ? json_decode($fileData, true) : [];
            if (!is_array($tracker)) $tracker = [];
        }
    }

    $twentyFourHoursAgo = time() - 86400;
    $tracker = array_filter($tracker, function($entry) use ($twentyFourHoursAgo) {
        return isset($entry['timestamp']) && $entry['timestamp'] > $twentyFourHoursAgo;
    });

    $ipUsageCount = 0;
    foreach ($tracker as $entry) {
        if (isset($entry['ip']) && $entry['ip'] === $ipAddress) {
            $ipUsageCount++;
        }
    }

    if ($ipUsageCount >= $maxRequestsPerDay) {
        echo json_encode(['success' => false, 'error' => "Daily AI limit reached ($maxRequestsPerDay max) to prevent abuse."]);
        exit;
    }

    // 2. Process and Validate Image Data
    $base64Image = $_POST['image_base64'] ?? '';
    if (empty($base64Image)) {
        echo json_encode(['success' => false, 'error' => 'No image data received.']);
        exit;
    }

    $base64Data = preg_replace('#^data:image/\w+;base64,#i', '', $base64Image);
    
    // Size Validation (Reject payloads estimating > 5MB to prevent memory exhaustion)
    $estimatedSize = (int)(strlen($base64Data) * (3/4));
    if ($estimatedSize > (5 * 1024 * 1024)) {
        echo json_encode(['success' => false, 'error' => 'Image exceeds 5MB limit for AI processing.']);
        exit;
    }

    $apiKey = 'yTZ5dKTPnXXe3qdFkkJRoJFt';

    // 3. Native cURL execution with timeouts
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, 'https://api.remove.bg/v1.0/removebg');
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($ch, CURLOPT_POST, 1);
    curl_setopt($ch, CURLOPT_POSTFIELDS, [
        'image_file_b64' => $base64Data,
        'size' => 'auto'
    ]);
    curl_setopt($ch, CURLOPT_HTTPHEADER, [
        'X-Api-Key: ' . $apiKey
    ]);
    curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Prevent hanging
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 10);
    curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); 

    $result = curl_exec($ch);
    $httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
    $error = curl_error($ch);
    curl_close($ch);

    if ($httpcode == 200) {
        // Log successful usage (Concurrency-Safe Write)
        $tracker[] = ['ip' => $ipAddress, 'timestamp' => time()];
        file_put_contents($rateLimitFile, json_encode(array_values($tracker)), LOCK_EX);

        $base64Result = base64_encode($result);
        echo json_encode([
            'success' => true,
            'image' => 'data:image/png;base64,' . $base64Result,
            'remaining' => $maxRequestsPerDay - ($ipUsageCount + 1)
        ]);
    } else {
        $errObj = json_decode($result, true);
        $errMsg = $errObj['errors'][0]['title'] ?? $error ?? 'Unknown API error.';
        echo json_encode(['success' => false, 'error' => 'API Error: ' . $errMsg]);
    }
    exit;
}

// Mock backend processing for preview environment demonstration
if ($_SERVER['REQUEST_METHOD'] === 'POST' && isset($_POST['action']) && $_POST['action'] === 'upload_image') {
    header('Content-Type: application/json');

    // Honeypot check
    if (!empty($_POST['website_url_honeypot'])) {
        echo json_encode(['success' => false, 'error' => 'Bot activity detected via security gate!']);
        exit;
    }

    $scheme  = (!empty($_SERVER['HTTPS']) && $_SERVER['HTTPS'] !== 'off') ? 'https' : 'http';
    $host    = isset($_SERVER['HTTP_HOST']) ? $_SERVER['HTTP_HOST'] : 'localhost';
    $siteUrl = $scheme . '://' . $host;

    echo json_encode([
        'success'    => true,
        'shortlink'  => $siteUrl.'/v/'.substr(md5(time()), 0, 8),
        'siteUrl'    => $siteUrl,
        'dimensions' => [
            'original'  => 'mock_url_original',
            'large'     => 'mock_url_large',
            'medium'    => 'mock_url_medium',
            'thumbnail' => 'mock_url_thumbnail'
        ]
    ]);
    exit;
}

$num1 = rand(3, 9);
$num2 = rand(2, 8);
$_SESSION['math_captcha_answer'] = $num1 + $num2;
?>
<!DOCTYPE html>
<html lang="en" class="h-full scroll-smooth">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Tpictures | Cinema Dispatcher Portal</title>
    <script src="https://cdn.tailwindcss.com"></script>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.4.0/css/all.min.css">
    <link rel="preconnect" href="https://fonts.googleapis.com">
    <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
    <link href="https://fonts.googleapis.com/css2?family=Inter:wght@300;400;500;600;700&family=Syne:wght@700;800&display=swap" rel="stylesheet">

    <script>
        tailwind.config = {
            theme: {
                extend: {
                    fontFamily: {
                        sans: ['Inter', 'sans-serif'],
                        cinematic: ['Syne', 'sans-serif'],
                    },
                    colors: {
                        brand: {
                            gold: '#D4AF37',
                            amber: '#F59E0B',
                            dark: '#0A0A0C',
                            darker: '#050507'
                        }
                    }
                }
            }
        }
    </script>
    <style>
        body {
            background-color: #050507;
            font-family: 'Inter', sans-serif;
            background-image: radial-gradient(circle at 50% -20%, rgba(212, 175, 55, 0.15) 0%, rgba(0,0,0,0) 70%);
            overflow-x: hidden;
        }
        .glass-panel {
            background: rgba(12, 12, 16, 0.82);
            backdrop-filter: blur(24px);
            -webkit-backdrop-filter: blur(24px);
            border: 1px solid rgba(255, 255, 255, 0.08);
        }
        .glow-gold {
            box-shadow: 0 0 50px rgba(212, 175, 55, 0.04);
            transition: all 0.4s cubic-bezier(0.16, 1, 0.3, 1);
        }
        .glow-gold:hover {
            box-shadow: 0 0 65px rgba(212, 175, 55, 0.12);
            border-color: rgba(212, 175, 55, 0.25);
        }
        .trap-field {
            display: none !important;
            visibility: hidden !important;
            position: absolute !important;
            left: -9999px !important;
        }
        .filter-btn, .dim-btn {
            transition: all 0.25s cubic-bezier(0.4, 0, 0.2, 1);
        }
        .preview-glow {
            filter: drop-shadow(0 0 15px rgba(212, 175, 55, 0.2));
        }
        .preview-vignette {
            box-shadow: inset 0 0 80px rgba(0,0,0,0.85);
            pointer-events: none;
            transition: opacity 0.3s ease;
        }
        .film-strip-border {
            background-image: radial-gradient(circle, #050507 40%, transparent 45%);
            background-size: 14px 14px;
            background-repeat: repeat-x;
        }
        @keyframes sweep {
            0% { transform: translateY(-100%); }
            100% { transform: translateY(100%); }
        }
        .scanning-line {
            animation: sweep 2s linear infinite;
        }
        /* Custom scrollbar for filmstrip */
        .scrollbar-thin::-webkit-scrollbar {
            height: 6px;
        }
        .scrollbar-thin::-webkit-scrollbar-track {
            background: rgba(255, 255, 255, 0.05);
            border-radius: 4px;
        }
        .scrollbar-thin::-webkit-scrollbar-thumb {
            background: rgba(212, 175, 55, 0.3);
            border-radius: 4px;
        }
        .scrollbar-thin::-webkit-scrollbar-thumb:hover {
            background: rgba(212, 175, 55, 0.6);
        }
    </style>
</head>
<body class="text-gray-200 min-h-screen flex flex-col justify-between selection:bg-brand-gold selection:text-black relative">

    <!-- Background Atmospheric Particles Canvas -->
    <canvas id="ambientCanvas" class="fixed inset-0 w-full h-full pointer-events-none z-0"></canvas>

    <header class="relative w-full max-w-7xl mx-auto px-4 md:px-8 pt-6 flex justify-between items-center z-10">
        <div class="flex items-center gap-3 cursor-pointer hover:opacity-80 transition">
            <div class="w-10 h-10 flex items-center justify-center rounded-xl border border-brand-gold/30 bg-brand-dark relative group overflow-hidden">
                <div class="absolute inset-0 bg-gradient-to-tr from-brand-gold/20 to-transparent opacity-0 group-hover:opacity-100 transition duration-500"></div>
                <svg class="w-6 h-6 text-brand-gold animate-[spin_20s_linear_infinite]" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="1.5">
                    <circle cx="12" cy="12" r="10"/>
                    <line x1="12" y1="2" x2="12" y2="22"/>
                    <line x1="2" y1="12" x2="22" y2="12"/>
                    <line x1="4.93" y1="4.93" x2="19.07" y2="19.07"/>
                </svg>
            </div>
            <div class="flex flex-col items-center sm:items-start text-center sm:text-left px-2 sm:px-0">
                <span class="font-cinematic text-lg md:text-xl font-extrabold tracking-[0.2em] text-white">
                    T<span class="text-brand-gold">PICTURES</span>
                </span>
                <span class="text-[8px] tracking-[0.3em] uppercase text-neutral-500 font-bold px-4 w-full block sm:px-0">Studio Editor</span>
            </div>
        </div>
        <button class="text-[11px] tracking-widest text-neutral-400 hover:text-brand-gold transition duration-300 uppercase flex items-center gap-1.5 font-medium">
            <i class="fa-solid fa-arrow-left text-[10px]"></i> <span class="hidden sm:inline">Main Menu</span>
        </button>
    </header>

    <!-- Custom Slide-in Notification Container -->
    <div id="toastBox" class="fixed top-6 right-6 z-50 transform translate-y-[-150%] opacity-0 pointer-events-none transition-all duration-500 max-w-sm w-full px-4 sm:px-0">
        <div id="toastContent" class="glass-panel p-4 rounded-2xl flex items-start gap-3 shadow-2xl border-l-4 border-l-brand-gold">
            <div id="toastIcon" class="text-brand-gold mt-0.5">
                <i class="fa-solid fa-circle-info"></i>
            </div>
            <div class="flex-1">
                <span id="toastTitle" class="font-bold text-xs tracking-wide uppercase text-white block">System Status</span>
                <span id="toastMessage" class="text-neutral-400 text-xs leading-relaxed block mt-0.5">Message body goes here.</span>
            </div>
        </div>
    </div>

    <main class="relative flex-1 flex flex-col justify-center items-center w-full max-w-5xl mx-auto px-4 py-8 z-10">
        
        <div id="envWarning" class="hidden w-full mb-6 p-4 rounded-2xl bg-amber-500/10 border border-amber-500/30 text-amber-200 text-xs md:text-sm leading-relaxed backdrop-blur-md px-6 text-center sm:text-left">
            <div class="flex flex-col sm:flex-row gap-3 items-center sm:items-start">
                <i class="fa-solid fa-bolt text-brand-amber text-lg mt-0.5 animate-pulse"></i>
                <div>
                    <span class="font-bold block text-white mb-1">Sandbox Engine Active</span>
                    Running in powerful local rendering mode. Edits and uploads are simulated beautifully within your browser cache.
                </div>
            </div>
        </div>

        <div class="text-center mb-6 md:mb-10 w-full">
            <h1 class="font-cinematic text-3xl sm:text-5xl font-extrabold tracking-tight text-white mb-2 md:mb-3 px-4">
                Cinematic <span class="bg-clip-text text-transparent bg-gradient-to-r from-brand-gold to-brand-amber">Dispatcher</span>
            </h1>
            <p class="text-neutral-400 text-xs md:text-sm max-w-md mx-auto text-center px-6">
                Edit, grade, annotate, and dispatch your master frames directly to the secure archive.
            </p>
        </div>

        <div class="w-full glass-panel rounded-3xl p-4 md:p-8 glow-gold relative overflow-hidden">
            
            <form id="uploadForm" class="space-y-6">
                <!-- SECURITY HONEYPOT -->
                <div class="trap-field">
                    <label for="website_url_honeypot">Leave blank:</label>
                    <input type="text" name="website_url_honeypot" id="website_url_honeypot" tabindex="-1" autocomplete="off">
                </div>

                <div id="dropZone" class="relative group border-2 border-dashed border-white/10 hover:border-brand-gold/50 rounded-2xl p-6 md:p-10 text-center cursor-pointer transition-all duration-300 bg-neutral-950/40 overflow-hidden">
                    <div id="shutterOverlay" class="absolute inset-0 bg-white opacity-0 pointer-events-none transition-opacity duration-200 z-30"></div>
                    <input type="file" id="fileSelector" accept="image/jpeg,image/png,image/gif,image/webp" class="hidden">
                    
                    <div id="uploadPlaceholder" class="space-y-4 py-8 pointer-events-none">
                        <div class="w-16 h-16 rounded-full bg-brand-gold/10 text-brand-gold flex items-center justify-center mx-auto group-hover:scale-110 group-hover:bg-brand-gold/20 transition-all duration-300 shadow-[0_0_15px_rgba(212,175,55,0.1)]">
                            <i class="fa-solid fa-camera-retro text-3xl"></i>
                        </div>
                        <div class="px-4">
                            <span class="text-white font-medium text-sm block">Select image or drop files here</span>
                            <span class="text-[11px] text-neutral-500 block mt-1">Supports JPG, PNG, GIF, WEBP files</span>
                        </div>
                    </div>

                    <!-- Selected File Preview & Editor -->
                    <div id="filePreviewState" class="hidden space-y-6 lg:space-y-0 lg:grid lg:grid-cols-12 lg:gap-8 items-stretch text-left py-2" onclick="event.stopPropagation();">
                        
                        <!-- Left Side: Viewfinder -->
                        <div class="col-span-12 lg:col-span-7 flex flex-col justify-between items-center bg-black/40 p-4 rounded-2xl border border-white/5 relative">
                            <div class="relative w-full aspect-square max-w-[400px] sm:max-w-[450px] mx-auto rounded-xl overflow-hidden border border-brand-gold/30 bg-neutral-950 flex items-center justify-center cursor-crosshair shadow-2xl">
                                <!-- Background pattern to show transparency -->
                                <div class="absolute inset-0 opacity-20" style="background-image: radial-gradient(#444 1px, transparent 1px); background-size: 10px 10px;"></div>
                                
                                <div id="vignetteOverlay" class="preview-vignette absolute inset-0 z-10 opacity-60"></div>
                                <canvas id="editorCanvas" class="max-w-full max-h-full object-contain relative z-0 shadow-lg" style="transition: filter 0.15s ease;"></canvas>

                                <div id="canvasTextWatermark" class="absolute z-20 select-none text-white font-cinematic font-extrabold tracking-wider uppercase drop-shadow-[0_2px_8px_rgba(0,0,0,0.85)] cursor-move hidden transition-transform px-4 text-center" style="top: 50%; left: 50%; transform: translate(-50%, -50%);">
                                    Tpictures Studio
                                </div>

                                <!-- Crop overlay box with drag handles -->
                                <div id="cropOverlay" class="absolute z-30 hidden border-2 border-brand-gold shadow-[0_0_0_9999px_rgba(0,0,0,0.55)] cursor-move touch-none" style="left:10%; top:10%; width:80%; height:80%;">
                                    <div class="absolute inset-0 grid grid-cols-3 grid-rows-3 pointer-events-none opacity-60">
                                        <div class="border-r border-b border-white/40"></div><div class="border-r border-b border-white/40"></div><div class="border-b border-white/40"></div>
                                        <div class="border-r border-b border-white/40"></div><div class="border-r border-b border-white/40"></div><div class="border-b border-white/40"></div>
                                        <div class="border-r border-white/40"></div><div class="border-r border-white/40"></div><div></div>
                                    </div>
                                    <div data-handle="nw" class="crop-handle absolute -top-3 -left-3 w-7 h-7 sm:w-6 sm:h-6 bg-brand-gold rounded-full border-2 border-black cursor-nwse-resize touch-none"></div>
                                    <div data-handle="ne" class="crop-handle absolute -top-3 -right-3 w-7 h-7 sm:w-6 sm:h-6 bg-brand-gold rounded-full border-2 border-black cursor-nesw-resize touch-none"></div>
                                    <div data-handle="sw" class="crop-handle absolute -bottom-3 -left-3 w-7 h-7 sm:w-6 sm:h-6 bg-brand-gold rounded-full border-2 border-black cursor-nesw-resize touch-none"></div>
                                    <div data-handle="se" class="crop-handle absolute -bottom-3 -right-3 w-7 h-7 sm:w-6 sm:h-6 bg-brand-gold rounded-full border-2 border-black cursor-nwse-resize touch-none"></div>
                                </div>
                            </div>
                            
                            <div class="mt-5 flex justify-between items-center w-full max-w-[450px] px-2 gap-3">
                                <div class="truncate pr-4 flex items-center gap-3 min-w-0">
                                    <button type="button" onclick="resetFileSelection()" class="w-9 h-9 shrink-0 rounded-full bg-white/5 hover:bg-red-500/20 text-neutral-400 hover:text-red-400 flex items-center justify-center transition" title="Remove File">
                                        <i class="fa-solid fa-trash-can text-[10px]"></i>
                                    </button>
                                    <div class="min-w-0">
                                        <span id="selectedFileName" class="text-white font-medium text-sm truncate max-w-[150px] block">filename.jpg</span>
                                        <span id="selectedFileSize" class="text-xs text-neutral-500 block">0.0 MB</span>
                                    </div>
                                </div>
                                <button type="button" onclick="downloadCurrentEdit()" title="Download edited image" class="shrink-0 w-9 h-9 rounded-full bg-brand-gold/10 border border-brand-gold/30 text-brand-gold hover:bg-brand-gold hover:text-black flex items-center justify-center transition shadow-[0_0_10px_rgba(212,175,55,0.15)]">
                                    <i class="fa-solid fa-download text-xs"></i>
                                </button>
                            </div>
                            <div class="mt-2 flex justify-end w-full max-w-[450px] px-2">
                                <div class="bg-brand-gold/10 border border-brand-gold/30 text-[9px] text-brand-gold px-2.5 py-1.5 rounded font-bold uppercase tracking-widest shadow-[0_0_10px_rgba(212,175,55,0.2)]" id="activeFilterName">
                                    Raw Frame
                                </div>
                            </div>
                        </div>

                        <!-- Right Side: Editor Controls -->
                        <div class="col-span-12 lg:col-span-5 space-y-6 bg-black/60 p-4 md:p-6 rounded-2xl border border-white/5 flex flex-col justify-between">
                            
                            <div class="space-y-5">
                                <div class="flex border-b border-white/15 overflow-x-auto scrollbar-thin whitespace-nowrap">
                                    <button type="button" onclick="switchEditorTab('grading')" id="tabBtn-grading" class="flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-brand-gold border-b-2 border-brand-gold transition-colors">Grading</button>
                                    <button type="button" onclick="switchEditorTab('transform')" id="tabBtn-transform" class="flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-neutral-400 hover:text-white transition-colors">Transform</button>
                                    <button type="button" onclick="switchEditorTab('crop')" id="tabBtn-crop" class="flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-neutral-400 hover:text-white transition-colors">Crop</button>
                                    <button type="button" onclick="switchEditorTab('markup')" id="tabBtn-markup" class="flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-neutral-400 hover:text-white transition-colors">Markup</button>
                                </div>

                                <!-- TAB 1: GRADING -->
                                <div id="editorTab-grading" class="space-y-5 animate-[fadeIn_0.3s_ease]">
                                    <div>
                                        <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold block mb-3 px-1 text-center sm:text-left">LUT Profiles</span>
                                        <div class="flex flex-wrap items-center justify-center sm:justify-start gap-2">
                                            <button type="button" onclick="applyPresetFilter('raw', this)" class="filter-btn px-2.5 py-1.5 rounded bg-brand-gold text-black text-[9px] uppercase tracking-wider font-bold border border-brand-gold shadow-[0_0_10px_rgba(212,175,55,0.3)]">Raw</button>
                                            <button type="button" onclick="applyPresetFilter('gold', this)" class="filter-btn px-2.5 py-1.5 rounded bg-white/5 text-neutral-300 hover:bg-white/15 text-[9px] uppercase tracking-wider font-bold border border-white/10">Gold Hour</button>
                                            <button type="button" onclick="applyPresetFilter('noir', this)" class="filter-btn px-2.5 py-1.5 rounded bg-white/5 text-neutral-300 hover:bg-white/15 text-[9px] uppercase tracking-wider font-bold border border-white/10">Lagos Noir</button>
                                            <button type="button" onclick="applyPresetFilter('cyber', this)" class="filter-btn px-2.5 py-1.5 rounded bg-white/5 text-neutral-300 hover:bg-white/15 text-[9px] uppercase tracking-wider font-bold border border-white/10">Cyber Neon</button>
                                        </div>
                                    </div>

                                    <div class="space-y-4 border-t border-white/5 pt-4 px-1">
                                        <div>
                                            <div class="flex justify-between text-[10px] text-neutral-400 mb-2">
                                                <span>Exposure</span>
                                                <span id="labelBrightness" class="font-mono text-brand-amber">100%</span>
                                            </div>
                                            <input type="range" id="sliderBrightness" min="30" max="170" value="100" oninput="updateManualFilters()" class="w-full accent-brand-gold bg-white/10 rounded-lg h-1.5 appearance-none cursor-pointer hover:bg-white/20 transition">
                                        </div>
                                        <div>
                                            <div class="flex justify-between text-[10px] text-neutral-400 mb-2">
                                                <span>Contrast</span>
                                                <span id="labelContrast" class="font-mono text-brand-amber">100%</span>
                                            </div>
                                            <input type="range" id="sliderContrast" min="30" max="170" value="100" oninput="updateManualFilters()" class="w-full accent-brand-gold bg-white/10 rounded-lg h-1.5 appearance-none cursor-pointer hover:bg-white/20 transition">
                                        </div>
                                        <div>
                                            <div class="flex justify-between text-[10px] text-neutral-400 mb-2">
                                                <span>Saturation</span>
                                                <span id="labelSaturation" class="font-mono text-brand-amber">100%</span>
                                            </div>
                                            <input type="range" id="sliderSaturation" min="0" max="200" value="100" oninput="updateManualFilters()" class="w-full accent-brand-gold bg-white/10 rounded-lg h-1.5 appearance-none cursor-pointer hover:bg-white/20 transition">
                                        </div>
                                        <div>
                                            <div class="flex justify-between text-[10px] text-neutral-400 mb-2">
                                                <span>Vignette Depth</span>
                                                <span id="labelVignette" class="font-mono text-brand-amber">60%</span>
                                            </div>
                                            <input type="range" id="sliderVignette" min="0" max="100" value="60" oninput="updateManualFilters()" class="w-full accent-brand-gold bg-white/10 rounded-lg h-1.5 appearance-none cursor-pointer hover:bg-white/20 transition">
                                        </div>
                                    </div>
                                </div>

                                <!-- TAB 2: TRANSFORM -->
                                <div id="editorTab-transform" class="space-y-4 hidden animate-[fadeIn_0.3s_ease]">
                                    <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold block px-2 text-center sm:text-left">Orientation Adjustments</span>
                                    <div class="grid grid-cols-3 gap-3">
                                        <button type="button" onclick="transformRotate()" class="p-4 bg-white/5 border border-white/10 hover:border-brand-gold hover:bg-brand-gold/10 hover:text-white rounded-xl flex flex-col items-center gap-2 transition group">
                                            <i class="fa-solid fa-rotate text-lg text-brand-gold group-hover:rotate-90 transition-transform duration-300"></i>
                                            <span class="text-[9px] uppercase font-bold">Rotate</span>
                                        </button>
                                        <button type="button" onclick="transformFlip('H')" class="p-4 bg-white/5 border border-white/10 hover:border-brand-gold hover:bg-brand-gold/10 hover:text-white rounded-xl flex flex-col items-center gap-2 transition">
                                            <i class="fa-solid fa-arrows-left-right text-lg text-brand-gold"></i>
                                            <span class="text-[9px] uppercase font-bold">Flip H</span>
                                        </button>
                                        <button type="button" onclick="transformFlip('V')" class="p-4 bg-white/5 border border-white/10 hover:border-brand-gold hover:bg-brand-gold/10 hover:text-white rounded-xl flex flex-col items-center gap-2 transition">
                                            <i class="fa-solid fa-arrows-up-down text-lg text-brand-gold"></i>
                                            <span class="text-[9px] uppercase font-bold">Flip V</span>
                                        </button>
                                    </div>
                                    <div class="p-3 bg-blue-500/10 border border-blue-500/20 rounded-xl mt-4">
                                        <p class="text-[10px] text-blue-300 leading-relaxed text-center px-4"><i class="fa-solid fa-info-circle mr-1"></i> Use these tools to correct camera orientation or create artistic mirrors before dispatching.</p>
                                    </div>
                                </div>

                                <!-- TAB 3: CROP -->
                                <div id="editorTab-crop" class="space-y-4 hidden animate-[fadeIn_0.3s_ease]">
                                    <div class="flex justify-between items-center px-1">
                                        <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold">Frame Crop</span>
                                        <button type="button" id="cropToggleBtn" onclick="toggleCropMode()" class="px-2.5 py-1.5 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-wider font-mono hover:border-brand-gold hover:text-white transition shadow-sm min-h-[32px]">Active: Off</button>
                                    </div>
                                    <div>
                                        <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold block mb-2 px-1">Aspect Ratio</span>
                                        <div class="grid grid-cols-3 gap-2">
                                            <button type="button" onclick="setCropAspect('free', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-brand-gold text-black text-[10px] uppercase tracking-wider font-bold rounded-lg border border-brand-gold">Free</button>
                                            <button type="button" onclick="setCropAspect('1:1', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10">Square</button>
                                            <button type="button" onclick="setCropAspect('4:5', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10">4:5</button>
                                            <button type="button" onclick="setCropAspect('16:9', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10">16:9</button>
                                            <button type="button" onclick="setCropAspect('3:2', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10">3:2</button>
                                            <button type="button" onclick="setCropAspect('9:16', this)" class="crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10">9:16</button>
                                        </div>
                                    </div>
                                    <div class="grid grid-cols-2 gap-3 pt-1">
                                        <button type="button" onclick="applyCrop()" class="p-3 min-h-[44px] bg-brand-gold/10 border border-brand-gold/40 hover:bg-brand-gold hover:text-black text-brand-gold rounded-xl text-[10px] uppercase tracking-wider font-bold transition">
                                            <i class="fa-solid fa-crop-simple mr-1.5"></i> Apply Crop
                                        </button>
                                        <button type="button" onclick="resetCrop()" class="p-3 min-h-[44px] bg-white/5 border border-white/10 hover:border-white/30 text-neutral-300 rounded-xl text-[10px] uppercase tracking-wider font-bold transition">
                                            <i class="fa-solid fa-arrow-rotate-left mr-1.5"></i> Reset Crop
                                        </button>
                                    </div>
                                    <div class="p-3 bg-blue-500/10 border border-blue-500/20 rounded-xl mt-2 mx-1">
                                        <p class="text-[10px] text-blue-300 leading-relaxed text-center px-4"><i class="fa-solid fa-info-circle mr-1"></i> Enable crop mode, drag the corner handles to frame your shot, then apply. Cropping is destructive — it bakes into the master frame.</p>
                                    </div>
                                </div>
                                <!-- TAB 4: MARKUP -->
                                <div id="editorTab-markup" class="space-y-5 hidden animate-[fadeIn_0.3s_ease]">
                                    <div class="space-y-3">
                                        <div class="flex justify-between items-center px-1">
                                            <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold">AI Background Removal</span>
                                            <button type="button" id="bgRemoveUndoBtn" onclick="undoBackgroundRemoval()" class="hidden px-2.5 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-wider font-mono hover:border-brand-gold hover:text-white transition shadow-sm">Undo</button>
                                        </div>
                                        
                                        <button type="button" id="bgRemoveBtn" onclick="removeBackground()" class="w-full p-3 min-h-[44px] bg-brand-gold/10 border border-brand-gold/40 hover:bg-brand-gold hover:text-black text-brand-gold rounded-xl text-[10px] uppercase tracking-wider font-bold transition flex items-center justify-center gap-2">
                                            <i class="fa-solid fa-wand-magic-sparkles"></i> Remove Background
                                        </button>

                                        <!-- NEW BACKGROUND REPLACEMENT UI -->
                                        <div id="bgReplacementUI" class="hidden space-y-3 pt-3 border-t border-white/5 mt-3 animate-[fadeIn_0.3s_ease] px-1">
                                            <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold block text-center sm:text-left">Backdrop Replacement</span>
                                            <div class="flex flex-wrap items-center justify-center sm:justify-start gap-2">
                                                <button type="button" onclick="setCustomBg('none')" class="w-7 h-7 rounded bg-[url('data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAoAAAAKCAYAAACNMs+9AAAAAXNSR0IArs4c6QAAACVJREFUKFNjZCASMDKgAnv37v3/n52dHUWjhoEAqhoYwII0OwEAtKIV/Qj6hVUAAAAASUVORK5CYII=')] border border-white/10 hover:border-brand-gold transition" title="Transparent"></button>
                                                <button type="button" onclick="setCustomBg('color', '#FFFFFF')" class="w-7 h-7 rounded bg-white border border-white/10 hover:border-brand-gold transition shadow-sm" title="Solid White"></button>
                                                <button type="button" onclick="setCustomBg('color', '#000000')" class="w-7 h-7 rounded bg-black border border-white/30 hover:border-brand-gold transition shadow-sm" title="Solid Black"></button>
                                                <button type="button" onclick="setCustomBg('color', '#D4AF37')" class="w-7 h-7 rounded bg-brand-gold border border-white/10 hover:border-brand-gold transition shadow-sm" title="Brand Gold"></button>
                                                <button type="button" onclick="setCustomBg('gradient', 'gold')" class="w-7 h-7 rounded bg-gradient-to-br from-brand-gold to-amber-600 border border-white/10 hover:border-brand-gold transition shadow-sm" title="Gold Gradient"></button>
                                                <button type="button" onclick="setCustomBg('gradient', 'cyber')" class="w-7 h-7 rounded bg-gradient-to-br from-purple-600 to-blue-500 border border-white/10 hover:border-brand-gold transition shadow-sm" title="Cyber Gradient"></button>
                                                <div class="relative ml-auto">
                                                    <input type="file" id="customBgUploader" accept="image/jpeg,image/png,image/webp" class="hidden" onchange="handleCustomBgUpload(this)">
                                                    <button type="button" onclick="document.getElementById('customBgUploader').click()" class="px-3 py-1.5 rounded bg-white/5 border border-white/10 text-[9px] uppercase font-bold text-neutral-300 hover:text-white hover:border-brand-gold transition flex items-center gap-1.5 shadow-sm">
                                                        <i class="fa-solid fa-image"></i> Custom
                                                    </button>
                                                </div>
                                            </div>
                                        </div>

                                        <p class="text-[9px] text-neutral-500 leading-relaxed text-center px-4"><i class="fa-solid fa-microchip text-brand-gold/70 mr-1"></i> Send frame to external remove.bg AI to perfectly isolate your subject. Limit 5 per day. Result returns as transparent PNG.</p>
                                    </div>

                                    <div class="space-y-3 border-t border-white/5 pt-4">
                                        <div class="flex justify-between items-center px-1">
                                            <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold">Annotation Brush</span>
                                            <button type="button" id="brushToggleBtn" onclick="toggleBrushActive()" class="px-2.5 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-wider font-mono hover:border-brand-gold hover:text-white transition shadow-sm">Active: Off</button>
                                        </div>
                                        
                                        <div class="grid grid-cols-2 gap-4 bg-black/30 p-3 rounded-xl border border-white/5">
                                            <div class="flex items-center gap-2.5 justify-center border-r border-white/10">
                                                <button type="button" onclick="setBrushColor('#D4AF37', this)" class="brush-color-btn w-6 h-6 rounded-full bg-[#D4AF37] border-2 border-white scale-110 shadow-[0_0_10px_rgba(212,175,55,0.5)] transition" title="Brand Gold"></button>
                                                <button type="button" onclick="setBrushColor('#EF4444', this)" class="brush-color-btn w-6 h-6 rounded-full bg-red-500 border-2 border-transparent hover:scale-110 transition" title="Alert Red"></button>
                                                <button type="button" onclick="setBrushColor('#10B981', this)" class="brush-color-btn w-6 h-6 rounded-full bg-emerald-500 border-2 border-transparent hover:scale-110 transition" title="Grass Green"></button>
                                                <button type="button" onclick="setBrushColor('#FFFFFF', this)" class="brush-color-btn w-6 h-6 rounded-full bg-white border-2 border-transparent hover:scale-110 transition" title="Pure White"></button>
                                            </div>
                                            <div class="flex flex-col justify-center gap-1.5 px-2">
                                                <div class="flex justify-between text-[9px] text-neutral-500 font-mono">
                                                    <span>Size</span>
                                                    <span id="brushSizeIndicator" class="text-brand-amber">6px</span>
                                                </div>
                                                <input type="range" id="sliderBrushSize" min="2" max="30" value="6" oninput="updateBrushIndicator()" class="w-full accent-brand-gold bg-white/10 rounded-lg h-1 appearance-none cursor-pointer">
                                            </div>
                                        </div>
                                        <button type="button" onclick="clearDrawings()" class="text-[9px] text-red-400 hover:text-red-300 uppercase tracking-wider font-bold w-full text-right px-2"><i class="fa-solid fa-eraser"></i> Clear Strokes</button>
                                    </div>

                                    <div class="space-y-3 border-t border-white/5 pt-4">
                                        <span class="text-[10px] tracking-wider text-neutral-400 uppercase font-bold block px-1 text-center sm:text-left">Watermark Metadata</span>
                                        <div class="flex flex-col sm:flex-row items-center gap-2">
                                            <input type="text" id="watermarkTextVal" placeholder="Enter text..." class="bg-black/60 border border-white/15 rounded-xl px-4 py-2 text-xs text-white placeholder-neutral-600 focus:outline-none focus:border-brand-gold focus:ring-1 focus:ring-brand-gold w-full flex-1 transition text-center sm:text-left">
                                            <button type="button" onclick="applyTextWatermark()" class="w-full sm:w-auto px-6 py-2 min-h-[38px] bg-brand-gold text-neutral-950 font-bold text-[10px] uppercase tracking-wider rounded-xl hover:bg-brand-amber active:scale-95 transition shadow-lg">Apply</button>
                                        </div>
                                        <p class="text-[9px] text-neutral-500 leading-relaxed text-center px-4"><i class="fa-solid fa-arrows-up-down-left-right text-brand-gold/70 mr-1"></i> Applied text can be dragged dynamically across the viewport.</p>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="flex flex-col gap-4 pt-2">
                    <div class="w-full flex flex-col sm:flex-row items-stretch sm:items-center justify-between gap-4 p-4 rounded-2xl bg-white/[0.02] border border-white/5">
                        <div class="flex items-center gap-3">
                            <div class="w-10 h-10 rounded-xl bg-brand-gold/10 border border-brand-gold/25 flex items-center justify-center text-brand-gold">
                                <i class="fa-solid fa-shield-halved text-sm"></i>
                            </div>
                            <div class="flex flex-col">
                                <span class="text-xs text-neutral-400 font-medium">Anti-Robot Verification</span>
                                <span class="text-[10px] text-neutral-500">Calculate the simple equation below</span>
                            </div>
                        </div>

                        <div class="flex items-center flex-wrap justify-center gap-2 mt-2 sm:mt-0 sm:flex-nowrap sm:justify-start">
                            <div class="flex items-center justify-center bg-brand-dark border border-brand-gold/30 rounded-xl px-3 sm:px-4 py-2 text-brand-gold font-mono text-sm font-bold tracking-wider shadow-inner">
                                <span id="mathNum1"><?php echo isset($num1) ? $num1 : '7'; ?></span> 
                                <span class="mx-1.5 text-neutral-500">+</span> 
                                <span id="mathNum2"><?php echo isset($num2) ? $num2 : '4'; ?></span> 
                                <span class="mx-1.5 text-neutral-500">=</span>
                            </div>
                            <input type="number" id="math_captcha_response" name="math_captcha_response" placeholder="?" required 
                                   class="bg-black/80 border border-white/15 rounded-xl px-3 py-2 text-base sm:text-sm text-white placeholder-neutral-600 focus:outline-none focus:border-brand-gold w-20 text-center transition">
                        </div>
                    </div>

                    <div class="flex items-center gap-3 w-full">
                        <button type="button" onclick="resetFormState()" title="Reset All" class="px-3 sm:px-5 py-4 min-h-[52px] border border-white/10 hover:border-white/30 bg-neutral-900/60 text-xs uppercase tracking-wide sm:tracking-widest text-neutral-400 hover:text-white rounded-xl transition duration-300 whitespace-nowrap">
                            <i class="fa-solid fa-arrow-rotate-left sm:hidden"></i><span class="hidden sm:inline">Reset All</span>
                        </button>
                        <button type="button" onclick="downloadCurrentEdit()" title="Download edited image" class="px-3 sm:px-5 py-4 min-h-[52px] border border-brand-gold/30 hover:border-brand-gold bg-brand-gold/10 hover:bg-brand-gold/20 text-xs uppercase tracking-wide sm:tracking-widest text-brand-gold rounded-xl transition duration-300 whitespace-nowrap flex items-center gap-2">
                            <i class="fa-solid fa-download"></i><span class="hidden sm:inline">Download</span>
                        </button>
                        <button type="submit" id="submitBtn" class="flex-[2] px-3 sm:px-6 py-4 min-h-[52px] bg-gradient-to-r from-brand-gold to-brand-amber text-neutral-950 font-bold text-xs uppercase tracking-wide sm:tracking-widest rounded-xl hover:shadow-[0_0_30px_rgba(245,158,11,0.4)] active:scale-[0.98] transition-all duration-300 whitespace-nowrap">
                            <i class="fa-solid fa-cloud-arrow-up mr-2"></i> Render & Deploy
                        </button>
                    </div>
                </div>
            </form>

            <div id="uploadLoader" class="hidden py-16 text-center space-y-8 animate-[fadeIn_0.5s_ease]">
                <div class="relative w-24 h-24 mx-auto">
                    <div class="absolute inset-0 rounded-full border-4 border-white/5 shadow-[inset_0_0_20px_rgba(255,255,255,0.05)]"></div>
                    <div class="absolute inset-0 rounded-full border-4 border-transparent border-t-brand-gold animate-spin"></div>
                    <div class="absolute inset-2 rounded-full border border-dashed border-brand-amber/40 animate-[spin_3s_linear_infinite_reverse]"></div>
                    <div class="absolute inset-0 flex items-center justify-center text-brand-gold">
                        <i class="fa-solid fa-microchip text-xl animate-pulse"></i>
                    </div>
                </div>
                <div class="space-y-3">
                    <div class="text-sm tracking-[0.3em] text-brand-gold uppercase font-bold text-center px-4" id="loaderText">Compiling Frame...</div>
                    <p class="text-neutral-500 text-xs max-w-sm mx-auto leading-relaxed text-center px-6">Baking edits, applying color grading matrices, and preparing high-definition payload.</p>
                </div>
                <div class="w-full max-w-md mx-auto h-1.5 bg-black rounded-full overflow-hidden relative border border-white/5">
                    <div id="uploadProgressBar" class="absolute left-0 top-0 bottom-0 bg-gradient-to-r from-brand-gold to-brand-amber w-0 transition-all duration-300 shadow-[0_0_10px_rgba(212,175,55,0.5)]"></div>
                </div>
            </div>

            <div id="resultDashboard" class="hidden space-y-8 pt-4 animate-[fadeIn_0.5s_ease]">
                <div class="flex items-center gap-4 p-5 bg-emerald-500/10 border border-emerald-500/30 text-emerald-400 rounded-2xl text-sm shadow-[0_0_30px_rgba(16,185,129,0.1)]">
                    <div class="w-10 h-10 rounded-full bg-emerald-500/20 flex items-center justify-center shrink-0">
                        <i class="fa-solid fa-check text-xl animate-pulse"></i>
                    </div>
                    <div class="px-2">
                        <span class="font-bold block text-white mb-0.5">Transmission Complete</span>
                        Archive successfully processed and saved in the Local Vault.
                    </div>
                </div>

                <div class="grid grid-cols-1 lg:grid-cols-2 gap-8">
                    <div class="space-y-5 px-1">
                        <h4 class="font-cinematic text-lg font-bold text-white flex items-center gap-2"><i class="fa-solid fa-link text-brand-gold text-sm"></i> Generated Links</h4>
                        <div class="space-y-4">
                            <div>
                                <label class="text-[11px] text-neutral-400 block mb-1.5 uppercase tracking-wider font-bold">Secure Shortlink</label>
                                <div class="flex items-center gap-1.5 p-1.5 rounded-xl bg-black border border-white/10 hover:border-brand-gold/50 transition">
                                    <input type="text" id="shortLinkVal" readonly class="bg-transparent border-none outline-none text-xs text-brand-gold px-4 py-2 flex-1 font-mono selection:bg-brand-gold selection:text-black text-center sm:text-left">
                                    <button onclick="copyToClipboard('shortLinkVal')" class="p-2.5 rounded-lg bg-white/5 text-neutral-400 hover:text-white hover:bg-brand-gold/20 transition group" title="Copy">
                                        <i class="fa-regular fa-copy text-sm group-hover:scale-110 transition"></i>
                                    </button>
                                </div>
                            </div>
                            <div>
                                <label class="text-[11px] text-neutral-400 block mb-1.5 uppercase tracking-wider font-bold">Direct Source File</label>
                                <div class="flex items-center gap-1.5 p-1.5 rounded-xl bg-black border border-white/10 hover:border-white/30 transition">
                                    <input type="text" id="originalLinkVal" readonly class="bg-transparent border-none outline-none text-xs text-neutral-300 px-4 py-2 flex-1 font-mono selection:bg-brand-gold selection:text-black text-center sm:text-left">
                                    <button onclick="copyToClipboard('originalLinkVal')" class="p-2.5 rounded-lg bg-white/5 text-neutral-400 hover:text-white hover:bg-white/10 transition group" title="Copy">
                                        <i class="fa-regular fa-copy text-sm group-hover:scale-110 transition"></i>
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>

                    <div class="space-y-5 px-1">
                        <h4 class="font-cinematic text-lg font-bold text-white flex items-center gap-2"><i class="fa-solid fa-layer-group text-brand-gold text-sm"></i> Vault Size Presets</h4>
                        
                        <div class="grid grid-cols-2 gap-3">
                            <button onclick="switchPreviewSize('thumbnail')" id="dimBtn-thumbnail" class="dim-btn p-3 bg-brand-gold/10 border border-brand-gold/40 rounded-xl text-left hover:bg-white/10 transition">
                                <span class="block text-white text-xs font-medium mb-0.5">Thumbnail</span>
                                <span class="text-[9px] text-brand-gold font-bold uppercase tracking-wider">Fast Load</span>
                            </button>
                            <button onclick="switchPreviewSize('medium')" id="dimBtn-medium" class="dim-btn p-3 bg-black/40 border border-white/10 rounded-xl text-left hover:bg-white/10 transition">
                                <span class="block text-white text-xs font-medium mb-0.5">Standard</span>
                                <span class="text-[9px] text-neutral-500 uppercase tracking-wider">Web Optimized</span>
                            </button>
                            <button onclick="switchPreviewSize('large')" id="dimBtn-large" class="dim-btn p-3 bg-black/40 border border-white/10 rounded-xl text-left hover:bg-white/10 transition">
                                <span class="block text-white text-xs font-medium mb-0.5">High Res</span>
                                <span class="text-[9px] text-neutral-500 uppercase tracking-wider">Fine Detail</span>
                            </button>
                            <button onclick="switchPreviewSize('original')" id="dimBtn-original" class="dim-btn p-3 bg-black/40 border border-white/10 rounded-xl text-left hover:bg-white/10 transition">
                                <span class="block text-white text-xs font-medium mb-0.5">Master File</span>
                                <span class="text-[9px] text-neutral-500 uppercase tracking-wider">Uncompressed</span>
                            </button>
                        </div>

                        <div class="relative w-full aspect-video rounded-xl overflow-hidden border border-white/10 bg-black flex items-center justify-center shadow-inner group">
                            <!-- Background grid for transparency view -->
                            <div class="absolute inset-0 opacity-10" style="background-image: radial-gradient(#fff 1px, transparent 1px); background-size: 10px 10px;"></div>
                            <img id="dimensionViewer" src="" class="max-w-full max-h-full object-contain relative z-10 transition-transform duration-500 group-hover:scale-105" alt="Selected size view">
                            <button onclick="downloadResultImage()" title="Download this size" class="absolute bottom-3 right-3 z-20 w-10 h-10 rounded-full bg-black/70 border border-brand-gold/40 text-brand-gold hover:bg-brand-gold hover:text-black flex items-center justify-center transition shadow-lg backdrop-blur-sm">
                                <i class="fa-solid fa-download text-sm"></i>
                            </button>
                        </div>
                    </div>
                </div>

                <div class="pt-6 border-t border-white/10 flex flex-col sm:flex-row justify-end gap-3 px-1">
                    <button onclick="downloadResultImage()" class="px-8 py-3.5 min-h-[48px] bg-brand-gold/10 border border-brand-gold/40 hover:bg-brand-gold hover:text-black text-xs uppercase tracking-widest text-brand-gold rounded-xl transition duration-300 shadow-lg flex items-center justify-center gap-2">
                        <i class="fa-solid fa-download"></i> Download Edited Image
                    </button>
                    <button onclick="resetFormState()" class="px-8 py-3.5 min-h-[48px] bg-white/5 border border-white/10 hover:border-brand-gold/50 text-xs uppercase tracking-widest text-brand-gold hover:bg-brand-gold/10 hover:text-white rounded-xl transition duration-300 shadow-lg w-full sm:w-auto">
                        Process Another Frame
                    </button>
                </div>
            </div>

        </div>

        <!-- Elegant Filmstrip of Recent Deployed Frames -->
        <div id="recentStripContainer" class="hidden w-full mt-10 space-y-4 animate-[fadeIn_0.5s_ease] px-2 sm:px-0">
            <div class="flex items-center justify-between border-b border-white/10 pb-3 px-4">
                <div class="flex items-center gap-3">
                    <span class="w-2.5 h-2.5 rounded-full bg-brand-gold shadow-[0_0_8px_rgba(212,175,55,0.8)] animate-pulse"></span>
                    <span class="font-cinematic text-sm tracking-[0.2em] text-white uppercase font-bold text-center sm:text-left">Local Archive Roll</span>
                </div>
                <button onclick="clearCachedGallery()" class="text-[10px] px-3 py-1.5 rounded-lg bg-red-500/10 border border-red-500/20 text-red-400 hover:text-white hover:bg-red-500 transition tracking-wider uppercase font-bold flex items-center gap-2">
                    <i class="fa-solid fa-fire text-xs"></i> Burn Cache
                </button>
            </div>
            
            <div class="relative py-5 glass-panel rounded-2xl overflow-hidden shadow-2xl">
                <div class="film-strip-border absolute top-1.5 left-0 right-0 h-4 opacity-40"></div>
                
                <div id="filmStripRow" class="flex items-center gap-4 overflow-x-auto px-6 py-4 scrollbar-thin scrollbar-thumb-brand-gold/30">
                    <!-- Film nodes render dynamically here -->
                </div>
                
                <div class="film-strip-border absolute bottom-1.5 left-0 right-0 h-4 opacity-40"></div>
            </div>
        </div>

    </main>

    <footer class="w-full max-w-7xl mx-auto px-4 md:px-6 py-6 border-t border-white/10 flex flex-col md:flex-row justify-between items-center gap-4 z-10 bg-neutral-950/80 backdrop-blur-md">
        <div class="flex flex-col items-center md:items-start gap-1.5 px-4 text-center sm:text-left">
            <span class="text-xs text-neutral-500">&copy; 2026 Tpictures. Advanced visual manipulation node.</span>
            <span class="text-xs text-brand-gold/80 font-medium">
                Developed by <span class="text-white hover:text-brand-amber transition duration-300 font-semibold tracking-wide cursor-pointer">Olojede Treasure</span>
            </span>
        </div>
        <div class="flex items-center gap-2 text-[11px] text-neutral-400 bg-black/50 px-4 py-2 rounded-full border border-white/5 text-center">
            <span class="inline-block w-2 h-2 rounded-full bg-emerald-500 animate-pulse"></span>
            <span>Secure Neural Uplink Established</span>
        </div>
    </footer>

    <!-- Interactive Fullscreen Negative inspector modal -->
    <div id="inspectorModal" class="fixed inset-0 bg-black/98 backdrop-blur-xl z-[150] flex items-center justify-center p-4 opacity-0 pointer-events-none transition-all duration-300">
        <div class="absolute inset-0 pointer-events-none film-strip-border opacity-20 h-12 top-4"></div>
        <div class="absolute inset-0 pointer-events-none film-strip-border opacity-20 h-12 bottom-4 top-auto"></div>
        
        <button onclick="closeInspector()" class="absolute top-6 right-6 w-12 h-12 rounded-xl border border-white/10 hover:border-brand-gold bg-black/50 text-neutral-400 hover:text-white flex items-center justify-center transition-all z-[200] hover:scale-105">
            <i class="fa-solid fa-xmark text-xl"></i>
        </button>
        <button onclick="downloadInspectorImage()" title="Download this image" class="absolute top-6 right-24 sm:right-24 w-12 h-12 rounded-xl border border-brand-gold/40 hover:border-brand-gold bg-brand-gold/10 hover:bg-brand-gold hover:text-black text-brand-gold flex items-center justify-center transition-all z-[200] hover:scale-105">
            <i class="fa-solid fa-download text-lg"></i>
        </button>
        
        <div class="relative w-full h-full flex flex-col items-center justify-center gap-6">
            <div class="relative max-w-[90vw] max-h-[80vh] flex items-center justify-center group">
                <!-- Decorative scanline over modal image -->
                <div class="absolute inset-0 bg-[linear-gradient(transparent_50%,rgba(0,0,0,0.2)_50%)] bg-[length:100%_4px] pointer-events-none opacity-20"></div>
                <img id="inspectorImage" class="max-w-[90vw] max-h-[80vh] rounded-lg object-contain shadow-[0_0_50px_rgba(212,175,55,0.15)] ring-1 ring-white/10" src="" alt="Inspected frame">
                <button onclick="downloadInspectorImage()" title="Download" class="sm:hidden absolute bottom-3 right-3 w-11 h-11 rounded-full bg-brand-gold text-black flex items-center justify-center shadow-lg">
                    <i class="fa-solid fa-download"></i>
                </button>
            </div>
            <div class="flex flex-col items-center gap-1 text-center px-4">
                <div id="inspectorLabel" class="text-[11px] font-mono tracking-[0.3em] text-brand-gold uppercase bg-brand-gold/10 px-6 py-2 rounded border border-brand-gold/20">FRAME_01.RAW</div>
                <div class="text-[9px] text-neutral-500 uppercase tracking-widest" id="inspectorDate">Just now</div>
            </div>
        </div>
    </div>

    <script>
        // DOM Elements
        const dropZone = document.getElementById('dropZone');
        const fileSelector = document.getElementById('fileSelector');
        const uploadForm = document.getElementById('uploadForm');
        const uploadPlaceholder = document.getElementById('uploadPlaceholder');
        const filePreviewState = document.getElementById('filePreviewState');
        const selectedFileName = document.getElementById('selectedFileName');
        const selectedFileSize = document.getElementById('selectedFileSize');

        const uploadLoader = document.getElementById('uploadLoader');
        const loaderText = document.getElementById('loaderText');
        const progressBar = document.getElementById('uploadProgressBar');
        const resultDashboard = document.getElementById('resultDashboard');

        // Studio Workspace Variables
        const canvas = document.getElementById('editorCanvas');
        const ctx = canvas.getContext('2d');
        const watermarkTextEl = document.getElementById('canvasTextWatermark');
        
        let rawSourceImg = new Image();
        let currentFileObj = null; 

        // Editing State
        let activePreset = 'raw';
        let customBrightness = 100;
        let customContrast = 100;
        let customSaturation = 100;
        let customVignette = 60;

        let rotDegrees = 0;
        let hMirror = 1;
        let vMirror = 1;

        let brushActive = false;
        let activeBrushColor = '#D4AF37';
        let activeBrushSize = 6;
        let userDrawingCoordinates = [];
        let drawingActionInProgress = false;

        let watermarkActive = false;
        let watermarkText = "Tpictures Studio";
        let textPosX = 50; 
        let textPosY = 50; 
        let isDraggingWatermark = false;

        // Crop State
        const cropOverlayEl = document.getElementById('cropOverlay');
        const cropFrameEl = canvas.parentNode; 
        let cropModeActive = false;
        let cropAspect = 'free'; 
        let cropBox = { x: 10, y: 10, w: 80, h: 80 }; 
        let cropDrag = null; 

        // Background Removal State
        let bgRemovalBackup = null; 
        let bgRemovalBackupTransform = null; 
        let hasTransparency = false;

        // Background Replacement State
        let customBgType = 'none'; 
        let customBgValue = null;
        let customBgImgObj = null;

        // Mock resulting links data
        let currentLinksData = {};

        // Audio Engine
        let audioCtx = null;
        function getAudioContext() {
            if (!audioCtx) {
                audioCtx = new (window.AudioContext || window.webkitAudioContext)();
            }
            if (audioCtx.state === 'suspended') audioCtx.resume();
            return audioCtx;
        }

        function playFocusBeep() {
            try {
                const ctx = getAudioContext();
                const now = ctx.currentTime;
                const osc = ctx.createOscillator();
                const gain = ctx.createGain();
                osc.type = 'sine';
                osc.frequency.setValueAtTime(1800, now);
                gain.gain.setValueAtTime(0.05, now);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.05);
                osc.connect(gain);
                gain.connect(ctx.destination);
                osc.start(now);
                osc.stop(now + 0.06);
            } catch (e) {}
        }

        function playCameraShutterSound() {
            try {
                const ctx = getAudioContext();
                const now = ctx.currentTime;
                
                const bufferSize = ctx.sampleRate * 0.1; 
                const buffer = ctx.createBuffer(1, bufferSize, ctx.sampleRate);
                const data = buffer.getChannelData(0);
                for (let i = 0; i < bufferSize; i++) data[i] = Math.random() * 2 - 1;
                
                const noise = ctx.createBufferSource();
                noise.buffer = buffer;

                const filter = ctx.createBiquadFilter();
                filter.type = 'bandpass';
                filter.frequency.setValueAtTime(1000, now);
                filter.frequency.exponentialRampToValueAtTime(3000, now + 0.08);

                const gain = ctx.createGain();
                gain.gain.setValueAtTime(0.001, now);
                gain.gain.exponentialRampToValueAtTime(0.3, now + 0.01);
                gain.gain.exponentialRampToValueAtTime(0.001, now + 0.09);

                noise.connect(filter);
                filter.connect(gain);
                gain.connect(ctx.destination);
                noise.start(now);
            } catch (e) {}
        }

        function showToast(title, message, isError = false) {
            const toast = document.getElementById('toastBox');
            document.getElementById('toastTitle').innerText = title;
            document.getElementById('toastMessage').innerText = message;
            
            const content = document.getElementById('toastContent');
            const icon = document.getElementById('toastIcon');

            if (isError) {
                content.className = "glass-panel p-4 rounded-2xl flex items-start gap-3 shadow-2xl border-l-4 border-l-red-500";
                icon.innerHTML = '<i class="fa-solid fa-triangle-exclamation text-red-500"></i>';
            } else {
                content.className = "glass-panel p-4 rounded-2xl flex items-start gap-3 shadow-2xl border-l-4 border-l-brand-gold";
                icon.innerHTML = '<i class="fa-solid fa-circle-check text-brand-gold animate-bounce"></i>';
            }

            toast.classList.remove('translate-y-[-150%]', 'opacity-0', 'pointer-events-none');
            toast.classList.add('translate-y-0', 'opacity-100');

            setTimeout(() => {
                toast.classList.add('translate-y-[-150%]', 'opacity-0', 'pointer-events-none');
                toast.classList.remove('translate-y-0', 'opacity-100');
            }, 4000);
        }

        function initAmbientBackground() {
            const bgCanvas = document.getElementById('ambientCanvas');
            const bgCtx = bgCanvas.getContext('2d');
            let particles = [];

            function resizeCanvas() {
                bgCanvas.width = window.innerWidth;
                bgCanvas.height = window.innerHeight;
            }
            window.addEventListener('resize', resizeCanvas);
            resizeCanvas();

            class Particle {
                constructor() {
                    this.reset();
                    this.y = Math.random() * bgCanvas.height; 
                }
                reset() {
                    this.x = Math.random() * bgCanvas.width;
                    this.y = bgCanvas.height + Math.random() * 200;
                    this.size = Math.random() * 2.5 + 0.5;
                    this.speedY = Math.random() * -0.5 - 0.1;
                    this.speedX = (Math.random() - 0.5) * 0.3;
                    this.opacity = Math.random() * 0.5 + 0.1;
                    this.color = Math.random() > 0.7 ? 'rgba(212, 175, 55,' : 'rgba(255, 255, 255,';
                }
                update() {
                    this.y += this.speedY;
                    this.x += this.speedX;
                    if (this.y < -10 || this.x < -10 || this.x > bgCanvas.width + 10) {
                        this.reset();
                    }
                }
                draw() {
                    bgCtx.beginPath();
                    bgCtx.arc(this.x, this.y, this.size, 0, Math.PI * 2);
                    bgCtx.fillStyle = `${this.color}${this.opacity})`;
                    bgCtx.fill();
                }
            }

            for(let i=0; i<40; i++) particles.push(new Particle());

            function animateBg() {
                bgCtx.clearRect(0, 0, bgCanvas.width, bgCanvas.height);
                particles.forEach(p => { p.update(); p.draw(); });
                requestAnimationFrame(animateBg);
            }
            animateBg();
        }
        initAmbientBackground();

        function switchEditorTab(tabName) {
            ['grading', 'transform', 'crop', 'markup'].forEach(t => {
                document.getElementById(`editorTab-${t}`).classList.add('hidden');
                document.getElementById(`tabBtn-${t}`).className = "flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-neutral-400 hover:text-white transition-colors";
            });

            document.getElementById(`editorTab-${tabName}`).classList.remove('hidden');
            document.getElementById(`tabBtn-${tabName}`).className = "flex-1 min-w-[70px] py-3 sm:pb-2.5 sm:py-0 text-xs font-semibold uppercase tracking-wider text-brand-gold border-b-2 border-brand-gold transition-colors";

            if (tabName !== 'crop' && cropModeActive) {
                toggleCropMode();
            }
            playFocusBeep();
        }

        function renderLiveStudioCanvas() {
            if (!rawSourceImg.src) return;

            const targetWidth = rawSourceImg.naturalWidth;
            const targetHeight = rawSourceImg.naturalHeight;

            if (rotDegrees === 90 || rotDegrees === 270) {
                canvas.width = targetHeight;
                canvas.height = targetWidth;
            } else {
                canvas.width = targetWidth;
                canvas.height = targetHeight;
            }

            ctx.clearRect(0, 0, canvas.width, canvas.height);

            if (hasTransparency && customBgType !== 'none') {
                if (customBgType === 'color') {
                    ctx.fillStyle = customBgValue;
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                } else if (customBgType === 'gradient') {
                    const grad = ctx.createLinearGradient(0, 0, canvas.width, canvas.height);
                    if (customBgValue === 'gold') {
                        grad.addColorStop(0, '#D4AF37');
                        grad.addColorStop(1, '#b45309');
                    } else if (customBgValue === 'cyber') {
                        grad.addColorStop(0, '#9333ea');
                        grad.addColorStop(1, '#3b82f6');
                    }
                    ctx.fillStyle = grad;
                    ctx.fillRect(0, 0, canvas.width, canvas.height);
                } else if (customBgType === 'image' && customBgImgObj) {
                    const imgRatio = customBgImgObj.width / customBgImgObj.height;
                    const canvasRatio = canvas.width / canvas.height;
                    let drawW, drawH, drawX, drawY;
                    if (imgRatio > canvasRatio) {
                        drawH = canvas.height;
                        drawW = canvas.height * imgRatio;
                        drawX = (canvas.width - drawW) / 2;
                        drawY = 0;
                    } else {
                        drawW = canvas.width;
                        drawH = canvas.width / imgRatio;
                        drawX = 0;
                        drawY = (canvas.height - drawH) / 2;
                    }
                    ctx.drawImage(customBgImgObj, drawX, drawY, drawW, drawH);
                }
            }

            ctx.save();
            ctx.translate(canvas.width / 2, canvas.height / 2);
            ctx.rotate((rotDegrees * Math.PI) / 180);
            ctx.scale(hMirror, vMirror);
            ctx.drawImage(rawSourceImg, -targetWidth / 2, -targetHeight / 2);
            ctx.restore();

            ctx.save();
            userDrawingCoordinates.forEach((pt) => {
                ctx.beginPath();
                ctx.strokeStyle = pt.color;
                
                const scaleFactor = Math.max(canvas.width, canvas.height) / 1000;
                ctx.lineWidth = pt.size * scaleFactor * 2; 
                ctx.lineCap = 'round';
                ctx.lineJoin = 'round';

                const scaledX = (pt.x / 100) * canvas.width;
                const scaledY = (pt.y / 100) * canvas.height;
                const scaledPrevX = (pt.prevX / 100) * canvas.width;
                const scaledPrevY = (pt.prevY / 100) * canvas.height;

                ctx.moveTo(scaledPrevX, scaledPrevY);
                ctx.lineTo(scaledX, scaledY);
                ctx.stroke();
            });
            ctx.restore();

            document.getElementById('vignetteOverlay').style.opacity = (customVignette / 100).toFixed(2);

            let filterStr = `brightness(${customBrightness}%) contrast(${customContrast}%) saturate(${customSaturation}%)`;
            if (activePreset === 'gold') filterStr += ' sepia(0.5) hue-rotate(-10deg)';
            else if (activePreset === 'noir') filterStr += ' grayscale(1) brightness(0.9) contrast(1.2)';
            else if (activePreset === 'cyber') filterStr += ' hue-rotate(130deg) saturate(1.5)';
            
            canvas.style.filter = filterStr;

            if (cropModeActive) paintCropOverlay();
        }

        function updateManualFilters() {
            customBrightness = document.getElementById('sliderBrightness').value;
            customContrast = document.getElementById('sliderContrast').value;
            customSaturation = document.getElementById('sliderSaturation').value;
            customVignette = document.getElementById('sliderVignette').value;

            document.getElementById('labelBrightness').innerText = `${customBrightness}%`;
            document.getElementById('labelContrast').innerText = `${customContrast}%`;
            document.getElementById('labelSaturation').innerText = `${customSaturation}%`;
            document.getElementById('labelVignette').innerText = `${customVignette}%`;

            renderLiveStudioCanvas();
        }

        function applyPresetFilter(filterType, btnEl) {
            activePreset = filterType;
            document.querySelectorAll('.filter-btn').forEach(b => {
                b.className = "filter-btn px-2.5 py-1.5 rounded bg-white/5 text-neutral-300 hover:bg-white/15 text-[9px] uppercase tracking-wider font-bold border border-white/10";
            });
            btnEl.className = "filter-btn px-2.5 py-1.5 rounded bg-brand-gold text-black text-[9px] uppercase tracking-wider font-bold border border-brand-gold shadow-[0_0_10px_rgba(212,175,55,0.3)]";

            playCameraShutterSound();
            const shutter = document.getElementById('shutterOverlay');
            shutter.style.opacity = '1';
            setTimeout(() => shutter.style.opacity = '0', 150);

            const sets = {
                'raw': {b:100, c:100, s:100, v:40, n:'Raw Frame'},
                'gold': {b:105, c:110, s:130, v:60, n:'Golden Hour'},
                'noir': {b:100, c:130, s:0, v:80, n:'Lagos Noir'},
                'cyber': {b:95, c:120, s:150, v:50, n:'Cyber Neon'}
            };

            const cfg = sets[filterType];
            document.getElementById('sliderBrightness').value = cfg.b;
            document.getElementById('sliderContrast').value = cfg.c;
            document.getElementById('sliderSaturation').value = cfg.s;
            document.getElementById('sliderVignette').value = cfg.v;
            document.getElementById('activeFilterName').innerText = cfg.n;

            updateManualFilters();
        }

        function transformRotate() { rotDegrees = (rotDegrees + 90) % 360; playFocusBeep(); renderLiveStudioCanvas(); }
        function transformFlip(d) { 
            if(d==='H') hMirror *= -1; 
            if(d==='V') vMirror *= -1; 
            playFocusBeep(); renderLiveStudioCanvas(); 
        }

        function clampNum(v, min, max) { return Math.max(min, Math.min(max, v)); }

        function getCanvasDisplayRect() {
            const canvasRect = canvas.getBoundingClientRect();
            const containerRect = cropFrameEl.getBoundingClientRect();
            return {
                left: canvasRect.left - containerRect.left,
                top: canvasRect.top - containerRect.top,
                width: canvasRect.width || 1,
                height: canvasRect.height || 1
            };
        }

        function computeCropBoxForAspect(aspect) {
            if (aspect === 'free') return { x: 8, y: 8, w: 84, h: 84 };
            const r = getCanvasDisplayRect();
            const [rw, rh] = aspect.split(':').map(Number);
            const ratio = rw / rh;
            const maxW = r.width * 0.88, maxH = r.height * 0.88;
            let boxWpx, boxHpx;
            if (maxW / maxH > ratio) { boxHpx = maxH; boxWpx = boxHpx * ratio; }
            else { boxWpx = maxW; boxHpx = boxWpx / ratio; }
            const xPx = (r.width - boxWpx) / 2, yPx = (r.height - boxHpx) / 2;
            return {
                x: (xPx / r.width) * 100, y: (yPx / r.height) * 100,
                w: (boxWpx / r.width) * 100, h: (boxHpx / r.height) * 100
            };
        }

        function paintCropOverlay() {
            if (!cropModeActive) return;
            const r = getCanvasDisplayRect();
            cropOverlayEl.style.left = (r.left + (cropBox.x / 100) * r.width) + 'px';
            cropOverlayEl.style.top = (r.top + (cropBox.y / 100) * r.height) + 'px';
            cropOverlayEl.style.width = ((cropBox.w / 100) * r.width) + 'px';
            cropOverlayEl.style.height = ((cropBox.h / 100) * r.height) + 'px';
        }

        function toggleCropMode() {
            if (!rawSourceImg.src) { showToast("No Image", "Select an image before cropping.", true); return; }
            cropModeActive = !cropModeActive;
            const btn = document.getElementById('cropToggleBtn');
            if (cropModeActive) {
                btn.className = "px-2.5 py-1.5 rounded border border-brand-gold bg-brand-gold/20 text-[9px] uppercase tracking-wider font-mono text-brand-gold transition shadow-[0_0_10px_rgba(212,175,55,0.2)] min-h-[32px]";
                btn.innerText = "Active: On";
                cropBox = computeCropBoxForAspect(cropAspect);
                cropOverlayEl.classList.remove('hidden');
                paintCropOverlay();
                showToast("Crop Mode", "Drag the gold handles to frame your crop.");
            } else {
                btn.className = "px-2.5 py-1.5 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-wider font-mono hover:border-brand-gold hover:text-white transition shadow-sm min-h-[32px]";
                btn.innerText = "Active: Off";
                cropOverlayEl.classList.add('hidden');
            }
            playFocusBeep();
        }

        function setCropAspect(aspect, btnEl) {
            cropAspect = aspect;
            document.querySelectorAll('.crop-ratio-btn').forEach(b => {
                b.className = "crop-ratio-btn p-2.5 min-h-[40px] bg-white/5 text-neutral-300 hover:bg-white/15 text-[10px] uppercase tracking-wider font-bold rounded-lg border border-white/10";
            });
            btnEl.className = "crop-ratio-btn p-2.5 min-h-[40px] bg-brand-gold text-black text-[10px] uppercase tracking-wider font-bold rounded-lg border border-brand-gold";
            if (cropModeActive) { cropBox = computeCropBoxForAspect(aspect); paintCropOverlay(); }
            playFocusBeep();
        }

        function resetCrop() {
            if (!cropModeActive) return;
            cropBox = computeCropBoxForAspect(cropAspect);
            paintCropOverlay();
            playFocusBeep();
        }

        function setCustomBg(type, value = null) {
            customBgType = type;
            customBgValue = value;
            renderLiveStudioCanvas();
            playFocusBeep();
        }

        function handleCustomBgUpload(input) {
            const file = input.files[0];
            if (!file) return;
            
            const validTypes = ['image/jpeg', 'image/png', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                showToast("Invalid Image", "Please upload a valid JPG, PNG, or WEBP.", true);
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                const img = new Image();
                img.onload = function() {
                    customBgImgObj = img;
                    setCustomBg('image');
                    input.value = '';
                }
                img.src = e.target.result;
            }
            reader.readAsDataURL(file);
        }

        function cropPointer(e) {
            return {
                cx: e.touches ? e.touches[0].clientX : e.clientX,
                cy: e.touches ? e.touches[0].clientY : e.clientY
            };
        }

        function cropDragStart(mode, e) {
            if (!cropModeActive) return;
            e.preventDefault();
            const p = cropPointer(e);
            cropDrag = { mode, startCX: p.cx, startCY: p.cy, startBox: { ...cropBox } };
        }

        function cropDragMove(e) {
            if (!cropDrag || !cropModeActive) return;
            e.preventDefault();
            const r = getCanvasDisplayRect();
            const p = cropPointer(e);
            const dxPct = ((p.cx - cropDrag.startCX) / r.width) * 100;
            const dyPct = ((p.cy - cropDrag.startCY) / r.height) * 100;
            const start = cropDrag.startBox;
            const aspectLocked = cropAspect !== 'free';
            let ratio = 1;
            if (aspectLocked) { const [rw, rh] = cropAspect.split(':').map(Number); ratio = rw / rh; }
            const toH = (wPct) => wPct * (r.width / r.height) / ratio;

            let box;
            if (cropDrag.mode === 'move') {
                box = {
                    x: clampNum(start.x + dxPct, 0, 100 - start.w),
                    y: clampNum(start.y + dyPct, 0, 100 - start.h),
                    w: start.w, h: start.h
                };
            } else {
                const x2 = start.x + start.w, y2 = start.y + start.h;
                let { x, y, w, h } = start;
                if (cropDrag.mode === 'se') {
                    w = clampNum(start.w + dxPct, 5, 100 - x);
                    h = aspectLocked ? toH(w) : clampNum(start.h + dyPct, 5, 100 - y);
                } else if (cropDrag.mode === 'nw') {
                    const newX = clampNum(start.x + dxPct, 0, x2 - 5);
                    w = x2 - newX; x = newX;
                    if (aspectLocked) { h = toH(w); y = y2 - h; } else { const newY = clampNum(start.y + dyPct, 0, y2 - 5); h = y2 - newY; y = newY; }
                } else if (cropDrag.mode === 'ne') {
                    w = clampNum(start.w + dxPct, 5, 100 - x);
                    if (aspectLocked) { h = toH(w); y = y2 - h; } else { const newY = clampNum(start.y + dyPct, 0, y2 - 5); h = y2 - newY; y = newY; }
                } else if (cropDrag.mode === 'sw') {
                    const newX = clampNum(start.x + dxPct, 0, x2 - 5);
                    w = x2 - newX; x = newX;
                    h = aspectLocked ? toH(w) : clampNum(start.h + dyPct, 5, 100 - y);
                }
                box = { x, y, w: clampNum(w, 5, 100), h: clampNum(h, 5, 100) };
            }
            cropBox = box;
            paintCropOverlay();
        }

        function cropDragEnd() { cropDrag = null; }

        cropOverlayEl.addEventListener('mousedown', (e) => cropDragStart('move', e));
        cropOverlayEl.addEventListener('touchstart', (e) => cropDragStart('move', e), { passive: false });
        document.querySelectorAll('.crop-handle').forEach(handle => {
            const mode = handle.dataset.handle;
            handle.addEventListener('mousedown', (e) => cropDragStart(mode, e));
            handle.addEventListener('touchstart', (e) => cropDragStart(mode, e), { passive: false });
        });
        window.addEventListener('mousemove', cropDragMove);
        window.addEventListener('touchmove', cropDragMove, { passive: false });
        window.addEventListener('mouseup', cropDragEnd);
        window.addEventListener('touchend', cropDragEnd);
        window.addEventListener('resize', () => { if (cropModeActive) paintCropOverlay(); });

        function applyCrop() {
            if (!rawSourceImg.src) { showToast("No Image", "Load an image first.", true); return; }
            const sx = Math.round((cropBox.x / 100) * canvas.width);
            const sy = Math.round((cropBox.y / 100) * canvas.height);
            const sw = Math.round((cropBox.w / 100) * canvas.width);
            const sh = Math.round((cropBox.h / 100) * canvas.height);
            if (sw < 4 || sh < 4) { showToast("Crop Too Small", "Widen the crop box before applying.", true); return; }

            const cropCanvas = document.createElement('canvas');
            cropCanvas.width = sw;
            cropCanvas.height = sh;
            const cCtx = cropCanvas.getContext('2d');
            cCtx.drawImage(canvas, sx, sy, sw, sh, 0, 0, sw, sh);

            rotDegrees = 0; hMirror = 1; vMirror = 1;
            userDrawingCoordinates = [];

            const wasCropOn = cropModeActive;
            rawSourceImg = new Image();
            rawSourceImg.onload = function() {
                renderLiveStudioCanvas();
                if (wasCropOn) toggleCropMode();
                showToast("Crop Applied", "Frame cropped successfully.");
                playCameraShutterSound();
            };
            rawSourceImg.src = cropCanvas.toDataURL(hasTransparency ? 'image/png' : 'image/jpeg', 0.98);
        }

        async function removeBackground() {
            if (!rawSourceImg.src) { showToast("No Image", "Load an image first.", true); return; }
            
            const btn = document.getElementById('bgRemoveBtn');
            const originalText = btn.innerHTML;
            
            btn.disabled = true;
            btn.innerHTML = '<i class="fa-solid fa-circle-notch fa-spin"></i> Processing AI...';
            showToast("Processing AI", "Transmitting frame to remove.bg neural core...");
            playFocusBeep();

            try {
                const finalCanvas = document.createElement('canvas');
                finalCanvas.width = canvas.width;
                finalCanvas.height = canvas.height;
                const fCtx = finalCanvas.getContext('2d');
                fCtx.filter = canvas.style.filter || 'none';
                fCtx.drawImage(canvas, 0, 0);

                const MAX_DIMENSION = 1920; 
                let exportCanvas = finalCanvas;
                if (finalCanvas.width > MAX_DIMENSION || finalCanvas.height > MAX_DIMENSION) {
                    exportCanvas = document.createElement('canvas');
                    const scale = Math.min(MAX_DIMENSION / finalCanvas.width, MAX_DIMENSION / finalCanvas.height);
                    exportCanvas.width = finalCanvas.width * scale;
                    exportCanvas.height = finalCanvas.height * scale;
                    const eCtx = exportCanvas.getContext('2d');
                    eCtx.drawImage(finalCanvas, 0, 0, exportCanvas.width, exportCanvas.height);
                }

                const base64Data = exportCanvas.toDataURL('image/jpeg', 0.85);

                const formData = new FormData();
                formData.append('action', 'remove_bg');
                formData.append('image_base64', base64Data);

                // Added an abort controller to prevent hanging fetch calls
                const controller = new AbortController();
                const timeoutId = setTimeout(() => controller.abort(), 45000);

                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData,
                    signal: controller.signal
                });

                clearTimeout(timeoutId);
                const data = await response.json();

                if (data.success) {
                    bgRemovalBackup = rawSourceImg.src;
                    bgRemovalBackupTransform = { rot: rotDegrees, h: hMirror, v: vMirror };
                    hasTransparency = true;
                    rotDegrees = 0; hMirror = 1; vMirror = 1;

                    rawSourceImg = new Image();
                    rawSourceImg.onload = function() {
                        renderLiveStudioCanvas();
                        document.getElementById('bgRemoveUndoBtn').classList.remove('hidden');
                        document.getElementById('bgReplacementUI').classList.remove('hidden');
                        showToast("Background Removed", `Subject isolated perfectly via AI. ${data.remaining} credits left today.`);
                        playCameraShutterSound();
                        btn.disabled = false;
                        btn.innerHTML = originalText;
                    };
                    rawSourceImg.src = data.image; 
                } else {
                    showToast("API Failed", data.error || "Could not process this image.", true);
                    btn.disabled = false;
                    btn.innerHTML = originalText;
                }
            } catch (err) {
                console.error(err);
                btn.disabled = false;
                btn.innerHTML = originalText;
                showToast("Network Error", "Communication with API backend failed or timed out.", true);
            }
        }

        function undoBackgroundRemoval() {
            if (!bgRemovalBackup) return;
            hasTransparency = false;
            const backup = bgRemovalBackup;
            bgRemovalBackup = null;
            if (bgRemovalBackupTransform) {
                rotDegrees = bgRemovalBackupTransform.rot;
                hMirror = bgRemovalBackupTransform.h;
                vMirror = bgRemovalBackupTransform.v;
                bgRemovalBackupTransform = null;
            }

            customBgType = 'none';
            customBgValue = null;
            customBgImgObj = null;
            document.getElementById('bgReplacementUI').classList.add('hidden');

            rawSourceImg = new Image();
            rawSourceImg.onload = function() {
                renderLiveStudioCanvas();
                document.getElementById('bgRemoveUndoBtn').classList.add('hidden');
                showToast("Restored", "Background removal undone.");
            };
            rawSourceImg.src = backup;
        }

        function sanitizeDownloadName(name) {
            const safe = (name || 'tpictures_edit').replace(/\.[a-z0-9]+$/i, '');
            const isActuallyTransparent = hasTransparency && customBgType === 'none';
            const ext = isActuallyTransparent ? 'png' : 'jpg';
            return `${safe.replace(/[^a-z0-9_\-]+/gi, '_')}_edited.${ext}`;
        }

        function downloadImageDataUrl(dataUrl, filename) {
            const a = document.createElement('a');
            a.href = dataUrl;
            a.download = filename || `tpictures_edit_${Date.now()}.jpg`;
            document.body.appendChild(a);
            a.click();
            a.remove();
            showToast("Download Started", "Your image is saving to this device.");
        }

        async function downloadCurrentEdit() {
            if (!currentFileObj || !rawSourceImg.src) {
                showToast("No Source Material", "Select and edit an image first.", true);
                return;
            }
            const exportData = await exportFinalImage();
            downloadImageDataUrl(exportData.dataUrl, sanitizeDownloadName(currentFileObj.name));
        }

        function downloadResultImage() {
            const activeBtn = document.querySelector('.dim-btn.bg-brand-gold\\/10');
            const sizeName = (activeBtn && activeBtn.id) ? activeBtn.id.replace('dimBtn-', '') : 'medium';
            const url = currentLinksData ? currentLinksData[sizeName] : null;
            if (!url) { showToast("Nothing To Download", "Process a frame first.", true); return; }
            const name = currentFileObj ? sanitizeDownloadName(currentFileObj.name) : `tpictures_${sizeName}_${Date.now()}.jpg`;
            downloadImageDataUrl(url, name);
        }

        function toggleBrushActive() {
            brushActive = !brushActive;
            const btn = document.getElementById('brushToggleBtn');
            if (brushActive) {
                btn.className = "px-2.5 py-1 rounded border border-brand-gold bg-brand-gold/20 text-[9px] uppercase tracking-wider font-mono text-brand-gold transition shadow-[0_0_10px_rgba(212,175,55,0.2)]";
                btn.innerText = "Active: On";
                showToast("Annotation Mode", "Draw directly on the image viewport.");
            } else {
                btn.className = "px-2.5 py-1 rounded border border-white/15 bg-white/5 text-[9px] uppercase tracking-wider font-mono hover:border-brand-gold hover:text-white transition shadow-sm";
                btn.innerText = "Active: Off";
            }
            playFocusBeep();
        }

        function setBrushColor(colorHex, btnEl) {
            activeBrushColor = colorHex;
            document.querySelectorAll('.brush-color-btn').forEach(b => {
                b.classList.remove('border-white', 'scale-110', 'border-transparent');
                b.classList.add('border-transparent');
                b.style.boxShadow = 'none';
            });
            btnEl.classList.remove('border-transparent');
            btnEl.classList.add('border-white', 'scale-110');
            btnEl.style.boxShadow = `0 0 10px ${colorHex}80`;
            playFocusBeep();
        }

        function updateBrushIndicator() {
            activeBrushSize = document.getElementById('sliderBrushSize').value;
            document.getElementById('brushSizeIndicator').innerText = `${activeBrushSize}px`;
        }

        function clearDrawings() {
            userDrawingCoordinates = [];
            renderLiveStudioCanvas();
            playFocusBeep();
        }

        function applyTextWatermark() {
            const inputVal = document.getElementById('watermarkTextVal').value.trim();
            if (!inputVal) {
                watermarkActive = false;
                watermarkTextEl.classList.add('hidden');
                return;
            }
            watermarkText = inputVal;
            watermarkActive = true;
            watermarkTextEl.innerText = watermarkText.toUpperCase();
            watermarkTextEl.classList.remove('hidden');
            showToast("Watermark Applied", "You can drag the text to position it.");
            playFocusBeep();
        }

        let lastLoggedX = 0, lastLoggedY = 0;
        function getRelCoords(e) {
            const rect = canvas.getBoundingClientRect();
            let cx = e.touches ? e.touches[0].clientX : e.clientX;
            let cy = e.touches ? e.touches[0].clientY : e.clientY;
            return { x: ((cx - rect.left) / rect.width) * 100, y: ((cy - rect.top) / rect.height) * 100 };
        }

        function handleDrawStart(e) {
            if (!brushActive) return;
            e.preventDefault();
            drawingActionInProgress = true;
            const pts = getRelCoords(e);
            lastLoggedX = pts.x; lastLoggedY = pts.y;
        }
        function handleDrawMove(e) {
            if (!brushActive || !drawingActionInProgress) return;
            e.preventDefault();
            const pts = getRelCoords(e);
            userDrawingCoordinates.push({
                x: pts.x, y: pts.y, prevX: lastLoggedX, prevY: lastLoggedY,
                color: activeBrushColor, size: activeBrushSize
            });
            lastLoggedX = pts.x; lastLoggedY = pts.y;
            renderLiveStudioCanvas();
        }
        function handleDrawEnd() { drawingActionInProgress = false; }

        canvas.addEventListener('mousedown', handleDrawStart);
        canvas.addEventListener('mousemove', handleDrawMove);
        window.addEventListener('mouseup', handleDrawEnd);
        canvas.addEventListener('touchstart', handleDrawStart, { passive: false });
        canvas.addEventListener('touchmove', handleDrawMove, { passive: false });
        window.addEventListener('touchend', handleDrawEnd);

        function wmDragStart(e) { isDraggingWatermark = true; e.preventDefault(); }
        function wmDragMove(e) {
            if (!isDraggingWatermark) return;
            e.preventDefault();
            const rect = canvas.parentNode.getBoundingClientRect();
            let cx = e.touches ? e.touches[0].clientX : e.clientX;
            let cy = e.touches ? e.touches[0].clientY : e.clientY;
            textPosX = Math.max(5, Math.min(95, ((cx - rect.left) / rect.width) * 100));
            textPosY = Math.max(5, Math.min(95, ((cy - rect.top) / rect.height) * 100));
            watermarkTextEl.style.left = `${textPosX}%`;
            watermarkTextEl.style.top = `${textPosY}%`;
        }
        function wmDragEnd() { isDraggingWatermark = false; }

        watermarkTextEl.addEventListener('mousedown', wmDragStart);
        canvas.parentNode.addEventListener('mousemove', wmDragMove);
        window.addEventListener('mouseup', wmDragEnd);
        watermarkTextEl.addEventListener('touchstart', wmDragStart, { passive: false });
        canvas.parentNode.addEventListener('touchmove', wmDragMove, { passive: false });

        function exportFinalImage() {
            return new Promise((resolve) => {
                const finalCanvas = document.createElement('canvas');
                finalCanvas.width = canvas.width;
                finalCanvas.height = canvas.height;
                const fCtx = finalCanvas.getContext('2d');

                fCtx.filter = canvas.style.filter || 'none';
                fCtx.drawImage(canvas, 0, 0);
                fCtx.filter = 'none'; 

                if (watermarkActive) {
                    fCtx.save();
                    fCtx.shadowColor = 'rgba(0, 0, 0, 0.85)';
                    fCtx.shadowBlur = 15;
                    fCtx.fillStyle = '#FFFFFF';
                    const fontSize = Math.max(20, Math.floor(finalCanvas.width * 0.05));
                    fCtx.font = `800 ${fontSize}px Syne, sans-serif`;
                    fCtx.textAlign = 'center';
                    fCtx.textBaseline = 'middle';
                    const pxX = (textPosX / 100) * finalCanvas.width;
                    const pxY = (textPosY / 100) * finalCanvas.height;
                    fCtx.fillText(watermarkText.toUpperCase(), pxX, pxY);
                    fCtx.restore();
                }

                const isActuallyTransparent = hasTransparency && customBgType === 'none';
                if (customVignette > 0 && !isActuallyTransparent) {
                    const gradient = fCtx.createRadialGradient(
                        finalCanvas.width/2, finalCanvas.height/2, Math.min(finalCanvas.width, finalCanvas.height) * 0.4,
                        finalCanvas.width/2, finalCanvas.height/2, Math.max(finalCanvas.width, finalCanvas.height) * 0.8
                    );
                    const alpha = (customVignette / 100) * 0.8;
                    gradient.addColorStop(0, 'rgba(0,0,0,0)');
                    gradient.addColorStop(1, `rgba(0,0,0,${alpha})`);
                    fCtx.fillStyle = gradient;
                    fCtx.fillRect(0, 0, finalCanvas.width, finalCanvas.height);
                }

                const mime = isActuallyTransparent ? 'image/png' : 'image/jpeg';
                finalCanvas.toBlob((blob) => {
                    resolve({
                        blob: blob,
                        dataUrl: isActuallyTransparent ? finalCanvas.toDataURL('image/png') : finalCanvas.toDataURL('image/jpeg', 0.9) 
                    });
                }, mime, isActuallyTransparent ? undefined : 0.95);
            });
        }

        dropZone.addEventListener('click', (e) => {
            if(e.target.id === 'dropZone' || e.target.id === 'uploadPlaceholder' || e.target.closest('#uploadPlaceholder')) {
                fileSelector.click();
            }
        });
        
        dropZone.addEventListener('dragover', (e) => {
            e.preventDefault();
            dropZone.classList.add('border-brand-gold/80', 'bg-brand-gold/10');
        });
        dropZone.addEventListener('dragleave', () => {
            dropZone.classList.remove('border-brand-gold/80', 'bg-brand-gold/10');
        });
        dropZone.addEventListener('drop', (e) => {
            e.preventDefault();
            dropZone.classList.remove('border-brand-gold/80', 'bg-brand-gold/10');
            if (e.dataTransfer.files.length) {
                fileSelector.files = e.dataTransfer.files;
                handleFileSelection();
            }
        });
        fileSelector.addEventListener('change', handleFileSelection);

        function handleFileSelection() {
            const file = fileSelector.files[0];
            if (!file) return;
            currentFileObj = file;
            
            const validTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/webp'];
            if (!validTypes.includes(file.type)) {
                showToast("Invalid File", "Only JPG, PNG, GIF, and WEBP formats are authorized.", true);
                return;
            }

            const reader = new FileReader();
            reader.onload = function(e) {
                rawSourceImg.src = e.target.result;
                rawSourceImg.onload = function() {
                    rotDegrees = 0; hMirror = 1; vMirror = 1;
                    userDrawingCoordinates = [];
                    watermarkActive = false;
                    watermarkTextEl.classList.add('hidden');
                    hasTransparency = false;
                    bgRemovalBackup = null;
                    bgRemovalBackupTransform = null;
                    customBgType = 'none';
                    customBgValue = null;
                    customBgImgObj = null;
                    
                    document.getElementById('bgRemoveUndoBtn').classList.add('hidden');
                    document.getElementById('bgReplacementUI').classList.add('hidden');
                    
                    if (cropModeActive) toggleCropMode();
                    cropAspect = 'free';
                    applyPresetFilter('raw', document.querySelector('.filter-btn'));
                    
                    selectedFileName.innerText = file.name;
                    selectedFileSize.innerText = (file.size / (1024 * 1024)).toFixed(2) + ' MB';
                    
                    uploadPlaceholder.classList.add('hidden');
                    filePreviewState.classList.remove('hidden');
                    renderLiveStudioCanvas();
                    playCameraShutterSound();
                }
            }
            reader.readAsDataURL(file);
        }

        function resetFileSelection() {
            fileSelector.value = '';
            currentFileObj = null;
            hasTransparency = false;
            bgRemovalBackup = null;
            bgRemovalBackupTransform = null;
            if (cropModeActive) toggleCropMode();
            uploadPlaceholder.classList.remove('hidden');
            filePreviewState.classList.add('hidden');
            playFocusBeep();
        }

        function resetFormState() {
            uploadForm.classList.remove('hidden');
            resultDashboard.classList.add('hidden');
            uploadLoader.classList.add('hidden');
            resetFileSelection();
            
            document.getElementById('math_captcha_response').value = '';
            document.getElementById('uploadProgressBar').style.width = '0%';
        }

        uploadForm.addEventListener('submit', async (e) => {
            e.preventDefault();
            
            if (!currentFileObj) {
                showToast("No Source Material", "Please drop an image onto the sensor plate.", true);
                return;
            }

            const n1 = parseInt(document.getElementById('mathNum1').innerText);
            const n2 = parseInt(document.getElementById('mathNum2').innerText);
            const userAns = parseInt(document.getElementById('math_captcha_response').value);
            if (userAns !== (n1 + n2)) {
                showToast("Security Violation", "Incorrect captcha equation answer.", true);
                return;
            }

            uploadForm.classList.add('hidden');
            uploadLoader.classList.remove('hidden');
            playFocusBeep();
            
            loaderText.innerText = "Compiling Raster Data...";
            const exportData = await exportFinalImage();

            let progress = 0;
            const progressInt = setInterval(() => {
                progress += Math.random() * 15;
                if(progress > 90) progress = 90;
                progressBar.style.width = `${progress}%`;
                
                if (progress > 30) loaderText.innerText = "Encrypting Payload...";
                if (progress > 60) loaderText.innerText = "Transmitting to Vault...";
            }, 300);

            const formData = new FormData();
            formData.append('action', 'upload_image');
            formData.append('image_base64', exportData.dataUrl);
            formData.append('website_url_honeypot', document.getElementById('website_url_honeypot').value);
            
            try {
                const response = await fetch(window.location.href, {
                    method: 'POST',
                    body: formData
                });
                
                const data = await response.json();
                clearInterval(progressInt);
                progressBar.style.width = '100%';
                loaderText.innerText = "Verifying Handshake...";
                
                setTimeout(() => {
                    if (data.success) {
                        handleUploadSuccess(exportData.dataUrl, currentFileObj.name, data);
                    } else {
                        showToast("Transmission Failed", data.error || "A fatal error occurred.", true);
                        resetFormState();
                    }
                }, 600);
                
            } catch(err) {
                clearInterval(progressInt);
                showToast("Network Error", "Unable to establish connection to the remote vault.", true);
                resetFormState();
            }
        });

        function handleUploadSuccess(compiledDataUrl, originalName, serverData) {
            uploadLoader.classList.add('hidden');
            resultDashboard.classList.remove('hidden');
            
            document.getElementById('shortLinkVal').value = serverData?.shortlink || `${window.location.origin}/v/${Math.random().toString(36).substring(2, 8).toUpperCase()}`;
            document.getElementById('originalLinkVal').value = serverData?.dimensions?.original || `${window.location.origin}/archive/raw_${Date.now()}.${hasTransparency ? 'png' : 'jpg'}`;

            currentLinksData = {
                thumbnail: serverData?.dimensions?.thumbnail || compiledDataUrl,
                medium: serverData?.dimensions?.medium || compiledDataUrl,
                large: serverData?.dimensions?.large || compiledDataUrl,
                original: serverData?.dimensions?.original || compiledDataUrl 
            };
            
            switchPreviewSize('medium');
            saveToLocalGallery(compiledDataUrl, originalName);
            
            try {
                const ctx = getAudioContext();
                const now = ctx.currentTime;
                [523.25, 659.25, 783.99, 1046.50].forEach((freq, idx) => {
                    const osc = ctx.createOscillator();
                    const gain = ctx.createGain();
                    osc.frequency.value = freq;
                    gain.gain.setValueAtTime(0.001, now + (idx*0.08));
                    gain.gain.exponentialRampToValueAtTime(0.1, now + (idx*0.08) + 0.02);
                    gain.gain.exponentialRampToValueAtTime(0.001, now + (idx*0.08) + 0.5);
                    osc.connect(gain); gain.connect(ctx.destination);
                    osc.start(now + (idx*0.08)); osc.stop(now + (idx*0.08) + 0.6);
                });
            } catch(e) {}
            
            showToast("Success", "File processed and secured locally.");
        }

        function switchPreviewSize(sizeName) {
            document.querySelectorAll('.dim-btn').forEach(btn => {
                btn.classList.remove('bg-brand-gold/10', 'border-brand-gold/40');
                btn.classList.add('bg-black/40', 'border-white/10');
                btn.querySelector('span:nth-child(2)').classList.remove('text-brand-gold');
                btn.querySelector('span:nth-child(2)').classList.add('text-neutral-500');
            });

            const activeBtn = document.getElementById(`dimBtn-${sizeName}`);
            activeBtn.classList.remove('bg-black/40', 'border-white/10');
            activeBtn.classList.add('bg-brand-gold/10', 'border-brand-gold/40');
            activeBtn.querySelector('span:nth-child(2)').classList.remove('text-neutral-500');
            activeBtn.querySelector('span:nth-child(2)').classList.add('text-brand-gold');

            const viewer = document.getElementById('dimensionViewer');
            viewer.style.opacity = '0';
            setTimeout(() => {
                viewer.src = currentLinksData[sizeName];
                viewer.style.opacity = '1';
            }, 150);
            
            playFocusBeep();
        }

        function copyToClipboard(elementId) {
            const copyText = document.getElementById(elementId);
            copyText.select();
            copyText.setSelectionRange(0, 99999); 
            try {
                document.execCommand("copy");
                showToast("Copied", "Link copied to clipboard successfully.");
            } catch(e) {
                showToast("Error", "Clipboard access denied.", true);
            }
        }

        function saveToLocalGallery(dataUrl, name) {
            try {
                let gallery = JSON.parse(localStorage.getItem('tpictures_gallery') || '[]');
                if (!Array.isArray(gallery)) gallery = [];
                gallery.unshift({
                    id: Date.now(),
                    url: dataUrl,
                    name: name,
                    date: new Date().toLocaleTimeString()
                });
                if(gallery.length > 8) gallery.pop(); 
                localStorage.setItem('tpictures_gallery', JSON.stringify(gallery));
                renderFilmstrip();
            } catch (error) {
                console.error("Local storage error:", error);
            }
        }

        function clearCachedGallery() {
            localStorage.removeItem('tpictures_gallery');
            renderFilmstrip();
            showToast("Cache Cleared", "Local filmstrip has been incinerated.");
            playFocusBeep();
        }

        function renderFilmstrip() {
            const container = document.getElementById('recentStripContainer');
            const row = document.getElementById('filmStripRow');
            
            let gallery = [];
            try {
                gallery = JSON.parse(localStorage.getItem('tpictures_gallery') || '[]');
            } catch (e) {
                gallery = [];
            }
            
            if (!Array.isArray(gallery) || gallery.length === 0) {
                container.classList.add('hidden');
                return;
            }
            
            container.classList.remove('hidden');
            row.innerHTML = '';
            
            gallery.forEach(item => {
                const node = document.createElement('div');
                node.className = 'shrink-0 relative group cursor-pointer border-2 border-white/10 hover:border-brand-gold rounded-lg overflow-hidden w-24 h-24 sm:w-28 sm:h-28 transition-all hover:-translate-y-1 shadow-lg bg-black flex items-center justify-center';
                node.onclick = () => openInspector(item);
                
                node.innerHTML = `
                    <img src="${item.url}" class="w-full h-full object-cover opacity-80 group-hover:opacity-100 transition-opacity" alt="Archive">
                    <div class="absolute inset-0 bg-gradient-to-t from-black/80 via-transparent to-transparent opacity-0 group-hover:opacity-100 transition-opacity flex flex-col justify-end p-2">
                        <span class="text-[8px] text-brand-gold uppercase tracking-widest font-mono truncate">${item.name}</span>
                    </div>
                    <button title="Download" class="film-download-btn absolute top-1.5 right-1.5 z-10 w-7 h-7 rounded-full bg-black/70 border border-brand-gold/50 text-brand-gold hover:bg-brand-gold hover:text-black flex items-center justify-center transition shadow-lg backdrop-blur-sm">
                        <i class="fa-solid fa-download text-[10px]"></i>
                    </button>
                `;
                node.querySelector('.film-download-btn').addEventListener('click', (e) => {
                    e.stopPropagation();
                    downloadImageDataUrl(item.url, item.name);
                });
                row.appendChild(node);
            });
        }

        let currentInspectorItem = null;
        function openInspector(item) {
            const modal = document.getElementById('inspectorModal');
            currentInspectorItem = item;
            document.getElementById('inspectorImage').src = item.url;
            document.getElementById('inspectorLabel').innerText = item.name.toUpperCase();
            document.getElementById('inspectorDate').innerText = "DISPATCHED: " + item.date;
            
            modal.classList.remove('opacity-0', 'pointer-events-none');
            playCameraShutterSound();
        }

        function downloadInspectorImage() {
            if (!currentInspectorItem) return;
            downloadImageDataUrl(currentInspectorItem.url, currentInspectorItem.name);
        }

        function closeInspector() {
            document.getElementById('inspectorModal').classList.add('opacity-0', 'pointer-events-none');
            playFocusBeep();
        }

        window.addEventListener('DOMContentLoaded', () => {
            renderFilmstrip();
            ensureCaptchaNumbersVisible();
        });

        function ensureCaptchaNumbersVisible() {
            const n1 = document.getElementById('mathNum1');
            const n2 = document.getElementById('mathNum2');
            if (!n1.innerText || !/^\d+$/.test(n1.innerText.trim())) {
                document.getElementById('envWarning').classList.remove('hidden');
                n1.innerText = Math.floor(Math.random() * 7) + 3;
                n2.innerText = Math.floor(Math.random() * 6) + 2;
            }
        }

    </script>
</body>
</html>