'use client';

import React, { useState, useEffect } from 'react';
import { createClient } from '@/lib/supabase/client';
import { ChevronLeft, Users, Calendar, GlassWater, Plus, Trash2, Loader2, Sparkles, ChevronRight, Play, Square, Zap } from 'lucide-react';
import Link from 'next/link';
import AvatarStack from '@/components/AvatarStack';
import { deleteSession } from '@/services/delete-session';
import { closeSession } from '@/services/close-session';
import { useSession } from '@/context/SessionContext';
import { useParams, useRouter } from 'next/navigation';
import { useI18n } from '@/i18n/I18nContext';
import { useAuth } from '@/context/AuthContext';
import SessionTimeline from '@/components/SessionTimeline';
import SessionABVCurve from '@/components/SessionABVCurve';
import OfflineIndicator from '@/components/OfflineIndicator';
import BulkScanSheet from '@/components/BulkScanSheet';
import BottleSkeletonCard from '@/components/BottleSkeletonCard';
import ScanAndTasteFlow from '@/components/ScanAndTasteFlow';

interface Buddy {
    id: string;
    name: string;
}

interface Participant {
    buddy_id: string;
    buddies: {
        name: string;
    };
}

interface Session {
    id: string;
    name: string;
    scheduled_at: string;
    ended_at?: string;
    is_blind: boolean;
    is_revealed: boolean;
    user_id: string;
}

interface SessionTasting {
    id: string;
    rating: number;
    tasted_at: string;
    blind_label?: string;
    guess_abv?: number;
    guess_age?: number;
    guess_region?: string;
    guess_points?: number;
    bottles: {
        id: string;
        name: string;
        distillery: string;
        image_url?: string | null;
        abv: number;
        category?: string;
        processing_status?: string;
    };
    tasting_tags: {
        tags: {
            name: string;
        };
    }[];
}

