import React, { useEffect, useState, useRef, useCallback, useMemo } from 'react';
import { StyleSheet, TouchableOpacity, ActivityIndicator, FlatList, ScrollView, Image, TextInput, Platform, useWindowDimensions, RefreshControl } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaEscrowProps } from '@bettoredge/types';
import { useCalcuttaAuction } from '../hooks/useCalcuttaAuction';
import { useCalcuttaCompetition } from '../hooks/useCalcuttaCompetition';
import { useCalcuttaEscrow } from '../hooks/useCalcuttaEscrow';
import { useCalcuttaBid } from '../hooks/useCalcuttaBid';
import { useCalcuttaSocket, CalcuttaPresence, CalcuttaPresencePlayer } from '../hooks/useCalcuttaSocket';
import { useCalcuttaItemImages } from '../hooks/useCalcuttaItemImages';
import { useCalcuttaPlayers } from '../hooks/useCalcuttaPlayers';
import { formatCurrency, getStatusLabel, resolveItemImageUrl } from '../helpers/formatting';
import { CalcuttaAuctionItem } from './CalcuttaAuctionItem';
import { CalcuttaEscrow } from './CalcuttaEscrow';
import { SealedBidAuction } from './sealed/SealedBidAuction';
import { AuctionPausedOverlay } from './AuctionPausedOverlay';
import { ItemSoldCelebration } from './ItemSoldCelebration';
import { AuctionCompleteOverlay } from './AuctionCompleteOverlay';

export interface CalcuttaAuctionProps {
    calcutta_competition_id: string;
    player_id?: string;
    onClose?: () => void;
    access_token?: string;
    device_id?: string;
    /** @deprecated Use access_token/device_id instead */
    getSocket?: () => WebSocket | null;
    /** @deprecated Use access_token/device_id instead */
    getAccessToken?: () => string | undefined;
    /** @deprecated Use access_token/device_id instead */
    getDeviceId?: () => string | undefined;
    player_data?: { username: string; profile_pic?: string };
    onPauseAuction?: () => Promise<void> | void;
    onResumeAuction?: () => Promise<void> | void;
    onNextItem?: () => Promise<void> | void;
    player_balance?: number;
    onDepositFunds?: (amount: number) => void;
    onManage?: () => void;
    onJoin?: () => void | Promise<void>;
    onLeave?: () => void | Promise<void>;
    onRefresh?: () => void | Promise<void>;
    onAuctionClosed?: () => void;
}

