const { useState, useEffect, useRef, useMemo } = React;
const { motion, AnimatePresence } = window.Motion || window.framerMotion || { motion: { div: 'div', button: 'button', span: 'span', h1: 'h1', h2: 'h2', h3: 'h3', p: 'p' }, AnimatePresence: ({ children }) => <>{children}</> };

function CustomBet({ t = {}, lang = 'TR', userProfile, formatMoney, Icons = window.Icons, API_URL, token, onBalanceUpdate, onBackToLobby, setShowDebtPanel })
{
    // 3-Tier Views: 'lobby' (Rooms) | 'room' (Bets in room) | 'bet' (Single Bet Detail)
    const [view, setView] = useState('lobby');
    const [rooms, setRooms] = useState([]);
    const [currentRoom, setCurrentRoom] = useState(null);
    const [activeBetId, setActiveBetId] = useState(null);
    
    // Betting State for Bet Detail view
    const [selectedOptionId, setSelectedOptionId] = useState(null);
    const [betAmount, setBetAmount] = useState(10000);
    
    // Room creation modal
    const [showCreateRoomModal, setShowCreateRoomModal] = useState(false);
    const [newRoomTitle, setNewRoomTitle] = useState('');
    const [newRoomDesc, setNewRoomDesc] = useState('');
    const [newRoomPassword, setNewRoomPassword] = useState('');
    const [initialQuestion, setInitialQuestion] = useState('');
    const [initialOptions, setInitialOptions] = useState(['', '']);

    // Add Bet to existing room modal
    const [showAddBetModal, setShowAddBetModal] = useState(false);
    const [newBetQuestion, setNewBetQuestion] = useState('');
    const [newBetOptions, setNewBetOptions] = useState(['', '']);

    // Edit Bet modal
    const [showEditBetModal, setShowEditBetModal] = useState(false);
    const [editModalBet, setEditModalBet] = useState(null);
    const [editBetQuestion, setEditBetQuestion] = useState('');
    const [editBetOptions, setEditBetOptions] = useState(['', '']);

    // Password prompt modal
    const [passwordModalRoom, setPasswordModalRoom] = useState(null);
    const [enteredPassword, setEnteredPassword] = useState('');
    const [passwordError, setPasswordError] = useState(null);

    // Resolve Modal / Results
    const [resolveModalBet, setResolveModalBet] = useState(null);
    const [selectedWinnerOptionId, setSelectedWinnerOptionId] = useState(null);
    const [resolveResults, setResolveResults] = useState(null);

    const [wsConnected, setWsConnected] = useState(false);
    const [error, setError] = useState(null);

    const wsRef = useRef(null);
    const reconnectTimeout = useRef(null);
    const audioCtxRef = useRef(null);

    const isAdmin = userProfile?.username?.toLowerCase() === 'admin';

    const wsUrl = useMemo(() =>
    {
        const api = API_URL || window.API_URL || (
            window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === ''
                ? 'http://localhost:3001'
                : 'https://api.tmn-studio.cloud'
        );
        const userToken = token || localStorage.getItem('luck_token') || '';
        const userVal = userProfile?.username || '';
        return api.replace(/^http/, 'ws') + `/ws/custom-bet?token=${encodeURIComponent(userToken)}&username=${encodeURIComponent(userVal)}`;
    }, [API_URL, token, userProfile?.username]);

    useEffect(() =>
    {
        audioCtxRef.current = new (window.AudioContext || window.webkitAudioContext)();
        return () =>
        {
            if (audioCtxRef.current)
            {
                audioCtxRef.current.close();
            }
        };
    }, []);

    const playSound = (type) =>
    {
        if (!audioCtxRef.current) return;
        const ctx = audioCtxRef.current;
        if (ctx.state === 'suspended')
        {
            ctx.resume();
        }

        const osc = ctx.createOscillator();
        const gainNode = ctx.createGain();

        osc.connect(gainNode);
        gainNode.connect(ctx.destination);

        if (type === 'bet')
        {
            osc.type = 'sine';
            osc.frequency.setValueAtTime(800, ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(1200, ctx.currentTime + 0.1);
            gainNode.gain.setValueAtTime(0.1, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.1);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.1);
        }
        else if (type === 'lock')
        {
            osc.type = 'square';
            osc.frequency.setValueAtTime(200, ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(150, ctx.currentTime + 0.3);
            gainNode.gain.setValueAtTime(0.1, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.3);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.3);
        }
        else if (type === 'win')
        {
            osc.type = 'triangle';
            osc.frequency.setValueAtTime(400, ctx.currentTime);
            osc.frequency.setValueAtTime(600, ctx.currentTime + 0.1);
            osc.frequency.setValueAtTime(800, ctx.currentTime + 0.2);
            gainNode.gain.setValueAtTime(0.15, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.5);
        }
        else if (type === 'lose')
        {
            osc.type = 'sawtooth';
            osc.frequency.setValueAtTime(300, ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(100, ctx.currentTime + 0.5);
            gainNode.gain.setValueAtTime(0.1, ctx.currentTime);
            gainNode.gain.exponentialRampToValueAtTime(0.01, ctx.currentTime + 0.5);
            osc.start(ctx.currentTime);
            osc.stop(ctx.currentTime + 0.5);
        }
    };

    const getUserBetOutcome = (bet) =>
    {
        if (!bet || !userProfile?.username) return null;
        const userBets = [];
        const lowerUser = (userProfile.username || '').toLowerCase();

        (bet.options || []).forEach(opt =>
        {
            (opt.bettors || []).forEach(b =>
            {
                if ((b.username || '').toLowerCase() === lowerUser)
                {
                    userBets.push({
                        optionId: opt.id,
                        label: opt.label,
                        amount: b.amount || 0
                    });
                }
            });
        });

        if (userBets.length === 0) return null;

        const totalBet = userBets.reduce((sum, b) => sum + b.amount, 0);

        if (bet.status !== 'resolved')
        {
            return {
                totalBet,
                isResolved: false,
                bets: userBets
            };
        }

        const effectivePool = (bet.totalPool || 0) * (1 - (bet.rakePercent || 0.05));
        const winningOpt = (bet.options || []).find(o => o.id === bet.winningOptionId);
        const winningTotal = winningOpt ? (winningOpt.totalBetAmount || 0) : 0;
        const minOdds = (window.GAME_CONFIG && window.GAME_CONFIG.customBet && window.GAME_CONFIG.customBet.MIN_ODDS) || 1.10;
        const rawWinningOdds = winningTotal > 0 ? (effectivePool / winningTotal) : 0;
        const winningOdds = rawWinningOdds > 0 ? Math.max(minOdds, rawWinningOdds) : 0;

        let totalPayout = 0;
        const breakdown = userBets.map(b =>
        {
            const isWinner = (b.optionId === bet.winningOptionId);
            let payout = 0;
            if (isWinner && winningTotal > 0)
            {
                payout = Math.floor(b.amount * winningOdds);
            }
            totalPayout += payout;
            return {
                ...b,
                payout,
                isWinner
            };
        });

        const netProfit = totalPayout - totalBet;

        return {
            totalBet,
            totalPayout,
            netProfit,
            winningOdds,
            isResolved: true,
            isWin: netProfit > 0,
            isPartialWin: netProfit <= 0 && totalPayout > 0,
            isLoss: totalPayout === 0,
            bets: breakdown
        };
    };

    const connectWs = () =>
    {
        try
        {
            const socket = new WebSocket(wsUrl);

            socket.onopen = () =>
            {
                setWsConnected(true);
                setError(null);
                sendAction('GET_CUSTOM_ROOMS', {}, socket);
            };

            socket.onmessage = (event) =>
            {
                try
                {
                    const data = JSON.parse(event.data);
                    handleSocketEvent(data);
                }
                catch (err)
                {
                    console.error('Failed to parse websocket message', err);
                }
            };

            socket.onclose = () =>
            {
                setWsConnected(false);
                reconnectTimeout.current = setTimeout(connectWs, 2500);
            };

            socket.onerror = (err) =>
            {
                console.error('WebSocket Error:', err);
                socket.close();
            };

            wsRef.current = socket;
        }
        catch (err)
        {
            console.error('CustomBet connectWs exception:', err);
            reconnectTimeout.current = setTimeout(connectWs, 2500);
        }
    };

    const fetchRoomsHttp = () =>
    {
        const httpUrl = (API_URL || window.API_URL || (
            window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === ''
                ? 'http://localhost:3001'
                : 'https://api.tmn-studio.cloud'
        )) + `/api/custom-bets?username=${encodeURIComponent(userProfile?.username || '')}`;

        const userToken = token || localStorage.getItem('luck_token');
        const headers = userToken ? { 'Authorization': `Bearer ${userToken}` } : {};

        fetch(httpUrl, { headers })
            .then(res => res.json())
            .then(data =>
            {
                if (data.success && Array.isArray(data.rooms))
                {
                    setRooms(data.rooms);
                }
            })
            .catch(() => {});
    };

    useEffect(() =>
    {
        fetchRoomsHttp();
    }, [view]);

    useEffect(() =>
    {
        fetchRoomsHttp();
        connectWs();
        return () =>
        {
            if (wsRef.current)
            {
                wsRef.current.close();
            }
            if (reconnectTimeout.current)
            {
                clearTimeout(reconnectTimeout.current);
            }
        };
    }, [wsUrl]);

    const sendAction = (action, payload = {}, socket = wsRef.current) =>
    {
        const targetSocket = socket || wsRef.current;
        if (targetSocket && targetSocket.readyState === WebSocket.OPEN)
        {
            targetSocket.send(JSON.stringify({
                action,
                payload: {
                    ...payload,
                    username: userProfile?.username
                },
                token: token || localStorage.getItem('luck_token')
            }));
        }
        else
        {
            console.warn('CustomBet socket not open yet. readyState:', targetSocket?.readyState);
        }
    };

    const handleSocketEvent = (data) =>
    {
        switch (data.type)
        {
            case 'CUSTOM_ROOMS_LIST':
                setRooms(data.rooms || []);
                break;

            case 'CUSTOM_ROOM_JOINED':
                setPasswordModalRoom(null);
                setEnteredPassword('');
                setPasswordError(null);
                setCurrentRoom(data.room);
                setView('room');
                setActiveBetId(null);
                setSelectedOptionId(null);
                setBetAmount(10000);
                break;

            case 'CUSTOM_ROOM_UPDATE':
                if (data.room)
                {
                    setCurrentRoom(prev => (prev && prev.id === data.room.id ? data.room : prev));
                }
                break;

            case 'CUSTOM_BET_PLACED':
                if (data.success)
                {
                    if (data.newBalance !== undefined)
                    {
                        onBalanceUpdate(data.newBalance);
                    }
                    playSound('bet');
                }
                break;

            case 'CUSTOM_BET_LOCKED':
                playSound('lock');
                break;

            case 'CUSTOM_BET_RESTARTED':
                setResolveResults(null);
                playSound('start');
                break;

            case 'CUSTOM_BET_RESOLVED':
                setResolveResults(data);
                {
                    const myResults = (data.results || []).filter(r => (r.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase());
                    if (myResults.length > 0)
                    {
                        const totalProfit = myResults.reduce((acc, r) => acc + (r.profit !== undefined ? r.profit : (r.payout || 0) - (r.amount || 0)), 0);
                        const totalPayout = myResults.reduce((acc, r) => acc + (r.payout || 0), 0);

                        if (totalProfit > 0 || totalPayout > 0)
                        {
                            playSound('win');
                        }
                        else
                        {
                            playSound('lose');
                        }

                        const resultWithBalance = myResults.find(r => r.newBalance !== undefined);
                        if (resultWithBalance && typeof onBalanceUpdate === 'function')
                        {
                            onBalanceUpdate(resultWithBalance.newBalance);
                        }
                    }
                }
                break;

            case 'ERROR':
                if (data.message === 'WRONG_PASSWORD')
                {
                    const msg = t.customBetWrongPassword || (lang === 'TR' ? 'Hatalı şifre girdiniz!' : 'Incorrect password!');
                    setPasswordError(msg);
                    setError(msg);
                }
                else
                {
                    setError(localizeError(data.message));
                }
                setTimeout(() => setError(null), 3500);
                break;

            default:
                break;
        }
    };

    const localizeError = (msg) =>
    {
        if (!msg) return '';
        const lower = String(msg).toLowerCase();
        if (lower.includes('insufficient balance') || lower.includes('yetersiz bakiye'))
        {
            return t.customBetInsufficientBalance || t.insufficientBalance || (lang === 'TR' ? 'Yetersiz bakiye!' : 'Insufficient balance!');
        }
        if (msg === 'WRONG_PASSWORD' || lower.includes('wrong_password') || lower.includes('şifre'))
        {
            return t.customBetWrongPassword || (lang === 'TR' ? 'Hatalı şifre girdiniz!' : 'Incorrect password!');
        }
        if (lower.includes('unauthorized') || lower.includes('yetkiniz yok'))
        {
            return t.customBetUnauthorized || (lang === 'TR' ? 'Bu işlem için yetkiniz yok!' : 'Unauthorized!');
        }
        if (lower.includes('room not found') || lower.includes('oda bulunamadı'))
        {
            return t.customBetRoomNotFound || (lang === 'TR' ? 'Oda bulunamadı!' : 'Room not found!');
        }
        if (lower.includes('not authenticated') || lower.includes('oturum'))
        {
            return t.customBetNotAuthenticated || (lang === 'TR' ? 'Oturum açmanız gerekiyor!' : 'Not authenticated!');
        }
        if (lower.includes('invalid bet or betting is closed') || lower.includes('bahisler kapandı'))
        {
            return t.customBetInvalidBetClosed || (lang === 'TR' ? 'Geçersiz bahis veya bahisler kapandı!' : 'Invalid bet or betting is closed!');
        }
        if (lower.includes('invalid bet amount') || lower.includes('geçersiz bahis miktarı'))
        {
            return t.customBetInvalidAmount || (lang === 'TR' ? 'Geçersiz bahis miktarı!' : 'Invalid bet amount!');
        }
        if (lower.includes('invalid option') || lower.includes('geçersiz seçenek'))
        {
            return t.customBetInvalidOption || (lang === 'TR' ? 'Geçersiz seçenek!' : 'Invalid option!');
        }
        if (lower.includes('invalid room') || lower.includes('geçersiz oda'))
        {
            return t.customBetInvalidRoom || (lang === 'TR' ? 'Geçersiz oda!' : 'Invalid room!');
        }
        if (lower.includes('invalid bet') || lower.includes('geçersiz bahis'))
        {
            return t.customBetInvalidBet || (lang === 'TR' ? 'Geçersiz bahis!' : 'Invalid bet!');
        }
        if (lower.includes('invalid winning option'))
        {
            return t.customBetInvalidWinningOption || (lang === 'TR' ? 'Geçersiz kazanan seçenek!' : 'Invalid winning option!');
        }
        if (lower.includes('bet not found') || lower.includes('bahis bulunamadı'))
        {
            return t.customBetNotFound || (lang === 'TR' ? 'Bahis bulunamadı!' : 'Bet not found!');
        }
        if (lower.includes('question and at least 2 options') || lower.includes('en az 2 seçenek'))
        {
            return t.customBetRequiredQuestionOptions || (lang === 'TR' ? 'Soru ve en az 2 seçenek gereklidir.' : 'Question and at least 2 options are required.');
        }
        return msg;
    };

    const handleCreateRoom = () =>
    {
        if (!newRoomTitle.trim())
        {
            setError(t.customBetRequiredTitle || (lang === 'TR' ? 'Lütfen oda adı belirleyin.' : 'Please enter room title.'));
            setTimeout(() => setError(null), 3000);
            return;
        }

        const validOptions = initialOptions.map(o => o.trim()).filter(o => o !== '');
        const hasInitialBet = initialQuestion.trim() !== '' && validOptions.length >= 2;

        sendAction('CREATE_CUSTOM_ROOM', {
            title: newRoomTitle.trim(),
            description: newRoomDesc.trim(),
            password: newRoomPassword.trim() || undefined,
            question: hasInitialBet ? initialQuestion.trim() : undefined,
            options: hasInitialBet ? validOptions : undefined
        });

        setShowCreateRoomModal(false);
        setNewRoomTitle('');
        setNewRoomDesc('');
        setNewRoomPassword('');
        setInitialQuestion('');
        setInitialOptions(['', '']);
    };

    const handleAddBetToRoom = () =>
    {
        if (!currentRoom) return;
        const validOptions = newBetOptions.map(o => o.trim()).filter(o => o !== '');
        if (newBetQuestion.trim() === '' || validOptions.length < 2)
        {
            setError(t.customBetRequiredQuestionOptions || (lang === 'TR' ? 'Soru ve en az 2 seçenek gereklidir.' : 'Question and at least 2 options are required.'));
            setTimeout(() => setError(null), 3500);
            return;
        }

        const tempBetId = 'b_' + Date.now().toString().slice(-6);
        const optimisticBet = {
            id: tempBetId,
            code: (Math.floor(1000 + Math.random() * 9000)).toString(),
            question: newBetQuestion.trim(),
            options: validOptions.map((opt, idx) => ({
                id: idx,
                label: opt,
                totalBetAmount: 0,
                bettors: []
            })),
            odds: validOptions.map((opt, idx) => ({
                optionId: idx,
                label: opt,
                totalBetAmount: 0,
                bettorCount: 0,
                odds: 0,
                percentage: 0
            })),
            totalPool: 0,
            rakePercent: 0.05,
            status: 'betting',
            winningOptionId: null,
            createdAt: new Date().toISOString()
        };

        // Optimistically update currentRoom immediately
        setCurrentRoom(prev => prev ? ({
            ...prev,
            bets: [...(prev.bets || []), optimisticBet],
            betsCount: ((prev.bets || []).length) + 1
        }) : prev);

        sendAction('ADD_BET_TO_ROOM', {
            roomId: currentRoom.id,
            question: newBetQuestion.trim(),
            options: validOptions
        });

        setShowAddBetModal(false);
        setNewBetQuestion('');
        setNewBetOptions(['', '']);
    };

    const handleOpenEditBet = (bet) =>
    {
        setEditModalBet(bet);
        setEditBetQuestion(bet.question || '');
        setEditBetOptions((bet.options || []).map(o => o.label || ''));
        setShowEditBetModal(true);
    };

    const handleSaveEditBet = () =>
    {
        if (!currentRoom || !editModalBet) return;
        const validOptions = editBetOptions.map(o => o.trim()).filter(o => o !== '');
        if (editBetQuestion.trim() === '' || validOptions.length < 2)
        {
            setError(t.customBetRequiredQuestionOptions || (lang === 'TR' ? 'Soru ve en az 2 seçenek gereklidir.' : 'Question and at least 2 options are required.'));
            setTimeout(() => setError(null), 3500);
            return;
        }

        // Optimistic update
        setCurrentRoom(prev =>
        {
            if (!prev) return prev;
            const updatedBets = (prev.bets || []).map(b =>
            {
                if (b.id === editModalBet.id)
                {
                    return {
                        ...b,
                        question: editBetQuestion.trim(),
                        options: validOptions.map((opt, idx) => ({
                            id: idx,
                            label: opt,
                            totalBetAmount: 0,
                            bettors: []
                        })),
                        odds: validOptions.map((opt, idx) => ({
                            optionId: idx,
                            label: opt,
                            totalBetAmount: 0,
                            bettorCount: 0,
                            odds: 0,
                            percentage: 0
                        }))
                    };
                }
                return b;
            });
            return { ...prev, bets: updatedBets };
        });

        sendAction('EDIT_BET', {
            roomId: currentRoom.id,
            betId: editModalBet.id,
            question: editBetQuestion.trim(),
            options: validOptions
        });

        setShowEditBetModal(false);
        setEditModalBet(null);
        setEditBetQuestion('');
        setEditBetOptions(['', '']);
    };

    const handleJoinRoom = (room) =>
    {
        if (room.hasPassword && !isAdmin)
        {
            setPasswordModalRoom(room);
            setEnteredPassword('');
            setPasswordError(null);
            return;
        }
        
        // Optimistic transition so the user immediately enters the room
        setCurrentRoom(room);
        setView('room');
        setActiveBetId(null);
        setSelectedOptionId(null);
        setBetAmount(10000);

        sendAction('JOIN_CUSTOM_ROOM', { roomId: room.id });
    };

    const handleJoinWithPassword = () =>
    {
        if (!passwordModalRoom) return;
        if (!enteredPassword.trim())
        {
            setPasswordError(t.customBetEnterPassword || (lang === 'TR' ? 'Şifreyi Girin' : 'Enter Password'));
            return;
        }
        sendAction('JOIN_CUSTOM_ROOM', { roomId: passwordModalRoom.id, password: enteredPassword.trim() });
    };

    const handleSelectBet = (betId) =>
    {
        // Enter Bet Detail View (Tier 3: Single bet wager screen)
        setActiveBetId(betId);
        setSelectedOptionId(null);
        setBetAmount(10000);
        setView('bet');
    };

    const handleBackToRoomBets = () =>
    {
        // Go back from Bet Detail (Tier 3) to Room Bets list (Tier 2)
        setView('room');
        setActiveBetId(null);
        setSelectedOptionId(null);
    };

    const handleLeaveRoom = () =>
    {
        // Go back from Room (Tier 2) to Lobby (Tier 1)
        if (currentRoom)
        {
            sendAction('LEAVE_CUSTOM_ROOM', { roomId: currentRoom.id });
        }
        setView('lobby');
        setCurrentRoom(null);
        setActiveBetId(null);
        setSelectedOptionId(null);
    };

    const handlePlaceBet = (betId) =>
    {
        if (selectedOptionId === null || betAmount <= 0 || !currentRoom) return;
        sendAction('PLACE_CUSTOM_BET', { roomId: currentRoom.id, betId, optionId: selectedOptionId, amount: betAmount });
        setSelectedOptionId(null);
    };

    const handleLockBet = (betId) =>
    {
        if (currentRoom)
        {
            setCurrentRoom(prev => prev ? ({
                ...prev,
                bets: (prev.bets || []).map(b => b.id === betId ? { ...b, status: 'locked' } : b)
            }) : prev);
            sendAction('LOCK_BET', { roomId: currentRoom.id, betId });
        }
    };

    const handleConfirmResolveBet = () =>
    {
        if (currentRoom && resolveModalBet && selectedWinnerOptionId !== null)
        {
            const targetBetId = resolveModalBet.id;
            const targetWinnerId = selectedWinnerOptionId;

            setCurrentRoom(prev => prev ? ({
                ...prev,
                bets: (prev.bets || []).map(b => b.id === targetBetId ? { ...b, status: 'resolved', winningOptionId: targetWinnerId } : b)
            }) : prev);

            sendAction('RESOLVE_BET', {
                roomId: currentRoom.id,
                betId: targetBetId,
                winningOptionId: targetWinnerId
            });
            setResolveModalBet(null);
            setSelectedWinnerOptionId(null);
        }
    };

    const handleRestartBet = (betId) =>
    {
        if (currentRoom && window.confirm(t.customBetRestartConfirm || (lang === 'TR' ? 'Bu tamamlanmış bahsi sıfırlayıp tekrar başlatmak istediğinize emin misiniz? Bahis havuzu sıfırlanacak ve bahisler yeniden açılacaktır.' : 'Are you sure you want to reset and restart this resolved bet? The bet pool will be reset and betting will reopen.')))
        {
            setCurrentRoom(prev => prev ? ({
                ...prev,
                bets: (prev.bets || []).map(b => b.id === betId ? {
                    ...b,
                    status: 'betting',
                    winningOptionId: null,
                    totalPool: 0,
                    resolvedResults: null,
                    resolvedSummary: null,
                    options: (b.options || []).map(o => ({ ...o, totalBetAmount: 0, bettors: [] }))
                } : b)
            }) : prev);
            sendAction('RESTART_BET', { roomId: currentRoom.id, betId });
        }
    };

    const handleDeleteBet = (betId) =>
    {
        if (currentRoom && window.confirm(lang === 'TR' ? 'Bu bahsi silmek istediğinize emin misiniz? Bahisler iade edilecektir.' : 'Delete this bet? Bets will be refunded.'))
        {
            setCurrentRoom(prev => prev ? ({
                ...prev,
                bets: (prev.bets || []).filter(b => b.id !== betId),
                betsCount: Math.max(0, ((prev.bets || []).length) - 1)
            }) : prev);
            sendAction('DELETE_BET', { roomId: currentRoom.id, betId });
            if (view === 'bet' && activeBetId === betId)
            {
                setView('room');
                setActiveBetId(null);
            }
        }
    };

    const handleDeleteRoom = () =>
    {
        if (currentRoom && window.confirm(lang === 'TR' ? 'Tüm odayı silmek istediğinize emin misiniz? Açık bahisler iade edilecektir.' : 'Are you sure you want to delete this room? Open bets will be refunded.'))
        {
            const targetRoomId = currentRoom.id;
            setRooms(prev => prev.filter(r => r.id !== targetRoomId));
            sendAction('DELETE_CUSTOM_ROOM', { roomId: targetRoomId });
            setView('lobby');
            setCurrentRoom(null);
            setActiveBetId(null);
        }
    };

    // Calculate projected win for active bet in Tier 3
    const activeBet = useMemo(() =>
    {
        if (!currentRoom || !activeBetId) return null;
        return (currentRoom.bets || []).find(b => b.id === activeBetId) || null;
    }, [currentRoom, activeBetId]);

    const activeOption = useMemo(() =>
    {
        if (!activeBet || selectedOptionId === null) return null;
        return (activeBet.odds || []).find(o => o.optionId === selectedOptionId) || null;
    }, [activeBet, selectedOptionId]);

    const projectedPotentialWin = useMemo(() =>
    {
        if (!activeBet || !activeOption || betAmount <= 0) return 0;
        const rake = activeBet.rakePercent || 0.05;
        const nextPool = (activeBet.totalPool || 0) + betAmount;
        const nextEffectivePool = nextPool * (1 - rake);
        const nextOptAmount = (activeOption.totalBetAmount || 0) + betAmount;
        if (nextOptAmount <= 0) return 0;
        const minOdds = (window.GAME_CONFIG && window.GAME_CONFIG.customBet && window.GAME_CONFIG.customBet.MIN_ODDS) || 1.10;
        const rawProjectedOdds = nextEffectivePool / nextOptAmount;
        const projectedOdds = Math.max(minOdds, rawProjectedOdds);
        return Math.floor(betAmount * projectedOdds);
    }, [activeBet, activeOption, betAmount]);

    // RENDER: LOBBY (ROOMS LIST)
    const renderLobby = () =>
    {
        return (
            <div className="flex flex-col text-white p-4 md:p-6 max-w-6xl mx-auto w-full">
                {/* Lobby Header */}
                <div className="flex flex-col sm:flex-row justify-between items-center gap-4 mb-8 pb-6 border-b border-white/10">
                    <button
                        onClick={onBackToLobby}
                        className="w-full sm:w-auto px-5 py-2.5 bg-slate-900/80 hover:bg-slate-800 text-white rounded-2xl font-bold flex items-center justify-center gap-2 transition-all hover:scale-105 active:scale-95 border border-white/10 shadow-lg"
                    >
                        <span>←</span>
                        <span>{t.mainMenu || (lang === 'TR' ? 'Ana Menü' : 'Main Menu')}</span>
                    </button>

                    <div className="text-center">
                        <h1 className="text-3xl md:text-4xl font-black bg-gradient-to-r from-purple-400 via-pink-400 to-amber-400 bg-clip-text text-transparent tracking-tight">
                            {t.customBetTitle || (lang === 'TR' ? 'Özel Bahis Odaları' : 'Custom Bet Rooms')}
                        </h1>
                        <p className="text-xs text-purple-300/70 font-semibold tracking-wide uppercase mt-1">
                            {t.customBetSubtitle || (lang === 'TR' ? 'Gerçek Dünya Soruları • Dinamik Oranlar' : 'Real-World Questions • Dynamic Odds')}
                        </p>
                    </div>

                    <div className="w-full sm:w-auto flex justify-end">
                        {isAdmin ? (
                            <button
                                onClick={() => setShowCreateRoomModal(true)}
                                className="w-full sm:w-auto px-5 py-2.5 bg-gradient-to-r from-purple-600 to-orange-500 rounded-2xl font-black text-sm hover:opacity-95 transition-all hover:scale-105 active:scale-95 shadow-lg shadow-purple-500/25 flex items-center justify-center gap-2 border border-purple-400/30"
                            >
                                <span>+</span>
                                <span>{t.customBetCreateRoom || (lang === 'TR' ? 'Yeni Oda Oluştur' : 'Create Room')}</span>
                            </button>
                        ) : (
                            <div className="hidden sm:block w-28"></div>
                        )}
                    </div>
                </div>

                {/* Rooms Grid */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {rooms.map(room => (
                        <motion.div
                            key={room.id}
                            whileHover={{ scale: 1.02, y: -4 }}
                            className="bg-slate-900/70 backdrop-blur-xl border border-white/10 rounded-3xl p-6 flex flex-col cursor-pointer hover:border-purple-500/50 hover:shadow-2xl hover:shadow-purple-500/15 transition-all relative overflow-hidden group"
                            onClick={() => handleJoinRoom(room)}
                        >
                            <div className="absolute -top-24 -right-24 w-48 h-48 bg-purple-600/10 rounded-full blur-3xl group-hover:bg-purple-600/20 transition-all pointer-events-none"></div>

                            <div className="flex justify-between items-start mb-4 gap-2 relative z-10">
                                <div className="flex items-center gap-2 flex-wrap">
                                    <span className="px-3 py-1 rounded-full text-xs font-black uppercase tracking-wider bg-purple-500/20 text-purple-300 border border-purple-500/30">
                                        {(room.bets || []).length} {t.customBetTotalBets || (lang === 'TR' ? 'Bahis' : 'Bets')}
                                    </span>
                                    {room.hasPassword ? (
                                        <span className="px-2.5 py-1 rounded-full text-xs font-bold bg-amber-500/20 text-amber-300 border border-amber-500/30 flex items-center gap-1">
                                            <span>🔒</span>
                                            <span>{t.customBetProtectedBadge || (lang === 'TR' ? 'Şifreli' : 'Protected')}</span>
                                        </span>
                                    ) : (
                                        <span className="px-2.5 py-1 rounded-full text-xs font-bold bg-emerald-500/20 text-emerald-300 border border-emerald-500/30">
                                            {t.customBetPublicBadge || (lang === 'TR' ? 'Herkese Açık' : 'Public')}
                                        </span>
                                    )}
                                </div>
                                <span className="text-xs text-white/40 font-mono bg-white/5 px-2 py-0.5 rounded-md border border-white/5">
                                    #{room.code || room.id.slice(-4)}
                                </span>
                            </div>

                            <h3 className="text-xl font-black mb-2 text-white group-hover:text-amber-300 transition-colors leading-snug relative z-10">
                                {room.title || 'Özel Bahis Odası'}
                            </h3>
                            {room.description && (
                                <p className="text-xs text-white/60 mb-6 line-clamp-2 relative z-10">
                                    {room.description}
                                </p>
                            )}

                            <div className="mt-auto pt-4 border-t border-white/10 space-y-2.5 relative z-10">
                                <div className="flex justify-between text-sm items-center">
                                    <span className="text-white/50 font-medium">{t.pot || (lang === 'TR' ? 'Toplam Havuz' : 'Total Pool')}:</span>
                                    <span className="text-amber-400 font-black text-base font-mono">{formatMoney(room.totalPool || 0)}</span>
                                </div>
                                {isAdmin && (
                                    <div className="flex justify-between text-xs pt-2.5 border-t border-white/10 font-mono items-center">
                                        <span className="text-white/50 flex items-center gap-1">
                                            <span>🔑</span>
                                            <span>{t.customBetPassword || (lang === 'TR' ? 'Oda Şifresi:' : 'Password:')}</span>
                                        </span>
                                        {room.password ? (
                                            <span 
                                                className="font-black bg-amber-500/20 text-amber-300 px-2.5 py-1 rounded-xl border border-amber-500/40 select-all flex items-center gap-1.5 hover:bg-amber-500/30 transition-all cursor-pointer shadow-sm"
                                                title={lang === 'TR' ? 'Kopyalamak için tıklayın' : 'Click to copy'}
                                                onClick={(e) => {
                                                    e.stopPropagation();
                                                    navigator.clipboard?.writeText(room.password);
                                                    setError(lang === 'TR' ? `Şifre kopyalandı: ${room.password}` : `Password copied: ${room.password}`);
                                                    setTimeout(() => setError(null), 2500);
                                                }}
                                            >
                                                <span>{room.password}</span>
                                                <span className="text-[10px] opacity-70">📋</span>
                                            </span>
                                        ) : room.hasPassword ? (
                                            <span className="text-amber-400 font-semibold text-xs">🔒 {lang === 'TR' ? 'Şifreli' : 'Protected'}</span>
                                        ) : (
                                            <span className="text-emerald-400/80 font-semibold text-xs">🔓 {lang === 'TR' ? 'Şifresiz' : 'No Password'}</span>
                                        )}
                                    </div>
                                )}
                            </div>
                        </motion.div>
                    ))}
                </div>

                {rooms.length === 0 && (
                    <div className="flex flex-col items-center justify-center my-auto py-20 text-center">
                        <div className="w-20 h-20 rounded-3xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-4xl mb-4 text-purple-400 shadow-inner">
                            ⚖️
                        </div>
                        <p className="text-lg text-white/70 font-bold mb-2">
                            {t.customBetNoRooms || (lang === 'TR' ? 'Aktif özel bahis odası bulunmamaktadır.' : 'No active custom bet rooms found.')}
                        </p>
                        {isAdmin && (
                            <button
                                onClick={() => setShowCreateRoomModal(true)}
                                className="mt-4 px-6 py-3 bg-gradient-to-r from-purple-600 to-orange-500 rounded-2xl font-bold text-sm hover:opacity-90 transition-all shadow-lg"
                            >
                                {t.customBetCreateRoom || (lang === 'TR' ? 'İlk Odayı Oluştur' : 'Create First Room')}
                            </button>
                        )}
                    </div>
                )}
            </div>
        );
    };

    // ====================================================
    // TIER 2: RENDER ROOM (LIST OF BETS / QUESTIONS IN ROOM)
    // ====================================================
    const renderRoom = () =>
    {
        if (!currentRoom) return null;
        const bets = currentRoom.bets || [];

        return (
            <div className="flex flex-col text-white p-4 md:p-6 max-w-7xl mx-auto w-full">
                {/* Room Top Header Bar */}
                <div className="bg-slate-900/80 backdrop-blur-xl border border-white/10 rounded-3xl p-5 mb-8 shadow-2xl">
                    <div className="flex flex-col md:flex-row items-center justify-between gap-4">
                        {/* Left: Back to Lobby & Room Title */}
                        <div className="flex items-center gap-4 w-full md:w-auto">
                            <button
                                onClick={handleLeaveRoom}
                                className="px-4 py-2.5 bg-white/10 hover:bg-white/20 rounded-2xl font-bold transition-all border border-white/10 flex items-center gap-2 hover:scale-105 active:scale-95 text-sm"
                            >
                                <span>←</span>
                                <span>{t.customBetBackToRooms || (lang === 'TR' ? 'Odalar' : 'Rooms')}</span>
                            </button>

                            <div>
                                <div className="flex items-center gap-2.5">
                                    <h2 className="text-xl md:text-2xl font-black text-white">{currentRoom.title}</h2>
                                    <span className="text-xs text-white/50 font-mono bg-white/5 px-2 py-0.5 rounded-md border border-white/5">
                                        #{currentRoom.code || currentRoom.id.slice(-4)}
                                    </span>
                                </div>
                                {currentRoom.description && (
                                    <p className="text-xs text-white/60 mt-0.5 line-clamp-1">{currentRoom.description}</p>
                                )}
                                {isAdmin && (
                                    <div className="flex items-center gap-2 mt-2">
                                        {currentRoom.password || currentRoom.hasPassword ? (
                                            <div 
                                                className="inline-flex items-center gap-1.5 text-xs bg-amber-500/15 text-amber-300 border border-amber-500/30 px-3 py-1 rounded-xl font-mono cursor-pointer hover:bg-amber-500/25 transition-all shadow-sm"
                                                title={lang === 'TR' ? 'Şifreyi kopyalamak için tıklayın' : 'Click to copy password'}
                                                onClick={() => {
                                                    if (currentRoom.password) {
                                                        navigator.clipboard?.writeText(currentRoom.password);
                                                        setError(lang === 'TR' ? `Oda şifresi kopyalandı: ${currentRoom.password}` : `Room password copied: ${currentRoom.password}`);
                                                        setTimeout(() => setError(null), 2500);
                                                    }
                                                }}
                                            >
                                                <span>🔑 {lang === 'TR' ? 'Oda Şifresi:' : 'Room Password:'}</span>
                                                <strong className="font-black text-amber-400 select-all">{currentRoom.password || (lang === 'TR' ? 'Korumalı' : 'Protected')}</strong>
                                                {currentRoom.password && <span className="text-[10px] opacity-70">📋</span>}
                                            </div>
                                        ) : (
                                            <div className="inline-flex items-center gap-1 text-xs bg-emerald-500/10 text-emerald-400 border border-emerald-500/20 px-2.5 py-1 rounded-xl font-medium">
                                                <span>🔓</span>
                                                <span>{lang === 'TR' ? 'Herkese Açık (Şifresiz)' : 'Public (No Password)'}</span>
                                            </div>
                                        )}
                                    </div>
                                )}
                            </div>
                        </div>

                        {/* Right: Room Pool & Admin Controls */}
                        <div className="flex items-center justify-between md:justify-end gap-3 w-full md:w-auto">
                            <div className="bg-black/40 border border-white/10 px-4 py-2 rounded-2xl flex items-center gap-3">
                                <span className="text-xs text-white/50 uppercase tracking-wider font-semibold">
                                    {t.pot || (lang === 'TR' ? 'Oda Havuzu' : 'Room Pool')}:
                                </span>
                                <span className="text-base font-black text-amber-400 font-mono">
                                    {formatMoney(currentRoom.totalPool || 0)}
                                </span>
                            </div>

                            {isAdmin && (
                                <div className="flex items-center gap-2">
                                    <button
                                        onClick={() => setShowAddBetModal(true)}
                                        className="px-4 py-2 bg-gradient-to-r from-purple-600 to-orange-500 rounded-xl font-black text-xs hover:opacity-90 transition-all shadow-lg shadow-purple-500/20 flex items-center gap-1.5"
                                    >
                                        <span>+</span>
                                        <span>{t.customBetAddBetToRoom || (lang === 'TR' ? 'Bahis Ekle' : 'Add Bet')}</span>
                                    </button>
                                    <button
                                        onClick={handleDeleteRoom}
                                        className="p-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-xl font-bold text-xs border border-red-500/30 transition-all"
                                        title={t.customBetDeleteRoom || (lang === 'TR' ? 'Odayı Sil' : 'Delete Room')}
                                    >
                                        🗑️
                                    </button>
                                </div>
                            )}
                        </div>
                    </div>
                </div>

                {/* Section Title */}
                <div className="flex items-center justify-between mb-6 px-1">
                    <div className="flex items-center gap-2.5">
                        <span className="text-2xl">📋</span>
                        <h3 className="text-xl font-black text-white">
                            {lang === 'TR' ? 'Bu Odadaki Bahisler' : 'Bets in this Room'}
                        </h3>
                        <span className="text-xs bg-purple-500/20 text-purple-300 px-2.5 py-0.5 rounded-full border border-purple-500/30 font-mono font-bold">
                            {bets.length}
                        </span>
                    </div>
                    <span className="text-xs text-white/50">
                        {lang === 'TR' ? 'Detayları görmek ve oynamak için bir bahse tıklayın' : 'Click a bet to view details and wager'}
                    </span>
                </div>

                {/* Bets Grid (Tier 2 Cards) */}
                <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-6">
                    {bets.map(bet =>
                    {
                        const outcome = getUserBetOutcome(bet);

                        return (
                            <motion.div
                                key={bet.id}
                                whileHover={{ scale: 1.02, y: -4 }}
                                onClick={() => handleSelectBet(bet.id)}
                                className="bg-slate-900/70 backdrop-blur-xl border border-white/10 hover:border-purple-500/50 rounded-3xl p-6 flex flex-col justify-between cursor-pointer hover:shadow-2xl hover:shadow-purple-500/10 transition-all relative overflow-hidden group"
                            >
                                <div className="absolute -top-20 -right-20 w-40 h-40 bg-purple-600/10 rounded-full blur-3xl group-hover:bg-purple-600/20 transition-all pointer-events-none"></div>

                                <div>
                                    {/* Status Badge & Code */}
                                    <div className="flex justify-between items-center mb-4 relative z-10">
                                        <span className={`px-3 py-1 rounded-full text-xs font-black uppercase tracking-wider ${
                                            bet.status === 'betting' ? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30' :
                                            bet.status === 'locked' ? 'bg-amber-500/20 text-amber-400 border border-amber-500/30' :
                                            'bg-slate-500/20 text-slate-400 border border-slate-500/30'
                                        }`}>
                                            {bet.status === 'betting' ? (t.customBetOpen || (lang === 'TR' ? 'BAHİSLERE AÇIK' : 'OPEN')) :
                                             bet.status === 'locked' ? (t.customBetLocked || (lang === 'TR' ? 'KİLİTLİ' : 'LOCKED')) :
                                             (t.customBetResolved || (lang === 'TR' ? 'SONUÇLANDI' : 'RESOLVED'))}
                                        </span>
                                        <div className="flex items-center gap-1.5">
                                            {isAdmin && bet.status === 'betting' && (!bet.totalPool || bet.totalPool === 0) && (
                                                <button
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleOpenEditBet(bet);
                                                    }}
                                                    className="px-2 py-0.5 bg-blue-500/20 hover:bg-blue-500/30 text-blue-300 rounded text-xs border border-blue-500/30 font-bold transition-all flex items-center gap-1"
                                                    title={lang === 'TR' ? 'Bahsi Düzenle' : 'Edit Bet'}
                                                >
                                                    <span>✏️</span>
                                                    <span>{lang === 'TR' ? 'Düzenle' : 'Edit'}</span>
                                                </button>
                                            )}
                                            {isAdmin && bet.status === 'resolved' && (
                                                <button
                                                    onClick={(e) => {
                                                        e.stopPropagation();
                                                        handleRestartBet(bet.id);
                                                    }}
                                                    className="px-2 py-0.5 bg-amber-500/20 hover:bg-amber-500/30 text-amber-300 rounded text-xs border border-amber-500/30 font-bold transition-all flex items-center gap-1"
                                                    title={t.customBetRestart || (lang === 'TR' ? 'Bahsi Tekrar Başlat' : 'Restart Bet')}
                                                >
                                                    <span>🔄</span>
                                                    <span>{t.customBetRestart || (lang === 'TR' ? 'Tekrar Başlat' : 'Restart')}</span>
                                                </button>
                                            )}
                                            <span className="text-xs text-white/40 font-mono bg-white/5 px-2 py-0.5 rounded border border-white/5">
                                                #{bet.code || bet.id.slice(-4)}
                                            </span>
                                        </div>
                                    </div>

                                    {/* Question Title */}
                                    <h4 className="text-lg font-black text-white group-hover:text-amber-300 transition-colors leading-snug mb-4 relative z-10">
                                        {bet.question}
                                    </h4>

                                    {/* Options Summary Pills */}
                                    <div className="flex flex-wrap gap-1.5 mb-5 relative z-10">
                                        {(bet.odds || []).map(opt =>
                                        {
                                            const fullOpt = (bet.options || []).find(o => o.id === opt.optionId);
                                            const optBettors = fullOpt?.bettors || [];
                                            return (
                                                <span
                                                    key={opt.optionId}
                                                    className={`text-xs px-2.5 py-1 rounded-xl border flex items-center gap-1.5 ${
                                                        bet.status === 'resolved' && bet.winningOptionId === opt.optionId
                                                            ? 'bg-emerald-500/20 text-emerald-300 border-emerald-500/40 font-bold'
                                                            : 'bg-white/5 text-white/70 border-white/10'
                                                    }`}
                                                >
                                                    <span>{opt.label}</span>
                                                    {bet.status === 'resolved' && bet.winningOptionId === opt.optionId && <span>👑</span>}
                                                    <span className="text-amber-400 font-mono font-bold">
                                                        {opt.odds > 0 ? `${opt.odds.toFixed(2)}x` : '-'}
                                                    </span>
                                                    {(bet.status === 'locked' || bet.status === 'resolved') && optBettors.length > 0 && (
                                                        <span className="text-[10px] bg-purple-500/25 text-purple-300 px-1.5 py-0.2 rounded-md font-mono font-bold border border-purple-500/30">
                                                            👥 {optBettors.length}
                                                        </span>
                                                    )}
                                                </span>
                                            );
                                        })}
                                    </div>
                                </div>

                                <div className="pt-4 border-t border-white/10 relative z-10 space-y-3">
                                    <div className="flex justify-between items-center text-xs">
                                        <span className="text-white/50">{t.pot || (lang === 'TR' ? 'Bahis Havuzu' : 'Bet Pool')}:</span>
                                        <span className="text-amber-400 font-mono font-black text-sm">{formatMoney(bet.totalPool || 0)}</span>
                                    </div>

                                    {outcome && (
                                        <div className={`flex justify-between items-center text-xs px-3 py-2 rounded-xl border ${
                                            !outcome.isResolved
                                                ? 'bg-purple-500/10 border-purple-500/20 text-purple-300'
                                                : outcome.isWin
                                                ? 'bg-emerald-500/15 border-emerald-500/30 text-emerald-300'
                                                : outcome.isPartialWin
                                                ? 'bg-amber-500/15 border-amber-500/30 text-amber-300'
                                                : 'bg-red-500/15 border-red-500/30 text-red-300'
                                        }`}>
                                            <span className="font-semibold">
                                                {!outcome.isResolved 
                                                    ? (lang === 'TR' ? 'Yatırımınız:' : 'Your Bet:')
                                                    : outcome.isWin
                                                    ? (lang === 'TR' ? '👑 Net Kazanç:' : '👑 Net Win:')
                                                    : outcome.isPartialWin
                                                    ? (lang === 'TR' ? '⚡ Ödeme:' : '⚡ Payout:')
                                                    : (lang === 'TR' ? '❌ Kayıp:' : '❌ Lost:')}
                                            </span>
                                            <span className="font-mono font-black">
                                                {!outcome.isResolved 
                                                    ? formatMoney(outcome.totalBet)
                                                    : outcome.isWin
                                                    ? `+${formatMoney(outcome.netProfit)}`
                                                    : outcome.isPartialWin
                                                    ? `${formatMoney(outcome.totalPayout)} (Net: ${formatMoney(outcome.netProfit)})`
                                                    : `-${formatMoney(outcome.totalBet)}`}
                                            </span>
                                        </div>
                                    )}

                                    {/* Open Bet Action Button */}
                                    <div className="w-full py-2.5 px-4 bg-gradient-to-r from-purple-600/30 to-amber-500/30 group-hover:from-purple-600 group-hover:to-amber-500 border border-purple-500/30 rounded-2xl text-center text-xs font-black tracking-wide text-white transition-all flex items-center justify-center gap-2">
                                        <span>{t.customBetViewBet || (lang === 'TR' ? 'Bahse Gir / İncele' : 'Open Bet')}</span>
                                        <span>→</span>
                                    </div>
                                </div>
                            </motion.div>
                        );
                    })}
                </div>

                {bets.length === 0 && (
                    <div className="bg-slate-900/50 border border-white/10 rounded-3xl p-16 text-center flex flex-col items-center justify-center my-auto">
                        <div className="w-16 h-16 rounded-2xl bg-purple-500/10 border border-purple-500/20 flex items-center justify-center text-3xl mb-4 text-purple-400">
                            🎯
                        </div>
                        <p className="text-base text-white/60 font-bold mb-3">
                            {t.customBetNoBetsInRoom || (lang === 'TR' ? 'Bu odada henüz aktif bahis bulunmamaktadır.' : 'No active bets in this room yet.')}
                        </p>
                        {isAdmin && (
                            <button
                                onClick={() => setShowAddBetModal(true)}
                                className="px-6 py-3 bg-gradient-to-r from-purple-600 to-orange-500 rounded-2xl font-bold text-xs hover:opacity-90 transition-all shadow-lg"
                            >
                                {t.customBetAddBetToRoom || (lang === 'TR' ? 'İlk Bahsi Ekle' : 'Add First Bet')}
                            </button>
                        )}
                    </div>
                )}
            </div>
        );
    };

    // ====================================================
    // TIER 3: RENDER BET DETAIL & WAGER SCREEN (SINGLE BET)
    // ====================================================
    const renderBetDetail = () =>
    {
        if (!currentRoom || !activeBet)
        {
            return (
                <div className="flex flex-col items-center justify-center py-20 text-white p-6">
                    <p className="mb-4 text-lg font-bold">{t.customBetBetNotFound || (lang === 'TR' ? 'Bahis bulunamadı.' : 'Bet not found.')}</p>
                    <button
                        onClick={handleBackToRoomBets}
                        className="px-5 py-2.5 bg-white/10 hover:bg-white/20 rounded-xl font-bold transition-all"
                    >
                        {lang === 'TR' ? '← Odaya Dön' : '← Back to Room'}
                    </button>
                </div>
            );
        }

        const bet = activeBet;
        const userBalance = userProfile?.totalWealth ?? 0;
        const outcome = getUserBetOutcome(bet);
        const totalMyBet = outcome ? outcome.totalBet : 0;

        return (
            <div className="flex flex-col text-white p-4 md:p-6 max-w-5xl mx-auto w-full">
                {/* Header Navigation */}
                <div className="flex items-center justify-between mb-6 pb-4 border-b border-white/10">
                    <button
                        onClick={handleBackToRoomBets}
                        className="px-4 py-2.5 bg-white/10 hover:bg-white/20 rounded-2xl font-bold transition-all border border-white/10 flex items-center gap-2 hover:scale-105 active:scale-95 text-sm"
                    >
                        <span>←</span>
                        <span>{currentRoom.title}</span>
                    </button>

                    <div className="flex items-center gap-3">
                        <span className={`px-3.5 py-1.5 rounded-full text-xs font-black uppercase tracking-wider ${
                            bet.status === 'betting' ? 'bg-emerald-500/20 text-emerald-400 border border-emerald-500/30' :
                            bet.status === 'locked' ? 'bg-amber-500/20 text-amber-400 border border-amber-500/30' :
                            'bg-slate-500/20 text-slate-400 border border-slate-500/30'
                        }`}>
                            {bet.status === 'betting' ? (t.customBetOpen || (lang === 'TR' ? 'BAHİSLERE AÇIK' : 'OPEN')) :
                             bet.status === 'locked' ? (t.customBetLocked || (lang === 'TR' ? 'KİLİTLİ' : 'LOCKED')) :
                             (t.customBetResolved || (lang === 'TR' ? 'SONUÇLANDI' : 'RESOLVED'))}
                        </span>
                        <span className="text-xs text-white/40 font-mono bg-white/5 px-2.5 py-1 rounded-lg border border-white/5">
                            #{bet.code || bet.id.slice(-4)}
                        </span>
                    </div>
                </div>

                {/* Big Question Banner */}
                <div className="bg-gradient-to-br from-slate-900 via-purple-950/40 to-slate-900 border border-purple-500/30 rounded-3xl p-6 md:p-8 mb-6 shadow-2xl relative overflow-hidden">
                    <div className="absolute top-0 right-0 w-64 h-64 bg-purple-600/10 rounded-full blur-3xl pointer-events-none"></div>

                    <div className="text-xs text-purple-300 font-bold uppercase tracking-wider mb-2 flex items-center gap-2">
                        <span>🎯 {lang === 'TR' ? 'Bahis Sorusu' : 'Bet Question'}</span>
                    </div>

                    <h2 className="text-2xl md:text-3xl font-black text-white leading-snug mb-6">
                        {bet.question}
                    </h2>

                    {/* Stats bar */}
                    <div className="flex flex-wrap items-center gap-4 text-xs pt-4 border-t border-white/10">
                        <div className="flex items-center gap-2 bg-black/40 px-3.5 py-1.5 rounded-xl border border-white/5">
                            <span className="text-white/50">{t.pot || (lang === 'TR' ? 'Toplam Havuz' : 'Total Pool')}:</span>
                            <span className="text-amber-400 font-black font-mono text-sm">{formatMoney(bet.totalPool || 0)}</span>
                        </div>
                        <div className="flex items-center gap-2 bg-black/40 px-3.5 py-1.5 rounded-xl border border-white/5">
                            <span className="text-white/50">{lang === 'TR' ? 'Kasa Kesintisi' : 'Rake'}:</span>
                            <span className="text-white/80 font-mono font-bold">%{(bet.rakePercent || 0.05) * 100}</span>
                        </div>
                        {totalMyBet > 0 && (
                            <div className="flex items-center gap-2 bg-emerald-500/15 border border-emerald-500/30 px-3.5 py-1.5 rounded-xl">
                                <span className="text-emerald-300 font-medium">{lang === 'TR' ? 'Bu Bahisteki Yatırımınız' : 'Your Wager'}:</span>
                                <span className="text-emerald-400 font-mono font-black text-sm">{formatMoney(totalMyBet)}</span>
                            </div>
                        )}
                    </div>
                </div>

                {/* Locked Bet Notification Banner */}
                {bet.status === 'locked' && (
                    <div className="mb-6 rounded-3xl p-5 border border-amber-500/40 bg-gradient-to-r from-amber-500/15 via-slate-900 to-slate-950 shadow-2xl flex items-center gap-4">
                        <div className="w-12 h-12 rounded-2xl bg-amber-500/20 border border-amber-500/40 flex items-center justify-center text-2xl text-amber-400 shrink-0">
                            🔒
                        </div>
                        <div>
                            <div className="text-sm font-black text-amber-300 uppercase tracking-wide">
                                {t.customBetLocked || (lang === 'TR' ? 'Bahisler Kilitlendi' : 'Betting is Locked')}
                            </div>
                            <p className="text-xs text-white/70 mt-0.5">
                                {t.customBetLockedBanner || (lang === 'TR' ? 'Bahisler kilitlendi! Katılımcıların hangi seçeneğe ne kadar oy verdiği aşağıda listelenmektedir.' : 'Betting is locked! Who voted for which option is shown below.')}
                            </p>
                        </div>
                    </div>
                )}

                {/* Resolved Bet Top Status & User Outcome */}
                {bet.status === 'resolved' && (() =>
                {
                    const winningOpt = (bet.options || []).find(o => o.id === bet.winningOptionId);
                    const effectivePool = (bet.totalPool || 0) * (1 - (bet.rakePercent || 0.05));
                    const minOdds = (window.GAME_CONFIG && window.GAME_CONFIG.customBet && window.GAME_CONFIG.customBet.MIN_ODDS) || 1.10;
                    const rawWinningOdds = winningOpt?.totalBetAmount > 0 ? (effectivePool / winningOpt.totalBetAmount) : 0;
                    const winningOdds = rawWinningOdds > 0 ? Math.max(minOdds, rawWinningOdds) : 0;

                    return (
                        <div className="mb-6 rounded-3xl p-6 border bg-gradient-to-br from-slate-900 via-slate-900/90 to-slate-950 shadow-2xl border-emerald-500/30">
                            <div className="flex flex-wrap items-center justify-between gap-4 pb-4 border-b border-white/10">
                                <div className="flex items-center gap-3.5">
                                    <div className="w-12 h-12 rounded-2xl bg-emerald-500/20 border border-emerald-400 flex items-center justify-center text-2xl shadow-lg shadow-emerald-500/20">
                                        👑
                                    </div>
                                    <div>
                                        <div className="text-xs font-bold text-emerald-400 uppercase tracking-wider">
                                            {lang === 'TR' ? 'Kazanan Seçenek' : 'Winning Option'}
                                        </div>
                                        <div className="text-xl font-black text-white">
                                            {winningOpt?.label || bet.winningOptionId}
                                        </div>
                                    </div>
                                </div>

                                <div className="flex items-center gap-3 text-xs font-mono">
                                    <div className="bg-white/5 px-3.5 py-2 rounded-xl border border-white/5 text-center">
                                        <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Çarpan' : 'Odds'}</div>
                                        <div className="text-amber-400 font-black text-sm">{winningOdds > 0 ? `${winningOdds.toFixed(2)}x` : '-'}</div>
                                    </div>
                                    <div className="bg-white/5 px-3.5 py-2 rounded-xl border border-white/5 text-center">
                                        <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Net Dağıtılan' : 'Total Distributed'}</div>
                                        <div className="text-emerald-400 font-black text-sm">{formatMoney(effectivePool)}</div>
                                    </div>
                                </div>
                            </div>

                            {outcome ? (
                                <div className="mt-4">
                                    <div className={`p-4 rounded-2xl border flex flex-wrap items-center justify-between gap-4 ${
                                        outcome.isWin
                                            ? 'bg-emerald-500/10 border-emerald-500/30'
                                            : outcome.isPartialWin
                                            ? 'bg-amber-500/10 border-amber-500/30'
                                            : 'bg-red-500/10 border-red-500/30'
                                    }`}>
                                        <div>
                                            <div className="text-xs font-bold uppercase tracking-wider text-white/70">
                                                {outcome.isWin
                                                    ? (lang === 'TR' ? '🎉 Tebrikler, Kârdasınız!' : '🎉 You Profited!')
                                                    : outcome.isPartialWin
                                                    ? (lang === 'TR' ? '⚡ Kazanan Seçenek Tuttu (Net Zarar)' : '⚡ Winning Pick Hit (Net Loss)')
                                                    : (lang === 'TR' ? '❌ Bu Bahsi Kaybettiniz' : '❌ You Lost')}
                                            </div>
                                            <div className={`text-2xl font-black font-mono mt-0.5 ${
                                                outcome.isWin ? 'text-emerald-400' : outcome.isPartialWin ? 'text-amber-400' : 'text-red-400'
                                            }`}>
                                                {outcome.netProfit > 0 ? '+' : ''}{formatMoney(outcome.netProfit)}
                                            </div>
                                        </div>

                                        <div className="flex items-center gap-4 text-xs font-semibold">
                                            <div>
                                                <span className="text-white/40 block text-[10px]">{lang === 'TR' ? 'Toplam Bahsiniz' : 'Total Bet'}</span>
                                                <span className="font-mono text-white text-sm">{formatMoney(outcome.totalBet)}</span>
                                            </div>
                                            <div className="h-6 w-px bg-white/10"></div>
                                            <div>
                                                <span className="text-white/40 block text-[10px]">{lang === 'TR' ? 'Geri Alınan Ödeme' : 'Payout'}</span>
                                                <span className="font-mono text-emerald-400 text-sm">{formatMoney(outcome.totalPayout)}</span>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            ) : (
                                <div className="mt-4 text-xs text-white/40 text-center py-2.5 bg-white/5 rounded-xl border border-white/5">
                                    {lang === 'TR' ? 'Bu bahiste herhangi bir yatırımınız bulunmuyor.' : 'You did not participate in this bet.'}
                                </div>
                            )}
                        </div>
                    );
                })()}

                {/* Options Selection Grid */}
                <div className="space-y-4 mb-8">
                    <h3 className="text-lg font-black text-white flex items-center gap-2">
                        <span>📊</span>
                        <span>{t.customBetOptions || (lang === 'TR' ? 'Seçenekler ve Oranlar' : 'Options & Odds')}</span>
                    </h3>

                    <div className="grid grid-cols-1 gap-3.5">
                        {(bet.odds || []).map(opt =>
                        {
                            const isSelected = selectedOptionId === opt.optionId;
                            const isWinner = bet.status === 'resolved' && bet.winningOptionId === opt.optionId;
                            const fullOpt = (bet.options || []).find(o => o.id === opt.optionId);
                            const optBettors = fullOpt?.bettors || [];
                            const userOptBets = optBettors.filter(b => (b.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase());
                            const userOptAmount = userOptBets.reduce((sum, b) => sum + (b.amount || 0), 0);

                            const effectivePool = (bet.totalPool || 0) * (1 - (bet.rakePercent || 0.05));
                            const minOdds = (window.GAME_CONFIG && window.GAME_CONFIG.customBet && window.GAME_CONFIG.customBet.MIN_ODDS) || 1.10;
                            const rawWinningOdds = (fullOpt?.totalBetAmount || 0) > 0 ? (effectivePool / fullOpt.totalBetAmount) : 0;
                            const winningOdds = rawWinningOdds > 0 ? Math.max(minOdds, rawWinningOdds) : 0;

                            return (
                                <motion.div
                                    key={opt.optionId}
                                    whileHover={{ scale: bet.status === 'betting' ? 1.01 : 1 }}
                                    onClick={() =>
                                    {
                                        if (bet.status === 'betting')
                                        {
                                            setSelectedOptionId(opt.optionId);
                                        }
                                    }}
                                    className={`relative overflow-hidden rounded-2xl p-5 transition-all ${
                                        bet.status === 'betting' ? 'cursor-pointer' : 'cursor-default'
                                    } ${
                                        isWinner
                                            ? 'bg-emerald-500/20 border-2 border-emerald-400 shadow-[0_0_25px_rgba(52,211,153,0.3)]'
                                            : isSelected
                                            ? 'bg-amber-500/15 border-2 border-amber-400 shadow-[0_0_25px_rgba(251,191,36,0.35)] ring-2 ring-amber-400/40'
                                            : 'bg-slate-900/80 border border-white/10 hover:border-white/30 hover:bg-slate-900'
                                    }`}
                                >
                                    {/* Pool Progress Bar */}
                                    <div
                                        className={`absolute left-0 top-0 bottom-0 transition-all duration-500 ${
                                            isWinner ? 'bg-emerald-500/20' : isSelected ? 'bg-amber-500/20' : 'bg-purple-600/15'
                                        }`}
                                        style={{ width: `${opt.percentage || 0}%` }}
                                    ></div>

                                    <div className="relative z-10 flex justify-between items-center gap-4">
                                        <div className="flex items-center gap-4 min-w-0">
                                            <div className={`w-8 h-8 rounded-full flex items-center justify-center text-sm font-black border transition-all ${
                                                isSelected
                                                    ? 'bg-amber-400 text-slate-950 border-amber-400 shadow-md'
                                                    : isWinner
                                                    ? 'bg-emerald-400 text-slate-950 border-emerald-400'
                                                    : 'bg-white/5 text-white/50 border-white/10'
                                            }`}>
                                                {isWinner ? '👑' : isSelected ? '✓' : ''}
                                            </div>

                                            <div className="min-w-0">
                                                <div className="text-lg font-bold text-white truncate">
                                                    {opt.label}
                                                </div>
                                                <div className="text-xs text-white/50 flex items-center gap-2 mt-0.5">
                                                    <span>{formatMoney(opt.totalBetAmount || 0)}</span>
                                                    <span>•</span>
                                                    <span>{opt.bettorCount || 0} {lang === 'TR' ? 'bahis' : 'bets'}</span>
                                                    <span>({opt.percentage || 0}%)</span>
                                                </div>
                                            </div>
                                        </div>

                                        <div className="flex items-center gap-3">
                                            <div className={`px-4 py-2 rounded-2xl font-mono font-black text-lg md:text-xl border ${
                                                isSelected
                                                    ? 'bg-amber-400 text-slate-950 border-amber-300 shadow-lg'
                                                    : isWinner
                                                    ? 'bg-emerald-400 text-slate-950 border-emerald-300'
                                                    : 'bg-black/40 text-amber-400 border-amber-400/20'
                                            }`}>
                                                {opt.odds > 0 ? `${opt.odds.toFixed(2)}x` : '-'}
                                            </div>
                                        </div>
                                    </div>

                                    {/* User Bet Breakdown on this option */}
                                    {userOptAmount > 0 && (
                                        <div className="relative z-10 mt-3 pt-2.5 border-t border-white/10 flex items-center justify-between text-xs">
                                            <span className="text-white/70">
                                                {lang === 'TR' ? 'Sizin Bahsiniz:' : 'Your Bet:'} <strong className="text-white font-mono">{formatMoney(userOptAmount)}</strong>
                                            </span>
                                            {bet.status === 'resolved' && (
                                                <span className={`font-mono font-bold px-2.5 py-0.5 rounded-lg text-[11px] ${
                                                    isWinner 
                                                        ? 'bg-emerald-500/20 text-emerald-300 border border-emerald-500/40' 
                                                        : 'bg-red-500/20 text-red-300 border border-red-500/30'
                                                }`}>
                                                    {isWinner 
                                                        ? `👑 ${lang === 'TR' ? 'Ödeme:' : 'Payout:'} +${formatMoney(Math.floor(userOptAmount * (opt.odds || 1)))}`
                                                        : `✕ ${lang === 'TR' ? 'Kaybetti' : 'Lost'}`}
                                                </span>
                                            )}
                                        </div>
                                    )}

                                    {/* Locked / Resolved: Show All Bettors Who Voted For This Option */}
                                    {(bet.status === 'locked' || bet.status === 'resolved') && (
                                        <div className="relative z-10 mt-3 pt-3 border-t border-white/10">
                                            <div className="flex items-center justify-between mb-2">
                                                <span className="text-[11px] font-bold text-white/50 uppercase tracking-wider flex items-center gap-1.5">
                                                    <span>👥</span>
                                                    <span>{t.customBetVoters || (lang === 'TR' ? 'Bu Seçeneğe Oy Verenler' : 'Voters on this option')}</span>
                                                </span>
                                                <span className="text-[10px] font-mono font-bold px-2 py-0.5 rounded-full bg-white/10 text-white/70">
                                                    {optBettors.length} {lang === 'TR' ? 'oy' : 'votes'}
                                                </span>
                                            </div>

                                            {optBettors.length > 0 ? (
                                                <div className="flex flex-wrap gap-2">
                                                    {optBettors.map((bettor, bIdx) =>
                                                    {
                                                        const isCurrentUser = (bettor.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase();
                                                        return (
                                                            <div
                                                                key={bIdx}
                                                                className={`inline-flex items-center gap-2 px-3 py-1.5 rounded-xl text-xs border transition-all ${
                                                                    isCurrentUser
                                                                        ? 'bg-purple-600/25 border-purple-400/50 text-purple-200 ring-1 ring-purple-400/30 font-bold'
                                                                        : 'bg-white/5 border-white/10 text-white/90 font-medium'
                                                                }`}
                                                            >
                                                                <span className="w-5 h-5 rounded-full bg-white/10 flex items-center justify-center text-[10px] font-black text-white/70">
                                                                    {(bettor.username || '?').charAt(0).toUpperCase()}
                                                                </span>
                                                                <span className="font-bold">{bettor.username}</span>
                                                                <span className="text-amber-400 font-mono font-black text-[11px] bg-black/40 px-2 py-0.5 rounded-lg border border-white/5">
                                                                    {formatMoney(bettor.amount || 0)}
                                                                </span>
                                                                {bet.status === 'resolved' && isWinner && (
                                                                    <span className="text-emerald-400 font-mono font-black text-[11px] bg-emerald-500/20 px-1.5 py-0.5 rounded border border-emerald-500/30">
                                                                        +{formatMoney(Math.floor((bettor.amount || 0) * (winningOdds || 1)))}
                                                                    </span>
                                                                )}
                                                            </div>
                                                        );
                                                    })}
                                                </div>
                                            ) : (
                                                <p className="text-[11px] text-white/40 italic">
                                                    {t.customBetNoVotes || (lang === 'TR' ? 'Bu seçeneğe oy veren yok' : 'No votes on this option')}
                                                </p>
                                            )}
                                        </div>
                                    )}
                                </motion.div>
                            );
                        })}
                    </div>
                </div>

                {/* Full Votes Breakdown Overview (When Locked or Resolved) */}
                {(bet.status === 'locked' || bet.status === 'resolved') && (() =>
                {
                    const allBettorsList = [];
                    (bet.options || []).forEach(opt =>
                    {
                        (opt.bettors || []).forEach(b =>
                        {
                            allBettorsList.push({
                                username: b.username,
                                amount: b.amount,
                                optionId: opt.id,
                                optionLabel: opt.label,
                                isWinner: bet.status === 'resolved' && opt.id === bet.winningOptionId
                            });
                        });
                    });

                    if (allBettorsList.length === 0) return null;

                    return (
                        <div className="bg-slate-900/70 backdrop-blur-xl border border-white/10 rounded-3xl p-6 mb-8 shadow-2xl">
                            <div className="flex items-center justify-between mb-4 pb-3 border-b border-white/10">
                                <div className="flex items-center gap-2">
                                    <span className="text-xl">🗳️</span>
                                    <h3 className="text-base font-black text-white">
                                        {t.customBetVoteBreakdown || (lang === 'TR' ? 'Tüm Oy ve Bahis Dağılımı' : 'All Votes & Wagers Breakdown')}
                                    </h3>
                                </div>
                                <span className="text-xs font-mono text-white/50 bg-white/5 px-2.5 py-1 rounded-xl border border-white/5">
                                    {allBettorsList.length} {t.customBetTotalVoters || (lang === 'TR' ? 'Toplam Oy' : 'Total Votes')}
                                </span>
                            </div>

                            <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-3">
                                {allBettorsList.map((entry, idx) =>
                                {
                                    const isCurrentUser = (entry.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase();
                                    return (
                                        <div
                                            key={idx}
                                            className={`p-3 rounded-2xl border flex items-center justify-between gap-3 ${
                                                entry.isWinner
                                                    ? 'bg-emerald-500/15 border-emerald-500/30 text-emerald-300'
                                                    : isCurrentUser
                                                    ? 'bg-purple-500/15 border-purple-500/30 text-purple-200'
                                                    : 'bg-slate-950/60 border-white/10 text-white/80'
                                            }`}
                                        >
                                            <div className="flex items-center gap-2.5 min-w-0">
                                                <div className="w-7 h-7 rounded-xl bg-white/10 flex items-center justify-center font-black text-xs shrink-0">
                                                    {(entry.username || '?').charAt(0).toUpperCase()}
                                                </div>
                                                <div className="min-w-0">
                                                    <div className="font-bold text-xs truncate text-white">
                                                        {entry.username} {isCurrentUser && <span className="text-purple-400 font-normal">({lang === 'TR' ? 'Siz' : 'You'})</span>}
                                                    </div>
                                                    <div className="text-[11px] text-white/50 truncate flex items-center gap-1">
                                                        <span>→</span>
                                                        <span className="text-amber-300 font-semibold">{entry.optionLabel}</span>
                                                    </div>
                                                </div>
                                            </div>
                                            <div className="text-right shrink-0">
                                                <div className="text-xs font-mono font-black text-amber-400">
                                                    {formatMoney(entry.amount)}
                                                </div>
                                                {entry.isWinner && (
                                                    <div className="text-[10px] font-bold text-emerald-400">
                                                        👑 {lang === 'TR' ? 'Kazandı' : 'Won'}
                                                    </div>
                                                )}
                                            </div>
                                        </div>
                                    );
                                })}
                            </div>
                        </div>
                    );
                })()}

                {/* Bet Placement Panel (When betting is OPEN) */}
                {bet.status === 'betting' && (
                    <div className="bg-slate-900/90 backdrop-blur-2xl border border-white/15 rounded-3xl p-6 shadow-2xl mb-8">
                        <div className="flex justify-between items-center pb-4 border-b border-white/10 mb-5">
                            <h3 className="text-lg font-black text-white flex items-center gap-2">
                                <span>💵</span>
                                <span>{lang === 'TR' ? 'Bahis Yatır' : 'Place Your Bet'}</span>
                            </h3>
                            <div className="text-xs text-white/50 font-mono">
                                {lang === 'TR' ? 'Kullanılabilir Bakiye' : 'Available Balance'}: <span className="text-emerald-400 font-bold">{formatMoney(userBalance)}</span>
                            </div>
                        </div>

                        {selectedOptionId !== null && activeOption ? (
                            <div className="space-y-5">
                                <div className="bg-slate-950/80 border border-amber-500/40 rounded-2xl p-4 flex justify-between items-center">
                                    <div>
                                        <span className="text-xs text-white/50 block mb-0.5">{t.customBetYourPick || (lang === 'TR' ? 'Seçiminiz' : 'Your Pick')}</span>
                                        <span className="text-base font-black text-amber-300">{activeOption.label}</span>
                                    </div>
                                    <span className="text-sm font-mono font-bold px-3 py-1 rounded-xl bg-amber-400/20 text-amber-300 border border-amber-400/30">
                                        {activeOption.odds > 0 ? `${activeOption.odds.toFixed(2)}x` : '-'}
                                    </span>
                                </div>

                                {/* Amount Input & Preset Chips */}
                                <div className="space-y-2.5">
                                    <label className="block text-xs font-bold text-white/60 uppercase tracking-wider">
                                        {t.customBetEnterAmount || (lang === 'TR' ? 'Bahis Miktarı ($)' : 'Bet Amount ($)')}
                                    </label>
                                    <div className="relative">
                                        <span className="absolute left-4 top-1/2 -translate-y-1/2 text-white/40 font-mono text-lg font-bold">$</span>
                                        <input
                                            type="number"
                                            value={betAmount || ''}
                                            onChange={(e) => setBetAmount(Math.max(0, Number(e.target.value)))}
                                            className="w-full bg-slate-950 border border-white/20 rounded-2xl pl-9 pr-4 py-3.5 text-white font-mono font-bold text-lg outline-none focus:border-amber-400 transition-colors"
                                            placeholder="10000"
                                        />
                                    </div>

                                    {/* Preset Buttons */}
                                    <div className="grid grid-cols-3 sm:grid-cols-6 gap-2">
                                        {[10000, 50000, 100000, 500000, 1000000, 5000000].map(amt => (
                                            <button
                                                key={amt}
                                                onClick={() => setBetAmount(amt)}
                                                className={`py-2 px-2 rounded-xl text-xs font-bold transition-all border ${
                                                    betAmount === amt
                                                        ? 'bg-purple-600 text-white border-purple-400 shadow-md'
                                                        : 'bg-white/5 hover:bg-white/10 text-white/80 border-white/10'
                                                }`}
                                            >
                                                {amt >= 1000000 ? `${amt / 1000000}M` : `${amt / 1000}k`}
                                            </button>
                                        ))}
                                    </div>
                                </div>

                                {/* Potential Win Box */}
                                <div className="bg-gradient-to-r from-amber-500/10 via-purple-500/10 to-transparent border border-amber-500/30 rounded-2xl p-4 flex justify-between items-center">
                                    <div>
                                        <span className="text-xs text-white/60 block">{t.customBetPotentialWin || (lang === 'TR' ? 'Olası Kazanç' : 'Potential Win')}</span>
                                        <span className="text-xl font-black text-amber-300 font-mono">{formatMoney(projectedPotentialWin)}</span>
                                    </div>
                                    <span className="text-xs text-amber-400/80 font-mono">({activeOption.odds}x)</span>
                                </div>

                                {/* Submit Button */}
                                <button
                                    onClick={() => handlePlaceBet(bet.id)}
                                    disabled={betAmount <= 0 || (userBalance < betAmount && !isAdmin)}
                                    className="w-full py-4 bg-gradient-to-r from-amber-500 via-orange-500 to-purple-600 hover:from-amber-400 hover:via-orange-400 hover:to-purple-500 disabled:opacity-40 disabled:cursor-not-allowed text-slate-950 font-black text-base rounded-2xl shadow-xl shadow-amber-500/20 transition-all hover:scale-[1.01] active:scale-[0.99] flex items-center justify-center gap-2"
                                >
                                    <span>{t.customBetPlaceBet || (lang === 'TR' ? 'Bahis Koy' : 'Place Bet')}</span>
                                    <span className="font-mono">({formatMoney(betAmount)})</span>
                                </button>
                            </div>
                        ) : (
                            <div className="py-8 text-center text-white/50 flex flex-col items-center justify-center">
                                <span className="text-3xl mb-2">👆</span>
                                <p className="text-sm font-semibold">{lang === 'TR' ? 'Bahis yapmak için lütfen yukarıdaki seçeneklerden birine tıklayın.' : 'Please click on an option above to place your bet.'}</p>
                            </div>
                        )}
                    </div>
                )}

                {/* Admin Actions Bar in Bet Detail */}
                {isAdmin && (
                    <div className="bg-slate-900/60 border border-white/10 rounded-3xl p-5 mb-8 flex flex-wrap items-center justify-between gap-4">
                        <span className="text-xs text-white/50 uppercase font-black tracking-wider">
                            🛡️ {t.customBetAdminControls || (lang === 'TR' ? 'Admin Kontrolleri' : 'Admin Controls')}
                        </span>

                        <div className="flex items-center gap-3">
                            {bet.status === 'betting' && (!bet.totalPool || bet.totalPool === 0) && (
                                <button
                                    onClick={() => handleOpenEditBet(bet)}
                                    className="px-4 py-2 bg-blue-500/20 text-blue-400 hover:bg-blue-500/30 rounded-xl text-xs font-bold border border-blue-500/30 transition-all flex items-center gap-1.5"
                                >
                                    <span>✏️</span>
                                    <span>{lang === 'TR' ? 'Bahsi Düzenle' : 'Edit Bet'}</span>
                                </button>
                            )}
                            {bet.status === 'betting' && (
                                <button
                                    onClick={() => handleLockBet(bet.id)}
                                    className="px-4 py-2 bg-amber-500/20 text-amber-400 hover:bg-amber-500/30 rounded-xl text-xs font-bold border border-amber-500/30 transition-all"
                                >
                                    🔒 {t.customBetLockBets || (lang === 'TR' ? 'Bahsi Kilitle' : 'Lock Bet')}
                                </button>
                            )}
                            {bet.status !== 'resolved' && (
                                <button
                                    onClick={() =>
                                    {
                                        setResolveModalBet(bet);
                                        setSelectedWinnerOptionId(bet.options[0]?.id ?? null);
                                    }}
                                    className="px-4 py-2 bg-emerald-500/20 text-emerald-400 hover:bg-emerald-500/30 rounded-xl text-xs font-bold border border-emerald-500/30 transition-all"
                                >
                                    ✓ {t.customBetResolve || (lang === 'TR' ? 'Sonuçlandır' : 'Resolve')}
                                </button>
                            )}
                            {bet.status === 'resolved' && (
                                <button
                                    onClick={() => handleRestartBet(bet.id)}
                                    className="px-4 py-2 bg-amber-500/20 text-amber-400 hover:bg-amber-500/30 rounded-xl text-xs font-bold border border-amber-500/30 transition-all flex items-center gap-1.5"
                                >
                                    <span>🔄</span>
                                    <span>{t.customBetRestart || (lang === 'TR' ? 'Bahsi Tekrar Başlat' : 'Restart Bet')}</span>
                                </button>
                            )}
                            <button
                                onClick={() => handleDeleteBet(bet.id)}
                                className="px-4 py-2 bg-red-500/20 text-red-400 hover:bg-red-500/30 rounded-xl text-xs font-bold border border-red-500/30 transition-all"
                            >
                                🗑️ {t.customBetDeleteBet || (lang === 'TR' ? 'Bahsi Sil' : 'Delete Bet')}
                            </button>
                        </div>
                    </div>
                )}
            </div>
        );
    };

    return (
        <div className="w-full font-['Outfit'] select-none">
            {error && (
                <div className="fixed top-6 left-1/2 -translate-x-1/2 z-50 bg-red-600/90 backdrop-blur-md text-white font-bold px-6 py-3 rounded-2xl shadow-2xl border border-red-400 text-sm animate-bounce">
                    {error}
                </div>
            )}

            <AnimatePresence mode="wait">
                <motion.div
                    key={view}
                    initial={{ opacity: 0, y: 15 }}
                    animate={{ opacity: 1, y: 0 }}
                    exit={{ opacity: 0, y: -15 }}
                    transition={{ duration: 0.25 }}
                    className="min-h-full"
                >
                    {view === 'lobby' && renderLobby()}
                    {view === 'room' && renderRoom()}
                    {view === 'bet' && renderBetDetail()}
                </motion.div>
            </AnimatePresence>

            {/* Create Room Modal */}
            {showCreateRoomModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-white/10 rounded-3xl p-6 w-full max-w-lg shadow-2xl relative max-h-[90vh] overflow-y-auto"
                    >
                        <button
                            onClick={() => setShowCreateRoomModal(false)}
                            className="absolute top-4 right-4 text-white/40 hover:text-white text-xl"
                        >
                            ✕
                        </button>

                        <h2 className="text-2xl font-black text-white mb-6 bg-gradient-to-r from-purple-400 to-orange-400 bg-clip-text text-transparent">
                            {t.customBetCreateRoom || (lang === 'TR' ? 'Yeni Oda Oluştur' : 'Create Custom Room')}
                        </h2>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetRoomTitle || (lang === 'TR' ? 'Oda Adı' : 'Room Title')} *
                                </label>
                                <input
                                    type="text"
                                    value={newRoomTitle}
                                    onChange={(e) => setNewRoomTitle(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-purple-500 transition-colors text-sm"
                                    placeholder={lang === 'TR' ? 'Örn: Perşembe Günlük Bahisleri' : 'e.g. Thursday Daily Bets'}
                                />
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetRoomDesc || (lang === 'TR' ? 'Oda Açıklaması' : 'Room Description')}
                                </label>
                                <input
                                    type="text"
                                    value={newRoomDesc}
                                    onChange={(e) => setNewRoomDesc(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-white outline-none focus:border-purple-500 transition-colors text-sm"
                                    placeholder={lang === 'TR' ? 'Örn: Ofis içi tahminler ve sürprizler' : 'e.g. Office predictions'}
                                />
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5 flex items-center justify-between">
                                    <span>{t.customBetOptionalPassword || (lang === 'TR' ? 'Oda Şifresi (İsteğe Bağlı)' : 'Room Password (Optional)')}</span>
                                    <span className="text-[10px] text-amber-400/80 font-normal">🔒 {lang === 'TR' ? 'Gizli Oda' : 'Private Room'}</span>
                                </label>
                                <input
                                    type="text"
                                    value={newRoomPassword}
                                    onChange={(e) => setNewRoomPassword(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-white outline-none focus:border-purple-500 transition-colors text-sm font-mono"
                                    placeholder={t.customBetPasswordPlaceholder || (lang === 'TR' ? 'Şifre belirleyin (Boş bırakılabilir)' : 'Set password (Leave blank for public)')}
                                />
                            </div>

                            <div className="pt-3 border-t border-white/10">
                                <label className="block text-xs font-bold text-amber-400 uppercase tracking-wider mb-1.5">
                                    {lang === 'TR' ? 'İlk Bahis Sorusu (İsteğe Bağlı)' : 'Initial Bet Question (Optional)'}
                                </label>
                                <input
                                    type="text"
                                    value={initialQuestion}
                                    onChange={(e) => setInitialQuestion(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-white outline-none focus:border-purple-500 transition-colors text-sm mb-2"
                                    placeholder={lang === 'TR' ? 'Örn: Giden adam Perşembe günü kaçta çıkar?' : 'e.g. When will the guest leave?'}
                                />

                                {initialQuestion.trim() !== '' && (
                                    <div className="space-y-2 mt-2">
                                        {initialOptions.map((opt, idx) => (
                                            <div key={idx} className="flex gap-2">
                                                <input
                                                    type="text"
                                                    value={opt}
                                                    onChange={(e) => {
                                                        const updated = [...initialOptions];
                                                        updated[idx] = e.target.value;
                                                        setInitialOptions(updated);
                                                    }}
                                                    className="flex-1 bg-slate-950 border border-white/10 rounded-xl px-4 py-2 text-white outline-none focus:border-purple-500 text-xs"
                                                    placeholder={`${lang === 'TR' ? 'Seçenek' : 'Option'} ${idx + 1}`}
                                                />
                                                {initialOptions.length > 2 && (
                                                    <button
                                                        onClick={() => setInitialOptions(initialOptions.filter((_, i) => i !== idx))}
                                                        className="w-8 bg-red-500/20 text-red-400 rounded-xl hover:bg-red-500/30 flex items-center justify-center font-bold text-xs"
                                                    >
                                                        ✕
                                                    </button>
                                                )}
                                            </div>
                                        ))}
                                        {initialOptions.length < 15 && (
                                            <button
                                                onClick={() => setInitialOptions([...initialOptions, ''])}
                                                className="text-xs font-bold text-purple-400 hover:text-purple-300 flex items-center gap-1 mt-1"
                                            >
                                                + {t.customBetAddOption || (lang === 'TR' ? 'Seçenek Ekle' : 'Add Option')}
                                            </button>
                                        )}
                                    </div>
                                )}
                            </div>
                        </div>

                        <div className="mt-8 flex justify-end gap-3">
                            <button
                                onClick={() => setShowCreateRoomModal(false)}
                                className="px-5 py-2.5 bg-white/5 hover:bg-white/10 text-white rounded-xl font-bold text-sm transition-all"
                            >
                                {t.customBetCancel || (lang === 'TR' ? 'İptal' : 'Cancel')}
                            </button>
                            <button
                                onClick={handleCreateRoom}
                                className="px-6 py-2.5 bg-gradient-to-r from-purple-600 to-orange-500 text-white rounded-xl font-black text-sm hover:opacity-90 transition-all shadow-lg"
                            >
                                {t.customBetCreateBtn || (lang === 'TR' ? 'Odayı Oluştur' : 'Create Room')}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}

            {/* Add Bet to Room Modal */}
            {showAddBetModal && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-white/10 rounded-3xl p-6 w-full max-w-lg shadow-2xl relative max-h-[90vh] overflow-y-auto"
                    >
                        <button
                            onClick={() => setShowAddBetModal(false)}
                            className="absolute top-4 right-4 text-white/40 hover:text-white text-xl"
                        >
                            ✕
                        </button>

                        <h2 className="text-2xl font-black text-white mb-6 bg-gradient-to-r from-purple-400 to-orange-400 bg-clip-text text-transparent">
                            {t.customBetAddBetToRoom || (lang === 'TR' ? 'Odaya Yeni Bahis Ekle' : 'Add Bet to Room')}
                        </h2>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetQuestion || (lang === 'TR' ? 'Bahis Sorusu' : 'Bet Question')} *
                                </label>
                                <input
                                    type="text"
                                    value={newBetQuestion}
                                    onChange={(e) => setNewBetQuestion(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-purple-500 transition-colors text-sm"
                                    placeholder={lang === 'TR' ? 'Örn: Giden adam Perşembe günü kaçta geri gelir?' : 'e.g. When will they return?'}
                                />
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetOptions || (lang === 'TR' ? 'Seçenekler' : 'Options')} *
                                </label>
                                <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
                                    {newBetOptions.map((opt, idx) => (
                                        <div key={idx} className="flex gap-2">
                                            <input
                                                type="text"
                                                value={opt}
                                                onChange={(e) => {
                                                    const updated = [...newBetOptions];
                                                    updated[idx] = e.target.value;
                                                    setNewBetOptions(updated);
                                                }}
                                                className="flex-1 bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-white outline-none focus:border-purple-500 text-sm"
                                                placeholder={`${lang === 'TR' ? 'Seçenek' : 'Option'} ${idx + 1}`}
                                            />
                                            {newBetOptions.length > 2 && (
                                                <button
                                                    onClick={() => setNewBetOptions(newBetOptions.filter((_, i) => i !== idx))}
                                                    className="w-10 bg-red-500/20 text-red-400 rounded-xl hover:bg-red-500/30 flex items-center justify-center font-bold"
                                                >
                                                    ✕
                                                </button>
                                            )}
                                        </div>
                                    ))}
                                </div>
                                {newBetOptions.length < 20 && (
                                    <button
                                        onClick={() => setNewBetOptions([...newBetOptions, ''])}
                                        className="mt-3 text-xs font-bold text-purple-400 hover:text-purple-300 flex items-center gap-1"
                                    >
                                        + {t.customBetAddOption || (lang === 'TR' ? 'Seçenek Ekle' : 'Add Option')}
                                    </button>
                                )}
                            </div>
                        </div>

                        <div className="mt-8 flex justify-end gap-3">
                            <button
                                onClick={() => setShowAddBetModal(false)}
                                className="px-5 py-2.5 bg-white/5 hover:bg-white/10 text-white rounded-xl font-bold text-sm transition-all"
                            >
                                {t.customBetCancel || (lang === 'TR' ? 'İptal' : 'Cancel')}
                            </button>
                            <button
                                onClick={handleAddBetToRoom}
                                className="px-6 py-2.5 bg-gradient-to-r from-purple-600 to-orange-500 text-white rounded-xl font-black text-sm hover:opacity-90 transition-all shadow-lg"
                            >
                                {t.customBetAddBetBtn || (lang === 'TR' ? 'Bahsi Ekle' : 'Add Bet')}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}

            {/* Edit Bet Modal */}
            {showEditBetModal && editModalBet && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/80 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-blue-500/30 rounded-3xl p-6 w-full max-w-lg shadow-2xl relative max-h-[90vh] overflow-y-auto"
                    >
                        <button
                            onClick={() => {
                                setShowEditBetModal(false);
                                setEditModalBet(null);
                            }}
                            className="absolute top-4 right-4 text-white/40 hover:text-white text-xl"
                        >
                            ✕
                        </button>

                        <h2 className="text-2xl font-black text-white mb-2 bg-gradient-to-r from-blue-400 to-teal-400 bg-clip-text text-transparent">
                            {lang === 'TR' ? 'Bahsi Düzenle' : 'Edit Bet'}
                        </h2>
                        <p className="text-xs text-white/50 mb-6">
                            {lang === 'TR' ? 'Henüz hiçbir bahis yatırılmadığı için soru ve seçenekleri güncelleyebilirsiniz.' : 'You can update question and options since no bets have been placed.'}
                        </p>

                        <div className="space-y-4">
                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetQuestion || (lang === 'TR' ? 'Bahis Sorusu' : 'Bet Question')} *
                                </label>
                                <input
                                    type="text"
                                    value={editBetQuestion}
                                    onChange={(e) => setEditBetQuestion(e.target.value)}
                                    className="w-full bg-slate-950 border border-white/10 rounded-xl px-4 py-3 text-white outline-none focus:border-blue-500 transition-colors text-sm"
                                    placeholder={lang === 'TR' ? 'Bahis Sorusu' : 'Bet Question'}
                                />
                            </div>

                            <div>
                                <label className="block text-xs font-bold text-white/50 uppercase tracking-wider mb-1.5">
                                    {t.customBetOptions || (lang === 'TR' ? 'Seçenekler' : 'Options')} *
                                </label>
                                <div className="space-y-2 max-h-48 overflow-y-auto pr-1">
                                    {editBetOptions.map((opt, idx) => (
                                        <div key={idx} className="flex gap-2">
                                            <input
                                                type="text"
                                                value={opt}
                                                onChange={(e) => {
                                                    const updated = [...editBetOptions];
                                                    updated[idx] = e.target.value;
                                                    setEditBetOptions(updated);
                                                }}
                                                className="flex-1 bg-slate-950 border border-white/10 rounded-xl px-4 py-2.5 text-white outline-none focus:border-blue-500 text-sm"
                                                placeholder={`${lang === 'TR' ? 'Seçenek' : 'Option'} ${idx + 1}`}
                                            />
                                            {editBetOptions.length > 2 && (
                                                <button
                                                    onClick={() => setEditBetOptions(editBetOptions.filter((_, i) => i !== idx))}
                                                    className="w-10 bg-red-500/20 text-red-400 rounded-xl hover:bg-red-500/30 flex items-center justify-center font-bold"
                                                >
                                                    ✕
                                                </button>
                                            )}
                                        </div>
                                    ))}
                                </div>
                                {editBetOptions.length < 20 && (
                                    <button
                                        onClick={() => setEditBetOptions([...editBetOptions, ''])}
                                        className="mt-3 text-xs font-bold text-blue-400 hover:text-blue-300 flex items-center gap-1"
                                    >
                                        + {t.customBetAddOption || (lang === 'TR' ? 'Seçenek Ekle' : 'Add Option')}
                                    </button>
                                )}
                            </div>
                        </div>

                        <div className="mt-8 flex justify-end gap-3">
                            <button
                                onClick={() => {
                                    setShowEditBetModal(false);
                                    setEditModalBet(null);
                                }}
                                className="px-5 py-2.5 bg-white/5 hover:bg-white/10 text-white rounded-xl font-bold text-sm transition-all"
                            >
                                {t.customBetCancel || (lang === 'TR' ? 'İptal' : 'Cancel')}
                            </button>
                            <button
                                onClick={handleSaveEditBet}
                                className="px-6 py-2.5 bg-gradient-to-r from-blue-600 to-teal-500 text-white rounded-xl font-black text-sm hover:opacity-90 transition-all shadow-lg"
                            >
                                {lang === 'TR' ? 'Kaydet ve Güncelle' : 'Save & Update'}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}

            {/* Resolve Modal */}
            {resolveModalBet && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-emerald-500/30 rounded-3xl p-6 w-full max-w-md shadow-2xl relative"
                    >
                        <h2 className="text-xl font-black text-white mb-2">
                            {t.customBetResolve || (lang === 'TR' ? 'Bahsi Sonuçlandır' : 'Resolve Bet')}
                        </h2>
                        <p className="text-xs text-white/60 mb-4">{resolveModalBet.question}</p>

                        <div className="space-y-2 mb-6">
                            {(resolveModalBet.options || []).map(opt => (
                                <div
                                    key={opt.id}
                                    onClick={() => setSelectedWinnerOptionId(opt.id)}
                                    className={`p-3.5 rounded-xl border cursor-pointer flex justify-between items-center transition-all ${
                                        selectedWinnerOptionId === opt.id ? 'bg-emerald-500/20 border-emerald-400 text-emerald-300 font-bold' : 'bg-slate-950 border-white/10 text-white/80'
                                    }`}
                                >
                                    <span>{opt.label}</span>
                                    {selectedWinnerOptionId === opt.id && <span>👑</span>}
                                </div>
                            ))}
                        </div>

                        <div className="flex justify-end gap-3">
                            <button
                                onClick={() => setResolveModalBet(null)}
                                className="px-4 py-2 bg-white/5 hover:bg-white/10 text-white rounded-xl font-bold text-xs"
                            >
                                {t.customBetCancel || (lang === 'TR' ? 'İptal' : 'Cancel')}
                            </button>
                            <button
                                onClick={handleConfirmResolveBet}
                                disabled={selectedWinnerOptionId === null}
                                className="px-5 py-2 bg-emerald-500 hover:bg-emerald-400 text-slate-950 font-black rounded-xl text-xs uppercase"
                            >
                                {t.customBetResolve || (lang === 'TR' ? 'Onayla ve Öde' : 'Confirm & Payout')}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}

            {/* Resolve Results Splash */}
            {resolveResults && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-white/10 rounded-3xl p-6 w-full max-w-lg shadow-2xl text-center max-h-[90vh] overflow-y-auto"
                    >
                        <div className="text-4xl mb-2">🎉</div>
                        <div className="text-2xl font-black bg-gradient-to-r from-emerald-400 to-teal-400 bg-clip-text text-transparent mb-3">
                            {resolveResults.winningLabel} {t.customBetWon || (lang === 'TR' ? 'KAZANDI!' : 'WON!')}
                        </div>

                        {/* Bet & Pool Stats Strip */}
                        <div className="grid grid-cols-2 sm:grid-cols-4 gap-2 mb-4 text-xs font-mono">
                            <div className="bg-white/5 p-2 rounded-xl border border-white/5">
                                <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Toplam Havuz' : 'Total Pool'}</div>
                                <div className="text-amber-400 font-bold">{formatMoney(resolveResults.totalPool || 0)}</div>
                            </div>
                            <div className="bg-white/5 p-2 rounded-xl border border-white/5">
                                <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Kazanan Oran' : 'Odds'}</div>
                                <div className="text-white font-bold">{resolveResults.winningOdds > 0 ? `${resolveResults.winningOdds.toFixed(2)}x` : '-'}</div>
                            </div>
                            <div className="bg-white/5 p-2 rounded-xl border border-white/5">
                                <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Komisyon' : 'Rake'}</div>
                                <div className="text-white/70 font-bold">%{(resolveResults.rakePercent || 0.05) * 100}</div>
                            </div>
                            <div className="bg-white/5 p-2 rounded-xl border border-white/5">
                                <div className="text-white/40 text-[10px] uppercase font-bold">{lang === 'TR' ? 'Dağıtılan' : 'Payout Pool'}</div>
                                <div className="text-emerald-400 font-bold">{formatMoney(resolveResults.effectivePool || 0)}</div>
                            </div>
                        </div>

                        {(() => {
                            const myResults = (resolveResults.results || []).filter(r => (r.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase());
                            
                            if (myResults.length === 0)
                            {
                                return (
                                    <div className="p-4 rounded-2xl border border-white/10 bg-white/5 text-xs text-white/60 mb-4">
                                        ℹ️ {lang === 'TR' ? 'Bu bahiste herhangi bir yatırımınız bulunmuyor.' : 'You did not place a bet on this round.'}
                                    </div>
                                );
                            }

                            const totalBet = myResults.reduce((acc, r) => acc + (r.totalBet ?? r.amount ?? 0), 0);
                            const totalPayout = myResults.reduce((acc, r) => acc + (r.payout || 0), 0);
                            const netProfit = myResults.reduce((acc, r) => acc + (r.profit !== undefined ? r.profit : (r.payout || 0) - (r.amount || 0)), 0);
                            const newBalance = myResults.find(r => r.newBalance !== undefined)?.newBalance;

                            const isWin = netProfit > 0;
                            const isPartialWin = !isWin && totalPayout > 0;

                            // Collect all option-level bets
                            const allOptionBets = [];
                            myResults.forEach(r => {
                                if (r.optionBets && r.optionBets.length > 0)
                                {
                                    allOptionBets.push(...r.optionBets);
                                }
                            });

                            return (
                                <div className="space-y-3 mb-5 text-left">
                                    {/* Main Outcome Card */}
                                    <div className={`p-4 rounded-2xl border text-center ${
                                        isWin 
                                            ? 'bg-emerald-500/10 border-emerald-500/30' 
                                            : isPartialWin 
                                                ? 'bg-amber-500/10 border-amber-500/30' 
                                                : 'bg-red-500/10 border-red-500/30'
                                    }`}>
                                        <div className="text-sm font-bold">
                                            {isWin 
                                                ? (lang === 'TR' ? '🎉 Tebrikler, Kazandınız!' : '🎉 Congratulations, You Won!') 
                                                : isPartialWin 
                                                    ? (lang === 'TR' ? '⚡ Kazanan Seçenek Tuttu (Net Zarar)' : '⚡ Winning Pick Hit (Net Loss)') 
                                                    : (lang === 'TR' ? '❌ Bu Bahsi Kaybettiniz' : '❌ You Lost')}
                                        </div>
                                        <div className={`text-2xl font-black font-mono mt-1 ${
                                            isWin 
                                                ? 'text-emerald-400' 
                                                : isPartialWin 
                                                    ? 'text-amber-400' 
                                                    : 'text-red-400'
                                        }`}>
                                            {netProfit > 0 ? '+' : ''}{formatMoney(netProfit)}
                                        </div>
                                        <div className="flex justify-around items-center mt-3 pt-3 border-t border-white/10 text-xs font-semibold text-slate-400">
                                            <div>
                                                <span>{lang === 'TR' ? 'Toplam Bahis' : 'Total Bet'}: </span>
                                                <span className="text-white font-mono">{formatMoney(totalBet)}</span>
                                            </div>
                                            <div>
                                                <span>{lang === 'TR' ? 'Alınan Ödeme' : 'Payout'}: </span>
                                                <span className="text-emerald-400 font-mono">{formatMoney(totalPayout)}</span>
                                            </div>
                                        </div>
                                    </div>

                                    {/* Option Breakdown List */}
                                    {allOptionBets.length > 0 && (
                                        <div className="bg-slate-950/70 border border-white/10 rounded-2xl p-3.5 space-y-2">
                                            <div className="text-[11px] font-bold text-white/50 uppercase tracking-wider mb-1">
                                                📋 {lang === 'TR' ? 'Bahislerinizin Dökümü' : 'Your Bets Breakdown'}
                                            </div>
                                            {allOptionBets.map((ob, idx) => (
                                                <div
                                                    key={idx}
                                                    className={`flex justify-between items-center p-2.5 rounded-xl border text-xs ${
                                                        ob.isWinner 
                                                            ? 'bg-emerald-500/10 border-emerald-500/30' 
                                                            : 'bg-white/5 border-white/5'
                                                    }`}
                                                >
                                                    <div className="flex items-center gap-2">
                                                        <span>{ob.isWinner ? '👑' : '✕'}</span>
                                                        <span className="font-bold text-white">{ob.optionLabel || `Seçenek ${ob.optionId}`}</span>
                                                        <span className="text-white/40 font-mono">({formatMoney(ob.amount)})</span>
                                                    </div>
                                                    <div className="font-mono font-bold">
                                                        {ob.isWinner ? (
                                                            <span className="text-emerald-400">+{formatMoney(ob.payout)}</span>
                                                        ) : (
                                                            <span className="text-red-400/80">$0</span>
                                                        )}
                                                    </div>
                                                </div>
                                            ))}
                                        </div>
                                    )}

                                    {/* Updated Balance Badge */}
                                    {newBalance !== undefined && (
                                        <div className="flex justify-between items-center px-4 py-2.5 bg-white/5 border border-white/10 rounded-xl text-xs">
                                            <span className="text-white/60">{lang === 'TR' ? 'Güncel Bakiyeniz:' : 'Your New Balance:'}</span>
                                            <span className="text-emerald-400 font-mono font-black">{formatMoney(newBalance)}</span>
                                        </div>
                                    )}
                                </div>
                            );
                        })()}

                        {/* All Participants List in Resolve Modal */}
                        {(resolveResults.results || []).length > 0 && (
                            <div className="bg-slate-950/70 border border-white/10 rounded-2xl p-3.5 space-y-2 mb-4 text-left">
                                <div className="text-[11px] font-bold text-white/50 uppercase tracking-wider mb-1 flex items-center justify-between">
                                    <span>👥 {t.customBetAllParticipants || (lang === 'TR' ? 'Tüm Katılımcılar ve Kazançları' : 'All Participants & Payouts')}</span>
                                    <span className="font-mono text-[10px] text-white/40">{(resolveResults.results || []).length} {lang === 'TR' ? 'katılımcı' : 'participants'}</span>
                                </div>
                                <div className="space-y-1.5 max-h-40 overflow-y-auto pr-1">
                                    {(resolveResults.results || []).map((res, rIdx) =>
                                    {
                                        const isUser = (res.username || '').toLowerCase() === (userProfile?.username || '').toLowerCase();
                                        return (
                                            <div
                                                key={rIdx}
                                                className={`flex justify-between items-center p-2 rounded-xl border text-xs ${
                                                    res.won
                                                        ? 'bg-emerald-500/10 border-emerald-500/30'
                                                        : 'bg-white/5 border-white/5'
                                                }`}
                                            >
                                                <div className="flex items-center gap-2">
                                                    <span className="w-5 h-5 rounded-full bg-white/10 flex items-center justify-center text-[10px] font-bold text-white/70">
                                                        {(res.username || '?').charAt(0).toUpperCase()}
                                                    </span>
                                                    <span className={`font-bold ${isUser ? 'text-purple-300' : 'text-white'}`}>
                                                        {res.username} {isUser && <span className="text-[10px] text-purple-400 font-normal">({lang === 'TR' ? 'Siz' : 'You'})</span>}
                                                    </span>
                                                </div>
                                                <div className="flex items-center gap-3 font-mono">
                                                    <span className="text-white/40 text-[11px]">{formatMoney(res.totalBet ?? res.amount ?? 0)}</span>
                                                    <span className={`font-bold ${res.won ? 'text-emerald-400' : 'text-red-400'}`}>
                                                        {res.won ? `+${formatMoney(res.payout)}` : '$0'}
                                                    </span>
                                                </div>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        )}

                        <button
                            onClick={() => setResolveResults(null)}
                            className="w-full py-3 bg-gradient-to-r from-purple-600 to-amber-500 hover:opacity-95 text-white font-bold rounded-xl text-sm transition-all shadow-lg"
                        >
                            {lang === 'TR' ? 'Harika, Anladım' : 'Got It'}
                        </button>
                    </motion.div>
                </div>
            )}

            {/* Password Prompt Modal */}
            {passwordModalRoom && (
                <div className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-black/85 backdrop-blur-md">
                    <motion.div
                        initial={{ scale: 0.9, opacity: 0 }}
                        animate={{ scale: 1, opacity: 1 }}
                        className="bg-slate-900 border border-amber-500/30 rounded-3xl p-6 w-full max-w-md shadow-2xl relative"
                    >
                        <button
                            onClick={() => {
                                setPasswordModalRoom(null);
                                setEnteredPassword('');
                                setPasswordError(null);
                            }}
                            className="absolute top-4 right-4 text-white/40 hover:text-white text-xl"
                        >
                            ✕
                        </button>

                        <div className="flex items-center gap-3 mb-4">
                            <div className="w-12 h-12 rounded-2xl bg-amber-500/20 border border-amber-500/30 flex items-center justify-center text-2xl text-amber-400">
                                🔒
                            </div>
                            <div>
                                <h2 className="text-xl font-black text-white">
                                    {t.customBetPasswordModalTitle || (lang === 'TR' ? 'Korumalı Oda' : 'Protected Room')}
                                </h2>
                                <p className="text-xs text-white/50">
                                    #{passwordModalRoom.code || passwordModalRoom.id.slice(-4)}
                                </p>
                            </div>
                        </div>

                        <p className="text-sm text-white/80 font-medium mb-4 p-3 bg-white/5 rounded-2xl border border-white/5">
                            {passwordModalRoom.title}
                        </p>

                        <p className="text-xs text-white/60 mb-3">
                            {t.customBetPasswordModalDesc || (lang === 'TR' ? 'Bu odaya katılmak ve bahisleri görmek için lütfen oda şifresini girin.' : 'Please enter the room password to join and view bets.')}
                        </p>

                        <div className="space-y-3">
                            <input
                                type="password"
                                autoFocus
                                value={enteredPassword}
                                onChange={(e) => {
                                    setEnteredPassword(e.target.value);
                                    setPasswordError(null);
                                }}
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        handleJoinWithPassword();
                                    }
                                }}
                                className="w-full bg-slate-950 border border-white/20 focus:border-amber-400 rounded-xl px-4 py-3 text-white outline-none font-mono text-center tracking-widest text-lg transition-colors"
                                placeholder="••••••"
                            />

                            {passwordError && (
                                <p className="text-xs text-red-400 font-bold text-center animate-pulse">
                                    {passwordError}
                                </p>
                            )}
                        </div>

                        <div className="mt-6 flex justify-end gap-3">
                            <button
                                onClick={() => {
                                    setPasswordModalRoom(null);
                                    setEnteredPassword('');
                                    setPasswordError(null);
                                }}
                                className="px-5 py-2.5 bg-white/5 hover:bg-white/10 text-white rounded-xl font-bold text-sm transition-all"
                            >
                                {t.customBetCancel || (lang === 'TR' ? 'İptal' : 'Cancel')}
                            </button>
                            <button
                                onClick={handleJoinWithPassword}
                                className="px-6 py-2.5 bg-gradient-to-r from-amber-500 to-orange-500 text-slate-950 font-black text-sm hover:opacity-90 transition-all rounded-xl shadow-lg shadow-amber-500/20"
                            >
                                {t.customBetJoinWithPassword || (lang === 'TR' ? 'Giriş Yap' : 'Join Room')}
                            </button>
                        </div>
                    </motion.div>
                </div>
            )}
        </div>
    );
}

window.CustomBet = CustomBet;