export default function SessionDetailPage() {
    const { t, locale } = useI18n();
    const { id } = useParams();
    const router = useRouter();
    const { activeSession, setActiveSession } = useSession();
    const supabase = createClient();

    const [session, setSession] = useState<Session | null>(null);
    const [tastings, setTastings] = useState<SessionTasting[]>([]);
    const [participants, setParticipants] = useState<Participant[]>([]);
    const [allBuddies, setAllBuddies] = useState<Buddy[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const { user, isLoading: isAuthLoading } = useAuth();
    const [isAddingParticipant, setIsAddingParticipant] = useState(false);
    const [isDeleting, setIsDeleting] = useState(false);
    const [isClosing, setIsClosing] = useState(false);
    const [isBulkScanOpen, setIsBulkScanOpen] = useState(false);
    const [isUpdatingBlind, setIsUpdatingBlind] = useState(false);

    // New: Direct Scan Flow
    const [isScanFlowOpen, setIsScanFlowOpen] = useState(false);
    const [selectedFile, setSelectedFile] = useState<File | null>(null);
    const fileInputRef = React.useRef<HTMLInputElement>(null);

    const handleFileSelect = (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (file) {
            setSelectedFile(file);
            setIsScanFlowOpen(true);
        }
    };

    useEffect(() => {
        if (!isAuthLoading && user) {
            fetchSessionData();
        }

        // Subscribe to bottle updates for realtime processing status
        const channel = supabase
            .channel('bottle-updates')
            .on(
                'postgres_changes',
                { event: 'UPDATE', schema: 'public', table: 'bottles' },
                (payload) => {
                    // Refresh if a bottle's processing_status changed
                    if (payload.new && payload.old) {
                        if (payload.new.processing_status !== payload.old.processing_status) {
                            fetchSessionData();
                        }
                    }
                }
            )
            .subscribe();

        return () => {
            supabase.removeChannel(channel);
        };
    }, [id]);

    const fetchSessionData = async () => {
        setIsLoading(true);

        // Fetch Session
        const { data: sessionData } = await supabase
            .from('tasting_sessions')
            .select('*')
            .eq('id', id)
            .single();

        if (sessionData) {
            setSession(sessionData);

            // Fetch Participants
            const { data: partData } = await supabase
                .from('session_participants')
                .select('buddy_id, buddies(name)')
                .eq('session_id', id);

            setParticipants((partData as any)?.map((p: any) => ({
                buddy_id: p.buddy_id,
                buddies: p.buddies
            })) || []);

            // Fetch Tastings in this session
            const { data: tastingData } = await supabase
                .from('tastings')
                .select(`
                    id, 
                    rating, 
                    tasted_at, 
                    blind_label,
                    guess_abv,
                    guess_age,
                    guess_region,
                    guess_points,
                    bottles(id, name, distillery, image_url, abv, category, processing_status),
                    tasting_tags(tags(name))
                `)
                .eq('session_id', id)
                .order('tasted_at', { ascending: true });

            setTastings((tastingData as any) || []);

            // Fetch all buddies for the picker
            const { data: buddies } = await supabase
                .from('buddies')
                .select('id, name')
                .order('name');
            setAllBuddies(buddies || []);
        }

        setIsLoading(false);
    };

    const handleAddParticipant = async (buddyId: string) => {
        if (participants.some(p => p.buddy_id === buddyId)) return;

        const { data: { user } } = await supabase.auth.getUser();
        if (!user) return;

        const { error } = await supabase
            .from('session_participants')
            .insert([{
                session_id: id,
                buddy_id: buddyId,
                user_id: user.id
            }]);

        if (!error) {
            fetchSessionData();
        }
    };

    const handleRemoveParticipant = async (buddyId: string) => {
        const { error } = await supabase
            .from('session_participants')
            .delete()
            .eq('session_id', id)
            .eq('buddy_id', buddyId);

        if (!error) {
            fetchSessionData();
        }
    };

    const handleCloseSession = async () => {
        if (!confirm('Möchtest du diese Session wirklich abschließen?')) return;
        setIsClosing(true);
        const { success } = await closeSession(id as string);
        if (success) {
            if (activeSession?.id === id) {
                setActiveSession(null);
            }
            fetchSessionData();
        }
        setIsClosing(false);
    };

    const handleToggleBlindMode = async () => {
        if (!session) return;
        setIsUpdatingBlind(true);
        const { error } = await supabase
            .from('tasting_sessions')
            .update({ is_blind: !session.is_blind })
            .eq('id', id);

        if (!error) {
            fetchSessionData();
        }
        setIsUpdatingBlind(false);
    };

    const handleRevealBlindMode = async () => {
        if (!session) return;
        if (!confirm('Möchtest du alle Flaschen aufdecken?')) return;

        setIsUpdatingBlind(true);
        const { error } = await supabase
            .from('tasting_sessions')
            .update({ is_revealed: true })
            .eq('id', id);

        if (!error) {
            fetchSessionData();
        }
        setIsUpdatingBlind(false);
    };

    const calculateGuessPoints = (tasting: SessionTasting) => {
        let points = 0;

        // ABV Scoring (100 base - 10 per 1% dev)
        if (tasting.guess_abv && tasting.bottles.abv) {
            const abvDev = Math.abs(tasting.guess_abv - tasting.bottles.abv);
            points += Math.max(0, 100 - (abvDev * 10));
        }

        // Age Scoring (100 base - 5 per year dev)
        // Note: bottles table has 'age' as integer
        const bottleAge = (tasting.bottles as any).age;
        if (tasting.guess_age && bottleAge) {
            const ageDev = Math.abs(tasting.guess_age - bottleAge);
            points += Math.max(0, 100 - (ageDev * 5));
        }

        return Math.round(points);
    };

    const handleDeleteSession = async () => {
        if (!confirm('Möchtest du diese Session wirklich löschen? Alle Verknüpfungen gehen verloren.')) return;

        setIsDeleting(true);
        const result = await deleteSession(id as string);

        if (result.success) {
            if (activeSession?.id === id) {
                setActiveSession(null);
            }
            router.push('/');
        } else {
            alert(result.error);
            setIsDeleting(false);
        }
    };

    if (isLoading) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-zinc-950">
                <Loader2 size={48} className="animate-spin text-orange-600" />
            </div>
        );
    }

    if (!session) {
        return (
            <div className="min-h-screen flex flex-col items-center justify-center gap-4 bg-zinc-950 p-6">
                <h1 className="text-2xl font-bold text-zinc-50">Session nicht gefunden</h1>
                <Link href="/" className="text-orange-600 font-bold">Zurück zum Start</Link>
            </div>
        );
    }

    return (
        <main className="min-h-screen bg-[var(--background)] p-4 md:p-12 lg:p-24 pb-32">
            <div className="max-w-6xl mx-auto space-y-12">
                {/* Back Link & Info */}
                <div className="flex justify-between items-center">
                    <Link
                        href="/"
                        className="group inline-flex items-center gap-3 text-zinc-500 hover:text-orange-600 transition-all font-black uppercase text-[10px] tracking-[0.3em]"
                    >
                        <div className="p-2 rounded-full border border-zinc-800 group-hover:border-orange-500/50 transition-colors">
                            <ChevronLeft size={16} />
                        </div>
                        Alle Sessions
                    </Link>
                    <div className="flex items-center gap-4">
                        <OfflineIndicator />
                        <input
                            type="file"
                            accept="image/*"
                            capture="environment"
                            className="hidden"
                            ref={fileInputRef}
                            onChange={handleFileSelect}
                        />
                    </div>
                </div>

                {/* Immersive Header */}
                <header className="relative bg-zinc-900 border border-white/5 rounded-[48px] p-8 md:p-12 shadow-[0_20px_80px_rgba(0,0,0,0.5)] overflow-hidden group">
                    {/* Background Visuals */}
                    <div className="absolute inset-0 bg-gradient-to-br from-zinc-900 via-zinc-900 to-black z-0" />
                    {tastings.length > 0 && tastings[0].bottles.image_url && (
                        <div className="absolute top-0 right-0 w-2/3 h-full opacity-30 z-0">
                            <div
                                className="absolute inset-0 bg-cover bg-center scale-150 blur-[100px]"
                                style={{ backgroundImage: `url(${tastings[0].bottles.image_url})` }}
                            />
                        </div>
                    )}

                    {/* Decorative Rings */}
                    <div className="absolute -top-24 -right-24 w-96 h-96 border border-orange-500/10 rounded-full z-0" />
                    <div className="absolute -top-12 -right-12 w-96 h-96 border border-orange-500/5 rounded-full z-0" />

                    <div className="relative z-10 flex flex-col lg:flex-row justify-between items-start lg:items-end gap-8">
                        <div className="space-y-6 flex-1">
                            <div className="flex items-center gap-3">
                                <div className="px-3 py-1 bg-orange-600/10 border border-orange-500/20 rounded-full flex items-center gap-2">
                                    <Sparkles size={12} className="text-orange-500 animate-pulse" />
                                    <span className="text-[10px] font-black text-orange-500 uppercase tracking-[0.2em]">Tasting Session</span>
                                </div>
                                {session.ended_at && (
                                    <span className="px-3 py-1 bg-zinc-800/50 border border-zinc-700/50 rounded-full text-[10px] font-black text-zinc-500 uppercase tracking-[0.2em]">Archiviert</span>
                                )}
                                {session.is_blind && (
                                    <span className="px-3 py-1 bg-purple-600/10 border border-purple-500/20 rounded-full flex items-center gap-2">
                                        <div className="w-1.5 h-1.5 bg-purple-500 rounded-full animate-pulse" />
                                        <span className="text-[10px] font-black text-purple-500 uppercase tracking-[0.2em]">Blind Modus</span>
                                    </span>
                                )}
                                {session.is_blind && session.is_revealed && (
                                    <span className="px-3 py-1 bg-green-600/10 border border-green-500/20 rounded-full flex items-center gap-2">
                                        <Sparkles size={10} className="text-green-500" />
                                        <span className="text-[10px] font-black text-green-500 uppercase tracking-[0.2em]">Revealed</span>
                                    </span>
                                )}
                            </div>

                            <h1 className="text-5xl md:text-7xl font-black text-white tracking-tighter leading-[0.9]">
                                {session.name}
                            </h1>

                            <div className="flex flex-wrap items-center gap-4 text-zinc-400">
                                <div className="flex items-center gap-2 bg-black/30 backdrop-blur-md px-4 py-2 rounded-2xl border border-white/5 shadow-inner">
                                    <Calendar size={16} className="text-orange-600" />
                                    <span className="text-xs font-black uppercase tracking-widest">{new Date(session.scheduled_at).toLocaleDateString('de-DE')}</span>
                                </div>
                                {participants.length > 0 && (
                                    <div className="flex items-center gap-3 bg-black/30 backdrop-blur-md px-4 py-2 rounded-2xl border border-white/5">
                                        <Users size={16} className="text-orange-600" />
                                        <AvatarStack names={participants.map(p => p.buddies.name)} limit={5} />
                                    </div>
                                )}
                                <div className="flex items-center gap-2 bg-black/30 backdrop-blur-md px-4 py-2 rounded-2xl border border-white/5">
                                    <GlassWater size={16} className="text-orange-600" />
                                    <span className="text-xs font-black tracking-widest">{tastings.length} {tastings.length === 1 ? 'DRAM' : 'DRAMS'}</span>
                                </div>
                            </div>
                        </div>

                        <div className="flex flex-wrap gap-3 z-20">
                            {/* Host Controls for Blind Mode */}
                            {user?.id === session.user_id && !session.ended_at && (
                                <>
                                    <button
                                        onClick={handleToggleBlindMode}
                                        disabled={isUpdatingBlind}
                                        className={`px-6 py-4 rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center gap-3 transition-all border ${session.is_blind
                                            ? 'bg-purple-600/20 border-purple-500/50 text-purple-400'
                                            : 'bg-zinc-800/50 border-zinc-700/50 text-zinc-400 hover:border-zinc-500'
                                            }`}
                                    >
                                        {isUpdatingBlind ? <Loader2 size={16} className="animate-spin" /> : <Play size={14} className={session.is_blind ? "fill-purple-400" : ""} />}
                                        Blind Mode
                                    </button>

                                    {session.is_blind && !session.is_revealed && (
                                        <button
                                            onClick={handleRevealBlindMode}
                                            disabled={isUpdatingBlind}
                                            className="px-6 py-4 bg-green-600 hover:bg-green-500 text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center gap-3 transition-all shadow-lg shadow-green-950/20"
                                        >
                                            <Sparkles size={16} />
                                            Reveal
                                        </button>
                                    )}
                                </>
                            )}

                            {!session.ended_at && (
                                activeSession?.id !== session.id ? (
                                    <button
                                        onClick={() => setActiveSession({ id: session.id, name: session.name })}
                                        className="px-8 py-4 bg-orange-600 hover:bg-orange-500 text-white rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center gap-3 transition-all shadow-[0_10px_40px_rgba(234,88,12,0.3)] hover:-translate-y-1 active:translate-y-0"
                                    >
                                        <Play size={18} fill="currentColor" />
                                        Starten
                                    </button>
                                ) : (
                                    <button
                                        onClick={handleCloseSession}
                                        disabled={isClosing}
                                        className="px-8 py-4 bg-zinc-800/50 backdrop-blur-xl border border-zinc-700/50 text-zinc-100 hover:bg-red-600 hover:border-red-500 rounded-2xl text-[10px] font-black uppercase tracking-[0.2em] flex items-center gap-3 transition-all hover:shadow-[0_10px_40px_rgba(220,38,38,0.2)]"
                                    >
                                        {isClosing ? <Loader2 size={18} className="animate-spin" /> : <Square size={16} className="text-red-500 group-hover:text-white" fill="currentColor" />}
                                        Session Beenden
                                    </button>
                                )
                            )}
                            <button
                                onClick={handleDeleteSession}
                                disabled={isDeleting}
                                className="p-4 bg-zinc-950 border border-white/5 text-zinc-600 hover:text-red-500 rounded-2xl transition-all"
                            >
                                {isDeleting ? <Loader2 size={18} className="animate-spin" /> : <Trash2 size={18} />}
                            </button>
                        </div>
                    </div>
                </header>

                {/* Blind Mode Reveal Leaderboard */}
                {session.is_blind && session.is_revealed && (
                    <section className="bg-purple-900/10 rounded-[40px] p-8 md:p-12 border border-purple-500/30 shadow-2xl relative overflow-hidden">
                        <div className="absolute top-0 right-0 p-12 opacity-5">
                            <Sparkles size={120} className="text-purple-500" />
                        </div>

                        <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-12 relative">
                            <div className="space-y-1">
                                <h3 className="text-[10px] font-black uppercase tracking-[0.4em] text-purple-400">Leaderboard</h3>
                                <p className="text-3xl font-black text-white tracking-tight leading-none italic">Die Goldene Nase</p>
                            </div>
                            <div className="px-4 py-2 bg-purple-600/20 border border-purple-500/30 rounded-2xl text-[10px] font-black text-purple-400 uppercase tracking-widest">
                                Mystery Revealed
                            </div>
                        </div>

                        <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6 relative">
                            {tastings.map((t, idx) => {
                                const score = calculateGuessPoints(t);
                                return (
                                    <div key={t.id} className="bg-black/40 border border-white/5 rounded-[32px] p-6 group hover:border-purple-500/30 transition-all">
                                        <div className="flex justify-between items-start mb-6">
                                            <div className="w-10 h-10 bg-purple-600/20 border border-purple-500/20 rounded-full flex items-center justify-center text-xs font-black text-purple-400">
                                                {String.fromCharCode(65 + idx)}
                                            </div>
                                            <div className="text-right">
                                                <div className="text-2xl font-black text-white">{score}</div>
                                                <div className="text-[9px] font-black text-purple-400 uppercase tracking-tighter">Punkte</div>
                                            </div>
                                        </div>

                                        <div className="space-y-4">
                                            <div className="text-[11px] font-black text-zinc-300 uppercase truncate group-hover:text-white transition-colors">
                                                {t.bottles.name}
                                            </div>

                                            <div className="grid grid-cols-2 gap-2 pt-4 border-t border-white/5">
                                                <div>
                                                    <div className="text-[8px] font-black text-zinc-500 uppercase tracking-widest mb-1">Guess</div>
                                                    <div className="text-[10px] font-bold text-purple-400">
                                                        {t.guess_abv ? `${t.guess_abv}%` : '-'} / {t.guess_age ? `${t.guess_age}y` : '-'}
                                                    </div>
                                                </div>
                                                <div className="text-right">
                                                    <div className="text-[8px] font-black text-zinc-500 uppercase tracking-widest mb-1">Reality</div>
                                                    <div className="text-[10px] font-bold text-white">
                                                        {t.bottles.abv}% / {(t.bottles as any).age || '?'}y
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                );
                            })}
                        </div>
                    </section>
                )}

                <div className="grid grid-cols-1 lg:grid-cols-12 gap-12 items-start">
                    {/* Left Rail: Stats & Team */}
                    <div className="lg:col-span-4 space-y-8 lg:sticky lg:top-12">
                        {/* ABV Analysis */}
                        {tastings.length > 0 && (
                            <SessionABVCurve
                                tastings={tastings.map(t => ({
                                    id: t.id,
                                    abv: t.bottles.abv || 40,
                                    tasted_at: t.tasted_at
                                }))}
                            />
                        )}

                        {/* Team */}
                        <div className="bg-zinc-900 rounded-[32px] p-8 border border-white/5 shadow-2xl">
                            <h3 className="text-[10px] font-black uppercase tracking-[0.3em] text-zinc-500 mb-8 flex items-center justify-between">
                                <span className="flex items-center gap-2">
                                    <Users size={14} className="text-orange-600" />
                                    Crew
                                </span>
                                <span className="opacity-50">{participants.length}</span>
                            </h3>

                            <div className="space-y-4 mb-8">
                                {participants.length === 0 ? (
                                    <p className="text-[10px] text-zinc-600 font-bold uppercase italic tracking-wider">Noch keiner an Bord...</p>
                                ) : (
                                    participants.map((p) => (
                                        <div key={p.buddy_id} className="group flex items-center justify-between p-3 rounded-2xl hover:bg-white/5 transition-colors border border-transparent hover:border-white/5">
                                            <div className="flex items-center gap-3">
                                                <div className="w-8 h-8 rounded-full bg-zinc-800 flex items-center justify-center text-[10px] font-black text-orange-500 border border-white/5 uppercase">
                                                    {p.buddies.name[0]}
                                                </div>
                                                <span className="text-sm font-black text-zinc-200">{p.buddies.name}</span>
                                            </div>
                                            <button
                                                onClick={() => handleRemoveParticipant(p.buddy_id)}
                                                className="p-2 text-zinc-700 hover:text-red-500 opacity-0 group-hover:opacity-100 transition-all"
                                            >
                                                <Trash2 size={14} />
                                            </button>
                                        </div>
                                    ))
                                )}
                            </div>

                            <div className="pt-8 border-t border-white/5">
                                <p className="text-[8px] font-black uppercase tracking-widest text-zinc-600 mb-4 ml-1">Buddy hinzufügen</p>
                                <select
                                    onChange={(e) => {
                                        if (e.target.value) handleAddParticipant(e.target.value);
                                        e.target.value = "";
                                    }}
                                    className="w-full bg-zinc-950 border border-zinc-800 rounded-2xl px-4 py-3 text-[10px] font-black uppercase tracking-wider text-zinc-400 outline-none focus:border-orange-500/50 transition-colors appearance-none"
                                    style={{ backgroundImage: 'url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' fill=\'none\' viewBox=\'0 0 24 24\' stroke=\'%23a1a1aa\'%3E%3Cpath stroke-linecap=\'round\' stroke-linejoin=\'round\' stroke-width=\'2\' d=\'M19 9l-7 7-7-7\'/%3E%3C/svg%3E")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 1rem center', backgroundSize: '1rem' }}
                                >
                                    <option value="">Auswahl...</option>
                                    {allBuddies
                                        .filter(b => !participants.some(p => p.buddy_id === b.id))
                                        .map(b => (
                                            <option key={b.id} value={b.id}>{b.name}</option>
                                        ))
                                    }
                                </select>
                            </div>
                        </div>
                    </div>

                    {/* Main Feed: Timeline */}
                    <div className="lg:col-span-8 space-y-8">
                        <section className="bg-zinc-900 rounded-[40px] p-8 md:p-12 border border-white/5 shadow-2xl min-h-screen">
                            <div className="flex flex-col md:flex-row justify-between items-start md:items-center gap-6 mb-12">
                                <div className="space-y-1">
                                    <h3 className="text-[10px] font-black uppercase tracking-[0.4em] text-orange-600">Timeline</h3>
                                    <p className="text-2xl font-black text-white tracking-tight">Verkostungs-Historie</p>
                                </div>
                                <div className="flex gap-2 w-full md:w-auto">
                                    {!session.ended_at && (
                                        <button
                                            onClick={() => setIsBulkScanOpen(true)}
                                            className="flex-1 md:flex-none bg-zinc-950 border border-white/5 hover:border-orange-500/30 text-zinc-400 hover:text-orange-500 px-5 py-3 rounded-2xl text-[10px] font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all group"
                                        >
                                            <Zap size={14} className="group-hover:animate-pulse" />
                                            Bulk Scan
                                        </button>
                                    )}
                                    <button
                                        onClick={() => fileInputRef.current?.click()}
                                        className="flex-1 md:flex-none bg-orange-600 hover:bg-orange-500 text-white px-6 py-3 rounded-2xl text-[10px] font-black uppercase tracking-widest flex items-center justify-center gap-2 transition-all shadow-xl shadow-orange-950/20"
                                    >
                                        <Plus size={16} />
                                        Flasche
                                    </button>
                                </div>
                            </div>

                            <SessionTimeline
                                tastings={tastings.map(t => ({
                                    id: t.id,
                                    bottle_id: t.bottles.id,
                                    bottle_name: t.bottles.name,
                                    tasted_at: t.tasted_at,
                                    rating: t.rating,
                                    tags: t.tasting_tags?.map((tg: any) => tg.tags.name) || [],
                                    category: t.bottles.category
                                }))}
                                sessionStart={session.scheduled_at}
                                isBlind={session.is_blind}
                                isRevealed={session.is_revealed}
                            />
                        </section>
                    </div>
                </div>
            </div>

            <BulkScanSheet
                isOpen={isBulkScanOpen}
                onClose={() => setIsBulkScanOpen(false)}
                sessionId={id as string}
                sessionName={session.name}
                onSuccess={() => {
                    setIsBulkScanOpen(false);
                    fetchSessionData();
                }}
            />

            <ScanAndTasteFlow
                isOpen={isScanFlowOpen}
                onClose={() => {
                    setIsScanFlowOpen(false);
                    setSelectedFile(null);
                    if (fileInputRef.current) fileInputRef.current.value = "";
                }}
                imageFile={selectedFile}
                onBottleSaved={() => {
                    fetchSessionData();
                }}
            />
        </main>
    );
}