// Inner component for live auction (original layout)
const LiveAuction: React.FC<CalcuttaAuctionProps> = ({
    calcutta_competition_id,
    player_id,
    onClose,
    access_token,
    device_id,
    player_data,
    onPauseAuction,
    onResumeAuction,
    onNextItem,
    player_balance,
    onDepositFunds,
    onRefresh,
    onAuctionClosed: onAuctionClosedProp,
}) => {
    const { theme } = useTheme();
    const { width: windowWidth } = useWindowDimensions();
    const [containerWidth, setContainerWidth] = useState(0);
    const measuredWidth = containerWidth || windowWidth;
    const isDesktop = Platform.OS === 'web' && measuredWidth >= 700;
    const [refreshing, setRefreshing] = useState(false);
    const {
        loading,
        competition,
        items,
        bids,
        my_bids,
        paused,
        escrow_summaries,
        total_escrow_balance,
        refresh: refreshAuction,
        stopPolling,
        handleBidUpdate,
        handleItemActive,
        handleItemSold,
        handleItemUnsold,
        handleAuctionPaused,
        handleAuctionResumed,
        handleAuctionClosed,
    } = useCalcuttaAuction(calcutta_competition_id, 5000, player_id);

    const { rounds, payout_rules } = useCalcuttaCompetition(calcutta_competition_id);
    const { escrow, fetchEscrow, updateEscrowLocally } = useCalcuttaEscrow(calcutta_competition_id);
    const { placeBid, loading: bidLoading } = useCalcuttaBid();
    const { images: itemImages } = useCalcuttaItemImages(items);

    const isAdmin = player_id != null && competition?.admin_id === player_id;

    const handleRefresh = async () => {
        setRefreshing(true);
        try {
            await Promise.all([refreshAuction(), fetchEscrow(), onRefresh?.()]);
        } catch {} finally { setRefreshing(false); }
    };

    // Auction complete overlay
    const [showAuctionComplete, setShowAuctionComplete] = useState(false);

    const wrappedHandleAuctionClosed = useCallback((data: any) => {
        handleAuctionClosed(data);
        // Show complete overlay after a short delay (let last item celebration finish)
        setTimeout(() => setShowAuctionComplete(true), 1000);
        onAuctionClosedProp?.();
    }, [handleAuctionClosed, onAuctionClosedProp]);

    // Celebration modal state
    const [celebrationData, setCelebrationData] = useState<{
        item?: any;
        winnerName?: string;
        winnerProfilePic?: string;
        winningBid?: number;
        isMe?: boolean;
        nextItem?: any;
        nextItemDeadline?: string;
        itemImage?: string;
    } | null>(null);

    // Wrap socket handlers to intercept item sold/active for celebration
    const wrappedHandleItemSold = useCallback((data: any) => {
        handleItemSold(data);

        // Find next pending item to preview
        const nextPending = items.find(i =>
            i.status === 'pending' && i.calcutta_auction_item_id !== data.item.calcutta_auction_item_id
        );

        setCelebrationData({
            item: data.item,
            winnerName: data.winning_player_id === player_id ? 'You' : undefined,
            winningBid: data.winning_bid?.bid_amount ?? data.item.winning_bid,
            isMe: data.winning_player_id === player_id,
            nextItem: nextPending,
            itemImage: itemImages[data.item.item_id]?.url,
        });
    }, [handleItemSold, items, player_id, itemImages]);

    const wrappedHandleItemUnsold = useCallback((data: any) => {
        handleItemUnsold(data);

        const nextPending = items.find(i =>
            i.status === 'pending' && i.calcutta_auction_item_id !== data.item.calcutta_auction_item_id
        );

        setCelebrationData({
            item: data.item,
            winnerName: undefined,
            winningBid: 0,
            isMe: false,
            nextItem: nextPending,
        });
    }, [handleItemUnsold, items]);

    // Socket connection for live auctions
    const { connected, presence, broadcast } = useCalcuttaSocket(
        calcutta_competition_id,
        access_token,
        device_id,
        player_data || { username: '' },
        {
            onBidUpdate: (data: any) => {
                handleBidUpdate(data);
                // Update escrow from socket — check if our player's escrow is in the update
                if (player_id && data.escrow_updates?.[player_id]) {
                    updateEscrowLocally(data.escrow_updates[player_id]);
                }
            },
            onItemActive: handleItemActive,
            onItemSold: wrappedHandleItemSold,
            onItemUnsold: wrappedHandleItemUnsold,
            onAuctionPaused: handleAuctionPaused,
            onAuctionResumed: handleAuctionResumed,
            onAuctionClosed: wrappedHandleAuctionClosed,
            onRefresh: () => { refreshAuction(); },
        },
    );

    // Resolve player profiles for bidders, winners, and presence
    const bidderIds = useMemo(() => {
        const ids = new Set(bids.map(b => b.player_id).filter(Boolean));
        items.forEach(i => { if (i.winning_player_id) ids.add(i.winning_player_id); });
        (presence?.players || []).forEach(p => { if (p.player_id) ids.add(p.player_id); });
        return [...ids];
    }, [bids, items, presence?.players]);
    const { players: bidderProfiles } = useCalcuttaPlayers(bidderIds);

    // Initial escrow fetch on mount
    useEffect(() => {
        fetchEscrow();
    }, []);

    const handlePlaceBid = async (calcutta_auction_item_id: string, amount: number) => {
        const bid = await placeBid(calcutta_auction_item_id, amount);
        // Refresh own auction state + escrow immediately
        refreshAuction();
        fetchEscrow();
        // Broadcast to other clients via direct WS relay
        if (bid) {
            broadcast({ type: 'CALCUTTA_REFRESH', reason: 'bid' });
        }
    };

    const [escrowExpanded, setEscrowExpanded] = useState(true);
    const [hasAutoCollapsed, setHasAutoCollapsed] = useState(false);

    // Auto-collapse escrow panel once funds are loaded
    useEffect(() => {
        if (!hasAutoCollapsed && escrow && Number(escrow.escrow_balance) > 0) {
            setEscrowExpanded(false);
            setHasAutoCollapsed(true);
        }
    }, [escrow, hasAutoCollapsed]);

    // Presence bar visibility
    const [showPresenceList, setShowPresenceList] = useState(false);
    const [infoTab, setInfoTab] = useState<'items' | 'players' | 'escrow' | 'info' | 'completed_desktop' | null>('items');
    const [selectedPlayerId, setSelectedPlayerId] = useState<string | null>(null);

    const livePot = useMemo(() =>
        items.filter((i: any) => i.status === 'sold').reduce((sum: number, i: any) => sum + Number(i.winning_bid || 0), 0) || Number(competition?.total_pot) || 0,
        [items, competition?.total_pot]
    );

    if (loading && !competition) {
        return (
            <View variant="transparent" style={[styles.loadingContainer, { backgroundColor: theme.colors.surface.base }]}>
                <ActivityIndicator size="large" color={theme.colors.primary.default} />
            </View>
        );
    }

    if (!competition) {
        return (
            <View variant="transparent" style={[styles.loadingContainer, { backgroundColor: theme.colors.surface.base }]}>
                <Text variant="body" color="secondary">Auction not found</Text>
            </View>
        );
    }

    const activeItem = items.find(i => i.calcutta_auction_item_id === competition.current_auction_item_id);
    const activeMyBid = activeItem ? my_bids.find(b => b.calcutta_auction_item_id === activeItem.calcutta_auction_item_id && b.bid_status === 'active') : undefined;

    // Resolve highest bidder for active item
    const activeHighestBid = activeItem
        ? bids.filter(b => b.calcutta_auction_item_id === activeItem.calcutta_auction_item_id && b.bid_status === 'active')
            .sort((a, b) => Number(b.bid_amount) - Number(a.bid_amount))[0]
        : undefined;
    const activeHighestBidder = activeHighestBid
        ? {
            username: activeHighestBid.player_id === player_id
                ? player_data?.username
                : bidderProfiles[activeHighestBid.player_id]?.username || presence.players.find(p => p.player_id === activeHighestBid.player_id)?.username,
            profile_pic: activeHighestBid.player_id === player_id
                ? player_data?.profile_pic
                : bidderProfiles[activeHighestBid.player_id]?.profile_pic,
            is_me: activeHighestBid.player_id === player_id,
        }
        : undefined;
    const pendingItems = items.filter(i => i.status === 'pending' && i.calcutta_auction_item_id !== competition.current_auction_item_id);
    const completedItems = items.filter(i => ['sold', 'unsold'].includes(i.status));

    // ═══ SHARED RENDER HELPERS ═══

    const renderItemRow = (item: any) => {
        const myBid = my_bids.find((b: any) => b.calcutta_auction_item_id === item.calcutta_auction_item_id && (item.status === 'sold' || item.status === 'unsold' ? true : b.bid_status === 'active'));
        const itemWinner = item.winning_player_id ? (() => {
            const wp = bidderProfiles[item.winning_player_id];
            return wp ? { username: wp.username || wp.show_name, profile_pic: wp.profile_pic, is_me: item.winning_player_id === player_id }
                : item.winning_player_id === player_id ? { username: player_data?.username, profile_pic: player_data?.profile_pic, is_me: true } : undefined;
        })() : undefined;
        return (
            <CalcuttaAuctionItem
                key={item.calcutta_auction_item_id}
                item={item}
                my_bid={myBid}
                auction_type="live"
                min_bid={competition.min_bid}
                bid_increment={competition.bid_increment}
                escrow_balance={escrow?.escrow_balance ?? 0}
                onPlaceBid={(amount) => handlePlaceBid(item.calcutta_auction_item_id, amount)}
                is_active_item={false}
                is_paused={paused}
                itemImage={itemImages[item.item_id]}
                winner={itemWinner}
            />
        );
    };

    const renderPotBar = () => (
        <View variant="transparent" style={{ flexDirection: 'row', paddingHorizontal: 12, paddingVertical: 8, gap: 12 }}>
            <View variant="transparent" style={{ flex: 1, backgroundColor: theme.colors.surface.elevated, borderRadius: 10, padding: 10, alignItems: 'center', borderWidth: 1, borderColor: theme.colors.border.subtle }}>
                <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Pot</Text>
                <Text variant="h3" bold style={{ color: '#F59E0B' }}>{formatCurrency(livePot, competition.market_type)}</Text>
            </View>
            <View variant="transparent" style={{ flex: 1, backgroundColor: theme.colors.surface.elevated, borderRadius: 10, padding: 10, alignItems: 'center', borderWidth: 1, borderColor: theme.colors.border.subtle }}>
                <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Total Escrow</Text>
                <Text variant="h3" bold>{formatCurrency(total_escrow_balance, competition.market_type)}</Text>
            </View>
            <View variant="transparent" style={{ flex: 1, backgroundColor: theme.colors.surface.elevated, borderRadius: 10, padding: 10, alignItems: 'center', borderWidth: 1, borderColor: theme.colors.border.subtle }}>
                <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Items Sold</Text>
                <Text variant="h3" bold>{completedItems.filter(i => i.status === 'sold').length}/{items.length}</Text>
            </View>
        </View>
    );

    const renderAdminControls = () => {
        if (!isAdmin || competition.auction_status !== 'in_progress' || paused) return null;
        return (
            <View variant="transparent" style={{ flexDirection: 'row', justifyContent: 'flex-end', padding: 10, gap: 8 }}>
                {onPauseAuction && (
                    <TouchableOpacity
                        style={[styles.adminButton, { backgroundColor: theme.colors.status.error + '15', flexDirection: 'row', paddingHorizontal: 12 }]}
                        onPress={async () => { await onPauseAuction?.(); refreshAuction(); broadcast({ type: 'CALCUTTA_REFRESH', reason: 'paused' }); }}
                    >
                        <Ionicons name="pause" size={14} color={theme.colors.status.error} />
                        <Text variant="caption" bold style={{ color: theme.colors.status.error, marginLeft: 6 }}>Pause</Text>
                    </TouchableOpacity>
                )}
                {onNextItem && (
                    <TouchableOpacity
                        style={[styles.adminButton, { backgroundColor: theme.colors.primary.subtle, flexDirection: 'row', paddingHorizontal: 12 }]}
                        onPress={async () => { await onNextItem?.(); refreshAuction(); fetchEscrow(); broadcast({ type: 'CALCUTTA_REFRESH', reason: 'next_item' }); }}
                    >
                        <Ionicons name="play-skip-forward" size={14} color={theme.colors.primary.default} />
                        <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 6 }}>Next Item</Text>
                    </TouchableOpacity>
                )}
            </View>
        );
    };

    const renderActiveItem = () => {
        if (!activeItem) return null;
        return (
            <CalcuttaAuctionItem
                item={activeItem}
                my_bid={activeMyBid}
                auction_type="live"
                min_bid={competition.min_bid}
                bid_increment={competition.bid_increment}
                escrow_balance={escrow?.escrow_balance ?? 0}
                onPlaceBid={(amount) => handlePlaceBid(activeItem.calcutta_auction_item_id, amount)}
                is_active_item
                is_paused={paused}
                itemImage={itemImages[activeItem.item_id]}
                highest_bidder={activeHighestBidder}
            />
        );
    };

    const renderPlayersContent = () => (
        <View variant="transparent">
            {(presence?.players || []).length > 0 ? (presence?.players || []).map((p: any) => {
                const profile = bidderProfiles[p.player_id];
                const profilePic = profile?.profile_pic || p.profile_pic;
                const username = profile?.username || p.username || 'Player';
                const isMe = p.player_id === player_id;
                const isSelected = selectedPlayerId === p.player_id;
                const wonItems = items.filter((i: any) => i.winning_player_id === p.player_id && i.status === 'sold');
                return (
                    <View key={p.player_id} variant="transparent">
                        <TouchableOpacity style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 8 }} onPress={() => setSelectedPlayerId(isSelected ? null : p.player_id)} activeOpacity={0.7}>
                            {profilePic ? (
                                <Image source={{ uri: profilePic }} style={{ width: 28, height: 28, borderRadius: 14 }} />
                            ) : (
                                <View variant="transparent" style={{ width: 28, height: 28, borderRadius: 14, backgroundColor: isMe ? '#10B98120' : theme.colors.primary.subtle, alignItems: 'center', justifyContent: 'center' }}>
                                    <Text variant="caption" bold style={{ fontSize: 12, lineHeight: 16, color: isMe ? '#10B981' : theme.colors.primary.default }}>{username.charAt(0).toUpperCase()}</Text>
                                </View>
                            )}
                            <View variant="transparent" style={{ flex: 1, marginLeft: 10 }}>
                                <Text variant="body" bold={isMe} style={isMe ? { color: '#10B981' } : undefined}>{isMe ? 'You' : username}</Text>
                                <Text variant="caption" color="tertiary">
                                    {wonItems.length > 0 ? `${wonItems.length} item${wonItems.length !== 1 ? 's' : ''} won` : 'No items'}
                                    {escrow_summaries[p.player_id] ? ` · ${formatCurrency(escrow_summaries[p.player_id].escrow_balance, competition.market_type)} avail` : ''}
                                </Text>
                            </View>
                            <View variant="transparent" style={{ width: 8, height: 8, borderRadius: 4, backgroundColor: '#10B981' }} />
                            {wonItems.length > 0 && <Ionicons name={isSelected ? 'chevron-up' : 'chevron-down'} size={14} color={theme.colors.text.tertiary} style={{ marginLeft: 8 }} />}
                        </TouchableOpacity>
                        {isSelected && wonItems.length > 0 && (
                            <View variant="transparent" style={{ paddingLeft: 38, paddingBottom: 8 }}>
                                {wonItems.map((wi: any) => (
                                    <View key={wi.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 4 }}>
                                        <Ionicons name="trophy" size={12} color="#F59E0B" />
                                        <Text variant="caption" style={{ marginLeft: 6, flex: 1 }}>{wi.item_name}</Text>
                                        <Text variant="caption" bold>{formatCurrency(wi.winning_bid, competition.market_type)}</Text>
                                    </View>
                                ))}
                            </View>
                        )}
                    </View>
                );
            }) : (
                <Text variant="caption" color="tertiary">No players connected</Text>
            )}
        </View>
    );

    const renderEscrowContent = () => (
        <CalcuttaEscrow
            calcutta_competition_id={calcutta_competition_id}
            escrow={escrow ?? undefined}
            market_type={competition.market_type}
            max_escrow={competition.max_escrow}
            player_balance={player_balance}
            onDepositFunds={onDepositFunds}
            onUpdate={() => fetchEscrow()}
        />
    );

    const renderInfoContent = () => {
        const livePot = items.filter((it: any) => it.status === 'sold').reduce((sum: number, it: any) => sum + Number(it.winning_bid || 0), 0) || Number(competition.total_pot) || 0;
        return (
            <View variant="transparent">
                {!isDesktop && competition.image?.url && (
                    <Image source={{ uri: competition.image.url }} style={{ width: '100%', height: 120, borderRadius: 10, marginBottom: 12 }} resizeMode="cover" />
                )}
                {isDesktop && competition.image?.url && (
                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 10 }}>
                        <Image source={{ uri: competition.image.url }} style={{ width: 40, height: 40, borderRadius: 8, marginRight: 10 }} resizeMode="cover" />
                        <View variant="transparent" style={{ flex: 1 }}>
                            <Text variant="body" bold>{competition.competition_name}</Text>
                            {competition.competition_description ? <Text variant="caption" color="secondary" numberOfLines={2}>{competition.competition_description}</Text> : null}
                        </View>
                    </View>
                )}
                {!(isDesktop && competition.image?.url) && (
                    <>
                        <Text variant="body" bold>{competition.competition_name}</Text>
                        {competition.competition_description ? <Text variant="caption" color="secondary" style={{ marginTop: 4 }}>{competition.competition_description}</Text> : null}
                    </>
                )}

                <View variant="transparent" style={{ marginTop: 14, borderTopWidth: 1, borderTopColor: theme.colors.border.subtle, paddingTop: 12 }}>
                    <Text variant="caption" bold color="tertiary" style={{ textTransform: 'uppercase', letterSpacing: 1, marginBottom: 8, fontSize: 10, lineHeight: 13 }}>Auction Settings</Text>
                    {[
                        ['Type', competition.auction_type === 'live' ? 'Live Auction' : competition.auction_type === 'sealed_bid' ? 'Sealed Bid' : 'Sweepstakes'],
                        ['Entry Fee', Number(competition.entry_fee) > 0 ? formatCurrency(competition.entry_fee, competition.market_type) : 'Free'],
                        Number(competition.min_bid) > 0 ? ['Min Bid', formatCurrency(competition.min_bid, competition.market_type)] : null,
                        Number(competition.bid_increment) > 0 ? ['Bid Increment', formatCurrency(competition.bid_increment, competition.market_type)] : null,
                        Number(competition.item_timer_seconds) > 0 ? ['Timer per Item', `${competition.item_timer_seconds}s`] : null,
                        Number(competition.bid_extension_seconds) > 0 ? ['Bid Extension', `${competition.bid_extension_seconds}s`] : null,
                        Number(competition.max_escrow) > 0 ? ['Budget Cap', formatCurrency(competition.max_escrow, competition.market_type)] : null,
                        Number(competition.min_spend_pct) > 0 ? ['Min Spend', `${competition.min_spend_pct}%`] : null,
                        ['Items', `${items.length}`],
                    ].filter(Boolean).map((row: any, i) => (
                        <View key={i} variant="transparent" style={styles.infoRow}>
                            <Text variant="caption" color="secondary">{row[0]}</Text>
                            <Text variant="caption" bold>{row[1]}</Text>
                        </View>
                    ))}
                </View>

                {payout_rules.length > 0 && (
                    <View variant="transparent" style={{ marginTop: 14, borderTopWidth: 1, borderTopColor: theme.colors.border.subtle, paddingTop: 12 }}>
                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 }}>
                            <Text variant="caption" bold color="tertiary" style={{ textTransform: 'uppercase', letterSpacing: 1, fontSize: 10, lineHeight: 13 }}>Payouts</Text>
                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 8, backgroundColor: '#10B98115', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 6 }}>
                                <View variant="transparent" style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: '#10B981', marginRight: 4 }} />
                                <Text variant="caption" bold style={{ color: '#10B981', fontSize: 9, lineHeight: 12 }}>LIVE</Text>
                            </View>
                            <View variant="transparent" style={{ flex: 1 }} />
                            <Text variant="caption" bold>Pot: {formatCurrency(livePot, competition.market_type)}</Text>
                        </View>
                        {payout_rules.map((rule: any, i: number) => {
                            const round = rounds.find((r: any) => r.round_number === rule.round_number);
                            const amount = livePot > 0 ? (Number(rule.payout_pct) / 100) * livePot : 0;
                            return (
                                <View key={rule.calcutta_payout_rule_id || `r-${i}`} variant="transparent" style={styles.infoRow}>
                                    <Text variant="caption" color="secondary">{rule.description || round?.round_name || `Round ${rule.round_number}`}</Text>
                                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center' }}>
                                        <Text variant="caption" bold>{rule.payout_pct}%</Text>
                                        <Text variant="caption" bold style={{ marginLeft: 8, color: '#10B981' }}>{formatCurrency(amount, competition.market_type)}</Text>
                                    </View>
                                </View>
                            );
                        })}
                    </View>
                )}
            </View>
        );
    };

    // ═══ RENDER ═══

    return (
        <View variant="transparent" style={[styles.container, { backgroundColor: theme.colors.surface.base }]} onLayout={(e) => setContainerWidth(e.nativeEvent.layout.width)}>
            {/* Overlays */}
            <AuctionPausedOverlay
                visible={paused}
                isAdmin={isAdmin}
                onResume={async () => { await onResumeAuction?.(); refreshAuction(); broadcast({ type: 'CALCUTTA_REFRESH', reason: 'resumed' }); }}
            />
            <ItemSoldCelebration
                visible={!!celebrationData}
                item={celebrationData?.item}
                winnerName={celebrationData?.winnerName}
                winnerProfilePic={celebrationData?.winnerProfilePic}
                winningBid={celebrationData?.winningBid}
                isMe={celebrationData?.isMe}
                marketType={competition.market_type}
                nextItem={celebrationData?.nextItem}
                itemImage={celebrationData?.itemImage}
                autoDismissMs={5000}
                onDismiss={() => setCelebrationData(null)}
            />

            <AuctionCompleteOverlay
                visible={showAuctionComplete}
                competitionName={competition.competition_name}
                totalPot={Number(competition.total_pot) || items.filter(i => i.status === 'sold').reduce((sum, i) => sum + Number(i.winning_bid || 0), 0)}
                marketType={competition.market_type}
                myItemsWon={items.filter(i => i.status === 'sold' && i.winning_player_id === player_id)}
                myTotalSpent={items.filter(i => i.status === 'sold' && i.winning_player_id === player_id).reduce((sum, i) => sum + Number(i.winning_bid || 0), 0)}
                leaderboard={(() => {
                    const soldItems = items.filter(i => i.status === 'sold' && i.winning_player_id);
                    const playerMap: Record<string, { items_won: number; total_spent: number }> = {};
                    soldItems.forEach(i => {
                        if (!playerMap[i.winning_player_id!]) playerMap[i.winning_player_id!] = { items_won: 0, total_spent: 0 };
                        playerMap[i.winning_player_id!].items_won++;
                        playerMap[i.winning_player_id!].total_spent += Number(i.winning_bid || 0);
                    });
                    return Object.entries(playerMap)
                        .map(([pid, data]) => ({
                            player_id: pid,
                            username: bidderProfiles[pid]?.username || bidderProfiles[pid]?.show_name,
                            profile_pic: bidderProfiles[pid]?.profile_pic,
                            is_me: pid === player_id,
                            ...data,
                        }))
                        .sort((a, b) => b.total_spent - a.total_spent);
                })()}
                onDismiss={() => {
                    setShowAuctionComplete(false);
                    refreshAuction();
                }}
            />

            {isDesktop ? (
                /* ═══════════════════════════════════════
                   DESKTOP LAYOUT
                   Top bar: escrow summary + admin controls
                   Full width: Active item
                   Below: [Items (paginated)] [Players] [Info]
                   ═══════════════════════════════════════ */
                <ScrollView style={{ flex: 1 }} contentContainerStyle={{ padding: 12, paddingBottom: 40 }} keyboardShouldPersistTaps="handled" refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}>
                    {/* Top bar: escrow + admin */}
                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 12, zIndex: 200 }}>
                        <View variant="transparent" style={{ position: 'relative', zIndex: 200 }}>
                            <TouchableOpacity
                                style={[styles.desktopPanel, { flexDirection: 'row', alignItems: 'center', backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, paddingVertical: 8 }]}
                                onPress={() => setInfoTab(infoTab === 'escrow' ? null : 'escrow')}
                                activeOpacity={0.7}
                            >
                                <Ionicons name="wallet-outline" size={16} color={theme.colors.text.secondary} />
                                <Text variant="body" bold style={{ marginLeft: 8 }}>{escrow ? formatCurrency(escrow.escrow_balance, competition.market_type) : '$0.00'}</Text>
                                {escrow && Number(escrow.committed_balance) > 0 && (
                                    <Text variant="caption" color="tertiary" style={{ marginLeft: 6 }}>({formatCurrency(escrow.committed_balance, competition.market_type)} held)</Text>
                                )}
                                <Ionicons name={infoTab === 'escrow' ? 'chevron-up' : 'chevron-down'} size={14} color={theme.colors.text.tertiary} style={{ marginLeft: 8 }} />
                            </TouchableOpacity>

                            {/* Escrow popover */}
                            {infoTab === 'escrow' && (
                                <View variant="transparent" style={[styles.desktopPanel, {
                                    position: 'absolute',
                                    top: '100%',
                                    left: 0,
                                    marginTop: 4,
                                    width: 380,
                                    backgroundColor: theme.colors.surface.elevated,
                                    borderColor: theme.colors.border.subtle,
                                    zIndex: 100,
                                    shadowColor: '#000',
                                    shadowOffset: { width: 0, height: 8 },
                                    shadowOpacity: 0.25,
                                    shadowRadius: 16,
                                    elevation: 10,
                                }]}>
                                    {renderEscrowContent()}
                                </View>
                            )}
                        </View>

                        <View variant="transparent" style={{ flex: 1 }} />
                        {renderAdminControls()}
                    </View>

                    <View variant="transparent" style={{ zIndex: 1 }}>
                    {renderPotBar()}

                    {/* Row 1: Active item + Up Next (same height) */}
                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12 }}>
                        {/* Active item */}
                        <View variant="transparent" style={{ flex: 3 }}>
                            {renderActiveItem() || (
                                <View variant="transparent" style={[styles.desktopPanel, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, alignItems: 'center', justifyContent: 'center', flex: 1 }]}>
                                    <Ionicons name="hammer-outline" size={32} color={theme.colors.text.tertiary} />
                                    <Text variant="caption" color="tertiary" style={{ marginTop: 8 }}>No active item</Text>
                                </View>
                            )}
                        </View>

                        {/* Up Next — matches active item height */}
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 2, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" bold color="tertiary" style={[styles.panelTitle, { marginBottom: 8 }]}>Up Next ({pendingItems.length})</Text>
                            <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false} style={{ flex: 1 }}>
                                {pendingItems.length > 0 ? pendingItems.map(item => renderItemRow(item)) : (
                                    <Text variant="caption" color="tertiary">No items in queue</Text>
                                )}
                            </ScrollView>
                        </View>
                    </View>

                    {/* Row 2: Completed + Players + Info */}
                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12, marginTop: 12 }}>
                        {/* Completed */}
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 3, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" bold color="tertiary" style={[styles.panelTitle, { marginBottom: 8 }]}>Completed ({completedItems.length})</Text>
                            <ScrollView style={{ maxHeight: 250 }} nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {completedItems.length > 0 ? completedItems.map(item => renderItemRow(item)) : (
                                    <Text variant="caption" color="tertiary">No items sold yet</Text>
                                )}
                            </ScrollView>
                        </View>

                        {/* Players */}
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 2, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 8 }}>
                                <Text variant="caption" bold color="tertiary" style={styles.panelTitle}>Players</Text>
                                {(presence?.count || 0) > 0 && (
                                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 8, backgroundColor: '#10B98115', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 6 }}>
                                        <View variant="transparent" style={{ width: 5, height: 5, borderRadius: 3, backgroundColor: '#10B981', marginRight: 4 }} />
                                        <Text variant="caption" bold style={{ color: '#10B981', fontSize: 9, lineHeight: 12 }}>{presence.count} LIVE</Text>
                                    </View>
                                )}
                            </View>
                            <ScrollView style={{ maxHeight: 250 }} nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {renderPlayersContent()}
                            </ScrollView>
                        </View>

                        {/* Info + Payouts */}
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 2, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <ScrollView style={{ maxHeight: 250 }} nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {renderInfoContent()}
                            </ScrollView>
                        </View>
                    </View>
                    </View>
                </ScrollView>
            ) : (
                /* ═══════════════════════════════════════
                   MOBILE LAYOUT — tabs
                   ═══════════════════════════════════════ */
                <FlatList
                    data={(() => {
                        if (infoTab !== 'items') return [];
                        const rows: { type: string; item?: any; label?: string; key: string }[] = [];
                        if (pendingItems.length > 0) {
                            rows.push({ type: 'header', label: `Up Next (${pendingItems.length})`, key: 'h-pending' });
                            pendingItems.forEach(i => rows.push({ type: 'item', item: i, key: i.calcutta_auction_item_id }));
                        }
                        if (completedItems.length > 0) {
                            rows.push({ type: 'header', label: `Completed (${completedItems.length})`, key: 'h-completed' });
                            completedItems.forEach(i => rows.push({ type: 'item', item: i, key: i.calcutta_auction_item_id }));
                        }
                        if (rows.length === 0) {
                            rows.push({ type: 'empty', key: 'empty' });
                        }
                        return rows;
                    })()}
                    keyExtractor={row => row.key}
                    keyboardShouldPersistTaps="handled"
                    contentContainerStyle={{ paddingBottom: 40 }}
                    style={{ backgroundColor: theme.colors.surface.base }}
                    refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}
                    extraData={`${infoTab}-${items.map(i => `${i.calcutta_auction_item_id}:${i.status}:${i.current_bid}`).join(',')}-${my_bids.length}-${paused}-${escrow?.escrow_balance}`}
                    ListHeaderComponent={
                        <View variant="transparent">
                            {renderAdminControls()}
                            {renderPotBar()}
                            {renderActiveItem()}

                            {/* Tabs */}
                            <View variant="transparent" style={{ flexDirection: 'row', paddingHorizontal: 12, paddingTop: 10, gap: 6 }}>
                                {([
                                    { key: 'items' as const, icon: 'list-outline', label: `Items (${items.length})` },
                                    { key: 'players' as const, icon: 'people-outline', label: (presence?.count || 0) > 0 ? `${presence.count} Live` : 'Players' },
                                    { key: 'escrow' as const, icon: 'wallet-outline', label: escrow ? formatCurrency(escrow.escrow_balance, competition.market_type) : '$0.00' },
                                    { key: 'info' as const, icon: 'information-circle-outline', label: 'Info' },
                                ]).map(tab => {
                                    const active = infoTab === tab.key;
                                    return (
                                        <TouchableOpacity
                                            key={tab.key}
                                            style={[styles.infoTabBtn, {
                                                backgroundColor: active ? theme.colors.primary.default : theme.colors.surface.elevated,
                                                borderColor: active ? theme.colors.primary.default : theme.colors.border.subtle,
                                            }]}
                                            onPress={() => setInfoTab(infoTab === tab.key ? null : tab.key)}
                                            activeOpacity={0.7}
                                        >
                                            <Ionicons name={tab.icon as any} size={13} color={active ? '#FFFFFF' : theme.colors.text.secondary} />
                                            <Text variant="caption" bold style={{ color: active ? '#FFFFFF' : theme.colors.text.secondary, marginLeft: 4, fontSize: 11, lineHeight: 15 }}>
                                                {tab.label}
                                            </Text>
                                        </TouchableOpacity>
                                    );
                                })}
                            </View>

                            {infoTab === 'players' && (
                                <View variant="transparent" style={[styles.infoTabContent, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                                    {renderPlayersContent()}
                                </View>
                            )}
                            {infoTab === 'escrow' && (
                                <View variant="transparent" style={[styles.infoTabContent, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                                    {renderEscrowContent()}
                                </View>
                            )}
                            {infoTab === 'info' && (
                                <View variant="transparent" style={[styles.infoTabContent, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                                    {renderInfoContent()}
                                </View>
                            )}
                        </View>
                    }
                    renderItem={({ item: row }) => {
                        if (row.type === 'header') {
                            return (
                                <View variant="transparent" style={{ paddingHorizontal: 14, paddingTop: 16, paddingBottom: 6 }}>
                                    <Text variant="caption" bold color="tertiary" style={{ textTransform: 'uppercase', letterSpacing: 1 }}>
                                        {row.label}
                                    </Text>
                                </View>
                            );
                        }
                        if (row.type === 'empty') {
                            return <Text variant="caption" color="tertiary" style={styles.emptyText}>No auction items available</Text>;
                        }
                        return renderItemRow(row.item);
                    }}
                />
            )}
        </View>
    );
};

// Sweepstakes: no auction, show the player's assigned item and prize structure
const SweepstakesWaiting: React.FC<CalcuttaAuctionProps & { competition: any }> = ({
    calcutta_competition_id,
    player_id,
    onClose,
    onManage,
    onRefresh,
    competition,
}) => {
    const { theme } = useTheme();
    const { items, rounds, participants, item_results, refresh } = useCalcuttaCompetition(calcutta_competition_id);
    const { images: itemImages } = useCalcuttaItemImages(items);
    const isAdmin = player_id != null && competition?.admin_id == player_id;
    const [refreshing, setRefreshing] = useState(false);
    const handleRefresh = async () => {
        setRefreshing(true);
        try { await Promise.all([refresh(), onRefresh?.()]); }
        catch {} finally { setRefreshing(false); }
    };

    // Build player lookup for owner usernames
    const ownerIds = items.filter(i => i.winning_player_id).map(i => i.winning_player_id!);
    const { players: enrichedPlayers } = useCalcuttaPlayers(ownerIds);

    const [searchQuery, setSearchQuery] = useState('');

    const [expandedRound, setExpandedRound] = useState<string | null>(null);

    const myItem = items.find(i => i.winning_player_id == player_id);
    const myItems = items.filter(i => i.winning_player_id == player_id).sort((a, b) => Number(b.winning_bid || 0) - Number(a.winning_bid || 0));
    const isSweepstakes = competition.auction_type === 'sweepstakes';
    const sortedRounds = [...(rounds ?? [])].sort((a, b) => a.round_number - b.round_number);

    const filteredItems = useMemo(() => {
        if (!searchQuery.trim()) return items;
        const q = searchQuery.toLowerCase().trim();
        return items.filter(item => {
            if (item.item_name.toLowerCase().includes(q)) return true;
            if (item.winning_player_id) {
                const owner = enrichedPlayers[item.winning_player_id];
                const ownerName = (owner?.username || owner?.show_name || '').toLowerCase();
                if (ownerName.includes(q)) return true;
            }
            return false;
        });
    }, [items, searchQuery, enrichedPlayers]);
    const statusLabel = competition.status === 'inprogress' ? 'In Progress'
        : competition.status === 'closed' ? 'Completed' : 'Scheduled';

    const statusColor = competition.status === 'inprogress' ? '#8B5CF6'
        : competition.status === 'closed' ? '#6B7280'
        : '#10B981';

    return (
        <View variant="transparent" style={[styles.container, { backgroundColor: theme.colors.surface.base }]}>
            <ScrollView style={{ flex: 1, backgroundColor: theme.colors.surface.base }} contentContainerStyle={{ gap: 16, paddingBottom: Platform.OS === 'web' ? 300 : 40, backgroundColor: theme.colors.surface.base }} keyboardShouldPersistTaps="handled" refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}>
                {/* Hero with embedded title */}
                <View style={{ position: 'relative' }}>
                    {competition.image?.url ? (
                        <Image source={{ uri: competition.image.url }} style={{ width: '100%', aspectRatio: 16 / 9 }} resizeMode="cover" />
                    ) : (
                        <View variant="transparent" style={{ width: '100%', aspectRatio: 16 / 9, backgroundColor: '#1e1b4b' }} />
                    )}
                    {/* Dark overlay for text readability */}
                    <View variant="transparent" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, height: '70%', backgroundColor: 'rgba(0,0,0,0.5)' }} />
                    {/* Top bar: status badge + manage */}
                    <View variant="transparent" style={{ position: 'absolute', top: 12, left: 16, right: 16, flexDirection: 'row', justifyContent: 'space-between', alignItems: 'center' }}>
                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: statusColor + '30', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12, gap: 6 }}>
                            <View variant="transparent" style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: statusColor }} />
                            <Text variant="caption" bold style={{ color: statusColor }}>{statusLabel}</Text>
                        </View>
                        {isAdmin && onManage && (
                            <TouchableOpacity
                                onPress={onManage}
                                activeOpacity={0.7}
                                style={{ flexDirection: 'row', alignItems: 'center', gap: 6, backgroundColor: 'rgba(0,0,0,0.55)', paddingHorizontal: 12, paddingVertical: 6, borderRadius: 8, borderWidth: 1, borderColor: 'rgba(255,255,255,0.3)' }}
                            >
                                <Ionicons name="settings-outline" size={14} color="#fff" />
                                <Text variant="caption" bold style={{ color: '#fff' }}>Manage</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                    {/* Title overlay */}
                    <View variant="transparent" style={{ position: 'absolute', left: 0, right: 0, bottom: 0, paddingHorizontal: 20, paddingBottom: 28 }}>
                        <Text variant="h2" bold style={{ color: '#fff', fontSize: 26, lineHeight: 34, fontWeight: '800', letterSpacing: -0.5 }}>
                            {competition.competition_name}
                        </Text>
                        <Text variant="caption" style={{ color: 'rgba(255,255,255,0.7)', marginTop: 4 }}>
                            {competition.auction_type === 'sweepstakes' ? 'Sweepstakes' : competition.auction_type === 'live' ? 'Live Auction' : 'Sealed Bid'}
                            {' · '}{statusLabel}
                        </Text>
                    </View>
                </View>

                {/* Assigned item */}
                {myItems.length > 0 && (
                    <View variant="transparent" style={{ marginHorizontal: 16 }}>
                        <Text variant="caption" bold color="tertiary" style={{ textTransform: 'uppercase', letterSpacing: 1, fontSize: 10, lineHeight: 13, marginBottom: 8 }}>
                            {isSweepstakes ? 'Your Item' : `Your Items (${myItems.length})`}
                        </Text>
                        <ScrollView horizontal showsHorizontalScrollIndicator={false} contentContainerStyle={{ gap: 8 }}>
                            {myItems.map(mi => {
                                const imgUrl = resolveItemImageUrl(mi.item_image) || itemImages[mi.item_id]?.url;
                                return (
                                    <View key={mi.calcutta_auction_item_id} variant="transparent" style={{ backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderWidth: 1, borderRadius: 10, padding: 10, alignItems: 'center', width: 110 }}>
                                        {imgUrl ? (
                                            <Image source={{ uri: imgUrl }} style={{ width: 40, height: 40, borderRadius: 8, marginBottom: 6 }} resizeMode="cover" />
                                        ) : (
                                            <Ionicons name="trophy" size={24} color={theme.colors.primary.default} style={{ marginBottom: 6 }} />
                                        )}
                                        <Text variant="caption" bold numberOfLines={2} style={{ textAlign: 'center', fontSize: 12, lineHeight: 16 }}>{mi.item_name}</Text>
                                        {mi.seed != null && <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>#{mi.seed}</Text>}
                                        {Number(mi.winning_bid) > 0 && (
                                            <Text variant="caption" bold style={{ color: '#10B981', marginTop: 2, fontSize: 11, lineHeight: 15 }}>{formatCurrency(mi.winning_bid, competition.market_type)}</Text>
                                        )}
                                    </View>
                                );
                            })}
                        </ScrollView>
                    </View>
                )}

                {/* Stats */}
                <View variant="transparent" style={{ flexDirection: 'row', gap: 12, paddingHorizontal: 16 }}>
                    <View variant="transparent" style={[styles.desktopPanel, { flex: 1, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderRadius: 10, alignItems: 'center' }]}>
                        <Text variant="caption" color="tertiary">Players</Text>
                        <Text variant="body" bold>{participants.length}</Text>
                    </View>
                    <View variant="transparent" style={[styles.desktopPanel, { flex: 1, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderRadius: 10, alignItems: 'center' }]}>
                        <Text variant="caption" color="tertiary">Items</Text>
                        <Text variant="body" bold>{items.length}</Text>
                    </View>
                    <View variant="transparent" style={[styles.desktopPanel, { flex: 1, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, borderRadius: 10, alignItems: 'center' }]}>
                        <Text variant="caption" color="tertiary">Rounds</Text>
                        <Text variant="body" bold>{rounds.length}</Text>
                    </View>
                </View>

                {/* Rounds with results */}
                {sortedRounds.length > 0 && (
                    <View variant="transparent" style={{ paddingHorizontal: 16 }}>
                        <Text variant="body" bold style={{ marginBottom: 10 }}>Rounds</Text>
                        {sortedRounds.map((round: any) => {
                            const isExpanded = expandedRound === round.calcutta_round_id;
                            const roundResults = item_results.filter(r => r.round_number === round.round_number);
                            const advancedIds = roundResults.filter(r => r.result === 'advanced' || r.result === 'won').map(r => r.calcutta_auction_item_id);
                            const eliminatedIds = roundResults.filter(r => r.result === 'eliminated').map(r => r.calcutta_auction_item_id);
                            const advancedItems = items.filter(i => advancedIds.includes(i.calcutta_auction_item_id));
                            const eliminatedItems = items.filter(i => eliminatedIds.includes(i.calcutta_auction_item_id));
                            const hasResults = roundResults.length > 0;
                            const statusColor = round.status === 'closed' ? theme.colors.status.success
                                : round.status === 'inprogress' ? theme.colors.primary.default
                                : theme.colors.text.tertiary;

                            return (
                                <View key={round.calcutta_round_id} variant="transparent" style={{ borderBottomWidth: 1, borderColor: theme.colors.border.subtle }}>
                                    <TouchableOpacity
                                        onPress={() => setExpandedRound(isExpanded ? null : round.calcutta_round_id)}
                                        activeOpacity={0.7}
                                        style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 12 }}
                                    >
                                        <View variant="transparent" style={{ flex: 1 }}>
                                            <Text variant="body" bold>{round.round_name}</Text>
                                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginTop: 4, gap: 8 }}>
                                                <View variant="transparent" style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: statusColor }} />
                                                <Text variant="caption" color="tertiary">
                                                    {round.status === 'closed' ? 'Resolved' : round.status === 'inprogress' ? 'In Progress' : 'Pending'}
                                                </Text>
                                                {hasResults && (
                                                    <Text variant="caption" style={{ color: theme.colors.status.success }}>
                                                        {advancedItems.length} advanced
                                                    </Text>
                                                )}
                                            </View>
                                            {round.prize_description && (
                                                <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginTop: 4 }}>
                                                    <Ionicons name="gift-outline" size={12} color={theme.colors.primary.default} />
                                                    <Text variant="caption" style={{ color: theme.colors.primary.default, marginLeft: 4 }}>{round.prize_description}</Text>
                                                </View>
                                            )}
                                        </View>
                                        <Ionicons name={isExpanded ? 'chevron-up' : 'chevron-down'} size={16} color={theme.colors.text.tertiary} />
                                    </TouchableOpacity>

                                    {isExpanded && (
                                        <View variant="transparent" style={{ paddingBottom: 12 }}>
                                            {!hasResults && (
                                                <Text variant="caption" color="tertiary" style={{ paddingVertical: 8 }}>No results yet</Text>
                                            )}
                                            {advancedItems.length > 0 && (
                                                <>
                                                    <Text variant="caption" bold color="secondary" style={{ marginTop: 4, marginBottom: 4 }}>Advanced ({advancedItems.length})</Text>
                                                    {advancedItems.map(item => {
                                                        const imgUrl = resolveItemImageUrl(item.item_image) || itemImages[item.item_id]?.url;
                                                        const isMe = item.winning_player_id == player_id;
                                                        return (
                                                            <View key={item.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 4, paddingLeft: 4 }}>
                                                                {imgUrl ? (
                                                                    <Image source={{ uri: imgUrl }} style={{ width: 20, height: 20, borderRadius: 4 }} resizeMode="cover" />
                                                                ) : (
                                                                    <Ionicons name="checkmark-circle" size={16} color={theme.colors.status.success} />
                                                                )}
                                                                <Text variant="caption" style={{ marginLeft: 6, flex: 1 }}>{item.item_name}</Text>
                                                                {isMe && <Text variant="caption" bold style={{ color: theme.colors.primary.default }}>YOU</Text>}
                                                            </View>
                                                        );
                                                    })}
                                                </>
                                            )}
                                            {eliminatedItems.length > 0 && (
                                                <>
                                                    <Text variant="caption" bold color="secondary" style={{ marginTop: 8, marginBottom: 4 }}>Eliminated ({eliminatedItems.length})</Text>
                                                    {eliminatedItems.map(item => {
                                                        const imgUrl = resolveItemImageUrl(item.item_image) || itemImages[item.item_id]?.url;
                                                        const isMe = item.winning_player_id == player_id;
                                                        return (
                                                            <View key={item.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 4, paddingLeft: 4, opacity: 0.5 }}>
                                                                {imgUrl ? (
                                                                    <Image source={{ uri: imgUrl }} style={{ width: 20, height: 20, borderRadius: 4 }} resizeMode="cover" />
                                                                ) : (
                                                                    <Ionicons name="close-circle" size={16} color={theme.colors.status.error} />
                                                                )}
                                                                <Text variant="caption" style={{ marginLeft: 6, flex: 1 }}>{item.item_name}</Text>
                                                                {isMe && <Text variant="caption" bold style={{ color: theme.colors.status.error }}>YOU</Text>}
                                                            </View>
                                                        );
                                                    })}
                                                </>
                                            )}
                                        </View>
                                    )}
                                </View>
                            );
                        })}
                    </View>
                )}

                {/* All teams list */}
                {items.length > 0 && (
                    <View variant="transparent" style={{ paddingHorizontal: 16 }}>
                        <Text variant="body" bold style={{ marginBottom: 10 }}>All Items</Text>
                        <TextInput
                            style={{
                                height: 36,
                                borderRadius: 8,
                                borderWidth: 1,
                                borderColor: theme.colors.border.subtle,
                                backgroundColor: theme.colors.surface.input,
                                color: theme.colors.text.primary,
                                paddingHorizontal: 12,
                                fontSize: 14,
                                lineHeight: 19,
                                marginBottom: 8,
                            }}
                            placeholder="Search by team or owner..."
                            placeholderTextColor={theme.colors.text.tertiary}
                            value={searchQuery}
                            onChangeText={setSearchQuery}
                            autoCapitalize="none"
                            autoCorrect={false}
                            onFocus={(e: any) => {
                                if (Platform.OS === 'web' && e?.target?.scrollIntoView) {
                                    setTimeout(() => e.target.scrollIntoView({ behavior: 'smooth', block: 'center' }), 300);
                                }
                            }}
                        />
                        {filteredItems.map((item) => {
                            const isMyItem = item.winning_player_id == player_id;
                            const isEliminated = item.status === 'eliminated';
                            const imageUrl = resolveItemImageUrl(item.item_image) || itemImages[item.item_id]?.url;
                            const owner = item.winning_player_id ? enrichedPlayers[item.winning_player_id] : undefined;
                            const ownerName = owner?.username || owner?.show_name;
                            return (
                                <View
                                    key={item.calcutta_auction_item_id}
                                    variant="transparent"
                                    style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 8, borderBottomWidth: 1, borderColor: theme.colors.border.subtle, opacity: isEliminated ? 0.5 : 1 }}
                                >
                                    {imageUrl ? (
                                        <Image source={{ uri: imageUrl }} style={{ width: 28, height: 28, borderRadius: 6 }} resizeMode="cover" />
                                    ) : (
                                        <Ionicons
                                            name={isEliminated ? 'close-circle' : isMyItem ? 'star' : 'ellipse-outline'}
                                            size={16}
                                            color={isEliminated ? theme.colors.status.error : isMyItem ? theme.colors.primary.default : theme.colors.text.tertiary}
                                        />
                                    )}
                                    <View variant="transparent" style={{ marginLeft: 8, flex: 1 }}>
                                        <Text variant="body">{item.item_name}</Text>
                                        {ownerName && (
                                            <Text variant="caption" color="tertiary">
                                                {isMyItem ? 'You' : ownerName}
                                            </Text>
                                        )}
                                        {!item.winning_player_id && item.status !== 'unsold' && (
                                            <Text variant="caption" color="tertiary">Unclaimed</Text>
                                        )}
                                        {item.status === 'unsold' && (
                                            <Text variant="caption" color="tertiary">No owner</Text>
                                        )}
                                    </View>
                                    {item.seed != null && <Text variant="caption" color="tertiary">#{item.seed}</Text>}
                                    {isMyItem && <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 8 }}>YOU</Text>}
                                </View>
                            );
                        })}
                    </View>
                )}

                {!myItem && !isAdmin && (
                    <View variant="transparent" style={{ alignItems: 'center', paddingVertical: 20, paddingHorizontal: 16 }}>
                        <Ionicons name="time-outline" size={32} color={theme.colors.text.tertiary} />
                        <Text variant="body" color="tertiary" style={{ marginTop: 8 }}>
                            Waiting for the tournament to begin
                        </Text>
                    </View>
                )}
            </ScrollView>
        </View>
    );
};

