import React, { useState, useMemo, useEffect } from 'react';
import { StyleSheet, ScrollView, TouchableOpacity, Image, FlatList, Platform, useWindowDimensions, RefreshControl, TextInput, KeyboardAvoidingView } 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 { useCalcuttaResults } from '../hooks/useCalcuttaResults';
import { useCalcuttaSocket } from '../hooks/useCalcuttaSocket';
import { formatCurrency, getStatusLabel, resolveItemImageUrl } from '../helpers/formatting';

export interface CalcuttaResultsProps {
    calcutta_competition_id: string;
    player_id?: string;
    access_token?: string;
    device_id?: string;
    player_username?: string;
    player_profile_pic?: string;
    onManage?: () => void;
    onShare?: () => void;
    onRefresh?: () => void | Promise<void>;
}

export const CalcuttaResults: React.FC<CalcuttaResultsProps> = ({
    calcutta_competition_id,
    player_id,
    access_token,
    device_id,
    player_username,
    player_profile_pic,
    onManage,
    onShare,
    onRefresh,
}) => {
    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,
        rounds,
        items,
        participants,
        payout_rules,
        item_results,
        refresh,
    } = useCalcuttaCompetition(calcutta_competition_id);

    const participantIds = useMemo(() => participants.map(p => p.player_id), [participants]);
    const { players: enrichedPlayers } = useCalcuttaPlayers(participantIds);
    const { images: itemImages } = useCalcuttaItemImages(items);
    const { roundSummaries, itemPerformance } = useCalcuttaResults(rounds, items, item_results, payout_rules);

    const { presence, socketState } = useCalcuttaSocket(
        calcutta_competition_id,
        access_token,
        device_id,
        { username: player_username, profile_pic: player_profile_pic },
    );

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

    // Derived data
    const isAdmin = player_id != null && competition?.admin_id == player_id;
    const myItems = useMemo(() =>
        items.filter(i => i.winning_player_id == player_id).sort((a, b) => Number(b.winning_bid || 0) - Number(a.winning_bid || 0)),
        [items, player_id]
    );
    const totalPot = useMemo(() =>
        items.filter(i => i.status === 'sold').reduce((sum, i) => sum + Number(i.winning_bid || 0), 0) || Number(competition?.total_pot) || 0,
        [items, competition?.total_pot]
    );
    const unclaimedPot = Number(competition?.unclaimed_pot) || 0;
    const myParticipant = useMemo(() => participants.find(p => p.player_id == player_id), [participants, player_id]);
    const myTotalSpent = Number(myParticipant?.total_spent) || 0;
    const myTotalEarned = Number(myParticipant?.total_winnings) || 0;

    const statusLabel = competition?.status === 'closed' ? 'Completed'
        : competition?.status === 'inprogress' ? 'In Progress'
        : 'Auction Closed';
    const statusColor = competition?.status === 'closed' ? '#6B7280'
        : competition?.status === 'inprogress' ? '#8B5CF6'
        : '#F59E0B';

    // Sorted leaderboard
    const leaderboard = useMemo(() =>
        [...participants].sort((a, b) => {
            if (a.place && b.place) return a.place - b.place;
            if (a.place) return -1;
            if (b.place) return 1;
            return Number(b.total_winnings) - Number(a.total_winnings);
        }),
        [participants]
    );

    // Mobile tab
    type BottomTab = 'rounds' | 'leaderboard' | 'items';
    const [mobileTab, setMobileTab] = useState<BottomTab>('rounds');

    // Expandable rounds
    const [expandedRound, setExpandedRound] = useState<number | null>(null);

    // Leaderboard search, pagination
    const [leaderSearch, setLeaderSearch] = useState('');
    const LEADERS_PER_PAGE = 20;
    const [leaderPage, setLeaderPage] = useState(0);

    const filteredLeaderboard = useMemo(() => {
        if (!leaderSearch.trim()) return leaderboard;
        const q = leaderSearch.toLowerCase();
        return leaderboard.filter(p => {
            const profile = enrichedPlayers[p.player_id];
            const username = (profile?.username || profile?.show_name || '').toLowerCase();
            if (username.includes(q)) return true;
            if (p.player_id == player_id && 'you'.includes(q)) return true;
            return false;
        });
    }, [leaderboard, leaderSearch, enrichedPlayers, player_id]);

    const pagedLeaderboard = useMemo(() => {
        const start = leaderPage * LEADERS_PER_PAGE;
        return filteredLeaderboard.slice(start, start + LEADERS_PER_PAGE);
    }, [filteredLeaderboard, leaderPage]);

    const totalLeaderPages = Math.ceil(filteredLeaderboard.length / LEADERS_PER_PAGE);

    // Item search, sort, pagination
    const [itemSearch, setItemSearch] = useState('');
    type ItemSort = 'name' | 'paid' | 'bid';
    const [itemSort, setItemSort] = useState<ItemSort>('paid');
    const ITEMS_PER_PAGE = 20;
    const [itemPage, setItemPage] = useState(0);

    const itemEarningsMap = useMemo(() => {
        const map: Record<string, number> = {};
        for (const ip of itemPerformance) {
            map[ip.item.calcutta_auction_item_id] = ip.total_earned;
        }
        return map;
    }, [itemPerformance]);

    const filteredItems = useMemo(() => {
        let result = items;
        if (itemSearch.trim()) {
            const q = itemSearch.toLowerCase();
            result = result.filter(i => {
                if (i.item_name.toLowerCase().includes(q)) return true;
                if (i.winning_player_id) {
                    const owner = enrichedPlayers[i.winning_player_id];
                    if ((owner?.username || '').toLowerCase().includes(q)) return true;
                }
                return false;
            });
        }
        return [...result].sort((a, b) => {
            switch (itemSort) {
                case 'paid':
                    return (itemEarningsMap[b.calcutta_auction_item_id] || 0) - (itemEarningsMap[a.calcutta_auction_item_id] || 0);
                case 'bid':
                    return Number(b.winning_bid || 0) - Number(a.winning_bid || 0);
                case 'name':
                default:
                    return a.item_name.localeCompare(b.item_name);
            }
        });
    }, [items, itemSearch, enrichedPlayers, itemSort, itemEarningsMap]);

    const pagedItems = useMemo(() => {
        const start = itemPage * ITEMS_PER_PAGE;
        return filteredItems.slice(start, start + ITEMS_PER_PAGE);
    }, [filteredItems, itemPage]);

    const totalItemPages = Math.ceil(filteredItems.length / ITEMS_PER_PAGE);

    if (loading && !competition) {
        return (
            <View variant="transparent" style={[styles.container, { backgroundColor: theme.colors.surface.base, alignItems: 'center', justifyContent: 'center' }]}>
                <Text variant="body" color="secondary">Loading...</Text>
            </View>
        );
    }

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

    const marketType = competition.market_type;
    const isSweepstakes = competition.auction_type === 'sweepstakes';

    // ═══ RENDER HELPERS ═══

    const renderHeader = () => (
        <View variant="transparent" style={{ paddingHorizontal: 16, paddingVertical: 12 }}>
            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center' }}>
                <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', backgroundColor: statusColor + '20', paddingHorizontal: 10, paddingVertical: 4, borderRadius: 12 }}>
                    <View variant="transparent" style={{ width: 6, height: 6, borderRadius: 3, backgroundColor: statusColor, marginRight: 6 }} />
                    <Text variant="caption" bold style={{ color: statusColor, fontSize: 11, lineHeight: 15 }}>{statusLabel}</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 }} />
                {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 style={{ marginTop: 8 }}>{competition.competition_name}</Text>
            {competition.competition_description ? (
                <Text variant="caption" color="secondary" style={{ marginTop: 4 }}>{competition.competition_description}</Text>
            ) : null}
        </View>
    );

    const renderMyItems = () => {
        if (myItems.length === 0) return null;
        return (
            <View variant="transparent" style={{ paddingHorizontal: 16 }}>
                <Text variant="caption" bold color="tertiary" style={styles.sectionLabel}>
                    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;
                        const isEliminated = mi.status === 'eliminated';
                        return (
                            <View key={mi.calcutta_auction_item_id} variant="transparent" style={{
                                backgroundColor: theme.colors.surface.elevated, borderColor: isEliminated ? theme.colors.status.error + '40' : theme.colors.border.subtle,
                                borderWidth: 1, borderRadius: 10, padding: 10, alignItems: 'center', width: 110, opacity: isEliminated ? 0.6 : 1,
                            }}>
                                {imgUrl ? (
                                    <Image source={{ uri: imgUrl }} style={{ width: 40, height: 40, borderRadius: 8, marginBottom: 6 }} resizeMode="cover" />
                                ) : (
                                    <Ionicons name="trophy" size={24} color={isEliminated ? theme.colors.text.tertiary : 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 && !isSweepstakes && (
                                    <Text variant="caption" bold style={{ color: '#10B981', marginTop: 2, fontSize: 11, lineHeight: 15 }}>{formatCurrency(mi.winning_bid, marketType)}</Text>
                                )}
                                {isEliminated && (
                                    <Text variant="caption" style={{ color: theme.colors.status.error, fontSize: 9, lineHeight: 12, marginTop: 2 }}>Eliminated</Text>
                                )}
                            </View>
                        );
                    })}
                </ScrollView>
            </View>
        );
    };

    const renderPotKPIs = () => {
        const kpiStyle = isDesktop
            ? [styles.kpiCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]
            : [styles.kpiCard, { flex: 0, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle, minWidth: '31%' as any, flexGrow: 1 }];

        return (
            <View variant="transparent" style={{ flexDirection: 'row', flexWrap: 'wrap', paddingHorizontal: 16, paddingVertical: 8, gap: 10 }}>
                {!isSweepstakes && (
                    <View variant="transparent" style={kpiStyle}>
                        <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Pot</Text>
                        <Text variant="h3" bold style={{ color: '#F59E0B' }}>{formatCurrency(totalPot, marketType)}</Text>
                    </View>
                )}
                {!isSweepstakes && unclaimedPot > 0 && (
                    <View variant="transparent" style={kpiStyle}>
                        <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Unclaimed</Text>
                        <Text variant="h3" bold style={{ color: '#8B5CF6' }}>{formatCurrency(unclaimedPot, marketType)}</Text>
                    </View>
                )}
                {!isSweepstakes && myTotalSpent > 0 && (
                    <View variant="transparent" style={kpiStyle}>
                        <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>You Spent</Text>
                        <Text variant="h3" bold>{formatCurrency(myTotalSpent, marketType)}</Text>
                    </View>
                )}
                {myTotalEarned > 0 && (
                    <View variant="transparent" style={kpiStyle}>
                        <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>You Earned</Text>
                        <Text variant="h3" bold style={{ color: '#10B981' }}>{formatCurrency(myTotalEarned, marketType)}</Text>
                    </View>
                )}
                <View variant="transparent" style={kpiStyle}>
                    <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>Players</Text>
                    <Text variant="h3" bold>{participants.length}</Text>
                </View>
            </View>
        );
    };

    const renderRounds = () => {
        if (roundSummaries.length === 0) return null;
        const sortedRounds = [...roundSummaries].sort((a, b) => a.round.round_number - b.round.round_number);

        // Compute running unclaimed balance per round
        // Each closed round: pool = (pct * pot) + rolledIn, paid out = total_payout, rolled out = pool - paid
        const roundUnclaimed: { rolledIn: number; pool: number; rolledOut: number }[] = [];
        let runningUnclaimed = 0;
        for (const rs of sortedRounds) {
            const basePool = rs.payout_rule ? (rs.payout_rule.payout_pct / 100) * totalPot : 0;
            const pool = basePool + runningUnclaimed;
            const isClosed = rs.round.status === 'closed';
            const rolledOut = isClosed ? Math.max(pool - rs.total_payout, 0) : 0;
            roundUnclaimed.push({ rolledIn: runningUnclaimed, pool, rolledOut });
            if (isClosed) { runningUnclaimed = rolledOut; }
        }

        return (
            <View variant="transparent" style={{ paddingHorizontal: 16 }}>
                <Text variant="caption" bold color="tertiary" style={styles.sectionLabel}>Rounds</Text>
                {sortedRounds.map((rs, idx) => {
                    const isExpanded = expandedRound === rs.round.round_number;
                    const isClosed = rs.round.status === 'closed';
                    const isFinalRound = idx === sortedRounds.length - 1;
                    const { rolledIn, pool: roundPool, rolledOut } = roundUnclaimed[idx];
                    return (
                        <TouchableOpacity
                            key={rs.round.calcutta_round_id}
                            style={[styles.roundCard, { backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}
                            onPress={() => setExpandedRound(isExpanded ? null : rs.round.round_number)}
                            activeOpacity={0.7}
                        >
                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center' }}>
                                <Ionicons name={isClosed ? 'checkmark-circle' : 'ellipse-outline'} size={16} color={isClosed ? '#10B981' : theme.colors.text.tertiary} />
                                <Text variant="body" bold style={{ flex: 1, marginLeft: 8 }}>{rs.round.round_name}</Text>
                                {rs.payout_rule && (
                                    <Text variant="caption" bold style={{ color: '#F59E0B' }}>{rs.payout_rule.payout_pct}%</Text>
                                )}
                                {isClosed && rs.payout_rule && !isSweepstakes && rs.total_payout > 0 && (
                                    <Text variant="caption" bold style={{ color: '#10B981', marginLeft: 8 }}>{formatCurrency(rs.total_payout, marketType)}</Text>
                                )}
                                {isClosed && rs.payout_rule && !isSweepstakes && rs.total_payout < 0.01 && !isFinalRound && (
                                    <Text variant="caption" bold style={{ color: '#8B5CF6', marginLeft: 8 }}>Unclaimed</Text>
                                )}
                                {isClosed && isFinalRound && !isSweepstakes && runningUnclaimed > 0.01 && (
                                    <Text variant="caption" bold style={{ color: '#10B981', marginLeft: 8 }}>Redistributed</Text>
                                )}
                                <Ionicons name={isExpanded ? 'chevron-up' : 'chevron-down'} size={14} color={theme.colors.text.tertiary} style={{ marginLeft: 8 }} />
                            </View>
                            {!isExpanded && isClosed && (
                                <Text variant="caption" color="tertiary" style={{ marginTop: 4, fontSize: 11, lineHeight: 15 }}>
                                    {rs.advanced_items.length} advanced · {rs.eliminated_items.length} eliminated
                                </Text>
                            )}
                            {!isExpanded && !isClosed && rs.payout_rule && !isSweepstakes && (
                                <Text variant="caption" color="tertiary" style={{ marginTop: 4, fontSize: 11, lineHeight: 15 }}>
                                    {formatCurrency(roundPool, marketType)} payout pool{rolledIn > 0.01 ? ` (incl. ${formatCurrency(rolledIn, marketType)} rolled in)` : ''}
                                </Text>
                            )}
                            {isExpanded && (
                                <View variant="transparent" style={{ marginTop: 10 }}>
                                    {!isSweepstakes && rs.payout_rule && (
                                        <View variant="transparent" style={{ marginBottom: 10, paddingVertical: 6, paddingHorizontal: 8, backgroundColor: theme.colors.surface.base, borderRadius: 6, gap: 4 }}>
                                            <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center' }}>
                                                <Ionicons name="cash-outline" size={14} color="#F59E0B" />
                                                <Text variant="caption" color="secondary" style={{ marginLeft: 6, flex: 1 }}>
                                                    {rs.payout_rule.payout_pct}% of pot{rolledIn > 0.01 ? ` + ${formatCurrency(rolledIn, marketType)} rolled in` : ''}
                                                </Text>
                                                <Text variant="caption" bold style={{ color: '#F59E0B' }}>
                                                    {formatCurrency(roundPool, marketType)}
                                                </Text>
                                            </View>
                                            {isClosed && (
                                                <>
                                                    <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingLeft: 20 }}>
                                                        <Ionicons name="checkmark-circle-outline" size={12} color="#10B981" />
                                                        <Text variant="caption" style={{ marginLeft: 6, flex: 1, color: theme.colors.text.tertiary }}>Paid to owners</Text>
                                                        <Text variant="caption" bold style={{ color: '#10B981' }}>{formatCurrency(rs.total_payout, marketType)}</Text>
                                                    </View>
                                                    {rolledOut > 0.01 && !isFinalRound && (
                                                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingLeft: 20 }}>
                                                            <Ionicons name="arrow-forward-outline" size={12} color="#8B5CF6" />
                                                            <Text variant="caption" style={{ marginLeft: 6, flex: 1, color: theme.colors.text.tertiary }}>Rolled to unclaimed</Text>
                                                            <Text variant="caption" bold style={{ color: '#8B5CF6' }}>{formatCurrency(rolledOut, marketType)}</Text>
                                                        </View>
                                                    )}
                                                    {isFinalRound && runningUnclaimed > 0.01 && (
                                                        <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingLeft: 20 }}>
                                                            <Ionicons name="people-outline" size={12} color="#10B981" />
                                                            <Text variant="caption" style={{ marginLeft: 6, flex: 1, color: theme.colors.text.tertiary }}>Redistributed to all players by spend</Text>
                                                            <Text variant="caption" bold style={{ color: '#10B981' }}>{formatCurrency(runningUnclaimed, marketType)}</Text>
                                                        </View>
                                                    )}
                                                </>
                                            )}
                                        </View>
                                    )}
                                    {rs.advanced_items.length > 0 && (
                                        <>
                                            <Text variant="caption" bold style={{ color: '#10B981', marginBottom: 4, fontSize: 10, lineHeight: 13 }}>ADVANCED ({rs.advanced_items.length})</Text>
                                            {rs.advanced_items.map(item => {
                                                const isMe = item.winning_player_id == player_id;
                                                const result = item_results.find(r => r.calcutta_auction_item_id === item.calcutta_auction_item_id && r.round_number === rs.round.round_number);
                                                const payout = Number(result?.payout_earned || 0);
                                                const owner = item.winning_player_id ? enrichedPlayers[item.winning_player_id] : undefined;
                                                const ownerName = isMe ? 'You' : owner?.username || owner?.show_name || '';
                                                return (
                                                    <View key={item.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 3 }}>
                                                        <Ionicons name="checkmark-circle" size={12} color="#10B981" />
                                                        <Text variant="caption" style={{ marginLeft: 6, flex: 1 }} numberOfLines={1}>{item.item_name}</Text>
                                                        {ownerName ? <Text variant="caption" color="tertiary" style={{ marginLeft: 4, fontSize: 10, lineHeight: 13 }}>{ownerName}</Text> : null}
                                                        {payout > 0 && <Text variant="caption" bold style={{ color: '#10B981', marginLeft: 6, fontSize: 10, lineHeight: 13 }}>{formatCurrency(payout, marketType)}</Text>}
                                                    </View>
                                                );
                                            })}
                                        </>
                                    )}
                                    {rs.eliminated_items.length > 0 && (
                                        <>
                                            <Text variant="caption" bold style={{ color: theme.colors.status.error, marginTop: 8, marginBottom: 4, fontSize: 10, lineHeight: 13 }}>ELIMINATED ({rs.eliminated_items.length})</Text>
                                            {rs.eliminated_items.map(item => {
                                                const isMe = item.winning_player_id == player_id;
                                                const result = item_results.find(r => r.calcutta_auction_item_id === item.calcutta_auction_item_id && r.round_number === rs.round.round_number);
                                                const payout = Number(result?.payout_earned || 0);
                                                const owner = item.winning_player_id ? enrichedPlayers[item.winning_player_id] : undefined;
                                                const ownerName = isMe ? 'You' : owner?.username || owner?.show_name || '';
                                                return (
                                                    <View key={item.calcutta_auction_item_id} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 3, opacity: 0.6 }}>
                                                        <Ionicons name="close-circle" size={12} color={theme.colors.status.error} />
                                                        <Text variant="caption" style={{ marginLeft: 6, flex: 1 }} numberOfLines={1}>{item.item_name}</Text>
                                                        {ownerName ? <Text variant="caption" color="tertiary" style={{ marginLeft: 4, fontSize: 10, lineHeight: 13 }}>{ownerName}</Text> : null}
                                                        {payout > 0 && <Text variant="caption" bold style={{ color: '#10B981', marginLeft: 6, fontSize: 10, lineHeight: 13 }}>{formatCurrency(payout, marketType)}</Text>}
                                                    </View>
                                                );
                                            })}
                                        </>
                                    )}
                                    {isClosed && rs.advanced_items.length === 0 && rs.eliminated_items.length === 0 && (
                                        <Text variant="caption" color="tertiary" style={{ fontSize: 11, lineHeight: 15, fontStyle: 'italic' }}>
                                            No items remaining — round resolved with empty field
                                        </Text>
                                    )}
                                    {isClosed && !isSweepstakes && rolledOut > 0.01 && !isFinalRound && (
                                        <View variant="transparent" style={{ marginTop: 8, flexDirection: 'row', alignItems: 'center', backgroundColor: '#8B5CF610', paddingVertical: 6, paddingHorizontal: 8, borderRadius: 6 }}>
                                            <Ionicons name="arrow-forward-outline" size={14} color="#8B5CF6" />
                                            <Text variant="caption" style={{ marginLeft: 6, color: '#8B5CF6', flex: 1 }}>
                                                {formatCurrency(rolledOut, marketType)} unclaimed — rolls forward to next round
                                            </Text>
                                        </View>
                                    )}
                                    {isClosed && !isSweepstakes && isFinalRound && runningUnclaimed > 0.01 && (() => {
                                        const totalSpentAll = participants.reduce((s, p) => s + Number(p.total_spent), 0);
                                        const playerShares = totalSpentAll > 0
                                            ? participants
                                                .filter(p => Number(p.total_spent) > 0)
                                                .map(p => {
                                                    const pct = (Number(p.total_spent) / totalSpentAll) * 100;
                                                    const share = (pct / 100) * runningUnclaimed;
                                                    const profile = enrichedPlayers[p.player_id];
                                                    const isMe = p.player_id == player_id;
                                                    const name = isMe ? 'You' : profile?.username || profile?.show_name || 'Player';
                                                    return { name, share, pct, isMe };
                                                })
                                                .sort((a, b) => b.share - a.share)
                                            : [];
                                        return (
                                            <View variant="transparent" style={{ marginTop: 8, backgroundColor: '#10B98110', paddingVertical: 8, paddingHorizontal: 10, borderRadius: 6 }}>
                                                <View variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', marginBottom: 6 }}>
                                                    <Ionicons name="people-outline" size={14} color="#10B981" />
                                                    <Text variant="caption" bold style={{ marginLeft: 6, color: '#10B981' }}>
                                                        {formatCurrency(runningUnclaimed, marketType)} redistributed by spend
                                                    </Text>
                                                </View>
                                                {playerShares.map((ps, i) => (
                                                    <View key={i} variant="transparent" style={{ flexDirection: 'row', alignItems: 'center', paddingVertical: 2, paddingLeft: 20 }}>
                                                        <Text variant="caption" style={{ flex: 1, color: ps.isMe ? '#10B981' : theme.colors.text.secondary }} numberOfLines={1}>
                                                            {ps.name} <Text variant="caption" color="tertiary" style={{ fontSize: 10, lineHeight: 13 }}>({ps.pct.toFixed(1)}%)</Text>
                                                        </Text>
                                                        <Text variant="caption" bold style={{ color: '#10B981' }}>
                                                            {formatCurrency(ps.share, marketType)}
                                                        </Text>
                                                    </View>
                                                ))}
                                            </View>
                                        );
                                    })()}
                                    {rs.prize_description && (
                                        <View variant="transparent" style={{ marginTop: 8, flexDirection: 'row', alignItems: 'center' }}>
                                            <Ionicons name="gift" size={14} color="#8B5CF6" />
                                            <Text variant="caption" style={{ marginLeft: 6, color: '#8B5CF6' }}>{rs.prize_description}</Text>
                                        </View>
                                    )}
                                </View>
                            )}
                        </TouchableOpacity>
                    );
                })}
            </View>
        );
    };

    const renderLeaderboard = () => {
        const medals = ['🥇', '🥈', '🥉'];

        // Map original rank from the full leaderboard
        const rankMap = new Map<string, number>();
        leaderboard.forEach((p, i) => rankMap.set(p.calcutta_participant_id, i));

        return (
            <View variant="transparent" style={{ paddingHorizontal: 16 }}>
                <Text variant="caption" bold color="tertiary" style={styles.sectionLabel}>Leaderboard ({participants.length})</Text>

                <TextInput
                    value={leaderSearch}
                    onChangeText={v => { setLeaderSearch(v); setLeaderPage(0); }}
                    placeholder="Search players..."
                    placeholderTextColor={theme.colors.text.tertiary}
                    style={{
                        color: theme.colors.text.primary,
                        backgroundColor: theme.colors.surface.elevated,
                        borderColor: theme.colors.border.subtle,
                        borderWidth: 1,
                        borderRadius: 8,
                        paddingHorizontal: 10,
                        paddingVertical: 8,
                        fontSize: 13,
                        marginBottom: 8,
                    }}
                />

                {pagedLeaderboard.map(p => {
                    const rank = rankMap.get(p.calcutta_participant_id) ?? 0;
                    const profile = enrichedPlayers[p.player_id];
                    const username = profile?.username || profile?.show_name || `Player`;
                    const profilePic = profile?.profile_pic;
                    const isMe = p.player_id == player_id;
                    return (
                        <View key={p.calcutta_participant_id} variant="transparent" style={[styles.leaderRow, { borderColor: theme.colors.border.subtle }]}>
                            <Text style={{ width: 28, textAlign: 'center', fontSize: 14, lineHeight: 19 }}>{rank < 3 ? medals[rank] : `${rank + 1}`}</Text>
                            {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: 8 }}>
                                <Text variant="body" bold={isMe} style={isMe ? { color: '#10B981' } : undefined}>{isMe ? 'You' : username}</Text>
                                <Text variant="caption" color="tertiary">{p.items_owned} item{p.items_owned !== 1 ? 's' : ''} · {formatCurrency(p.total_spent, marketType)} spent{totalPot > 0 ? ` · ${((Number(p.total_spent) / totalPot) * 100).toFixed(1)}%` : ''}</Text>
                            </View>
                            {Number(p.total_spent) > 0 && (
                                <View variant="transparent" style={{ alignItems: 'flex-end' }}>
                                    <Text variant="caption" bold style={{ color: '#10B981' }}>{formatCurrency(p.total_winnings, marketType)}</Text>
                                    {(() => {
                                        const roi = ((Number(p.total_winnings) - Number(p.total_spent)) / Number(p.total_spent)) * 100;
                                        return (
                                            <Text variant="caption" style={{ color: roi >= 0 ? '#10B981' : theme.colors.status.error, fontSize: 10, lineHeight: 13 }}>
                                                {roi >= 0 ? '+' : ''}{roi.toFixed(1)}%
                                            </Text>
                                        );
                                    })()}
                                </View>
                            )}
                        </View>
                    );
                })}

                {totalLeaderPages > 1 && (
                    <View variant="transparent" style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 12, gap: 12 }}>
                        <TouchableOpacity
                            onPress={() => setLeaderPage(p => Math.max(0, p - 1))}
                            disabled={leaderPage === 0}
                            style={{ opacity: leaderPage === 0 ? 0.3 : 1 }}
                        >
                            <Ionicons name="chevron-back" size={20} color={theme.colors.text.secondary} />
                        </TouchableOpacity>
                        <Text variant="caption" color="secondary">
                            {leaderPage + 1} / {totalLeaderPages}
                        </Text>
                        <TouchableOpacity
                            onPress={() => setLeaderPage(p => Math.min(totalLeaderPages - 1, p + 1))}
                            disabled={leaderPage >= totalLeaderPages - 1}
                            style={{ opacity: leaderPage >= totalLeaderPages - 1 ? 0.3 : 1 }}
                        >
                            <Ionicons name="chevron-forward" size={20} color={theme.colors.text.secondary} />
                        </TouchableOpacity>
                    </View>
                )}
            </View>
        );
    };

    const renderAllItems = () => {
        const sortOptions: { key: ItemSort; label: string }[] = [
            { key: 'paid', label: 'Most Paid' },
            { key: 'bid', label: 'Highest Bid' },
            { key: 'name', label: 'Name' },
        ];

        return (
            <View variant="transparent" style={{ paddingHorizontal: 16, paddingBottom: 40 }}>
                <Text variant="caption" bold color="tertiary" style={styles.sectionLabel}>All Items ({items.length})</Text>

                {/* Search */}
                <TextInput
                    value={itemSearch}
                    onChangeText={v => { setItemSearch(v); setItemPage(0); }}
                    placeholder="Search items or owners..."
                    placeholderTextColor={theme.colors.text.tertiary}
                    style={{
                        color: theme.colors.text.primary,
                        backgroundColor: theme.colors.surface.elevated,
                        borderColor: theme.colors.border.subtle,
                        borderWidth: 1,
                        borderRadius: 8,
                        paddingHorizontal: 10,
                        paddingVertical: 8,
                        fontSize: 13,
                        marginBottom: 8,
                    }}
                />

                {/* Sort pills */}
                <View variant="transparent" style={{ flexDirection: 'row', gap: 6, marginBottom: 10 }}>
                    {sortOptions.map(opt => {
                        const active = itemSort === opt.key;
                        return (
                            <TouchableOpacity
                                key={opt.key}
                                onPress={() => { setItemSort(opt.key); setItemPage(0); }}
                                style={{
                                    paddingHorizontal: 10,
                                    paddingVertical: 4,
                                    borderRadius: 12,
                                    backgroundColor: active ? theme.colors.primary.default : theme.colors.surface.elevated,
                                    borderWidth: 1,
                                    borderColor: active ? theme.colors.primary.default : theme.colors.border.subtle,
                                }}
                            >
                                <Text variant="caption" bold={active} style={{ color: active ? '#FFF' : theme.colors.text.secondary, fontSize: 11, lineHeight: 15 }}>
                                    {opt.label}
                                </Text>
                            </TouchableOpacity>
                        );
                    })}
                </View>

                {/* Items */}
                {pagedItems.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;
                    const earned = itemEarningsMap[item.calcutta_auction_item_id] || 0;
                    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: 28, height: 28, borderRadius: 6 }} resizeMode="cover" />
                            ) : (
                                <View variant="transparent" style={{ width: 28, height: 28, borderRadius: 6, backgroundColor: theme.colors.surface.elevated, alignItems: 'center', justifyContent: 'center' }}>
                                    <Ionicons name="trophy-outline" size={14} color={theme.colors.text.tertiary} />
                                </View>
                            )}
                            <View variant="transparent" style={{ marginLeft: 8, flex: 1 }}>
                                <Text variant="body" numberOfLines={1}>{item.item_name}</Text>
                                <Text variant="caption" color="tertiary">
                                    {ownerName ? (isMe ? 'You' : ownerName) : 'Unowned'}
                                    {item.status === 'eliminated' ? ' · Eliminated' : item.status === 'sold' ? '' : ` · ${getStatusLabel(item.status)}`}
                                </Text>
                            </View>
                            <View variant="transparent" style={{ alignItems: 'flex-end' }}>
                                {Number(item.winning_bid) > 0 && !isSweepstakes && (
                                    <Text variant="caption" bold>{formatCurrency(item.winning_bid, marketType)}</Text>
                                )}
                                {earned > 0 && (
                                    <Text variant="caption" bold style={{ color: '#10B981', fontSize: 10, lineHeight: 13 }}>{formatCurrency(earned, marketType)} earned</Text>
                                )}
                            </View>
                            {isMe && <Text variant="caption" bold style={{ color: '#10B981', marginLeft: 6, fontSize: 10, lineHeight: 13 }}>YOU</Text>}
                        </View>
                    );
                })}

                {/* Pagination */}
                {totalItemPages > 1 && (
                    <View variant="transparent" style={{ flexDirection: 'row', justifyContent: 'center', alignItems: 'center', marginTop: 12, gap: 12 }}>
                        <TouchableOpacity
                            onPress={() => setItemPage(p => Math.max(0, p - 1))}
                            disabled={itemPage === 0}
                            style={{ opacity: itemPage === 0 ? 0.3 : 1 }}
                        >
                            <Ionicons name="chevron-back" size={20} color={theme.colors.text.secondary} />
                        </TouchableOpacity>
                        <Text variant="caption" color="secondary">
                            {itemPage + 1} / {totalItemPages}
                        </Text>
                        <TouchableOpacity
                            onPress={() => setItemPage(p => Math.min(totalItemPages - 1, p + 1))}
                            disabled={itemPage >= totalItemPages - 1}
                            style={{ opacity: itemPage >= totalItemPages - 1 ? 0.3 : 1 }}
                        >
                            <Ionicons name="chevron-forward" size={20} color={theme.colors.text.secondary} />
                        </TouchableOpacity>
                    </View>
                )}
            </View>
        );
    };

    // ═══ RENDER ═══

    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} />}>
                    {renderHeader()}
                    {renderMyItems()}
                    {renderPotKPIs()}

                    <View variant="transparent" style={{ flexDirection: 'row', gap: 12, marginTop: 12, paddingHorizontal: 4 }}>
                        {/* Left: Rounds */}
                        <View variant="transparent" style={[styles.panel, { flex: 3, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {renderRounds()}
                            </ScrollView>
                        </View>

                        {/* Right: Leaderboard */}
                        <View variant="transparent" style={[styles.panel, { flex: 2, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                            <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false}>
                                {renderLeaderboard()}
                            </ScrollView>
                        </View>
                    </View>

                    <View variant="transparent" style={[styles.panel, { marginTop: 12, marginHorizontal: 4, backgroundColor: theme.colors.surface.elevated, borderColor: theme.colors.border.subtle }]}>
                        <ScrollView nestedScrollEnabled showsVerticalScrollIndicator={false} style={{ maxHeight: 400 }}>
                            {renderAllItems()}
                        </ScrollView>
                    </View>
                </ScrollView>
            ) : (
                <KeyboardAvoidingView style={{ flex: 1 }} behavior={Platform.OS === 'ios' ? 'padding' : undefined} keyboardVerticalOffset={Platform.OS === 'ios' ? 90 : 0}>
                    <ScrollView style={{ flex: 1, backgroundColor: theme.colors.surface.base }} contentContainerStyle={{ paddingBottom: 40, backgroundColor: theme.colors.surface.base }} keyboardShouldPersistTaps="handled" refreshControl={<RefreshControl refreshing={refreshing} onRefresh={handleRefresh} />}>
                        {renderHeader()}
                        {renderMyItems()}
                        {renderPotKPIs()}
                        <View variant="transparent" style={{ flexDirection: 'row', marginHorizontal: 16, marginTop: 8, marginBottom: 4, borderRadius: 10, backgroundColor: theme.colors.surface.elevated, borderWidth: 1, borderColor: theme.colors.border.subtle, overflow: 'hidden' }}>
                            {([
                                { key: 'rounds' as BottomTab, label: 'Rounds', icon: 'layers-outline' as const },
                                { key: 'leaderboard' as BottomTab, label: 'Leaderboard', icon: 'podium-outline' as const },
                                { key: 'items' as BottomTab, label: 'Items', icon: 'list-outline' as const },
                            ]).map(tab => {
                                const active = mobileTab === tab.key;
                                return (
                                    <TouchableOpacity
                                        key={tab.key}
                                        onPress={() => setMobileTab(tab.key)}
                                        style={{ flex: 1, flexDirection: 'row', alignItems: 'center', justifyContent: 'center', gap: 6, height: 44, backgroundColor: active ? theme.colors.primary.default : 'transparent' }}
                                        activeOpacity={0.7}
                                    >
                                        <Ionicons name={tab.icon} size={14} color={active ? '#FFF' : theme.colors.text.tertiary} />
                                        <Text variant="caption" bold={active} style={{ color: active ? '#FFF' : theme.colors.text.tertiary }}>
                                            {tab.label}
                                        </Text>
                                    </TouchableOpacity>
                                );
                            })}
                        </View>
                        {mobileTab === 'rounds' && renderRounds()}
                        {mobileTab === 'leaderboard' && renderLeaderboard()}
                        {mobileTab === 'items' && renderAllItems()}
                    </ScrollView>
                </KeyboardAvoidingView>
            )}
        </View>
    );
};

const styles = StyleSheet.create({
    container: {
        flex: 1,
    },
    sectionLabel: {
        textTransform: 'uppercase',
        letterSpacing: 1,
        fontSize: 10,
        lineHeight: 13,
        marginBottom: 8,
        marginTop: 16,
    },
    kpiCard: {
        flex: 1,
        borderRadius: 10,
        padding: 10,
        alignItems: 'center',
        borderWidth: 1,
    },
    roundCard: {
        borderRadius: 10,
        borderWidth: 1,
        padding: 12,
        marginBottom: 8,
    },
    leaderRow: {
        flexDirection: 'row',
        alignItems: 'center',
        paddingVertical: 8,
        borderBottomWidth: 1,
    },
    panel: {
        borderRadius: 12,
        borderWidth: 1,
        padding: 8,
    },
});
