import React, { useState, useMemo, useCallback, useEffect, useRef } from 'react';
import { StyleSheet, TouchableOpacity, ActivityIndicator, ScrollView, Image, FlatList, TextInput, Platform, useWindowDimensions, RefreshControl } from 'react-native';
import { View, Text, useTheme } from '@bettoredge/styles';
import { Ionicons } from '@expo/vector-icons';
import type { CalcuttaParticipantProps } from '@bettoredge/types';
import { useCalcuttaCompetition } from '../hooks/useCalcuttaCompetition';
import { useCalcuttaPlayers } from '../hooks/useCalcuttaPlayers';
import { useCalcuttaItemImages } from '../hooks/useCalcuttaItemImages';
import { formatCurrency, getStatusLabel, resolveItemImageUrl } from '../helpers/formatting';
import { deriveLifecycleState, canManageEscrow } from '../helpers/lifecycleState';
import { useCalcuttaEscrow } from '../hooks/useCalcuttaEscrow';
import { startSweepstakesCompetition, startCalcuttaAuction } from '@bettoredge/api';
import { CalcuttaActionCard } from './CalcuttaActionCard';
import { CalcuttaCountdown } from './CalcuttaCountdown';
import { AuctionInfoChips } from './AuctionInfoChips';
import { EscrowWidget } from './EscrowWidget';
import { AuctionCountdownOverlay } from './AuctionCountdownOverlay';
import { CalcuttaWalkthrough } from './CalcuttaWalkthrough';
import { useCalcuttaSocket } from '../hooks/useCalcuttaSocket';

export interface CalcuttaDetailProps {
    calcutta_competition_id: string;
    player_id?: string;
    access_token?: string;
    device_id?: string;
    player_username?: string;
    player_profile_pic?: string;
    onClose?: () => void;
    onJoin?: () => Promise<void>;
    onLeave?: () => Promise<void>;
    onShare?: () => void;
    onManage?: () => void;
    player_balance?: number;
    onDepositFunds?: (amount: number) => void;
    initialShowWalkthrough?: boolean;
    onWalkthroughDismiss?: () => void;
    onRefresh?: () => void | Promise<void>;
    onAuctionStarted?: () => void;
}

const getStatusConfig = (status: string) => {
    switch (status) {
        case 'pending': return { label: 'Pending', color: '#F59E0B', bg: '#F59E0B15' };
        case 'scheduled': return { label: 'Open to Join', color: '#3B82F6', bg: '#3B82F615' };
        case 'auction_open': return { label: 'Auction Live', color: '#10B981', bg: '#10B98115' };
        case 'inprogress': return { label: 'In Progress', color: '#8B5CF6', bg: '#8B5CF615' };
        case 'closed': return { label: 'Completed', color: '#6B7280', bg: '#6B728015' };
        default: return { label: status, color: '#6B7280', bg: '#6B728015' };
    }
};