// Main exported component — routes to sealed bid or live layout
export const CalcuttaAuction: React.FC<CalcuttaAuctionProps> = (props) => {
    const { theme } = useTheme();

    // Peek at auction type to decide which layout to render.
    // Use useCalcuttaCompetition for a single fetch (no polling).
    const { loading, competition } = useCalcuttaCompetition(props.calcutta_competition_id);

    if (loading && !competition) {
        return (
            <View variant="transparent" style={[styles.loadingContainer, { backgroundColor: theme.colors.surface.base }]}>
                <ActivityIndicator size="large" color={theme.colors.primary.default} />
            </View>
        );
    }

    if (!competition) {
        return (
            <View variant="transparent" style={[styles.loadingContainer, { backgroundColor: theme.colors.surface.base }]}>
                <Text variant="body" color="secondary">Auction not found</Text>
            </View>
        );
    }

    if (competition.auction_type === 'sealed_bid') {
        return <SealedBidAuction {...props} />;
    }

    return <LiveAuction {...props} />;
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    loadingContainer: {
        flex: 1,
        alignItems: 'center',
        justifyContent: 'center',
        padding: 40,
    },
    adminButton: {
        height: 32,
        borderRadius: 16,
        alignItems: 'center',
        justifyContent: 'center',
        paddingHorizontal: 12,
    },
    infoTabBtn: {
        flex: 1,
        flexDirection: 'row',
        alignItems: 'center',
        justifyContent: 'center',
        height: 38,
        borderRadius: 10,
        borderWidth: 1,
    },
    infoTabContent: {
        marginHorizontal: 12,
        marginTop: 8,
        padding: 14,
        borderRadius: 12,
        borderWidth: 1,
    },
    presenceAvatar: {
        width: 24,
        height: 24,
        borderRadius: 12,
        alignItems: 'center',
        justifyContent: 'center',
    },
    desktopPanel: {
        borderRadius: 12,
        borderWidth: 1,
        padding: 14,
    },
    panelTitle: {
        textTransform: 'uppercase',
        letterSpacing: 1,
        fontSize: 10,
        lineHeight: 13,
    },
    infoRow: {
        flexDirection: 'row',
        justifyContent: 'space-between',
        alignItems: 'center',
        paddingVertical: 6,
    },
    emptyText: {
        textAlign: 'center',
        padding: 20,
    },
});
