'use client';

import React, { useRef, useState, useEffect } from 'react';
import { Camera, Upload, CheckCircle2, AlertCircle, X, Search, ExternalLink, ArrowRight, Loader2, Wand2, Plus, Sparkles, Droplets, ChevronRight, User, Clock } from 'lucide-react';

import { createClient } from '@/lib/supabase/client';
import { useRouter, useSearchParams } from 'next/navigation';
import { saveBottle } from '@/services/save-bottle';
import { BottleMetadata } from '@/types/whisky';
import { db } from '@/lib/db';
import { findMatchingBottle } from '@/services/find-matching-bottle';
import { validateSession } from '@/services/validate-session';
import { discoverWhiskybaseId } from '@/services/discover-whiskybase';
import { updateBottle } from '@/services/update-bottle';
import Link from 'next/link';
import { useI18n } from '@/i18n/I18nContext';
import { useSession } from '@/context/SessionContext';
import { shortenCategory } from '@/lib/format';
import { scanLabel } from '@/app/actions/scanner';
import { enrichData } from '@/app/actions/enrich-data';
import { processImageForAI } from '@/utils/image-processing';
import { runCascadeOCR } from '@/services/cascade-ocr';
import { FEATURES } from '@/config/features';

interface CameraCaptureProps {
    onImageCaptured?: (base64Image: string) => void;
    onAnalysisComplete?: (data: BottleMetadata) => void;
    onSaveComplete?: () => void;
}

