'use client';

import React, { useState, useEffect } from 'react';
import { motion } from 'framer-motion';
import { ChevronDown, Wind, Utensils, Droplets, Sparkles, Send, Users, Star, AlertTriangle, Check, Zap, Loader2 } from 'lucide-react';
import { BottleMetadata } from '@/types/whisky';
import TagSelector from './TagSelector';
import { useLiveQuery } from 'dexie-react-hooks';
import { db } from '@/lib/db';
import { createClient } from '@/lib/supabase/client';
import { useI18n } from '@/i18n/I18nContext';
import { discoverWhiskybaseId } from '@/services/discover-whiskybase';
import TastingFormBody from './TastingFormBody';

interface TastingEditorProps {
    bottleMetadata: BottleMetadata;
    image: string | null;
    onSave: (data: any) => void;
    onOpenSessions: () => void;
    activeSessionName?: string;
    activeSessionId?: string;
    isEnriching?: boolean;
    defaultExpanded?: boolean;
}

export default function TastingEditor({ bottleMetadata, image, onSave, onOpenSessions, activeSessionName, activeSessionId, isEnriching, defaultExpanded = false }: TastingEditorProps) {
    const { t } = useI18n();
    const supabase = createClient();
    const [status, setStatus] = React.useState<string>('sealed');
    const [isUpdating, setIsUpdating] = React.useState(false);
    const [isFormVisible, setIsFormVisible] = React.useState(false);

    const [rating, setRating] = useState(85);
    const [noseNotes, setNoseNotes] = useState('');
    const [palateNotes, setPalateNotes] = useState('');
    const [finishNotes, setFinishNotes] = useState('');
    const [isSample, setIsSample] = useState(false);

    const [noseTagIds, setNoseTagIds] = useState<string[]>([]);
    const [palateTagIds, setPalateTagIds] = useState<string[]>([]);
    const [finishTagIds, setFinishTagIds] = useState<string[]>([]);

    // Editable bottle metadata
    const [bottleName, setBottleName] = useState(bottleMetadata.name || '');
    const [bottleDistillery, setBottleDistillery] = useState(bottleMetadata.distillery || '');
    const [bottleAbv, setBottleAbv] = useState(bottleMetadata.abv?.toString() || '');
    const [bottleAge, setBottleAge] = useState(bottleMetadata.age?.toString() || '');
    const [bottleCategory, setBottleCategory] = useState(bottleMetadata.category || 'Whisky');

    const [bottleVintage, setBottleVintage] = useState(bottleMetadata.vintage || '');
    const [bottleCaskType, setBottleCaskType] = useState(bottleMetadata.cask_type || '');
    const [bottleBottler, setBottleBottler] = useState(bottleMetadata.bottler || '');
    const [bottleBatchInfo, setBottleBatchInfo] = useState(bottleMetadata.batch_info || '');
    const [bottleCode, setBottleCode] = useState(bottleMetadata.bottleCode || '');
    const [bottleDistilledAt, setBottleDistilledAt] = useState(bottleMetadata.distilled_at || '');
    const [bottleBottledAt, setBottleBottledAt] = useState(bottleMetadata.bottled_at || '');
    const [showBottleDetails, setShowBottleDetails] = useState(false);

    // Whiskybase discovery
    const [whiskybaseId, setWhiskybaseId] = useState(bottleMetadata.whiskybaseId || '');
    const [whiskybaseDiscovery, setWhiskybaseDiscovery] = useState<{ id: string; url: string; title: string } | null>(null);
    const [isDiscoveringWb, setIsDiscoveringWb] = useState(false);
    const [whiskybaseError, setWhiskybaseError] = useState<string | null>(null);
    const [textureTagIds, setTextureTagIds] = useState<string[]>([]);
    const [selectedBuddyIds, setSelectedBuddyIds] = useState<string[]>([]);
    const [bottlePurchasePrice, setBottlePurchasePrice] = useState(bottleMetadata.purchase_price?.toString() || '');

    // Guessing State (Blind Mode)
    const [guessAbv, setGuessAbv] = useState<string>('');
    const [guessAge, setGuessAge] = useState<string>('');
    const [guessRegion, setGuessRegion] = useState<string>('');
    const [isSessionBlind, setIsSessionBlind] = useState(false);

    // Section collapse states
    const [isNoseExpanded, setIsNoseExpanded] = useState(defaultExpanded);
    const [isPalateExpanded, setIsPalateExpanded] = useState(defaultExpanded);
    const [isFinishExpanded, setIsFinishExpanded] = useState(defaultExpanded);

    const buddies = useLiveQuery(() => db.cache_buddies.toArray(), [], [] as any[]);
    const [lastDramInSession, setLastDramInSession] = useState<{ name: string; isSmoky: boolean; timestamp: number } | null>(null);
    const [showPaletteWarning, setShowPaletteWarning] = useState(false);

    const suggestedTags = bottleMetadata.suggested_tags || [];
    const suggestedCustomTags = bottleMetadata.suggested_custom_tags || [];

    // Track last seen confidence to detect cloud vs local updates
    const lastConfidenceRef = React.useRef<number>(0);

    // Sync bottleMetadata prop changes to internal state (for live AI updates)
    // Cloud data (confidence >= 0.6 OR >= 60) overrides local OCR (confidence ~50 or ~0.5)
    useEffect(() => {
        // Normalize confidence to 0-100 scale (Gemini returns 0-1, local returns 0-100)
        const rawConfidence = bottleMetadata.confidence ?? 0;
        const newConfidence = rawConfidence <= 1 ? rawConfidence * 100 : rawConfidence;
        const isCloudUpdate = newConfidence >= 60;
        const isUpgrade = newConfidence > lastConfidenceRef.current;

        console.log('[TastingEditor] Syncing bottleMetadata update:', {
            rawConfidence,
            normalizedConfidence: newConfidence,
            isCloudUpdate,
            isUpgrade,
            previousConfidence: lastConfidenceRef.current,
        });

        // For cloud updates (higher confidence), allow overwriting local OCR values
        // For local updates, only fill empty fields
        if (isCloudUpdate || isUpgrade) {
            // Cloud vision: update all fields that have new data
            if (bottleMetadata.name) setBottleName(bottleMetadata.name);
            if (bottleMetadata.distillery) setBottleDistillery(bottleMetadata.distillery);
            if (bottleMetadata.abv) setBottleAbv(bottleMetadata.abv.toString());
            if (bottleMetadata.age) setBottleAge(bottleMetadata.age.toString());
            if (bottleMetadata.category) setBottleCategory(bottleMetadata.category);
            if (bottleMetadata.vintage) setBottleVintage(bottleMetadata.vintage);
            if (bottleMetadata.cask_type) setBottleCaskType(bottleMetadata.cask_type);
            if (bottleMetadata.bottler) setBottleBottler(bottleMetadata.bottler);
            if (bottleMetadata.batch_info) setBottleBatchInfo(bottleMetadata.batch_info);
            if (bottleMetadata.distilled_at) setBottleDistilledAt(bottleMetadata.distilled_at);
            if (bottleMetadata.bottled_at) setBottleBottledAt(bottleMetadata.bottled_at);
        } else {
            // Local OCR or initial: only update empty fields
            if (!bottleName && bottleMetadata.name) setBottleName(bottleMetadata.name);
            if (!bottleDistillery && bottleMetadata.distillery) setBottleDistillery(bottleMetadata.distillery);
            if (!bottleAbv && bottleMetadata.abv) setBottleAbv(bottleMetadata.abv.toString());
            if (!bottleAge && bottleMetadata.age) setBottleAge(bottleMetadata.age.toString());
            if ((!bottleCategory || bottleCategory === 'Whisky') && bottleMetadata.category) setBottleCategory(bottleMetadata.category);
            if (!bottleVintage && bottleMetadata.vintage) setBottleVintage(bottleMetadata.vintage);
            if (!bottleCaskType && bottleMetadata.cask_type) setBottleCaskType(bottleMetadata.cask_type);
            if (!bottleBottler && bottleMetadata.bottler) setBottleBottler(bottleMetadata.bottler);
            if (!bottleBatchInfo && bottleMetadata.batch_info) setBottleBatchInfo(bottleMetadata.batch_info);
            if (!bottleDistilledAt && bottleMetadata.distilled_at) setBottleDistilledAt(bottleMetadata.distilled_at);
            if (!bottleBottledAt && bottleMetadata.bottled_at) setBottleBottledAt(bottleMetadata.bottled_at);
        }

        lastConfidenceRef.current = newConfidence;
    }, [bottleMetadata]);

    // Session-based pre-fill and Palette Checker
    useEffect(() => {
        const fetchSessionData = async () => {
            if (activeSessionId) {
                const { data: participants } = await supabase
                    .from('session_participants')
                    .select('buddy_id')
                    .eq('session_id', activeSessionId);

                if (participants) {
                    setSelectedBuddyIds(participants.map(p => p.buddy_id));
                }

                // Check if session is blind
                const { data: sessionData } = await supabase
                    .from('tasting_sessions')
                    .select('is_blind')
                    .eq('id', activeSessionId)
                    .single();

                if (sessionData?.is_blind) {
                    setIsSessionBlind(true);
                }

                const { data: lastTastings } = await supabase
                    .from('tastings')
                    .select(`
                        id,
                        tasted_at,
                        bottles(name, category),
                        tasting_tags(tags(name))
                    `)
                    .eq('session_id', activeSessionId)
                    .order('tasted_at', { ascending: false })
                    .limit(1);

                if (lastTastings && lastTastings.length > 0) {
                    const last = lastTastings[0];
                    const tags = (last as any).tasting_tags?.map((t: any) => t.tags.name) || [];
                    const category = (last as any).bottles?.category || '';
                    const text = (tags.join(' ') + ' ' + category).toLowerCase();
                    const smokyKeywords = ['rauch', 'torf', 'smoke', 'peat', 'islay', 'ash', 'lagerfeuer'];
                    const isSmoky = smokyKeywords.some(kw => text.includes(kw));

                    setLastDramInSession({
                        name: (last as any).bottles?.name || 'Unbekannt',
                        isSmoky,
                        timestamp: new Date(last.tasted_at).getTime()
                    });
                }
            }
        };
        fetchSessionData();
    }, [activeSessionId, supabase]);

    useEffect(() => {
        if (lastDramInSession?.isSmoky) {
            const now = Date.now();
            const diffMin = (now - lastDramInSession.timestamp) / (1000 * 60);
            if (diffMin < 20) setShowPaletteWarning(true);
        }
    }, [lastDramInSession]);

    // Automatic Whiskybase discovery when details are expanded
    useEffect(() => {
        const searchWhiskybase = async () => {
            if (showBottleDetails && (bottleName || bottleMetadata.name) && !whiskybaseId && !whiskybaseDiscovery && !isDiscoveringWb) {
                setIsDiscoveringWb(true);
                try {
                    const searchName = bottleName || bottleMetadata.name;
                    if (!searchName) {
                        setIsDiscoveringWb(false);
                        return;
                    }

                    const result = await discoverWhiskybaseId({
                        name: searchName,
                        distillery: bottleDistillery || undefined,
                        abv: bottleAbv ? parseFloat(bottleAbv) : undefined,
                        age: bottleAge ? parseInt(bottleAge) : undefined,
                        batch_info: bottleBatchInfo || undefined,
                        distilled_at: bottleDistilledAt || undefined,
                        bottled_at: bottleBottledAt || undefined,
                    });

                    if (result.success && result.id) {
                        setWhiskybaseDiscovery({ id: result.id, url: result.url, title: result.title });
                        setWhiskybaseId(result.id);
                        setWhiskybaseError(null);
                    } else {
                        // No results found
                        setWhiskybaseError('Keine Ergebnisse gefunden');
                    }
                } catch (err: any) {
                    console.error('[TastingEditor] Whiskybase discovery failed:', err);
                    setWhiskybaseError(err.message || 'Suche fehlgeschlagen');
                } finally {
                    setIsDiscoveringWb(false);
                }
            }
        };

        searchWhiskybase();
    }, [showBottleDetails]); // Only trigger when details are expanded

    const toggleBuddy = (id: string) => {
        setSelectedBuddyIds(prev => prev.includes(id) ? prev.filter(bid => bid !== id) : [...prev, id]);
    };

    const handleInternalSave = () => {
        onSave({
            rating,
            nose_notes: noseNotes,
            palate_notes: palateNotes,
            finish_notes: finishNotes,
            is_sample: isSample,
            buddy_ids: selectedBuddyIds,
            tag_ids: [...noseTagIds, ...palateTagIds, ...finishTagIds, ...textureTagIds],
            // Guessing Data
            guess_abv: guessAbv ? parseFloat(guessAbv) : null,
            guess_age: guessAge ? parseInt(guessAge) : null,
            guess_region: guessRegion || null,
            // Visual data for ResultCard
            // Edited bottle metadata
            bottleMetadata: {
                ...bottleMetadata,
                name: bottleName || bottleMetadata.name,
                distillery: bottleDistillery || bottleMetadata.distillery,
                abv: bottleAbv ? parseFloat(bottleAbv) : bottleMetadata.abv,
                age: bottleAge ? parseInt(bottleAge) : bottleMetadata.age,
                category: bottleCategory || bottleMetadata.category,
                vintage: bottleVintage || null,
                cask_type: bottleCaskType || null,
                bottler: bottleBottler || null,
                batch_info: bottleBatchInfo || null,
                bottleCode: bottleCode || null,
                distilled_at: bottleDistilledAt || null,
                bottled_at: bottleBottledAt || null,
                whiskybaseId: whiskybaseId || null,
                purchase_price: bottlePurchasePrice ? parseFloat(bottlePurchasePrice) : null,
                status: status,
            }
        });
    };

    return (
        <div className="flex-1 flex flex-col w-full bg-zinc-950 h-full overflow-hidden">
            {/* Main Scrollable Content */}
            <div className="flex-1 overflow-y-auto overflow-x-hidden">
                <div className="max-w-2xl mx-auto px-6 py-12 space-y-12">
                    {/* Palette Warning */}
                    {showPaletteWarning && (
                        <motion.div
                            initial={{ opacity: 0, y: -20 }}
                            animate={{ opacity: 1, y: 0 }}
                            className="p-5 bg-orange-500/10 border border-orange-500/20 rounded-2xl flex items-start gap-3"
                        >
                            <AlertTriangle size={24} className="text-orange-500 shrink-0 mt-0.5" />
                            <div className="space-y-1">
                                <p className="text-[10px] font-bold uppercase tracking-wider text-orange-500">Palette-Checker</p>
                                <p className="text-xs font-bold text-zinc-50 leading-relaxed">
                                    Dein letzter Dram "{lastDramInSession?.name}" war torfig. Trink etwas Wasser!
                                </p>
                                <button onClick={() => setShowPaletteWarning(false)} className="text-[10px] font-bold uppercase text-orange-500 underline mt-2 block">Verstanden</button>
                            </div>
                        </motion.div>
                    )}

                    {/* Hero Section */}
                    <div className="flex items-center gap-6">
                        <div className="w-24 h-32 bg-zinc-900 rounded-xl border border-zinc-800 flex items-center justify-center overflow-hidden shrink-0 shadow-2xl relative">
                            {image ? (
                                <img src={image} alt="Bottle Preview" className="w-full h-full object-cover" />
                            ) : (
                                <div className="text-[10px] text-zinc-700 uppercase font-bold rotate-[-15deg]">No Photo</div>
                            )}
                        </div>
                        <div className="flex-1 min-w-0">
                            <h1 className="text-3xl font-bold text-orange-600 mb-1 truncate leading-none uppercase tracking-tight">
                                {bottleDistillery || 'Destillerie'}
                            </h1>
                            <p className="text-zinc-50 text-xl font-bold truncate mb-2">{bottleName || 'Unbekannter Malt'}</p>
                            <p className="text-zinc-500 text-[10px] font-bold uppercase tracking-widest leading-none">
                                {bottleCategory || 'Whisky'} {bottleAbv ? `• ${bottleAbv}%` : ''} {bottleAge ? `• ${bottleAge}y` : ''}
                            </p>
                            {bottlePurchasePrice && (
                                <div className="mt-3 flex items-center gap-1.5">
                                    <span className="text-[10px] font-black text-orange-600 bg-orange-600/10 px-2 py-0.5 rounded-md border border-orange-600/20">
                                        EK: {bottlePurchasePrice}€
                                    </span>
                                </div>
                            )}
                        </div>
                    </div>

                    {/* Expandable Bottle Details */}
                    <div className="bg-zinc-900/50 rounded-2xl border border-zinc-800 overflow-hidden">
                        <button
                            onClick={() => setShowBottleDetails(!showBottleDetails)}
                            className="w-full p-4 flex items-center justify-between hover:bg-zinc-900/70 transition-colors"
                        >
                            <span className="text-[10px] font-bold uppercase tracking-widest text-zinc-500">
                                Bottle Details
                            </span>
                            <ChevronDown
                                size={16}
                                className={`text-zinc-500 transition-transform ${showBottleDetails ? 'rotate-180' : ''}`}
                            />
                        </button>

                        {showBottleDetails && (
                            <div className="p-4 pt-0 space-y-3 border-t border-zinc-800/50">
                                {/* Helper to check field confidence */}
                                {(() => {
                                    const checkConfidence = (field: string) => {
                                        const scores = bottleMetadata.confidence_scores;
                                        if (!scores) return true; // Default to neutral if no scores
                                        const score = scores[field];
                                        return score === undefined || score >= 80;
                                    };

                                    return (
                                        <>
                                            {/* Name */}
                                            <div className="mt-3">
                                                <div className="flex justify-between items-center mb-1.5">
                                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block">
                                                        Flaschenname
                                                    </label>
                                                    {!checkConfidence('name') && (
                                                        <span className="flex items-center gap-1 text-[8px] font-black text-yellow-600 uppercase tracking-tighter animate-pulse">
                                                            <AlertTriangle size={8} /> Unsicher
                                                        </span>
                                                    )}
                                                </div>
                                                <input
                                                    type="text"
                                                    value={bottleName}
                                                    onChange={(e) => setBottleName(e.target.value)}
                                                    placeholder="e.g. 12 Year Old"
                                                    className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-all ${!checkConfidence('name') ? 'border-yellow-600/50 shadow-[0_0_10px_rgba(202,138,4,0.1)]' : 'border-zinc-800'
                                                        }`}
                                                />
                                            </div>

                                            {/* Distillery */}
                                            <div>
                                                <div className="flex justify-between items-center mb-1.5">
                                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block">
                                                        Destillerie
                                                    </label>
                                                    {!checkConfidence('distillery') && (
                                                        <span className="flex items-center gap-1 text-[8px] font-black text-yellow-600 uppercase tracking-tighter animate-pulse">
                                                            <AlertTriangle size={8} /> Unsicher
                                                        </span>
                                                    )}
                                                </div>
                                                <input
                                                    type="text"
                                                    value={bottleDistillery}
                                                    onChange={(e) => setBottleDistillery(e.target.value)}
                                                    placeholder="e.g. Lagavulin"
                                                    className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-all ${!checkConfidence('distillery') ? 'border-yellow-600/50 shadow-[0_0_10px_rgba(202,138,4,0.1)]' : 'border-zinc-800'
                                                        }`}
                                                />
                                            </div>

                                            <div className="grid grid-cols-2 gap-3">
                                                {/* ABV */}
                                                <div>
                                                    <div className="flex justify-between items-center mb-1.5">
                                                        <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block">
                                                            Alkohol (ABV %)
                                                        </label>
                                                        {!checkConfidence('abv') && (
                                                            <AlertTriangle size={8} className="text-yellow-600 animate-pulse" />
                                                        )}
                                                    </div>
                                                    <input
                                                        type="number"
                                                        step="0.1"
                                                        value={bottleAbv}
                                                        onChange={(e) => setBottleAbv(e.target.value)}
                                                        placeholder="43.0"
                                                        className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-all ${!checkConfidence('abv') ? 'border-yellow-600/50 shadow-[0_0_10px_rgba(202,138,4,0.1)]' : 'border-zinc-800'
                                                            }`}
                                                    />
                                                </div>
                                                {/* Age */}
                                                <div>
                                                    <div className="flex justify-between items-center mb-1.5">
                                                        <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block">
                                                            Alter (Jahre)
                                                        </label>
                                                        {!checkConfidence('age') && (
                                                            <AlertTriangle size={8} className="text-yellow-600 animate-pulse" />
                                                        )}
                                                    </div>
                                                    <input
                                                        type="number"
                                                        value={bottleAge}
                                                        onChange={(e) => setBottleAge(e.target.value)}
                                                        placeholder="12"
                                                        className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-all ${!checkConfidence('age') ? 'border-yellow-600/50 shadow-[0_0_10px_rgba(202,138,4,0.1)]' : 'border-zinc-800'
                                                            }`}
                                                    />
                                                </div>
                                            </div>

                                            {/* Category */}
                                            <div>
                                                <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                                    Kategorie
                                                </label>
                                                <input
                                                    type="text"
                                                    value={bottleCategory}
                                                    onChange={(e) => setBottleCategory(e.target.value)}
                                                    placeholder="e.g. Single Malt"
                                                    className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                                />
                                            </div>
                                            {/* Cask Type */}
                                            <div>
                                                <div className="flex justify-between items-center mb-1.5">
                                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block">
                                                        Fass-Typ (Cask)
                                                    </label>
                                                    {!checkConfidence('cask_type') && (
                                                        <span className="flex items-center gap-1 text-[8px] font-black text-yellow-600 uppercase tracking-tighter animate-pulse">
                                                            <AlertTriangle size={8} /> Unsicher
                                                        </span>
                                                    )}
                                                </div>
                                                <input
                                                    type="text"
                                                    value={bottleCaskType}
                                                    onChange={(e) => setBottleCaskType(e.target.value)}
                                                    placeholder="e.g. Oloroso Sherry Cask"
                                                    className={`w-full bg-zinc-950 border rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-all ${!checkConfidence('cask_type') ? 'border-yellow-600/50 shadow-[0_0_10px_rgba(202,138,4,0.1)]' : 'border-zinc-800'
                                                        }`}
                                                />
                                            </div>
                                        </>
                                    );
                                })()}
                                {/* Vintage */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Vintage
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleVintage}
                                        onChange={(e) => setBottleVintage(e.target.value)}
                                        placeholder="e.g. 2007"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>

                                {/* Bottler */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Bottler
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleBottler}
                                        onChange={(e) => setBottleBottler(e.target.value)}
                                        placeholder="e.g. Independent Bottler"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>

                                {/* Distilled At */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Distilled At
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleDistilledAt}
                                        onChange={(e) => setBottleDistilledAt(e.target.value)}
                                        placeholder="e.g. 2007"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>

                                {/* Bottled At */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Bottled At
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleBottledAt}
                                        onChange={(e) => setBottleBottledAt(e.target.value)}
                                        placeholder="e.g. 2024"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>

                                {/* Batch Info */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Batch Info
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleBatchInfo}
                                        onChange={(e) => setBottleBatchInfo(e.target.value)}
                                        placeholder="e.g. Oloroso Sherry Cask"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>

                                {/* Bottle Code */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Bottle Code
                                    </label>
                                    <input
                                        type="text"
                                        value={bottleCode}
                                        onChange={(e) => setBottleCode(e.target.value)}
                                        placeholder="e.g. WB271235"
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 placeholder-zinc-700 font-mono focus:outline-none focus:border-orange-600 transition-colors"
                                    />
                                </div>


                                {/* Bottle Status */}
                                <div>
                                    <label className="text-[9px] font-bold uppercase tracking-wider text-zinc-600 block mb-1.5">
                                        Status
                                    </label>
                                    <select
                                        value={status}
                                        onChange={(e) => setStatus(e.target.value)}
                                        className="w-full bg-zinc-950 border border-zinc-800 rounded-lg px-3 py-2 text-sm text-zinc-100 focus:outline-none focus:border-orange-600 transition-colors"
                                    >
                                        <option value="sealed">Versiegelt</option>
                                        <option value="open">Offen</option>
                                        <option value="sampled">Sample</option>
                                        <option value="empty">Leer</option>
                                    </select>
                                </div>

                                {/* Whiskybase Discovery */}
                                {isDiscoveringWb && (
                                    <div className="flex items-center gap-2 p-3 bg-zinc-900 rounded-lg border border-zinc-800">
                                        <Loader2 size={16} className="animate-spin text-orange-500" />
                                        <span className="text-xs text-zinc-400">Searching Whiskybase...</span>
                                    </div>
                                )}

                                {whiskybaseDiscovery && (
                                    <div className="p-3 bg-orange-500/10 border border-orange-500/20 rounded-lg space-y-2">
                                        <div className="flex items-start justify-between gap-2">
                                            <div className="flex-1 min-w-0">
                                                <p className="text-[9px] font-bold uppercase tracking-wider text-orange-500 mb-1">
                                                    Whiskybase Found
                                                </p>
                                                <p className="text-xs text-zinc-200 truncate">
                                                    {whiskybaseDiscovery.title}
                                                </p>
                                                <a
                                                    href={whiskybaseDiscovery.url}
                                                    target="_blank"
                                                    rel="noopener noreferrer"
                                                    className="text-[10px] text-orange-500 hover:underline mt-1 inline-block"
                                                >
                                                    View on Whiskybase →
                                                </a>
                                            </div>
                                        </div>
                                        <p className="text-[10px] text-zinc-500 font-mono">
                                            ID: {whiskybaseDiscovery.id}
                                        </p>
                                    </div>
                                )}

                                {/* Whiskybase Error */}
                                {whiskybaseError && !whiskybaseDiscovery && !isDiscoveringWb && (
                                    <div className="p-3 bg-zinc-900 border border-zinc-800 rounded-lg">
                                        <p className="text-xs text-zinc-500">
                                            {whiskybaseError}
                                        </p>
                                    </div>
                                )}
                            </div>
                        )}
                    </div>

                    {/* Session Selector */}
                    <button
                        onClick={onOpenSessions}
                        className="w-full p-6 bg-zinc-900/50 rounded-2xl border border-zinc-800 flex items-center justify-between group hover:bg-zinc-900/70 hover:border-orange-500/30 transition-all"
                    >
                        <div className="text-left">
                            <p className="text-[10px] font-bold uppercase tracking-widest text-zinc-500 mb-1">
                                Session
                            </p>
                            <p className="font-bold text-zinc-50 leading-none">
                                {activeSessionName || 'Trinkst du in Gesellschaft?'}
                            </p>
                        </div>
                        <div className="flex items-center gap-2">
                            {activeSessionName && (
                                <Users size={18} className="text-orange-500" />
                            )}
                            <ChevronDown size={18} className="text-zinc-500 group-hover:text-orange-500 group-hover:translate-y-0.5 transition-all" />
                        </div>
                    </button>

                    {/* Blind Guessing Section */}
                    {isSessionBlind && (
                        <div className="bg-purple-900/10 rounded-[32px] p-8 border border-purple-500/30 space-y-8 relative overflow-hidden group">
                            <div className="absolute top-0 right-0 p-8 opacity-10 group-hover:opacity-20 transition-opacity">
                                <Sparkles size={80} className="text-purple-500" />
                            </div>

                            <div className="relative">
                                <h3 className="text-[10px] font-black uppercase tracking-[0.4em] text-purple-400 mb-1">Experimenteller Gaumen</h3>
                                <p className="text-2xl font-black text-white tracking-tighter">Was ist im Glas?</p>
                            </div>

                            <div className="grid grid-cols-1 md:grid-cols-2 gap-4 relative">
                                <div className="space-y-2">
                                    <label className="text-[9px] font-black uppercase tracking-widest text-purple-400/60 ml-1">Geschätzter ABV (%)</label>
                                    <input
                                        type="number"
                                        step="0.1"
                                        value={guessAbv}
                                        onChange={(e) => setGuessAbv(e.target.value)}
                                        placeholder="z.B. 46.3"
                                        className="w-full bg-black/40 border border-purple-500/20 rounded-2xl px-5 py-3 text-sm text-white focus:border-purple-500/50 outline-none transition-all"
                                    />
                                </div>
                                <div className="space-y-2">
                                    <label className="text-[9px] font-black uppercase tracking-widest text-purple-400/60 ml-1">Geschätztes Alter</label>
                                    <input
                                        type="number"
                                        value={guessAge}
                                        onChange={(e) => setGuessAge(e.target.value)}
                                        placeholder="z.B. 12"
                                        className="w-full bg-black/40 border border-purple-500/20 rounded-2xl px-5 py-3 text-sm text-white focus:border-purple-500/50 outline-none transition-all"
                                    />
                                </div>
                                <div className="md:col-span-2 space-y-2">
                                    <label className="text-[9px] font-black uppercase tracking-widest text-purple-400/60 ml-1">Region / Destillerie Tipp</label>
                                    <input
                                        type="text"
                                        value={guessRegion}
                                        onChange={(e) => setGuessRegion(e.target.value)}
                                        placeholder="z.B. Islay / Lagavulin"
                                        className="w-full bg-black/40 border border-purple-500/20 rounded-2xl px-5 py-3 text-sm text-white focus:border-purple-500/50 outline-none transition-all"
                                    />
                                </div>
                            </div>
                        </div>
                    )}

                    {/* Shared Tasting Form Body */}
                    <TastingFormBody
                        rating={rating}
                        setRating={setRating}
                        isSample={isSample}
                        setIsSample={setIsSample}
                        nose={noseNotes}
                        setNose={setNoseNotes}
                        noseTagIds={noseTagIds}
                        setNoseTagIds={setNoseTagIds}
                        palate={palateNotes}
                        setPalate={setPalateNotes}
                        palateTagIds={palateTagIds}
                        setPalateTagIds={setPalateTagIds}
                        finish={finishNotes}
                        setFinish={setFinishNotes}
                        finishTagIds={finishTagIds}
                        setFinishTagIds={setFinishTagIds}
                        selectedBuddyIds={selectedBuddyIds}
                        setSelectedBuddyIds={setSelectedBuddyIds}
                        availableBuddies={buddies || []}
                        suggestedTags={suggestedTags}
                        suggestedCustomTags={suggestedCustomTags}
                        defaultExpanded={defaultExpanded}
                        t={t}
                    />
                </div>
            </div>

            {/* Fixed/Sticky Footer for Save Action */}
            <div className="w-full p-6 bg-gradient-to-t from-zinc-950 via-zinc-950/95 to-transparent border-t border-white/5 shrink-0 z-20">
                <div className="max-w-2xl mx-auto">
                    <button
                        onClick={handleInternalSave}
                        className="w-full py-5 bg-orange-600 text-white rounded-2xl font-bold uppercase tracking-widest text-xs flex items-center justify-center gap-4 shadow-2xl shadow-orange-950/40 active:scale-[0.98] transition-all hover:bg-orange-500"
                    >
                        <Send size={20} />
                        {t('tasting.saveTasting')}
                    </button>
                </div>
            </div>
        </div>
    );
}

function CustomSlider({ label, value, onChange, icon }: any) {
    return (
        <div className="space-y-4 bg-zinc-900/50 p-6 rounded-2xl border border-zinc-800 shadow-inner">
            <div className="flex items-center justify-between">
                <div className="flex items-center gap-3 text-zinc-500">
                    <div className="p-2 rounded-xl bg-orange-500/10 text-orange-500">
                        {icon}
                    </div>
                    <span className="text-[10px] font-bold uppercase tracking-[0.2em]">{label}</span>
                </div>
                <span className="text-2xl font-bold text-orange-500 tracking-tighter">{value}</span>
            </div>
            <input
                type="range"
                min="0"
                max="100"
                value={value}
                onChange={(e) => onChange(parseInt(e.target.value))}
                className="w-full h-1.5 bg-zinc-800 rounded-full appearance-none cursor-pointer accent-orange-600 transition-all"
            />
        </div>
    );
}