export const CalcuttaDetail: React.FC<CalcuttaDetailProps> = ({
    calcutta_competition_id,
    player_id,
    onClose,
    onJoin,
    onLeave,
    onShare,
    onManage,
    player_balance,
    onDepositFunds,
    initialShowWalkthrough,
    onWalkthroughDismiss,
    access_token,
    device_id,
    player_username,
    player_profile_pic,
    onRefresh,
    onAuctionStarted,
}) => {
    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);

    // Walkthrough state
    const [showWalkthrough, setShowWalkthrough] = useState(false);
    const walkthroughTriggered = useRef(false);
    useEffect(() => {
        if (initialShowWalkthrough && !walkthroughTriggered.current) {
            walkthroughTriggered.current = true;
            setShowWalkthrough(true);
        }
    }, [initialShowWalkthrough]);

    // Countdown overlay state
    const [showCountdown, setShowCountdown] = useState(false);
    const [countdownItem, setCountdownItem] = useState<any>(undefined);

    // Socket for presence + auction start detection
    const handleItemActive = useCallback((data: any) => {
        // Auction just started — show countdown for ALL connected clients
        setCountdownItem(data.item);
        setShowCountdown(true);
    }, []);

    const { connected: socketConnected, presence, socketState } = useCalcuttaSocket(
        calcutta_competition_id,
        access_token,
        device_id,
        { username: player_username, profile_pic: player_profile_pic },
        { onItemActive: handleItemActive },
    );
    const onlinePlayers = presence.players;
    const onlinePlayerIds = useMemo(() => new Set(onlinePlayers.map(p => p.player_id)), [onlinePlayers]);
    const {
        loading,
        competition,
        rounds,
        items,
        participants,
        payout_rules,
        refresh,
    } = useCalcuttaCompetition(calcutta_competition_id);

    const participantIds = useMemo(() => participants.map(p => p.player_id), [participants]);
    const { players: enrichedPlayers } = useCalcuttaPlayers(participantIds);
    const { escrow, fetchEscrow } = useCalcuttaEscrow(calcutta_competition_id);
    const [escrowExpanded, setEscrowExpanded] = useState(false);

    const { images: itemImages } = useCalcuttaItemImages(items);

    const [joining, setJoining] = useState(false);
    const [leaving, setLeaving] = useState(false);
    const [startingComp, setStartingComp] = useState(false);
    const [itemSearch, setItemSearch] = useState('');
    const [itemsPage, setItemsPage] = useState(1);
    const ITEMS_PER_PAGE = 10;
    const [mobileListTab, setMobileListTab] = useState<'items' | 'players'>('items');

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

    const filteredItems = useMemo(() => {
        if (!itemSearch.trim()) return items;
        const q = itemSearch.toLowerCase().trim();
        return items.filter(item => {
            if (item.item_name.toLowerCase().includes(q)) return true;
            if (item.seed != null && `#${item.seed}`.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, itemSearch, enrichedPlayers]);

    // Reset page when search changes
    useEffect(() => { setItemsPage(1); }, [itemSearch]);

    const totalItemPages = Math.max(1, Math.ceil(filteredItems.length / ITEMS_PER_PAGE));
    const paginatedItems = useMemo(() => {
        const start = (itemsPage - 1) * ITEMS_PER_PAGE;
        return filteredItems.slice(start, start + ITEMS_PER_PAGE);
    }, [filteredItems, itemsPage]);

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

    if (!competition) {
        return (
            <View variant="transparent" style={styles.loadingContainer}>
                <Text variant="body" color="secondary">Competition not found</Text>
            </View>
        );
    }

    const statusConfig = getStatusConfig(competition.status);
    const isAdmin = player_id != null && player_id == competition.admin_id;
    const hasJoined = participants.some(p => p.player_id == player_id);
    const entryFee = Number(competition.entry_fee) || 0;
    const isFree = entryFee === 0;
    const isSweepstakes = competition.auction_type === 'sweepstakes';
    const isJoinable = isSweepstakes
        ? competition.status === 'scheduled'
        : ['scheduled', 'auction_open'].includes(competition.status);
    const totalPot = Number(competition.total_pot) || 0;
    const canLeave = hasJoined && !isSweepstakes && ['pending', 'scheduled'].includes(competition.status);
    const heroImage = competition.image?.url;
    const lifecycleState = deriveLifecycleState(competition.status, competition.auction_status, competition.auction_type);
    const showEscrow = canManageEscrow(lifecycleState, competition.auction_type) && hasJoined;

    // Sweepstakes: find the player's assigned item
    const myParticipant = participants.find(p => p.player_id == player_id);
    const myAssignedItem = isSweepstakes && hasJoined
        ? items.find(i => i.winning_player_id == player_id)
        : undefined;
    const unassignedItemCount = isSweepstakes
        ? items.filter(i => !i.winning_player_id && i.status === 'pending').length
        : 0;

    const sections = [
        { key: 'hero' },
        { key: 'info' },
        { key: 'action-card' },
        ...(showEscrow ? [{ key: 'escrow' }] : []),
        { key: 'stats' },
        { key: 'payouts' },
        { key: 'items-players-tabbed' },
        ...(canLeave ? [{ key: 'leave' }] : []),
    ];

    const renderItemsList = () => {
        if (items.length === 0) {
            return (
                <View variant="transparent" style={{ padding: 20, alignItems: 'center' }}>
                    <Ionicons name="list-outline" size={32} color={theme.colors.text.tertiary} />
                    <Text variant="caption" color="tertiary" style={{ marginTop: 8 }}>No items added yet.</Text>
                </View>
            );
        }

        return (
            <View variant="transparent" style={{ paddingHorizontal: 16, paddingBottom: 8 }}>
                <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={isSweepstakes ? "Search by team or owner..." : "Search items..."}
                    placeholderTextColor={theme.colors.text.tertiary}
                    value={itemSearch}
                    onChangeText={setItemSearch}
                    autoCapitalize="none"
                    autoCorrect={false}
                    onFocus={(e: any) => {
                        if (Platform.OS === 'web' && e?.target?.scrollIntoView) {
                            setTimeout(() => e.target.scrollIntoView({ behavior: 'smooth', block: 'center' }), 300);
                        }
                    }}
                />
                {itemSearch.trim() !== '' && (
                    <Text variant="caption" color="tertiary" style={{ marginBottom: 6 }}>
                        {filteredItems.length} of {items.length} items
                    </Text>
                )}
                {paginatedItems.map(item => {
                    const imgUrl = 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;
                    const isMe = item.winning_player_id == player_id;
                    return (
                        <View key={item.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 8, borderBottomWidth: 1, borderColor: theme.colors.border.subtle }}>
                            {imgUrl ? (
                                <Image source={{ uri: imgUrl }} style={{ width: 36, height: 36, borderRadius: 8 }} resizeMode="cover" />
                            ) : (
                                <View variant="transparent" style={{ width: 36, height: 36, borderRadius: 8, backgroundColor: theme.colors.surface.elevated, alignItems: 'center', justifyContent: 'center' }}>
                                    <Ionicons name="trophy-outline" size={16} color={theme.colors.text.tertiary} />
                                </View>
                            )}
                            <View variant="transparent" style={{ marginLeft: 10, flex: 1 }}>
                                <Text variant="body">{item.item_name}</Text>
                                {isSweepstakes && ownerName ? (
                                    <Text variant="caption" color="tertiary">{isMe ? 'You' : ownerName}</Text>
                                ) : isSweepstakes ? (
                                    <Text variant="caption" color="tertiary">Available</Text>
                                ) : null}
                            </View>
                            {item.seed != null && <Text variant="caption" color="tertiary">#{item.seed}</Text>}
                            {isMe && <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 8 }}>YOU</Text>}
                        </View>
                    );
                })}
                {totalItemPages > 1 && (
                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 10, gap: 16 }}>
                        <TouchableOpacity
                            onPress={() => setItemsPage(p => p - 1)}
                            disabled={itemsPage <= 1}
                            style={{ opacity: itemsPage <= 1 ? 0.3 : 1, padding: 4 }}
                        >
                            <Ionicons name="chevron-back" size={20} color={theme.colors.primary.default} />
                        </TouchableOpacity>
                        <Text variant="caption" color="secondary">
                            {itemsPage} of {totalItemPages}
                        </Text>
                        <TouchableOpacity
                            onPress={() => setItemsPage(p => p + 1)}
                            disabled={itemsPage >= totalItemPages}
                            style={{ opacity: itemsPage >= totalItemPages ? 0.3 : 1, padding: 4 }}
                        >
                            <Ionicons name="chevron-forward" size={20} color={theme.colors.primary.default} />
                        </TouchableOpacity>
                    </View>
                )}
            </View>
        );
    };

    const renderParticipantsList = () => {
        if (participants.length === 0) {
            return (
                <View variant="transparent" style={{ padding: 20, alignItems: 'center' }}>
                    <Ionicons name="people-outline" size={32} color={theme.colors.text.tertiary} />
                    <Text variant="caption" color="tertiary" style={{ marginTop: 8 }}>No players yet. Share the code to invite friends!</Text>
                </View>
            );
        }
        return (
            <View variant="transparent" style={{ paddingHorizontal: 16, paddingBottom: 8 }}>
                {participants.map((p, i) => {
                    const enriched = enrichedPlayers[p.player_id];
                    const username = enriched?.username || enriched?.show_name || `Player ${p.player_id.slice(0, 6)}`;
                    const profilePic = enriched?.profile_pic;
                    const isOnline = onlinePlayerIds.has(p.player_id);
                    return (
                        <View key={p.calcutta_participant_id} variant="transparent" style={[styles.participantRow, i < participants.length - 1 && { borderBottomWidth: 1, borderColor: theme.colors.border.subtle }]}>
                            <View variant="transparent" style={{ position: 'relative' }}>
                                {profilePic ? (
                                    <Image source={{ uri: profilePic }} style={[styles.avatarCircle, { overflow: 'hidden' }]} />
                                ) : (
                                    <View variant="transparent" style={[styles.avatarCircle, { backgroundColor: theme.colors.primary.subtle }]}>
                                        <Text variant="caption" bold style={{ color: theme.colors.primary.default }}>
                                            {username.charAt(0).toUpperCase()}
                                        </Text>
                                    </View>
                                )}
                                {isOnline && (
                                    <View variant="transparent" style={{ position: 'absolute', bottom: 0, right: 0, width: 10, height: 10, borderRadius: 5, backgroundColor: '#10B981', borderWidth: 2, borderColor: theme.colors.surface.base }} />
                                )}
                            </View>
                            <View variant="transparent" style={{ flex: 1 }}>
                                <Text variant="body">{username}</Text>
                                <Text variant="caption" color="tertiary">
                                    {p.items_owned > 0 ? `${p.items_owned} items \u00B7 ${formatCurrency(p.total_spent, competition.market_type)} spent` : 'Joined'}
                                </Text>
                            </View>
                            {p.player_id == player_id && (
                                <View variant="transparent" style={[styles.youBadge, { backgroundColor: theme.colors.primary.subtle }]}>
                                    <Text variant="caption" bold style={{ color: theme.colors.primary.default, fontSize: 10, lineHeight: 13 }}>YOU</Text>
                                </View>
                            )}
                        </View>
                    );
                })}
            </View>
        );
    };

    const renderSection = ({ item }: { item: { key: string } }) => {
        switch (item.key) {
            case 'hero':
                return heroImage ? (
                    <Image source={{ uri: heroImage }} style={styles.heroImage} resizeMode="cover" />
                ) : (
                    <View variant="transparent" style={[styles.heroPlaceholder, { backgroundColor: theme.colors.surface.elevated }]}>
                        <Ionicons name="hammer-outline" size={48} color={theme.colors.text.tertiary} />
                    </View>
                );

            case 'info':
                return (
                    <View variant="transparent" style={styles.infoSection}>
                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 6 }}>
                            <View variant="transparent" style={[styles.statusBadge, { backgroundColor: statusConfig.bg }]}>
                                <View variant="transparent" style={[styles.statusDot, { backgroundColor: statusConfig.color }]} />
                                <Text variant="caption" bold style={{ color: statusConfig.color }}>{statusConfig.label}</Text>
                            </View>
                            <Text variant="caption" color="tertiary" style={{ marginLeft: 8 }}>
                                {isSweepstakes ? 'Sweepstakes' : competition.auction_type === 'live' ? 'Live Auction' : 'Sealed Bid'}
                            </Text>
                            <View variant="transparent" style={{ flex: 1 }} />
                            <TouchableOpacity
                                onPress={() => setShowWalkthrough(true)}
                                style={{ marginRight: 8, padding: 4 }}
                                activeOpacity={0.7}
                                hitSlop={{ top: 8, bottom: 8, left: 8, right: 8 }}
                            >
                                <Ionicons name="help-circle-outline" size={20} color={theme.colors.text.tertiary} />
                            </TouchableOpacity>
                            {isAdmin && onManage && (
                                <TouchableOpacity
                                    onPress={onManage}
                                    style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: theme.colors.surface.elevated, paddingHorizontal: 10, paddingVertical: 5, borderRadius: 8, borderWidth: 1, borderColor: theme.colors.border.subtle }}
                                    activeOpacity={0.7}
                                >
                                    <Ionicons name="settings-outline" size={14} color={theme.colors.text.secondary} />
                                    <Text variant="caption" color="secondary" style={{ marginLeft: 4 }}>Manage</Text>
                                </TouchableOpacity>
                            )}
                        </View>
                        <Text variant="h3" bold>{competition.competition_name}</Text>
                        {competition.competition_description ? (
                            <Text variant="body" color="secondary" style={{ marginTop: 4 }}>{competition.competition_description}</Text>
                        ) : null}
                        {competition.competition_code ? (
                            <View variant="transparent" style={[styles.codeChip, { backgroundColor: theme.colors.primary.subtle }]}>
                                <Ionicons name="key-outline" size={12} color={theme.colors.primary.default} />
                                <Text variant="caption" bold style={{ color: theme.colors.primary.default, marginLeft: 4 }}>{competition.competition_code}</Text>
                            </View>
                        ) : null}
                        {competition.scheduled_datetime && (
                            <CalcuttaCountdown
                                targetDate={competition.scheduled_datetime}
                                label="Auction starts"
                            />
                        )}
                        {competition.auction_type === 'sealed_bid' && competition.auction_end_datetime && (
                            <CalcuttaCountdown
                                targetDate={competition.auction_end_datetime}
                                label="Bidding closes"
                            />
                        )}
                        <AuctionInfoChips competition={competition} />
                        {onShare && (
                            <TouchableOpacity onPress={onShare} style={{ flexDirection: 'row', alignItems: 'center', alignSelf: 'flex-start', marginTop: 10 }}>
                                <Ionicons name="share-outline" size={14} color={theme.colors.text.tertiary} />
                                <Text variant="caption" color="tertiary" style={{ marginLeft: 4 }}>Share</Text>
                            </TouchableOpacity>
                        )}
                    </View>
                );

            case 'stats':
                return (
                    <View variant="transparent" style={[styles.statsGrid, { borderColor: theme.colors.border.subtle }]}>
                        <View variant="transparent" style={styles.statBox}>
                            <Text variant="caption" color="tertiary">Entry Fee</Text>
                            <Text variant="body" bold>{isFree ? 'FREE' : formatCurrency(entryFee, competition.market_type)}</Text>
                        </View>
                        {isSweepstakes ? (
                            <View variant="transparent" style={[styles.statBox, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                <Text variant="caption" color="tertiary">Available</Text>
                                <Text variant="body" bold>{unassignedItemCount}/{items.length}</Text>
                            </View>
                        ) : (
                            <View variant="transparent" style={[styles.statBox, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                <Text variant="caption" color="tertiary">Pot</Text>
                                <Text variant="body" bold>{formatCurrency(totalPot, competition.market_type)}</Text>
                            </View>
                        )}
                        <View variant="transparent" style={[styles.statBox, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" color="tertiary">Players</Text>
                            <Text variant="body" bold>{participants.length}{competition.max_participants > 0 ? `/${competition.max_participants}` : ''}</Text>
                        </View>
                        <View variant="transparent" style={[styles.statBox, { borderLeftWidth: 1, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" color="tertiary">{isSweepstakes ? 'Prizes' : 'Items'}</Text>
                            <Text variant="body" bold>{isSweepstakes ? rounds.filter(r => r.prize_description).length : items.length}</Text>
                        </View>
                    </View>
                );

            case 'action-card':
                return (
                    <View variant="transparent" style={{ paddingHorizontal: 16, paddingTop: 4, paddingBottom: 12 }}>
                        <CalcuttaActionCard
                            competition={competition}
                            lifecycleState={lifecycleState}
                            hasJoined={hasJoined}
                            escrowBalance={Number(escrow?.escrow_balance ?? 0)}
                            isAdmin={isAdmin}
                            participantCount={participants.length}
                            onJoin={onJoin ? async () => {
                                setJoining(true);
                                try { await onJoin(); await refresh(); fetchEscrow(); } catch {}
                                setJoining(false);
                            } : undefined}
                            onDepositEscrow={undefined}
                            onManage={onManage}
                            onStartAuction={isAdmin && competition.status === 'scheduled' ? async () => {
                                setStartingComp(true);
                                try {
                                    if (isSweepstakes) {
                                        await startSweepstakesCompetition(calcutta_competition_id);
                                        await refresh();
                                    } else {
                                        await startCalcuttaAuction(calcutta_competition_id);
                                        // Socket will broadcast CALCUTTA_ITEM_ACTIVE which triggers countdown
                                        // refresh happens after countdown completes
                                    }
                                } catch {}
                                setStartingComp(false);
                            } : undefined}
                            joining={joining}
                        />
                        {/* Sweepstakes: show assigned item below action card */}
                        {isSweepstakes && myAssignedItem && (
                            <View variant="transparent" style={[styles.assignedItemCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, marginTop: 10 }]}>
                                {resolveItemImageUrl(myAssignedItem.item_image) ? (
                                    <Image source={{ uri: resolveItemImageUrl(myAssignedItem.item_image)! }} style={styles.assignedItemImage} resizeMode="cover" />
                                ) : (
                                    <View variant="transparent" style={[styles.assignedItemImage, { backgroundColor: theme.colors.primary.subtle, alignItems: 'center', justifyContent: 'center' }]}>
                                        <Ionicons name="trophy" size={20} color={theme.colors.primary.default} />
                                    </View>
                                )}
                                <View variant="transparent" style={{ flex: 1, marginLeft: 12 }}>
                                    <Text variant="caption" color="tertiary">Your Item</Text>
                                    <Text variant="body" bold>{myAssignedItem.item_name}</Text>
                                    {myAssignedItem.seed != null && <Text variant="caption" color="tertiary">Seed #{myAssignedItem.seed}</Text>}
                                </View>
                            </View>
                        )}
                    </View>
                );

            case 'escrow':
                return (
                    <View variant="transparent" style={{ paddingHorizontal: 16, paddingBottom: 12 }}>
                        <EscrowWidget
                            calcutta_competition_id={calcutta_competition_id}
                            market_type={competition.market_type}
                            max_escrow={competition.max_escrow}
                            player_balance={player_balance}
                            onUpdate={() => { refresh(); fetchEscrow(); }}
                            initialExpanded={Number(escrow?.escrow_balance ?? 0) <= 0}
                        />
                    </View>
                );

            case 'leave':
                return (
                    <View variant="transparent" style={{ alignItems: 'center', paddingVertical: 16, paddingBottom: 40 }}>
                        <TouchableOpacity
                            onPress={async () => {
                                if (!onLeave) return;
                                setLeaving(true);
                                try { await onLeave(); await refresh(); } catch {}
                                setLeaving(false);
                            }}
                            disabled={leaving}
                            style={{ opacity: leaving ? 0.5 : 1 }}
                        >
                            {leaving ? (
                                <ActivityIndicator size="small" color={theme.colors.status.error} />
                            ) : (
                                <Text variant="caption" style={{ color: theme.colors.status.error }}>Leave Competition</Text>
                            )}
                        </TouchableOpacity>
                    </View>
                );

            case 'payouts':
                // Sweepstakes: show prize list per round instead of payout percentages
                if (isSweepstakes) {
                    const prizeRounds = rounds.filter(r => r.prize_description);
                    if (prizeRounds.length === 0) return null;
                    return (
                        <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                            <Text variant="body" bold style={styles.sectionTitle}>Prizes</Text>
                            {prizeRounds.map((round, i) => (
                                <View key={round.calcutta_round_id} variant="transparent" style={[styles.payoutRow, i < prizeRounds.length - 1 && { borderBottomWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                    {round.prize_image?.url ? (
                                        <Image
                                            source={{ uri: round.prize_image.url }}
                                            style={{ width: 40, height: 40, borderRadius: 6, marginRight: 10 }}
                                            resizeMode="cover"
                                        />
                                    ) : null}
                                    <View variant="transparent" style={{ flex: 1 }}>
                                        <Text variant="body" bold>{round.round_name}</Text>
                                        <Text variant="caption" color="secondary" style={{ marginTop: 2 }}>{round.prize_description}</Text>
                                    </View>
                                </View>
                            ))}
                        </View>
                    );
                }

                if (payout_rules.length === 0) return null;
                return (
                    <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                        <Text variant="body" bold style={styles.sectionTitle}>Payout Structure</Text>
                        {payout_rules.map((rule, i) => {
                            const round = rounds.find(r => r.round_number === rule.round_number);
                            const pct = Number(rule.payout_pct);
                            const amount = totalPot > 0 ? (pct / 100) * totalPot : 0;
                            return (
                                <View key={rule.calcutta_payout_rule_id || `rule-${i}`} variant="transparent" style={[styles.payoutRow, i < payout_rules.length - 1 && { borderBottomWidth: 1, borderColor: theme.colors.border.subtle }]}>
                                    <View variant="transparent" style={{ flex: 1 }}>
                                        <Text variant="body">{rule.description || round?.round_name || `Round ${rule.round_number}`}</Text>
                                    </View>
                                    <Text variant="body" bold>{pct}%</Text>
                                    {totalPot > 0 && (
                                        <Text variant="caption" color="tertiary" style={{ marginLeft: 8, minWidth: 60, textAlign: 'right' }}>
                                            {formatCurrency(amount, competition.market_type)}
                                        </Text>
                                    )}
                                </View>
                            );
                        })}
                    </View>
                );

            case 'items':
                return renderItemsList();

            case 'participants':
                return renderParticipantsList();

            case 'items-players-tabbed':
                return (
                    <View variant="transparent" style={[styles.section, { borderColor: theme.colors.border.subtle }]}>
                        {/* Tab toggle */}
                        <View variant="transparent" style={[styles.listTabBar, { borderColor: theme.colors.border.subtle }]}>
                            <TouchableOpacity
                                style={[styles.listTab, mobileListTab === 'items' && { borderBottomWidth: 2, borderBottomColor: theme.colors.primary.default }]}
                                onPress={() => setMobileListTab('items')}
                            >
                                <Ionicons name="list-outline" size={16} color={mobileListTab === 'items' ? theme.colors.primary.default : theme.colors.text.tertiary} style={{ marginRight: 6 }} />
                                <Text variant="body" bold style={{ color: mobileListTab === 'items' ? theme.colors.primary.default : theme.colors.text.tertiary }}>
                                    {isSweepstakes ? 'Teams' : 'Items'} ({items.length})
                                </Text>
                            </TouchableOpacity>
                            <TouchableOpacity
                                style={[styles.listTab, mobileListTab === 'players' && { borderBottomWidth: 2, borderBottomColor: theme.colors.primary.default }]}
                                onPress={() => setMobileListTab('players')}
                            >
                                <Ionicons name="people-outline" size={16} color={mobileListTab === 'players' ? theme.colors.primary.default : theme.colors.text.tertiary} style={{ marginRight: 6 }} />
                                <Text variant="body" bold style={{ color: mobileListTab === 'players' ? theme.colors.primary.default : theme.colors.text.tertiary }}>
                                    Players ({participants.length})
                                </Text>
                                {onlinePlayers.length > 0 && (
                                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginLeft: 8, backgroundColor: '#10B98115', paddingHorizontal: 6, paddingVertical: 2, borderRadius: 8 }}>
                                        <View variant="transparent" style={{ width: 5, height: 5, borderRadius: 2.5, backgroundColor: '#10B981', marginRight: 3 }} />
                                        <Text variant="caption" bold style={{ color: '#10B981', fontSize: 10, lineHeight: 13 }}>{onlinePlayers.length}</Text>
                                    </View>
                                )}
                            </TouchableOpacity>
                        </View>
                        {mobileListTab === 'items' ? renderItemsList() : renderParticipantsList()}
                    </View>
                );

            default:
                return null;
        }
    };

    return (
        <View variant="transparent" style={[styles.container, { backgroundColor: theme.colors.surface.base }]} onLayout={e => setContainerWidth(e.nativeEvent.layout.width)}>
            {isDesktop ? (
                <ScrollView style={{ flex: 1, backgroundColor: theme.colors.surface.base }} contentContainerStyle={{ padding: 12, paddingBottom: 40, backgroundColor: theme.colors.surface.base }} keyboardShouldPersistTaps="handled" refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}>
                    {/* Row 1: Hero + Info/Action left, Items right */}
                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12 }}>
                        <View variant="transparent" style={{ flex: 3 }}>
                            {renderSection({ item: { key: 'hero' } })}
                            {renderSection({ item: { key: 'info' } })}
                            {renderSection({ item: { key: 'action-card' } })}
                            {showEscrow && renderSection({ item: { key: 'escrow' } })}
                        </View>
                        <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.desktopPanelTitle}>
                                {isSweepstakes ? 'Teams' : 'Auction Items'} ({items.length})
                            </Text>
                            <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {renderSection({ item: { key: 'items' } })}
                            </ScrollView>
                        </View>
                    </View>

                    {/* Row 2: Stats + Payouts + Participants */}
                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12, marginTop: 12 }}>
                        <View variant="transparent" style={{ flex: 1 }}>
                            {renderSection({ item: { key: 'stats' } })}
                        </View>
                    </View>

                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12, marginTop: 12 }}>
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 1, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" bold color="tertiary" style={styles.desktopPanelTitle}>Payouts</Text>
                            {renderSection({ item: { key: 'payouts' } })}
                        </View>
                        <View variant="transparent" style={[styles.desktopPanel, { flex: 1, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <Text variant="caption" bold color="tertiary" style={styles.desktopPanelTitle}>
                                Players ({participants.length})
                            </Text>
                            <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false} style={{ maxHeight: 300 }}>
                                {renderSection({ item: { key: 'participants' } })}
                            </ScrollView>
                        </View>
                    </View>

                    {canLeave && renderSection({ item: { key: 'leave' } })}
                </ScrollView>
            ) : (
                <FlatList
                    data={sections}
                    keyExtractor={(item) => item.key}
                    renderItem={renderSection}
                    extraData={`${escrowExpanded}-${onlinePlayers.length}`}
                    showsVerticalScrollIndicator={false}
                    style={{ backgroundColor: theme.colors.surface.base }}
                    contentContainerStyle={{ paddingBottom: Platform.OS === 'web' ? 300 : 40 }}
                    keyboardShouldPersistTaps="handled"
                    refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}
                />
            )}

            {/* Auction starting countdown overlay */}
            <AuctionCountdownOverlay
                visible={showCountdown}
                competitionName={competition?.competition_name}
                firstItem={countdownItem}
                countdownFrom={5}
                onComplete={() => {
                    setShowCountdown(false);
                    refresh();
                    onAuctionStarted?.();
                }}
            />

            {/* Walkthrough */}
            {competition && (
                <CalcuttaWalkthrough
                    visible={showWalkthrough}
                    onClose={() => { setShowWalkthrough(false); onWalkthroughDismiss?.(); }}
                    auction_type={competition.auction_type as any}
                />
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: { flex: 1 },
    loadingContainer: { flex: 1, alignItems: 'center', justifyContent: 'center', padding: 40 },
    headerBar: { flexDirection: 'row', alignItems: 'center', padding: 12, borderBottomWidth: 1 },
    heroImage: { width: '100%', height: 180 },
    heroPlaceholder: { width: '100%', height: 140, alignItems: 'center', justifyContent: 'center' },
    infoSection: { padding: 16 },
    statusBadge: { flexDirection: 'row', alignItems: 'center', paddingHorizontal: 8, paddingVertical: 4, borderRadius: 12 },
    statusDot: { width: 6, height: 6, borderRadius: 3, marginRight: 6 },
    codeChip: { flexDirection: 'row', alignItems: 'center', alignSelf: 'flex-start', paddingHorizontal: 10, paddingVertical: 5, borderRadius: 12, marginTop: 10 },
    statsGrid: { flexDirection: 'row', borderTopWidth: 1, borderBottomWidth: 1 },
    statBox: { flex: 1, alignItems: 'center', paddingVertical: 12 },
    ctaSection: { padding: 16, gap: 10 },
    ctaButton: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 14, borderRadius: 10 },
    ctaButtonOutline: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 10, borderRadius: 10, borderWidth: 1 },
    joinedBadge: { flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 10, borderRadius: 10 },
    section: { padding: 16, borderTopWidth: 1 },
    sectionTitle: { marginBottom: 10 },
    payoutRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10 },
    participantRow: { flexDirection: 'row', alignItems: 'center', paddingVertical: 10 },
    avatarCircle: { width: 36, height: 36, borderRadius: 18, alignItems: 'center', justifyContent: 'center', marginRight: 10 },
    youBadge: { paddingHorizontal: 8, paddingVertical: 3, borderRadius: 8 },
    assignedItemCard: { flexDirection: 'row', alignItems: 'center', padding: 12, borderRadius: 10, borderWidth: 1 },
    assignedItemImage: { width: 44, height: 44, borderRadius: 8 },
    listTabBar: { flexDirection: 'row', borderBottomWidth: 1, marginBottom: 8 },
    listTab: { flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', paddingVertical: 10 },
    desktopPanel: { borderRadius: 12, borderWidth: 1, padding: 14 },
    desktopPanelTitle: { textTransform: 'uppercase', letterSpacing: 1, fontSize: 10, lineHeight: 13, marginBottom: 8 },
});