export default function CameraCapture({ onImageCaptured, onAnalysisComplete, onSaveComplete }: CameraCaptureProps) {
    const { t, locale } = useI18n();
    const supabase = createClient();
    const router = useRouter();
    const searchParams = useSearchParams();
    const { activeSession } = useSession();

    const sessionIdFromUrl = searchParams.get('session_id');
    const effectiveSessionId = activeSession?.id || sessionIdFromUrl;

    const [validatedSessionId, setValidatedSessionId] = useState<string | null>(null);

    useEffect(() => {
        const checkSession = async () => {
            if (effectiveSessionId) {
                const isValid = await validateSession(effectiveSessionId);
                setValidatedSessionId(isValid ? effectiveSessionId : null);
            } else {
                setValidatedSessionId(null);
            }
        };
        checkSession();
    }, [effectiveSessionId]);

    const fileInputRef = useRef<HTMLInputElement>(null);
    const galleryInputRef = useRef<HTMLInputElement>(null);
    const [isProcessing, setIsProcessing] = useState(false);
    const [isSaving, setIsSaving] = useState(false);
    const [previewUrl, setPreviewUrl] = useState<string | null>(null);
    const [error, setError] = useState<string | null>(null);
    const [analysisResult, setAnalysisResult] = useState<BottleMetadata | null>(null);
    const [isQueued, setIsQueued] = useState(false);
    const [matchingBottle, setMatchingBottle] = useState<{ id: string; name: string } | null>(null);
    const [lastSavedId, setLastSavedId] = useState<string | null>(null);
    const [wbDiscovery, setWbDiscovery] = useState<{ id: string; url: string; title: string } | null>(null);
    const [isDiscovering, setIsDiscovering] = useState(false);
    const [originalFile, setOriginalFile] = useState<File | null>(null);
    const [isAdmin, setIsAdmin] = useState(false);
    const [aiProvider, setAiProvider] = useState<'gemini' | 'openrouter'>('gemini');

    const [perfMetrics, setPerfMetrics] = useState<{
        compression: number;
        ai: number;
        aiApi: number;
        aiParse: number;
        uploadSize: number;
        prep: number;
        // Detailed metrics
        imagePrep?: number;
        cacheCheck?: number;
        encoding?: number;
        modelInit?: number;
        validation?: number;
        dbOps?: number;
        total?: number;
        cacheHit?: boolean;
    } | null>(null);

    useEffect(() => {
        const checkAdmin = async () => {
            try {
                const { data: { user } } = await supabase.auth.getUser();
                if (user) {
                    const { data, error } = await supabase
                        .from('admin_users')
                        .select('role')
                        .eq('user_id', user.id)
                        .maybeSingle();

                    if (error) console.error('[CameraCapture] Admin check error:', error);
                    setIsAdmin(!!data);
                }
            } catch (err) {
                console.error('[CameraCapture] checkAdmin failed:', err);
            }
        };
        checkAdmin();
    }, [supabase]);

    const handleCapture = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;

        setIsProcessing(true);
        setError(null);
        setAnalysisResult(null);
        setIsQueued(false);
        setMatchingBottle(null);
        setPerfMetrics(null);

        try {
            let fileToProcess = file;
            const isHeic = file.type === 'image/heic' || file.type === 'image/heif' || file.name.toLowerCase().endsWith('.heic') || file.name.toLowerCase().endsWith('.heif');

            if (isHeic) {
                const heic2any = (await import('heic2any')).default;
                const convertedBlob = await heic2any({ blob: file, toType: 'image/jpeg', quality: 0.8 });
                const blob = Array.isArray(convertedBlob) ? convertedBlob[0] : convertedBlob;
                fileToProcess = new File([blob], file.name.replace(/\.(heic|heif)$/i, '.jpg'), { type: 'image/jpeg' });
            }

            setOriginalFile(fileToProcess);
            const startComp = performance.now();
            const processed = await processImageForAI(fileToProcess);
            const endComp = performance.now();

            setPreviewUrl(processed.base64);
            if (onImageCaptured) onImageCaptured(processed.base64);

            if (!navigator.onLine) {
                // Check for existing pending scan with same image to prevent duplicates
                const existingScan = await db.pending_scans
                    .filter(s => s.imageBase64 === processed.base64)
                    .first();

                if (existingScan) {
                    console.log('[CameraCapture] Existing pending scan found, skipping dual add');
                } else {
                    await db.pending_scans.add({
                        temp_id: crypto.randomUUID(),
                        imageBase64: processed.base64,
                        timestamp: Date.now(),
                        provider: aiProvider,
                        locale: locale
                    });
                }
                setIsQueued(true);
                return;
            }

            const formData = new FormData();
            formData.append('file', processed.file);

            // Run Cascade OCR in parallel (for comparison/logging only - doesn't block AI)
            if (FEATURES.ENABLE_CASCADE_OCR) {
                runCascadeOCR(processed.file).catch(err => {
                    console.warn('[CameraCapture] Cascade OCR failed:', err);
                });
            }

            const startAi = performance.now();
            const response = await scanLabel(formData);
            const endAi = performance.now();

            const startPrep = performance.now();
            if (response.success && response.data) {
                setAnalysisResult(response.data);
                const match = await findMatchingBottle(response.data);
                if (match) setMatchingBottle(match);
                if (onAnalysisComplete) onAnalysisComplete(response.data);

                const endPrep = performance.now();
                if (isAdmin && response.perf) {
                    setPerfMetrics({
                        compression: endComp - startComp,
                        ai: endAi - startAi,
                        aiApi: response.perf.apiCall || response.perf.apiDuration || 0,
                        aiParse: response.perf.parsing || response.perf.parseDuration || 0,
                        uploadSize: response.perf.uploadSize || 0,
                        prep: endPrep - startPrep,
                        imagePrep: response.perf.imagePrep,
                        cacheCheck: response.perf.cacheCheck,
                        encoding: response.perf.encoding,
                        modelInit: response.perf.modelInit,
                        validation: response.perf.validation,
                        dbOps: response.perf.dbOps,
                        total: response.perf.total,
                        cacheHit: response.perf.cacheHit
                    });
                }

                if (response.data.is_whisky && response.data.name && response.data.distillery) {
                    enrichData(response.data.name, response.data.distillery, undefined, locale)
                        .then(enrichResult => {
                            if (enrichResult.success && enrichResult.data) {
                                setAnalysisResult(prev => {
                                    if (!prev) return prev;
                                    return {
                                        ...prev,
                                        suggested_tags: enrichResult.data.suggested_tags,
                                        suggested_custom_tags: enrichResult.data.suggested_custom_tags,
                                        search_string: enrichResult.data.search_string
                                    };
                                });
                            }
                        })
                        .catch(err => console.error('[CameraCapture] Enrichment failed:', err));
                }
            } else {
                throw new Error(t('camera.analysisError'));
            }
        } catch (err: any) {
            console.error('Processing failed:', err);
            setError(err.message || t('camera.processingError'));
        } finally {
            setIsProcessing(false);
        }
    };

    const handleQuickSave = async () => {
        if (!analysisResult || !previewUrl) return;
        setIsSaving(true);
        setError(null);
        try {
            const { data: { user } = {} } = await supabase.auth.getUser();
            if (!user) throw new Error(t('camera.authRequired'));
            const response = await saveBottle(analysisResult, previewUrl, user.id);
            if (response.success && response.data) {
                const url = `/bottles/${response.data.id}${validatedSessionId ? `?session_id=${validatedSessionId}` : ''}`;
                router.push(url);
            } else {
                setError(response.error || t('common.error'));
            }
        } catch (err: any) {
            setError(err.message || t('common.error'));
        } finally {
            setIsSaving(false);
        }
    };

    const handleSave = async () => {
        if (!analysisResult || !previewUrl) return;
        setIsSaving(true);
        setError(null);
        try {
            const { data: { user } = {} } = await supabase.auth.getUser();
            if (!user) throw new Error(t('camera.authRequired'));
            const response = await saveBottle(analysisResult, previewUrl, user.id);
            if (response.success && response.data) {
                setLastSavedId(response.data.id);
                if (onSaveComplete) onSaveComplete();
            } else {
                setError(response.error || t('common.error'));
            }
        } catch (err: any) {
            setError(err.message || t('common.error'));
        } finally {
            setIsSaving(false);
        }
    };

    const handleDiscoverWb = async () => {
        if (!lastSavedId || !analysisResult) return;
        setIsDiscovering(true);
        const result = await discoverWhiskybaseId({
            name: analysisResult.name || '',
            distillery: analysisResult.distillery || undefined,
            abv: analysisResult.abv || undefined,
            age: analysisResult.age || undefined
        });
        if (result.success && result.id) {
            setWbDiscovery({ id: result.id, url: result.url!, title: result.title! });
        }
        setIsDiscovering(false);
    };

    const handleLinkWb = async () => {
        if (!lastSavedId || !wbDiscovery) return;
        const res = await updateBottle(lastSavedId, { whiskybase_id: wbDiscovery.id });
        if (res.success) setWbDiscovery(null);
    };

    const triggerUpload = () => fileInputRef.current?.click();
    const triggerGallery = () => galleryInputRef.current?.click();

    return (
        <div className="flex flex-col items-center gap-4 md:gap-6 w-full max-w-md mx-auto p-4 md:p-6 bg-zinc-900 rounded-3xl shadow-2xl border border-zinc-800 transition-all hover:shadow-orange-950/20">
            <div className="flex flex-col w-full gap-1">
                <div className="flex items-center justify-between w-full">
                    <h2 className="text-xl md:text-2xl font-bold text-zinc-100 italic">{t('camera.magicShot')}</h2>
                    {isAdmin && (
                        <div className="flex items-center gap-1 bg-zinc-800 p-1 rounded-xl border border-zinc-700">
                            <button
                                onClick={() => setAiProvider('gemini')}
                                className={`px-3 py-1 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${aiProvider === 'gemini' ? 'bg-orange-600 text-white shadow-xl shadow-orange-950/20' : 'text-zinc-500 hover:text-zinc-300'}`}
                            >
                                Gemini
                            </button>
                            <button
                                onClick={() => setAiProvider('openrouter')}
                                className={`px-3 py-1 text-[10px] font-black uppercase tracking-widest rounded-lg transition-all ${aiProvider === 'openrouter' ? 'bg-orange-600 text-white shadow-xl shadow-orange-950/20' : 'text-zinc-500 hover:text-zinc-300'}`}
                            >
                                Gemma 🇪🇺
                            </button>
                        </div>
                    )}
                </div>
                {activeSession && (
                    <div className="flex items-center gap-1.5 text-[9px] font-black uppercase tracking-widest text-orange-600 animate-in slide-in-from-left-2 duration-500">
                        <div className="relative flex h-1.5 w-1.5">
                            <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-orange-400 opacity-75"></span>
                            <span className="relative inline-flex rounded-full h-1.5 w-1.5 bg-orange-500"></span>
                        </div>
                        {activeSession.name}
                    </div>
                )}
            </div>

            <div
                className="relative group cursor-pointer w-full aspect-square rounded-2xl border-2 border-dashed border-zinc-800 overflow-hidden flex items-center justify-center bg-zinc-900/50 hover:border-orange-500/50 transition-colors"
                onClick={triggerUpload}
            >
                {previewUrl ? (
                    <img src={previewUrl} alt="Preview" className="w-full h-full object-cover" />
                ) : (
                    <div className="flex flex-col items-center gap-2 text-zinc-600 group-hover:text-orange-500 transition-colors">
                        <Camera size={48} strokeWidth={1.5} />
                        <span className="text-sm font-medium">{t('camera.scanBottle')}</span>
                    </div>
                )}

                {isAdmin && perfMetrics && (
                    <div className="absolute top-2 left-2 p-2 bg-black/80 backdrop-blur-md rounded-lg border border-orange-500/30 text-[9px] font-mono text-white/90 z-10 pointer-events-none">
                        <div className="font-bold text-orange-500 mb-1 uppercase tracking-tighter">Perf Metrics</div>
                        <div className="flex justify-between gap-4">
                            <span>Comp:</span>
                            <span className="text-orange-400">{perfMetrics.compression.toFixed(0)}ms</span>
                        </div>
                        <div className="flex justify-between gap-4">
                            <span>AI:</span>
                            <span className="text-orange-400">{perfMetrics.ai.toFixed(0)}ms</span>
                        </div>
                        <div className="flex justify-between gap-4">
                            <span>Prep:</span>
                            <span className="text-orange-400">{perfMetrics.prep.toFixed(0)}ms</span>
                        </div>
                        <div className="pt-1 mt-1 border-t border-white/10 flex justify-between gap-4 font-bold">
                            <span>Total:</span>
                            <span className="text-white">{(perfMetrics.compression + perfMetrics.ai + perfMetrics.prep).toFixed(0)}ms</span>
                        </div>
                    </div>
                )}

                {isProcessing && (
                    <div className="absolute inset-0 bg-black/60 backdrop-blur-md flex flex-col items-center justify-center gap-4 text-white p-6 text-center animate-in fade-in duration-300">
                        <div className="relative">
                            <Loader2 size={48} className="animate-spin text-orange-600" />
                            <Wand2 size={20} className="absolute top-1/2 left-1/2 -translate-x-1/2 -translate-y-1/2 text-white" />
                        </div>
                        <div className="space-y-1">
                            <p className="font-black uppercase tracking-[0.2em] text-[10px] text-orange-500">Magic Analysis</p>
                            <p className="text-sm font-bold">
                                {!navigator.onLine ? 'Offline: Speichere lokal...' : 'Analysiere Flasche...'}
                            </p>
                            <p className="text-[10px] text-zinc-400 max-w-[200px] mx-auto leading-relaxed">
                                {!navigator.onLine ? 'Dein Scan wird in der Warteschlange gespeichert und synchronisiert, sobald du wieder Empfang hast.' : 'Wir suchen in der Datenbank nach Details zu deinem Whisky...'}
                            </p>
                        </div>
                    </div>
                )}
            </div>

            <input type="file" accept="image/*" capture="environment" ref={fileInputRef} onChange={handleCapture} className="hidden" />
            <input type="file" accept="image/*" ref={galleryInputRef} onChange={handleCapture} className="hidden" />

            {lastSavedId ? (
                <div className="flex flex-col gap-3 w-full animate-in zoom-in-95 duration-300">
                    <div className="flex items-center gap-2 text-green-600 font-bold justify-center p-2">
                        <CheckCircle2 size={24} className="text-green-500" />
                        {t('camera.saveSuccess')}
                    </div>
                    <button
                        onClick={() => {
                            const url = `/bottles/${lastSavedId}${validatedSessionId ? `?session_id=${validatedSessionId}` : ''}`;
                            router.push(url);
                        }}
                        className="w-full py-4 px-6 bg-zinc-900 dark:bg-zinc-100 text-white dark:text-zinc-900 rounded-2xl font-black uppercase tracking-widest flex items-center justify-center gap-2 hover:bg-zinc-800 dark:hover:bg-white transition-all shadow-xl"
                    >
                        {t('camera.tastingNow')}
                        <ChevronRight size={20} />
                    </button>
                    {!wbDiscovery && !isDiscovering && (
                        <button onClick={handleDiscoverWb} className="w-full py-3 px-6 bg-orange-900/10 text-orange-500 rounded-xl font-bold flex items-center justify-center gap-2 border border-orange-900/20 hover:bg-orange-900/20 transition-all text-sm">
                            <Search size={16} />
                            {t('camera.whiskybaseSearch')}
                        </button>
                    )}
                    {isDiscovering && (
                        <div className="w-full py-3 px-6 text-zinc-400 font-bold flex items-center justify-center gap-2 text-sm italic">
                            <Loader2 size={16} className="animate-spin" />
                            {t('camera.searchingWb')}
                        </div>
                    )}
                    {wbDiscovery && (
                        <div className="p-4 bg-zinc-950 border border-orange-500/30 rounded-2xl space-y-3 animate-in fade-in slide-in-from-top-2">
                            <div className="flex items-center gap-2 text-[10px] font-black uppercase tracking-widest text-orange-600">
                                <Sparkles size={12} /> {t('camera.wbMatchFound')}
                            </div>
                            <p className="text-xs font-bold text-zinc-200 line-clamp-2 leading-snug">{wbDiscovery.title}</p>
                            <div className="flex gap-2">
                                <button onClick={handleLinkWb} className="flex-1 py-2.5 bg-orange-600 text-white text-[10px] font-black uppercase rounded-lg hover:bg-orange-700 transition-colors">{t('common.link')}</button>
                                <a href={wbDiscovery.url} target="_blank" rel="noopener noreferrer" className="flex-1 py-2.5 bg-zinc-800 text-zinc-300 text-[10px] font-black uppercase rounded-lg hover:bg-zinc-700 transition-colors flex items-center justify-center gap-1">
                                    <ExternalLink size={12} /> {t('common.check')}
                                </a>
                            </div>
                        </div>
                    )}
                    <button onClick={() => { setPreviewUrl(null); setAnalysisResult(null); setLastSavedId(null); }} className="w-full py-3 px-6 text-zinc-500 hover:text-zinc-200 font-bold transition-colors">{t('camera.later')}</button>
                </div>
            ) : matchingBottle ? (
                <div className="flex flex-col gap-3 w-full animate-in zoom-in-95 duration-300">
                    <Link href={`/bottles/${matchingBottle.id}${validatedSessionId ? `?session_id=${validatedSessionId}` : ''}`} className="w-full py-4 px-6 bg-orange-600 hover:bg-orange-700 text-white rounded-xl font-semibold flex items-center justify-center gap-2 transition-all active:scale-[0.98] shadow-lg shadow-orange-950/40">
                        <ExternalLink size={20} />
                        {t('camera.toVault')}
                    </Link>
                    <button onClick={() => setMatchingBottle(null)} className="w-full py-3 px-6 text-zinc-500 hover:text-zinc-200 font-bold transition-colors">{t('camera.saveAnyway')}</button>
                </div>
            ) : (
                <div className="flex flex-col gap-3 w-full">
                    <button
                        onClick={() => {
                            if (isQueued) setPreviewUrl(null);
                            else if (previewUrl && analysisResult) validatedSessionId ? handleQuickSave() : handleSave();
                            else triggerUpload();
                        }}
                        disabled={isProcessing || isSaving}
                        className={`w-full py-4 px-6 rounded-xl font-semibold flex items-center justify-center gap-2 transition-all active:scale-[0.98] shadow-lg disabled:opacity-50 ${validatedSessionId && previewUrl && analysisResult ? 'bg-zinc-100 text-zinc-900 shadow-black/10' : 'bg-orange-600 hover:bg-orange-700 text-white shadow-orange-950/40'}`}
                    >
                        {isSaving ? (
                            <><div className="animate-spin rounded-full h-5 w-5 border-b-2 border-current"></div>{t('camera.saving')}</>
                        ) : isQueued ? (
                            <><CheckCircle2 size={20} />{t('camera.nextBottle')}</>
                        ) : previewUrl && analysisResult ? (
                            validatedSessionId ? <><Droplets size={20} className="text-orange-500" />{t('camera.quickTasting')}</> : <><CheckCircle2 size={20} />{t('camera.inVault')}</>
                        ) : previewUrl ? (
                            <><Upload size={20} />{t('camera.newPhoto')}</>
                        ) : (
                            <><Camera size={20} />{t('camera.openingCamera')}</>
                        )}
                    </button>
                    {!previewUrl && !isProcessing && (
                        <button onClick={triggerGallery} className="w-full py-3 px-6 bg-zinc-800 text-zinc-300 rounded-xl font-bold flex items-center justify-center gap-2 border border-zinc-700 hover:bg-zinc-700 transition-all text-sm">
                            <Upload size={18} />{t('camera.uploadGallery')}
                        </button>
                    )}
                </div>
            )}

            {error && (
                <div className="flex items-center gap-2 text-red-500 text-sm bg-red-50 dark:bg-red-900/10 p-3 rounded-lg w-full">
                    <AlertCircle size={16} />{error}
                </div>
            )}

            {isQueued && (
                <div className="flex flex-col gap-3 p-5 bg-gradient-to-br from-purple-500/10 to-amber-500/10 dark:from-purple-900/20 dark:to-amber-900/20 border border-purple-500/20 rounded-3xl w-full animate-in zoom-in-95 duration-500">
                    <div className="flex items-center gap-3">
                        <div className="w-10 h-10 rounded-2xl bg-purple-500 flex items-center justify-center text-white shadow-lg shadow-purple-500/30"><Sparkles size={20} /></div>
                        <div className="flex flex-col">
                            <span className="text-sm font-black text-zinc-800 dark:text-zinc-100 italic">Lokal gespeichert!</span>
                            <span className="text-[10px] font-bold text-purple-600 dark:text-purple-400 uppercase tracking-widest">Warteschlange aktiv</span>
                        </div>
                    </div>
                    <p className="text-xs text-zinc-500 dark:text-zinc-400 leading-relaxed">Keine Sorge, dein Scan wurde sicher im Vault gespeichert. Sobald du wieder Empfang hast, wird die Analyse automatisch im Hintergrund gestartet.</p>
                </div>
            )}

            {matchingBottle && !lastSavedId && (
                <div className="flex flex-col gap-2 p-4 bg-blue-50 dark:bg-blue-900/10 border border-blue-200 dark:border-blue-900/30 rounded-xl w-full">
                    <div className="flex items-center gap-2 text-blue-600 dark:text-blue-400 font-bold text-sm"><AlertCircle size={16} />{t('camera.alreadyInVault')}</div>
                    <p className="text-xs text-blue-500/80">{t('camera.alreadyInVaultDesc')}</p>
                </div>
            )}

            {previewUrl && !isProcessing && !error && !isQueued && !matchingBottle && analysisResult && (
                <div className="flex flex-col gap-3 w-full animate-in fade-in slide-in-from-top-4 duration-500">
                    <div className="flex items-center gap-2 text-green-400 text-sm bg-green-900/10 p-3 rounded-lg w-full border border-green-900/30">
                        <CheckCircle2 size={16} />{t('camera.analysisSuccess')}
                    </div>
                    <div className="p-3 md:p-4 bg-zinc-950 rounded-2xl border border-zinc-800">
                        <div className="flex items-center gap-2 mb-2 md:mb-3 text-orange-600"><Sparkles size={18} /><span className="font-bold text-[10px] md:text-sm uppercase tracking-wider">{t('camera.results')}</span></div>
                        <div className="space-y-2">
                            <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">{t('bottle.nameLabel')}:</span><span className="font-semibold text-right text-zinc-100">{analysisResult.name || '-'}</span></div>
                            <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">{t('bottle.distilleryLabel')}:</span><span className="font-semibold text-right">{analysisResult.distillery || '-'}</span></div>
                            <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">{t('bottle.categoryLabel')}:</span><span className="font-semibold text-right">{shortenCategory(analysisResult.category || '-')}</span></div>
                            <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">{t('bottle.abvLabel')}:</span><span className="font-semibold text-right">{analysisResult.abv ? `${analysisResult.abv}%` : '-'}</span></div>
                            {analysisResult.age && <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">{t('bottle.ageLabel')}:</span><span className="font-semibold text-right">{analysisResult.age} {t('bottle.years')}</span></div>}
                            {analysisResult.vintage && <div className="flex justify-between items-center text-sm"><span className="text-zinc-500">Vintage:</span><span className="font-semibold text-right">{analysisResult.vintage}</span></div>}
                            {analysisResult.bottler && <div className="flex justify-between text-sm"><span className="text-zinc-500">Bottler:</span><span className="font-semibold">{analysisResult.bottler}</span></div>}
                            {analysisResult.distilled_at && <div className="flex justify-between text-sm"><span className="text-zinc-500">{t('bottle.distilledLabel')}:</span><span className="font-semibold">{analysisResult.distilled_at}</span></div>}
                            {analysisResult.bottled_at && <div className="flex justify-between text-sm"><span className="text-zinc-500">{t('bottle.bottledLabel')}:</span><span className="font-semibold">{analysisResult.bottled_at}</span></div>}
                            {analysisResult.batch_info && <div className="flex justify-between text-sm"><span className="text-zinc-500">{t('bottle.batchLabel')}:</span><span className="font-semibold text-zinc-100">{analysisResult.batch_info}</span></div>}
                            {analysisResult.bottleCode && <div className="flex justify-between text-sm"><span className="text-zinc-500">Bottle Code:</span><span className="font-semibold text-zinc-400 font-mono text-xs">{analysisResult.bottleCode}</span></div>}
                            {isAdmin && perfMetrics && (
                                <div className="pt-4 mt-2 border-t border-zinc-900/50 space-y-1">
                                    <div className="flex items-center gap-1.5 text-[9px] font-black text-orange-600 uppercase tracking-widest mb-1"><Clock size={10} /> Performance Data</div>
                                    <div className="grid grid-cols-2 gap-x-4 gap-y-1 text-[10px]">
                                        <div className="flex justify-between"><span className="text-zinc-600">CLIENT:</span><span className="text-zinc-400 font-mono">{perfMetrics.compression.toFixed(0)}ms</span></div>
                                        <div className="flex justify-between"><span className="text-zinc-600">({(perfMetrics.uploadSize / 1024).toFixed(0)}KB)</span></div>

                                        {perfMetrics.cacheHit ? (
                                            <div className="col-span-2 text-center py-1">
                                                <span className="text-green-500 font-bold text-[11px]">CACHE HIT</span>
                                            </div>
                                        ) : (
                                            <>
                                                <div className="col-span-2 border-t border-zinc-900/30 pt-1 mt-1">
                                                    <div className="text-[8px] text-zinc-600 mb-0.5">AI BREAKDOWN:</div>
                                                </div>
                                                {perfMetrics.imagePrep !== undefined && <div className="flex justify-between"><span className="text-zinc-600">Prep:</span><span className="text-zinc-400 font-mono">{perfMetrics.imagePrep.toFixed(0)}ms</span></div>}
                                                {perfMetrics.encoding !== undefined && <div className="flex justify-between"><span className="text-zinc-600">Encode:</span><span className="text-zinc-400 font-mono">{perfMetrics.encoding.toFixed(0)}ms</span></div>}
                                                {perfMetrics.modelInit !== undefined && <div className="flex justify-between"><span className="text-zinc-600">Init:</span><span className="text-zinc-400 font-mono">{perfMetrics.modelInit.toFixed(0)}ms</span></div>}
                                                <div className="flex justify-between"><span className="text-orange-400">API:</span><span className="text-orange-400 font-mono font-bold">{perfMetrics.aiApi.toFixed(0)}ms</span></div>
                                                {perfMetrics.validation !== undefined && <div className="flex justify-between"><span className="text-zinc-600">Valid:</span><span className="text-zinc-400 font-mono">{perfMetrics.validation.toFixed(0)}ms</span></div>}
                                                {perfMetrics.dbOps !== undefined && <div className="flex justify-between"><span className="text-zinc-600">DB:</span><span className="text-zinc-400 font-mono">{perfMetrics.dbOps.toFixed(0)}ms</span></div>}
                                                <div className="col-span-2 border-t border-zinc-900/30 pt-1 mt-1">
                                                    <div className="flex justify-between"><span className="text-zinc-500 font-bold">TOTAL:</span><span className="text-orange-500 font-mono font-bold">{(perfMetrics.compression + perfMetrics.ai).toFixed(0)}ms</span></div>
                                                </div>
                                            </>
                                        )}
                                    </div>
                                </div>
                            )}
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
