import discord
from discord import app_commands
from discord.ext import commands
import random
import asyncio
from datetime import datetime
import logging
import config
from database import db, InsufficientFunds
from utils.security import check_security_compliance
from utils.logger import log_suspicious_activity, log_transaction

logger = logging.getLogger("gamble_bot.cogs.games")

class GamesCog(commands.Cog, name="Kumar Oyunları"):
    def __init__(self, bot):
        self.bot = bot

    # --- 1. COINFLIP (YAZI-TURA) ---


    async def _play_coinflip(self, interaction: discord.Interaction, miktar: str, choice_val: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            msg = "❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 1b)."
            if interaction.response.is_done():
                await interaction.followup.send(msg, ephemeral=True)
            else:
                await interaction.response.send_message(msg, ephemeral=True)
            return

        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True)

        user_id = interaction.user.id

        try:
            # Deduct bet (raises InsufficientFunds if they don't have enough)
            await db.update_balance(user_id, -val_amount, "coinflip_bet", f"Coinflip bahsi: {val_amount}")

            # Calculate result with house edge (40% player win rate, 60% house win rate)
            if random.random() < 0.40:
                flip = choice_val
                win = True
            else:
                flip = "tura" if choice_val == "yazi" else "yazi"
                win = False

            embed = discord.Embed(
                title="🪙 Coinflip (Yazı-Tura)",
                timestamp=datetime.utcnow()
            )
            embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.display_avatar.url)

            if win:
                # Credit winnings (2x)
                winnings = val_amount * 2
                new_balance = await db.update_balance(user_id, winnings, "coinflip_win", f"Coinflip kazancı: {winnings}")
                
                embed.description = f"Para döndü ve **{flip.upper()}** geldi!\n\n🎉 **Tebrikler, Kazandınız!**"
                embed.color = discord.Color.green()
                from utils.security import format_money_string
                embed.add_field(name="Kazanç", value=f"💰 **+{format_money_string(val_amount)}**", inline=True)
                embed.add_field(name="Yeni Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)
            else:
                user_profile = await db.get_user(user_id)
                new_balance = user_profile["balance"]
                
                embed.description = f"Para döndü ve **{flip.upper()}** geldi!\n\n😔 **Maalesef, Kaybettiniz.**"
                embed.color = discord.Color.red()
                from utils.security import format_money_string
                embed.add_field(name="Kaybedilen", value=f"💰 **-{format_money_string(val_amount)}**", inline=True)
                embed.add_field(name="Kalan Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)

            msg = await interaction.followup.send(embed=embed, ephemeral=True)
            from utils.security import schedule_message_delete
            asyncio.create_task(schedule_message_delete(msg, 10.0))

            # Security: Log extremely high coinflip wins
            if win and val_amount >= 20000:
                await log_suspicious_activity(
                    self.bot, interaction.user, "High_Gamble_Win",
                    f"Coinflip oyunundan yüksek kazanç elde etti. Bahis: {val_amount}, Kazanç: {winnings}"
                )

        except InsufficientFunds:
            await interaction.followup.send("❌ Yetersiz bakiye! Bahis yapmak için yeterli paranız yok.", ephemeral=True)
        except Exception as e:
            logger.error(f"Coinflip error: {e}", exc_info=True)
            await interaction.followup.send("❌ Oyun sırasında bir veritabanı hatası oluştu.", ephemeral=True)


    # --- 2. BLACKJACK ---
    class BlackjackHand:
        def __init__(self):
            self.cards = []

        def add_card(self, card):
            self.cards.append(card)

        @property
        def value(self):
            val = 0
            aces = 0
            for card in self.cards:
                rank = card.split()[1]
                if rank in ["J", "Q", "K"]:
                    val += 10
                elif rank == "A":
                    aces += 1
                    val += 11
                else:
                    val += int(rank)
            
            # Adjust Aces
            while val > 21 and aces > 0:
                val -= 10
                aces -= 1
            return val

        def __str__(self):
            return ", ".join([f"`{c}`" for c in self.cards])

    class BlackjackView(discord.ui.View):
        def __init__(self, cog, interaction, user_id, bet):
            super().__init__(timeout=60.0)
            self.cog = cog
            self.interaction = interaction
            self.user_id = user_id
            self.bet = bet
            self.game_over = False

            # Deck creation
            suits = ["♠", "♥", "♦", "♣"]
            ranks = ["2", "3", "4", "5", "6", "7", "8", "9", "10", "J", "Q", "K", "A"]
            self.deck = [f"{s} {r}" for s in suits for r in ranks] * config.BLACKJACK_DECK_COUNT
            random.shuffle(self.deck)

            # Deal initial cards
            self.player_hand = GamesCog.BlackjackHand()
            self.dealer_hand = GamesCog.BlackjackHand()

            self.player_hand.add_card(self.deck.pop())
            self.dealer_hand.add_card(self.deck.pop())
            self.player_hand.add_card(self.deck.pop())
            self.dealer_hand.add_card(self.deck.pop())

        async def check_initial_bj(self):
            """Checks for immediate natural Blackjack wins."""
            if self.player_hand.value == 21 and self.dealer_hand.value == 21:
                await self.end_game(self.interaction, "push", "Her iki tarafta da Blackjack var! Berabere.")
                return True
            elif self.player_hand.value == 21:
                await self.end_game(self.interaction, "blackjack", "🎉 Blackjack! Kazandınız!")
                return True
            elif self.dealer_hand.value == 21:
                await self.end_game(self.interaction, "dealer_win", "Dealer Blackjack yaptı. Kaybettiniz.")
                return True
            return False

        def get_embed(self, hide_dealer=True):
            from utils.security import format_money_string
            embed = discord.Embed(
                title="🃏 Blackjack (21)",
                color=discord.Color.blue()
            )
            embed.set_author(name=self.interaction.user.display_name, icon_url=self.interaction.user.display_avatar.url)
            
            # Dealer hand display
            if hide_dealer:
                dealer_cards_str = f"`{self.dealer_hand.cards[0]}` , `🃏 Gizli`"
                dealer_value = "?"
            else:
                dealer_cards_str = str(self.dealer_hand)
                dealer_value = self.dealer_hand.value

            embed.add_field(
                name=f"Krupiye (Dealer) - Değer: {dealer_value}",
                value=dealer_cards_str,
                inline=False
            )

            # Player hand display
            embed.add_field(
                name=f"Siz (Oyuncu) - Değer: {self.player_hand.value}",
                value=str(self.player_hand),
                inline=False
            )
            
            embed.add_field(name="Aktif Bahis", value=f"💰 **{format_money_string(self.bet)}**", inline=True)
            return embed

        async def end_game(self, interaction, result, message):
            self.game_over = True
            self.stop()
            
            # Update buttons
            for child in self.children:
                child.disabled = True

            # Process database winnings/refunds
            payout = 0.0
            db_tx_desc = ""
            embed_color = discord.Color.blue()

            if result == "win":
                payout = self.bet * 2
                db_tx_desc = f"Blackjack Galibiyeti (Bahis: {self.bet})"
                embed_color = discord.Color.green()
            elif result == "blackjack":
                payout = self.bet * 2.5
                db_tx_desc = f"Blackjack Doğal (Bahis: {self.bet})"
                embed_color = discord.Color.green()
            elif result == "push":
                payout = self.bet
                db_tx_desc = f"Blackjack Beraberlik İadesi"
                embed_color = discord.Color.orange()
            else:
                # result is lose / dealer_win / bust
                embed_color = discord.Color.red()

            new_balance = 0.0
            if payout > 0:
                new_balance = await db.update_balance(self.user_id, payout, "blackjack_payout", db_tx_desc)
            else:
                user_profile = await db.get_user(self.user_id)
                new_balance = user_profile["balance"] if user_profile else 0.0

            from utils.security import format_money_string, schedule_message_delete
            embed = self.get_embed(hide_dealer=False)
            embed.color = embed_color
            embed.description = f"**Oyun Sonucu:** {message}\nGüncel Bakiyeniz: 💰 **{format_money_string(new_balance)}**"

            if interaction.response.is_done():
                await interaction.followup.edit_message(message_id=interaction.message.id, embed=embed, view=self)
            else:
                await interaction.response.edit_message(embed=embed, view=self)
            
            if hasattr(interaction, "message") and interaction.message:
                asyncio.create_task(schedule_message_delete(interaction.message, 10.0))

        async def stand_logic(self, interaction: discord.Interaction):
            # Dealer plays: hit until value >= 17
            while self.dealer_hand.value < 17:
                self.dealer_hand.add_card(self.deck.pop())

            # Evaluate winner
            p_val = self.player_hand.value
            d_val = self.dealer_hand.value

            if d_val > 21:
                await self.end_game(interaction, "win", "🎉 Krupiye battı! Kazandınız!")
            elif p_val > d_val:
                await self.end_game(interaction, "win", "🎉 Krupiyeden daha yüksek skora sahipsiniz! Kazandınız!")
            elif p_val < d_val:
                await self.end_game(interaction, "lose", f"Krupiye ({d_val}) sizden ({p_val}) daha yüksek skora sahip. Kaybettiniz.")
            else:
                await self.end_game(interaction, "push", f"Skorlar eşit ({p_val}). İade.")

        @discord.ui.button(label="Kart Çek (Hit)", style=discord.ButtonStyle.primary, emoji="➕", custom_id="bj_hit")
        async def hit(self, interaction: discord.Interaction, button: discord.ui.Button):
            if interaction.user.id != self.user_id:
                await interaction.response.send_message("❌ Bu oyunu siz oynamıyorsunuz!", ephemeral=True)
                return

            self.player_hand.add_card(self.deck.pop())

            if self.player_hand.value > 21:
                # Player Busts
                await self.end_game(interaction, "lose", "💥 21'i aştınız! Kaybettiniz (Bust).")
            elif self.player_hand.value == 21:
                # Auto Stand on 21
                await self.stand_logic(interaction)
            else:
                # Disable double down after drawing a card
                for child in self.children:
                    if child.custom_id == "bj_double":
                        child.disabled = True
                
                # Update embed and keep playing
                await interaction.response.edit_message(embed=self.get_embed(), view=self)

        @discord.ui.button(label="Pas (Stand)", style=discord.ButtonStyle.secondary, emoji="🛑", custom_id="bj_stand")
        async def stand(self, interaction: discord.Interaction, button: discord.ui.Button):
            if interaction.user.id != self.user_id:
                await interaction.response.send_message("❌ Bu oyunu siz oynamıyorsunuz!", ephemeral=True)
                return

            await self.stand_logic(interaction)

        @discord.ui.button(label="İkiye Katla (Double)", style=discord.ButtonStyle.success, emoji="💵", custom_id="bj_double")
        async def double(self, interaction: discord.Interaction, button: discord.ui.Button):
            if interaction.user.id != self.user_id:
                await interaction.response.send_message("❌ Bu oyunu siz oynamıyorsunuz!", ephemeral=True)
                return

            # Check if player has exactly 2 cards
            if len(self.player_hand.cards) != 2:
                await interaction.response.send_message("❌ İkiye katlama sadece ilk turda yapılabilir!", ephemeral=True)
                return

            try:
                # Deduct another bet amount for doubling down
                await db.update_balance(self.user_id, -self.bet, "blackjack_double_bet", f"Blackjack Double: {self.bet}")
                self.bet *= 2

                # Player gets exactly one card
                self.player_hand.add_card(self.deck.pop())

                if self.player_hand.value > 21:
                    await self.end_game(interaction, "lose", "💥 İkiye katladıktan sonra 21'i aştınız! Kaybettiniz.")
                else:
                    await self.stand_logic(interaction)

            except InsufficientFunds:
                await interaction.response.send_message("❌ İkiye katlamak için yeterli bakiyeniz bulunmuyor!", ephemeral=True)

        async def on_timeout(self):
            if not self.game_over:
                # Deduct bet and expire
                user_profile = await db.get_user(self.user_id)
                new_balance = user_profile["balance"] if user_profile else 0.0
                
                from utils.security import format_money_string, schedule_message_delete
                embed = self.get_embed(hide_dealer=False)
                embed.color = discord.Color.red()
                embed.description = f"⏰ **Oyun Süresi Doldu!** Oyunu terk ettiğiniz için kaybettiniz.\nKalan Bakiye: 💰 **{format_money_string(new_balance)}**"
                
                # Disable buttons
                for child in self.children:
                    child.disabled = True
                
                try:
                    await self.interaction.followup.edit_message(message_id=self.interaction.message.id, embed=embed, view=self)
                except Exception:
                    try:
                        await self.interaction.edit_original_response(embed=embed, view=self)
                    except Exception:
                        pass
                
                if hasattr(self.interaction, "message") and self.interaction.message:
                    asyncio.create_task(schedule_message_delete(self.interaction.message, 10.0))



    async def _play_blackjack(self, interaction: discord.Interaction, miktar: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            msg = "❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 1b)."
            if interaction.response.is_done():
                await interaction.followup.send(msg, ephemeral=True)
            else:
                await interaction.response.send_message(msg, ephemeral=True)
            return

        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True)
            
        user_id = interaction.user.id

        try:
            # Deduct bet first
            await db.update_balance(user_id, -val_amount, "blackjack_bet", f"Blackjack Bahsi: {val_amount}")

            view = self.BlackjackView(self, interaction, user_id, val_amount)
            
            # Check for natural BJ
            if await view.check_initial_bj():
                return
            
            # Send game view
            await interaction.followup.send(embed=view.get_embed(), view=view, ephemeral=True)

        except InsufficientFunds:
            await interaction.followup.send("❌ Yetersiz bakiye! Bahis yapmak için yeterli paranız yok.", ephemeral=True)
        except Exception as e:
            logger.error(f"Blackjack error: {e}", exc_info=True)
            await interaction.followup.send("❌ Oyun sırasında bir hata oluştu.", ephemeral=True)


    # --- 3. ROULETTE (RULET) ---


    async def _play_roulette(self, interaction: discord.Interaction, miktar: str, tahmin: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            msg = "❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 1b)."
            if interaction.response.is_done():
                await interaction.followup.send(msg, ephemeral=True)
            else:
                await interaction.response.send_message(msg, ephemeral=True)
            return

        tahmin_clean = tahmin.strip().lower()
        is_number_bet = False
        bet_number = -1

        # Input verification
        if tahmin_clean in ["kirmizi", "red"]:
            bet_type = "color"
            bet_value = "red"
        elif tahmin_clean in ["siyah", "black"]:
            bet_type = "color"
            bet_value = "black"
        elif tahmin_clean in ["yesil", "green"]:
            bet_type = "color"
            bet_value = "green"
        else:
            try:
                bet_number = int(tahmin_clean)
                if not (0 <= bet_number <= 36):
                    raise ValueError()
                bet_type = "number"
                is_number_bet = True
            except ValueError:
                msg = "❌ Hata: Lütfen geçerli bir renk ('kirmizi', 'siyah', 'yesil') veya sayı (0-36) girin."
                if interaction.response.is_done():
                    await interaction.followup.send(msg, ephemeral=True)
                else:
                    await interaction.response.send_message(msg, ephemeral=True)
                return

        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True)
            
        user_id = interaction.user.id

        try:
            # Deduct bet
            await db.update_balance(user_id, -val_amount, "roulette_bet", f"Rulet bahsi: {val_amount}")

            # Red/Black number groups
            red_numbers = [1, 3, 5, 7, 9, 12, 14, 16, 18, 19, 21, 23, 25, 27, 30, 32, 34, 36]
            black_numbers = [2, 4, 6, 8, 10, 11, 13, 15, 17, 20, 22, 24, 26, 28, 29, 31, 33, 35]

            # Spin with 40% player win rate for color bets
            if not is_number_bet:
                if random.random() < 0.40:
                    # Player wins (40%)
                    spin_color = bet_value
                    if bet_value == "red":
                        spin_num = random.choice(red_numbers)
                    elif bet_value == "black":
                        spin_num = random.choice(black_numbers)
                    else:
                        spin_num = 0
                else:
                    # House wins (60%)
                    if bet_value == "red":
                        spin_color = "black" if random.random() < 0.90 else "green"
                        spin_num = random.choice(black_numbers) if spin_color == "black" else 0
                    elif bet_value == "black":
                        spin_color = "red" if random.random() < 0.90 else "green"
                        spin_num = random.choice(red_numbers) if spin_color == "red" else 0
                    else:
                        spin_color = "red"
                        spin_num = random.choice(red_numbers)
            else:
                # Number bet (0-36)
                spin_num = random.randint(0, 36)
                if spin_num == 0:
                    spin_color = "green"
                elif spin_num in red_numbers:
                    spin_color = "red"
                else:
                    spin_color = "black"

            # Check win condition
            win = False
            payout_mult = 0.0
            
            if is_number_bet:
                if spin_num == bet_number:
                    win = True
                    payout_mult = 36.0
            else:
                if spin_color == bet_value:
                    win = True
                    payout_mult = 15.0 if bet_value == "green" else 2.0

            embed = discord.Embed(
                title="🎡 Rulet Masası",
                timestamp=datetime.utcnow()
            )
            embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.display_avatar.url)

            color_emoji = "🟢" if spin_color == "green" else "🔴" if spin_color == "red" else "⚫"
            result_desc = f"Rulet çarkı döndü ve **{color_emoji} {spin_num} ({spin_color.upper()})** geldi!\n\n"

            if win:
                winnings = val_amount * payout_mult
                new_balance = await db.update_balance(user_id, winnings, "roulette_win", f"Rulet kazancı: {winnings}")
                
                from utils.security import format_money_string
                embed.color = discord.Color.green()
                embed.description = result_desc + f"🎉 **Tebrikler, Kazandınız!** (Tahmininiz: `{tahmin_clean}`)"
                embed.add_field(name="Kazanç", value=f"💰 **+{format_money_string(winnings - val_amount)}** (Çarpan: {payout_mult}x)", inline=True)
                embed.add_field(name="Yeni Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)
                
                # Check for high winnings alert
                if winnings >= 25000:
                    await log_suspicious_activity(
                        self.bot, interaction.user, "High_Gamble_Win",
                        f"Rulet oyunundan yüksek kazanç elde etti. Bahis: {val_amount}, Kazanç: {winnings}"
                    )
            else:
                user_profile = await db.get_user(user_id)
                new_balance = user_profile["balance"] if user_profile else 0.0
                
                from utils.security import format_money_string
                embed.color = discord.Color.red()
                embed.description = result_desc + f"😔 **Maalesef, Kaybettiniz.** (Tahmininiz: `{tahmin_clean}`)"
                embed.add_field(name="Kaybedilen", value=f"💰 **-{format_money_string(val_amount)}**", inline=True)
                embed.add_field(name="Kalan Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)

            msg = await interaction.followup.send(embed=embed, ephemeral=True)
            from utils.security import schedule_message_delete
            asyncio.create_task(schedule_message_delete(msg, 10.0))

        except InsufficientFunds:
            await interaction.followup.send("❌ Yetersiz bakiye! Bahis yapmak için yeterli paranız yok.", ephemeral=True)
        except Exception as e:
            logger.error(f"Roulette error: {e}", exc_info=True)
            await interaction.followup.send("❌ Oyun sırasında bir hata oluştu.", ephemeral=True)


    # --- 4. SLOT MACHINE ---


    async def _play_slots(self, interaction: discord.Interaction, miktar: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            msg = "❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 1b)."
            if interaction.response.is_done():
                await interaction.followup.send(msg, ephemeral=True)
            else:
                await interaction.response.send_message(msg, ephemeral=True)
            return

        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True)
            
        user_id = interaction.user.id

        try:
            # Deduct bet
            await db.update_balance(user_id, -val_amount, "slots_bet", f"Slot bahsi: {val_amount}")

            # Define emojis
            emojis = config.SLOTS_EMOJIS

            # Create spinning animation embed
            embed = discord.Embed(
                title="🎰 Slot Makinesi",
                color=discord.Color.purple(),
                description="🎰 Makaralar dönüyor...\n\n`[ ⏳ | ⏳ | ⏳ ]`"
            )
            embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.display_avatar.url)
            msg = await interaction.followup.send(embed=embed, ephemeral=True)

            # Spin animations (message edits)
            for i in range(2):
                await asyncio.sleep(1.0)
                reel_anim = f"`[ {random.choice(emojis)} | {random.choice(emojis)} | {random.choice(emojis)} ]`"
                embed.description = f"🎰 Makaralar dönüyor...\n\n{reel_anim}"
                await msg.edit(embed=embed)

            # Final roll with 40% player win / 60% house win
            if random.random() < 0.40:
                # Player Wins (40%)
                if random.random() < 0.15:
                    # 3 matching symbols (Jackpot)
                    sym = random.choice(emojis)
                    r1, r2, r3 = sym, sym, sym
                else:
                    # 2 matching symbols
                    sym = random.choice(emojis)
                    diff_pool = [e for e in emojis if e != sym]
                    other = random.choice(diff_pool)
                    r1, r2, r3 = random.choice([(sym, sym, other), (other, sym, sym), (sym, other, sym)])
            else:
                # House Wins (60% - 3 completely different symbols)
                r1, r2, r3 = random.sample(emojis, 3)

            reel_final = f"`[ {r1} | {r2} | {r3} ]`"
            await asyncio.sleep(1.0)

            # Calculate payout
            win = False
            payout = 0.0
            details = ""

            if r1 == r2 == r3:
                win = True
                payout = val_amount * config.SLOTS_PAYOUTS[r1]
                details = f"3x Eşleşme ({r1})!"
            elif r1 == r2 or r2 == r3 or r1 == r3:
                win = True
                match_symbol = r2 if (r1 == r2 or r2 == r3) else r1
                payout = val_amount * (config.SLOTS_PAYOUTS[match_symbol] * 0.40)
                details = f"2x Eşleşme ({match_symbol})!"

            embed.description = f"🎰 Makaralar durdu!\n\n{reel_final}\n\n"

            from utils.security import format_money_string, schedule_message_delete
            if win and payout > 0:
                new_balance = await db.update_balance(user_id, payout, "slots_win", f"Slot kazancı: {payout} - {details}")
                embed.color = discord.Color.green()
                embed.description += f"🎉 **Tebrikler, Kazandınız!**\n*{details}*"
                embed.add_field(name="Kazanç", value=f"💰 **+{format_money_string(payout - val_amount)}** (Çarpan: {payout/val_amount:.1f}x)", inline=True)
                embed.add_field(name="Yeni Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)
            else:
                user_profile = await db.get_user(user_id)
                new_balance = user_profile["balance"] if user_profile else 0.0
                embed.color = discord.Color.red()
                embed.description += f"😔 **Maalesef, Kaybettiniz.**"
                embed.add_field(name="Kaybedilen", value=f"💰 **-{format_money_string(val_amount)}**", inline=True)
                embed.add_field(name="Kalan Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)

            await msg.edit(embed=embed)
            asyncio.create_task(schedule_message_delete(msg, 10.0))

        except InsufficientFunds:
            await interaction.followup.send("❌ Yetersiz bakiye! Bahis yapmak için yeterli paranız yok.", ephemeral=True)
        except Exception as e:
            logger.error(f"Slots error: {e}", exc_info=True)
            await interaction.followup.send("❌ Oyun sırasında bir hata oluştu.", ephemeral=True)


    # --- 5. CRASH / AVIATOR ---
    class CrashView(discord.ui.View):
        def __init__(self, user_id):
            super().__init__(timeout=45.0)
            self.user_id = user_id
            self.cashed_out = False

        @discord.ui.button(label="Cashout (Çek)", style=discord.ButtonStyle.success, emoji="💰", custom_id="crash_cashout")
        async def cashout_callback(self, interaction: discord.Interaction, button: discord.ui.Button):
            if interaction.user.id != self.user_id:
                await interaction.response.send_message("❌ Bu oyunu siz oynamıyorsunuz!", ephemeral=True)
                return

            if self.cashed_out:
                await interaction.response.send_message("❌ Zaten paranızı çektiniz!", ephemeral=True)
                return

            await interaction.response.defer()
            self.cashed_out = True
            self.stop()



    async def _play_crash(self, interaction: discord.Interaction, miktar: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            msg = "❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 1b)."
            if interaction.response.is_done():
                await interaction.followup.send(msg, ephemeral=True)
            else:
                await interaction.response.send_message(msg, ephemeral=True)
            return

        if not interaction.response.is_done():
            await interaction.response.defer(ephemeral=True)
            
        user_id = interaction.user.id

        try:
            # Deduct bet
            await db.update_balance(user_id, -val_amount, "crash_bet", f"Crash bahsi: {val_amount}")

            # Calculate actual crash point with 60% house edge
            rnd = random.random()
            if rnd < 0.25:
                # 25% instant drop at 1.00x - 1.15x
                crash_point = round(random.uniform(1.00, 1.15), 2)
            elif rnd < 0.60:
                # 35% early drop at 1.16x - 1.45x
                crash_point = round(random.uniform(1.16, 1.45), 2)
            else:
                # 40% high flights
                crash_point = max(1.46, round(0.65 / (1.0 - random.uniform(0.01, 0.88)), 2))

            view = self.CrashView(user_id)
            
            from utils.security import format_money_string
            embed = discord.Embed(
                title="🚀 Crash / Aviator",
                color=discord.Color.gold(),
                description=f"🚀 Uçak kalkıyor... Çarpan yükseliyor!\n\n📈 **Mevcut Çarpan: 1.00x**\n💵 Olası Kazanç: **{format_money_string(val_amount)}**"
            )
            embed.set_author(name=interaction.user.display_name, icon_url=interaction.user.display_avatar.url)
            msg = await interaction.followup.send(embed=embed, view=view, ephemeral=True)

            # Game loop
            current_multiplier = 1.00
            step = 0.05

            while current_multiplier < crash_point:
                await asyncio.sleep(1.2)
                
                # Check if user clicked cashout
                if view.cashed_out:
                    break

                # Increment multiplier
                # As multiplier grows, the steps grow faster (exponential feeling)
                if current_multiplier >= 10.0:
                    step = 2.0
                elif current_multiplier >= 5.0:
                    step = 0.5
                elif current_multiplier >= 2.0:
                    step = 0.2
                else:
                    step = 0.08
                
                current_multiplier = round(current_multiplier + step, 2)
                
                if current_multiplier >= crash_point:
                    current_multiplier = crash_point
                    break
                
                # Edit message with current multiplier
                potential_winnings = val_amount * current_multiplier
                embed.description = f"🚀 Uçak yükseliyor...\n\n📈 **Mevcut Çarpan: {current_multiplier:.2f}x**\n💵 Olası Kazanç: **{format_money_string(potential_winnings)}**"
                try:
                    await msg.edit(embed=embed)
                except discord.NotFound:
                    # Message deleted, force cashout or stop
                    break

            # Handle end of game
            from utils.security import schedule_message_delete
            if view.cashed_out and current_multiplier < crash_point:
                # User successfully cashed out
                winnings = val_amount * current_multiplier
                new_balance = await db.update_balance(user_id, winnings, "crash_payout", f"Crash kazancı: {winnings} at {current_multiplier}x")
                
                embed.color = discord.Color.green()
                embed.description = f"✅ **Parayı Çektiniz!**\n\n📈 Uçak **{current_multiplier:.2f}x** çarpanındayken çektiniz.\n💥 Uçak daha sonra **{crash_point:.2f}x** noktasında patladı."
                embed.clear_fields()
                embed.add_field(name="Kazanç", value=f"💰 **+{format_money_string(winnings - val_amount)}**", inline=True)
                embed.add_field(name="Yeni Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)
                
                # Disable buttons
                for child in view.children:
                    child.disabled = True
                await msg.edit(embed=embed, view=view)
                asyncio.create_task(schedule_message_delete(msg, 10.0))

                if winnings >= 30000:
                    await log_suspicious_activity(
                        self.bot, interaction.user, "High_Gamble_Win",
                        f"Crash oyunundan yüksek çarpan kazancı elde etti. Bahis: {val_amount}, Çarpan: {current_multiplier}x, Kazanç: {winnings}"
                    )
            else:
                # User crashed or timed out
                user_profile = await db.get_user(user_id)
                new_balance = user_profile["balance"] if user_profile else 0.0

                embed.color = discord.Color.red()
                embed.description = f"💥 **Uçak Patladı!**\n\n📈 Uçak **{crash_point:.2f}x** çarpanında infilak etti. Parayı çekemediniz!"
                embed.clear_fields()
                embed.add_field(name="Kaybedilen Miktar", value=f"💰 **-{format_money_string(val_amount)}**", inline=True)
                embed.add_field(name="Kalan Bakiye", value=f"💰 **{format_money_string(new_balance)}**", inline=True)
                
                # Disable buttons
                for child in view.children:
                    child.disabled = True
                await msg.edit(embed=embed, view=view)
                asyncio.create_task(schedule_message_delete(msg, 10.0))

        except InsufficientFunds:
            await interaction.followup.send("❌ Yetersiz bakiye! Bahis yapmak için yeterli paranız yok.", ephemeral=True)
        except Exception as e:
            logger.error(f"Crash error: {e}", exc_info=True)
            await interaction.followup.send("❌ Oyun sırasında bir hata oldu.", ephemeral=True)

    async def _play_crate(self, interaction: discord.Interaction, crate_tier: str):
        if not await check_security_compliance(interaction):
            return

        user_id = interaction.user.id
        
        CRATE_CONFIGS = {
            "kozmik": {
                "name": "🔥 Kozmik Kasa",
                "cost": 50000000.0,
                "color": discord.Color.red(),
                "items": [
                    {"emoji": "🪐", "name": "Meteor Taşı", "chance": 0.55, "payout_mult": 0.15},
                    {"emoji": "💫", "name": "Yıldız Tozu", "chance": 0.30, "payout_mult": 0.50},
                    {"emoji": "☄️", "name": "Kuyruklu Yıldız", "chance": 0.10, "payout_mult": 1.30},
                    {"emoji": "🌌", "name": "Nebula Çekirdeği", "chance": 0.04, "payout_mult": 2.50},
                    {"emoji": "⚛️", "name": "Kozmik Singularite", "chance": 0.01, "payout_mult": 8.00}
                ]
            },
            "poseidon": {
                "name": "🔱 Poseidon Kasası",
                "cost": 100000000.0,
                "color": discord.Color.blue(),
                "items": [
                    {"emoji": "🐚", "name": "Deniz Kabuğu", "chance": 0.55, "payout_mult": 0.15},
                    {"emoji": "🌊", "name": "Atlantis Altını", "chance": 0.30, "payout_mult": 0.50},
                    {"emoji": "🦈", "name": "Megalodon Dişi", "chance": 0.10, "payout_mult": 1.30},
                    {"emoji": "🔱", "name": "Poseidon Mızrağı", "chance": 0.04, "payout_mult": 2.50},
                    {"emoji": "💙", "name": "Okyanusun Kalbi", "chance": 0.01, "payout_mult": 8.00}
                ]
            },
            "hades": {
                "name": "💀 Hades'in Sandığı",
                "cost": 200000000.0,
                "color": discord.Color.dark_purple(),
                "items": [
                    {"emoji": "🪙", "name": "Ölülerin Akçesi", "chance": 0.55, "payout_mult": 0.15},
                    {"emoji": "🛡️", "name": "Hades Shield", "chance": 0.30, "payout_mult": 0.50},
                    {"emoji": "🐕", "name": "Cerberus Tasması", "chance": 0.10, "payout_mult": 1.40},
                    {"emoji": "☠️", "name": "Karanlık Ruh Gemisi", "chance": 0.04, "payout_mult": 2.80},
                    {"emoji": "👑", "name": "Yeraltı Dünyası Tacı", "chance": 0.01, "payout_mult": 8.00}
                ]
            },
            "zeus": {
                "name": "⚡ Zeus'un Yıldırımı",
                "cost": 300000000.0,
                "color": discord.Color.gold(),
                "items": [
                    {"emoji": "🏛️", "name": "Antik Mermer", "chance": 0.55, "payout_mult": 0.15},
                    {"emoji": "🍷", "name": "Tanrıların Şarabı (Nectar)", "chance": 0.30, "payout_mult": 0.50},
                    {"emoji": "🦅", "name": "Zeus'un Kartalı", "chance": 0.10, "payout_mult": 1.50},
                    {"emoji": "🔥", "name": "Olimpos Meşalesi", "chance": 0.04, "payout_mult": 3.00},
                    {"emoji": "⚡", "name": "Yıldırım Asası", "chance": 0.01, "payout_mult": 8.00}
                ]
            },
            "blackhole": {
                "name": "🌌 Kara Delik Kasası",
                "cost": 500000000.0,
                "color": discord.Color.from_rgb(10, 10, 20),
                "items": [
                    {"emoji": "🌑", "name": "Karanlık Madde", "chance": 0.55, "payout_mult": 0.15},
                    {"emoji": "✨", "name": "Yıldız Tozu Rezonansı", "chance": 0.30, "payout_mult": 0.50},
                    {"emoji": "🌀", "name": "Uzay-Zaman Bükücü", "chance": 0.10, "payout_mult": 1.50},
                    {"emoji": "🧬", "name": "Singularite Çekirdeği", "chance": 0.04, "payout_mult": 3.00},
                    {"emoji": "🌌", "name": "Sonsuzluk Boyutu", "chance": 0.01, "payout_mult": 8.00}
                ]
            }
        }

        config = CRATE_CONFIGS[crate_tier]
        cost = config["cost"]

        # Respond to interaction immediately to prevent timeout
        await interaction.response.send_message("⏳ Ödeme kontrol ediliyor...", ephemeral=True)

        try:
            # Deduct cost
            new_balance = await db.update_balance(user_id, -cost, "crate_buy", f"{config['name']} açıldı.")
            
            # Select reward item
            import random
            items = config["items"]
            weights = [i["chance"] for i in items]
            selected_item = random.choices(items, weights=weights)[0]
            
            winnings = cost * selected_item["payout_mult"]
            
            # Add winnings
            if winnings > 0:
                new_balance = await db.update_balance(user_id, winnings, "crate_win", f"{config['name']} kazancı.")
            
            from utils.logger import log_transaction
            await log_transaction(
                bot=interaction.client,
                user=interaction.user,
                tx_type="crate",
                amount=winnings - cost,
                status="completed",
                details=f"Kasa: {config['name']}, Çıkan Eşya: {selected_item['name']}, Kazanç: {winnings:,.2f}"
            )

            # Check for suspicious log if user got a jackpot
            if winnings >= 200000000.0:
                from utils.logger import log_suspicious_activity
                await log_suspicious_activity(
                    interaction.client,
                    interaction.user,
                    "High_Crate_Winnings",
                    f"Kasa: {config['name']} - Çıkan Eşya: {selected_item['name']} - Kazandı: {winnings:,.2f}"
                )

            # Send private roll message
            emojis_pool = [i["emoji"] for i in items]
            from utils.security import format_money_string
            
            # Create an 8-item pool where index 5 is the winner
            spinner_emojis = [random.choice(emojis_pool) for _ in range(8)]
            spinner_emojis[5] = selected_item["emoji"]
            
            def get_frame_text(t):
                window = spinner_emojis[t:t+5]
                return (
                    f"🎉 **{interaction.user.mention}** şansını deniyor!\n\n"
                    f"🎰 **KASA DÖNÜYOR (CS:GO Stili):**\n"
                    f"```\n"
                    f"|  {window[0]}  |  {window[1]}  |  👉 {window[2]} 👈  |  {window[3]}  |  {window[4]}  |\n"
                    f"```"
                )

            embed = discord.Embed(
                title=f"📦 {config['name']} Açılıyor...",
                description=get_frame_text(0),
                color=config["color"]
            )
            msg = await interaction.followup.send(embed=embed, ephemeral=True)
            
            import asyncio
            delays = [0.8, 1.0, 1.2]
            
            for t in range(1, 4):
                await asyncio.sleep(delays[t-1])
                embed.description = get_frame_text(t)
                await msg.edit(embed=embed)

            # Final delay before revealing the reward screen
            await asyncio.sleep(1.2)
            
            final_emoji = selected_item["emoji"]
            embed.title = f"✨ {config['name']} Açıldı!"
            embed.description = (
                f"🎉 **{interaction.user.mention}** kasayı başarıyla açtı!\n\n"
                f"🎰 **Kasa Çıktısı:**\n"
                f"```\n"
                f"|  {spinner_emojis[3]}  |  {spinner_emojis[4]}  |  ⭐ {final_emoji} ⭐  |  {spinner_emojis[6]}  |  {spinner_emojis[7]}  |\n"
                f"```\n"
                f"🌟 **Çıkan Eşya:** {final_emoji} **{selected_item['name']}**\n"
                f"💵 Bahis Çarpanı: `{selected_item['payout_mult']}x`\n\n"
                f"💰 **Kazanç:** **{format_money_string(winnings)}**\n"
                f"💳 Yeni Bakiye: **{format_money_string(new_balance)}**"
            )
            
            if selected_item["payout_mult"] > 1.0:
                embed.color = discord.Color.green()
            elif selected_item["payout_mult"] == 1.0:
                embed.color = discord.Color.orange()
            else:
                embed.color = discord.Color.red()

            await msg.edit(embed=embed)
            from utils.security import schedule_message_delete
            asyncio.create_task(schedule_message_delete(msg, 10.0))

        except InsufficientFunds:
            from utils.security import format_money_string
            await interaction.edit_original_response(
                content=f"❌ **Yetersiz Bakiye!**\nBu kasayı açmak için cüzdanınızda en az **{format_money_string(cost)}** bulunmalıdır."
            )
        except Exception as e:
            logger.error(f"Crate error: {e}", exc_info=True)
            try:
                await interaction.edit_original_response(content="❌ Kasa açılırken beklenmedik bir hata oluştu.")
            except Exception:
                pass

    async def _play_mines(self, interaction: discord.Interaction, miktar: str, mayin_sayisi: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            await interaction.response.send_message("❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 50m).", ephemeral=True)
            return

        try:
            mine_count = int(mayin_sayisi)
            if not (1 <= mine_count <= 7):
                await interaction.response.send_message("❌ Hata: Mayın sayısı 1 ile 7 arasında olmalıdır.", ephemeral=True)
                return
        except ValueError:
            mine_count = 3

        user_id = interaction.user.id

        try:
            # Deduct bet amount upfront
            await db.update_balance(user_id, -val_amount, "mines_bet", f"Mayın Tarlası bahsi ({mine_count} mayın).")
        except InsufficientFunds:
            from utils.security import format_money_string
            await interaction.response.send_message(
                f"❌ **Yetersiz Bakiye!** Bahis yapmak için en az **{format_money_string(val_amount)}** bakiyeniz olmalıdır.",
                ephemeral=True
            )
            return
        except Exception as e:
            logger.error(f"Error starting mines: {e}", exc_info=True)
            await interaction.response.send_message("❌ Oyun başlatılırken bir hata oluştu.", ephemeral=True)
            return

        # Start game
        view = MinesView(self.bot, user_id, val_amount, mine_count)
        from utils.security import format_money_string

        embed = discord.Embed(
            title="💣 Mayın Tarlası (Mines)",
            description=(
                f"🎮 {interaction.user.mention} Mayın Tarlası oyununu başlattı!\n\n"
                f"💵 **Bahis:** **{format_money_string(val_amount)}**\n"
                f"💣 **Gizli Mayın Sayısı:** `{mine_count}`\n"
                f"💎 **Toplam Elmas:** `{16 - mine_count}`\n\n"
                f"👇 *Aşağıdaki 16 kareden birine tıklayarak elmasları aramaya başlayın!*"
            ),
            color=discord.Color.dark_gray()
        )
        await interaction.response.send_message(embed=embed, view=view)
        view.msg = await interaction.original_response()

    @app_commands.command(name="tower", description="🏰 Şanslı Kule (Dragon's Tower) tırmanış oyununu başlatır.")
    @app_commands.describe(miktar="Bahis miktarı (Örn: 100k, 5m, 50m)")
    async def tower_command(self, interaction: discord.Interaction, miktar: str):
        """Slash command for Tower game."""
        await self._play_tower(interaction, miktar)

    async def _play_tower(self, interaction: discord.Interaction, miktar: str):
        if not await check_security_compliance(interaction):
            return

        from utils.security import parse_money_string
        val_amount = parse_money_string(miktar)
        if val_amount <= 0:
            await interaction.response.send_message("❌ Hata: Bahis miktarı pozitif bir sayı olmalıdır (Örn: 100k, 5m, 50m).", ephemeral=True)
            return

        user_id = interaction.user.id

        try:
            # Deduct bet amount upfront
            await db.update_balance(user_id, -val_amount, "tower_bet", f"Şanslı Kule oyunu bahsi.")
        except InsufficientFunds:
            from utils.security import format_money_string
            await interaction.response.send_message(
                f"❌ **Yetersiz Bakiye!** Bahis yapmak için en az **{format_money_string(val_amount)}** bakiyeniz olmalıdır.",
                ephemeral=True
            )
            return
        except Exception as e:
            logger.error(f"Error starting tower: {e}", exc_info=True)
            await interaction.response.send_message("❌ Oyun başlatılırken bir hata oluştu.", ephemeral=True)
            return

        # Start game
        view = TowerView(self.bot, user_id, val_amount)
        embed = view.render_embed(status="playing")
        await interaction.response.send_message(embed=embed, view=view)
        view.msg = await interaction.original_response()


# --- GAMBLE LOBBY VIEW & MODALS FOR BUTTON PLAY ---

class CoinflipModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="🪙 Coinflip (Yazı-Tura)")
        self.cog = cog
        
        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        self.choice = discord.ui.TextInput(
            label="Seçiminiz (yazi veya tura)",
            placeholder="yazi veya tura",
            min_length=4,
            max_length=5,
            required=True
        )
        
        self.add_item(self.amount)
        self.add_item(self.choice)

    async def on_submit(self, interaction: discord.Interaction):
        choice_str = self.choice.value.strip().lower()
        if choice_str in ["yazi", "yazı"]:
            choice_val = "yazi"
        elif choice_str in ["tura"]:
            choice_val = "tura"
        else:
            await interaction.response.send_message("❌ Hata: Seçiminiz sadece 'yazi' veya 'tura' olmalıdır.", ephemeral=True)
            return
        await self.cog._play_coinflip(interaction, self.amount.value, choice_val)


class SlotsModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="🎰 Slot Makinesi")
        self.cog = cog
        
        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        
        self.add_item(self.amount)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_slots(interaction, self.amount.value)


class BlackjackModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="🃏 Blackjack (21)")
        self.cog = cog
        
        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        
        self.add_item(self.amount)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_blackjack(interaction, self.amount.value)


class CrashModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="📈 Crash / Aviator")
        self.cog = cog
        
        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        
        self.add_item(self.amount)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_crash(interaction, self.amount.value)


class RouletteModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="🎡 Rulet Masası")
        self.cog = cog
        
        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        self.guess = discord.ui.TextInput(
            label="Tahmininiz (Renk veya Sayı)",
            placeholder="Renk (kirmizi, siyah, yesil) veya Sayı (0-36)",
            min_length=1,
            max_length=15,
            required=True
        )
        
        self.add_item(self.amount)
        self.add_item(self.guess)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_roulette(interaction, self.amount.value, self.guess.value)


class MinesModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="💣 Mayın Tarlası (Mines)")
        self.cog = cog

        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, 50m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        self.mine_count = discord.ui.TextInput(
            label="Mayın Sayısı (1 - 7)",
            placeholder="1 ile 7 arasında (Varsayılan: 3)",
            default="3",
            min_length=1,
            max_length=1,
            required=False
        )
        self.add_item(self.amount)
        self.add_item(self.mine_count)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_mines(interaction, self.amount.value, self.mine_count.value or "3")


class MinesTileButton(discord.ui.Button):
    def __init__(self, index: int, row: int):
        super().__init__(style=discord.ButtonStyle.secondary, label="❓", row=row)
        self.index = index

    async def callback(self, interaction: discord.Interaction):
        await self.view.handle_tile_click(interaction, self)


class MinesCashoutButton(discord.ui.Button):
    def __init__(self):
        super().__init__(style=discord.ButtonStyle.success, label="💰 Parayı Çek (Başlangıç)", row=4, disabled=True)

    async def callback(self, interaction: discord.Interaction):
        await self.view.handle_cashout(interaction)


class MinesView(discord.ui.View):
    def __init__(self, bot, user_id: int, bet_amount: float, mine_count: int):
        super().__init__(timeout=90.0)
        self.bot = bot
        self.user_id = user_id
        self.bet_amount = bet_amount
        self.mine_count = mine_count
        self.total_tiles = 16
        self.diamonds_total = self.total_tiles - mine_count
        
        # Place random mines
        import random
        self.mines = set(random.sample(range(self.total_tiles), self.mine_count))
        self.uncovered = set()
        self.current_mult = 1.0
        self.game_over = False
        self.msg = None

        # Build 4x4 grid of tiles
        self.tiles = {}
        for idx in range(self.total_tiles):
            row = idx // 4
            btn = MinesTileButton(idx, row)
            self.tiles[idx] = btn
            self.add_item(btn)

        # Cashout button
        self.cashout_btn = MinesCashoutButton()
        self.add_item(self.cashout_btn)

    def calculate_multiplier(self, count: int) -> float:
        # Dynamic Scaling Multipliers with balanced house edge
        prob = 1.0
        for j in range(count):
            prob *= (self.diamonds_total - j) / (self.total_tiles - j)
        
        mult = round(0.91 / prob, 2)
        
        # Mine count dynamic starting minimums
        floor_map = {
            1: 1.04,
            2: 1.09,
            3: 1.15,
            4: 1.22,
            5: 1.32,
            6: 1.45,
            7: 1.60
        }
        min_start = floor_map.get(self.mine_count, 1.12)
        return max(min_start, mult)

    async def handle_tile_click(self, interaction: discord.Interaction, button: MinesTileButton):
        if interaction.user.id != self.user_id:
            await interaction.response.send_message("❌ Bu mayın tarlası oyunu size ait değil!", ephemeral=True)
            return

        if self.game_over or button.index in self.uncovered:
            await interaction.response.defer()
            return

        idx = button.index

        # Dynamic trap chance scaling with mine count (balanced house edge)
        import random
        trap_chance = 0.22 if self.mine_count <= 2 else (0.32 if self.mine_count <= 4 else 0.42)
        if len(self.uncovered) >= 1 and idx not in self.mines and random.random() < trap_chance:
            unrevealed_mines = list(self.mines - self.uncovered)
            if unrevealed_mines:
                swap_mine = random.choice(unrevealed_mines)
                self.mines.remove(swap_mine)
                self.mines.add(idx)

        # Hit a mine!
        if idx in self.mines:
            self.game_over = True
            button.style = discord.ButtonStyle.danger
            button.label = "💥"
            button.disabled = True

            # Reveal all other tiles
            for i in range(self.total_tiles):
                b = self.tiles[i]
                b.disabled = True
                if i in self.mines:
                    if i != idx:
                        b.style = discord.ButtonStyle.danger
                        b.label = "💣"
                else:
                    if i in self.uncovered:
                        b.style = discord.ButtonStyle.success
                        b.label = "💎"
                    else:
                        b.style = discord.ButtonStyle.secondary
                        b.label = "💎"

            self.cashout_btn.disabled = True
            self.cashout_btn.style = discord.ButtonStyle.secondary
            self.cashout_btn.label = "💥 Patladınız!"

            from utils.security import format_money_string, schedule_message_delete
            user_db = await db.get_user(self.user_id)
            balance = user_db.get("balance", 0.0) if user_db else 0.0

            embed = discord.Embed(
                title="💥 Mayın Tarlası - PATLADINIZ!",
                description=(
                    f"💀 {interaction.user.mention} bir mayına bastı ve bahis yandı!\n\n"
                    f"💣 **Mayın Sayısı:** `{self.mine_count}`\n"
                    f"📉 **Kaybedilen Tutar:** **{format_money_string(self.bet_amount)}**\n"
                    f"💳 **Kalan Bakiye:** **{format_money_string(balance)}**"
                ),
                color=discord.Color.red()
            )
            await interaction.response.edit_message(embed=embed, view=self)
            if self.msg or getattr(interaction, "message", None):
                asyncio.create_task(schedule_message_delete(self.msg or interaction.message, 10.0))
            self.stop()
            return

        # Safe diamond!
        self.uncovered.add(idx)
        button.style = discord.ButtonStyle.success
        button.label = "💎"
        button.disabled = True

        self.current_mult = self.calculate_multiplier(len(self.uncovered))
        current_winnings = self.bet_amount * self.current_mult

        from utils.security import format_money_string
        self.cashout_btn.disabled = False
        self.cashout_btn.style = discord.ButtonStyle.success
        self.cashout_btn.label = f"💰 Parayı Çek ({self.current_mult}x - {format_money_string(current_winnings)})"

        # Check if all diamonds are uncovered!
        if len(self.uncovered) == self.diamonds_total:
            await self.handle_cashout(interaction, auto_win=True)
            return

        embed = discord.Embed(
            title="💎 Mayın Tarlası (Mines)",
            description=(
                f"🎉 {interaction.user.mention} güvenli bir elmas buldu!\n\n"
                f"📈 **Mevcut Çarpan:** `{self.current_mult}x`\n"
                f"💵 **Olası Kazanç:** **{format_money_string(current_winnings)}**\n"
                f"💎 **Açılan Elmas:** `{len(self.uncovered)}/{self.diamonds_total}` | 💣 **Mayınlar:** `{self.mine_count}`\n\n"
                f"*Kazanmak için istediğiniz an aşağıdaki '💰 Parayı Çek' butonuna tıklayabilirsiniz!*"
            ),
            color=discord.Color.green()
        )
        await interaction.response.edit_message(embed=embed, view=self)

    async def handle_cashout(self, interaction: discord.Interaction, auto_win: bool = False):
        if interaction.user.id != self.user_id:
            await interaction.response.send_message("❌ Bu mayın tarlası oyunu size ait değil!", ephemeral=True)
            return

        if self.game_over or len(self.uncovered) == 0:
            await interaction.response.defer()
            return

        self.game_over = True
        winnings = self.bet_amount * self.current_mult

        # Award winnings to user
        new_balance = await db.update_balance(self.user_id, winnings, "mines_win", f"Mayın Tarlası kazancı: {winnings:,.2f} ({self.current_mult}x)")

        # Reveal all tiles
        for i in range(self.total_tiles):
            b = self.tiles[i]
            b.disabled = True
            if i in self.mines:
                b.style = discord.ButtonStyle.danger
                b.label = "💣"
            else:
                b.style = discord.ButtonStyle.success
                b.label = "💎"

        self.cashout_btn.disabled = True
        self.cashout_btn.style = discord.ButtonStyle.secondary
        self.cashout_btn.label = "✅ Çekildi"

        from utils.logger import log_transaction
        await log_transaction(
            bot=self.bot,
            user=interaction.user,
            tx_type="mines",
            amount=winnings - self.bet_amount,
            status="completed",
            details=f"Mayın: {self.mine_count}, Açılan: {len(self.uncovered)}, Çarpan: {self.current_mult}x, Kazanç: {winnings:,.2f}"
        )

        if winnings >= 200000000.0:
            from utils.logger import log_suspicious_activity
            await log_suspicious_activity(
                self.bot,
                interaction.user,
                "High_Mines_Winnings",
                f"Mayın Tarlası yüksek kazanç: Bahis {self.bet_amount:,.2f} -> Çarpan {self.current_mult}x -> Kazanç {winnings:,.2f}"
            )

        from utils.security import format_money_string, schedule_message_delete
        embed = discord.Embed(
            title="🎉 Mayın Tarlası - KAZANDINIZ!",
            description=(
                f"🏆 {interaction.user.mention} **{self.current_mult}x** çarpanındayken parasını başarıyla çekti!\n\n"
                f"💎 **Toplanan Elmas:** `{len(self.uncovered)}/{self.diamonds_total}` | 💣 **Mayın Sayısı:** `{self.mine_count}`\n"
                f"💰 **Kazanılan Tutar:** **{format_money_string(winnings)}**\n"
                f"💳 **Yeni Bakiye:** **{format_money_string(new_balance)}**"
            ),
            color=discord.Color.gold() if auto_win else discord.Color.green()
        )
        await interaction.response.edit_message(embed=embed, view=self)
        if self.msg or getattr(interaction, "message", None):
            asyncio.create_task(schedule_message_delete(self.msg or interaction.message, 10.0))
        self.stop()

    async def on_timeout(self):
        if not self.game_over:
            self.game_over = True
            if len(self.uncovered) > 0:
                # Auto cashout on timeout
                winnings = self.bet_amount * self.current_mult
                new_balance = await db.update_balance(self.user_id, winnings, "mines_win", f"Mayın Tarlası zaman aşımı otomatik kazanç: {winnings:,.2f}")
                from utils.security import format_money_string, schedule_message_delete
                for i in range(self.total_tiles):
                    self.tiles[i].disabled = True
                self.cashout_btn.disabled = True
                if self.msg:
                    embed = discord.Embed(
                        title="⏱️ Mayın Tarlası - Otomatik Çekildi",
                        description=f"Süre dolduğu için son bakiyeniz otomatik çekildi.\nKazanç: **{format_money_string(winnings)}**",
                        color=discord.Color.blue()
                    )
                    try:
                        await self.msg.edit(embed=embed, view=self)
                        asyncio.create_task(schedule_message_delete(self.msg, 10.0))
                    except Exception:
                        pass
                    except Exception:
                        pass
            else:
                for i in range(self.total_tiles):
                    self.tiles[i].disabled = True
                self.cashout_btn.disabled = True
                if self.msg:
                    try:
                        await self.msg.edit(view=self)
                    except Exception:
                        pass


class MinesModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="💣 Mayın Tarlası (Mines)")
        self.cog = cog

        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, 50m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        self.mine_count = discord.ui.TextInput(
            label="Mayın Sayısı (1 - 7)",
            placeholder="1 ile 7 arasında (Varsayılan: 3)",
            default="3",
            min_length=1,
            max_length=1,
            required=False
        )
        self.add_item(self.amount)
        self.add_item(self.mine_count)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_mines(interaction, self.amount.value, self.mine_count.value or "3")


class TowerModal(discord.ui.Modal):
    def __init__(self, cog):
        super().__init__(title="🏰 Şanslı Kule (Dragon's Tower)")
        self.cog = cog

        self.amount = discord.ui.TextInput(
            label="Bahis Miktarı",
            placeholder="Örn: 100k, 5m, 50m, allin",
            min_length=1,
            max_length=20,
            required=True
        )
        self.add_item(self.amount)

    async def on_submit(self, interaction: discord.Interaction):
        await self.cog._play_tower(interaction, self.amount.value)


class TowerDoorButton(discord.ui.Button):
    def __init__(self, door_index: int):
        super().__init__(style=discord.ButtonStyle.secondary, label=f"🚪 {door_index + 1}. Kapı", row=0)
        self.door_index = door_index

    async def callback(self, interaction: discord.Interaction):
        await self.view.handle_door_click(interaction, self.door_index)


class TowerCashoutButton(discord.ui.Button):
    def __init__(self):
        super().__init__(style=discord.ButtonStyle.success, label="💰 Parayı Çek", emoji="💰", row=1, disabled=True)

    async def callback(self, interaction: discord.Interaction):
        await self.view.handle_cashout(interaction)


class TowerView(discord.ui.View):
    def __init__(self, bot, user_id: int, bet_amount: float):
        super().__init__(timeout=120.0)
        self.bot = bot
        self.user_id = user_id
        self.bet_amount = bet_amount
        self.current_floor = 0  # 0 to 7 -> Kat 1 to Kat 8
        self.max_floors = 8
        self.multipliers = [1.45, 2.18, 3.27, 4.90, 7.35, 11.02, 16.54, 25.00]
        
        # On each floor, 1 random door (0, 1, 2) is a trap
        import random
        self.floor_traps = [random.randint(0, 2) for _ in range(self.max_floors)]
        self.floor_history = []
        self.game_over = False
        self.msg = None

        # Add 3 door buttons (row 0)
        self.doors = [TowerDoorButton(i) for i in range(3)]
        for btn in self.doors:
            self.add_item(btn)

        # Add Cashout button (row 1)
        self.cashout_btn = TowerCashoutButton()
        self.add_item(self.cashout_btn)

    def render_embed(self, status: str = "playing", picked_door: int = -1, trap_door: int = -1) -> discord.Embed:
        from utils.security import format_money_string
        from datetime import datetime
        
        tower_lines = []
        floor_names = [
            ("Kat 8 (Zirve 👑)", 25.00),
            ("Kat 7", 16.54),
            ("Kat 6", 11.02),
            ("Kat 5", 7.35),
            ("Kat 4", 4.90),
            ("Kat 3", 3.27),
            ("Kat 2", 2.18),
            ("Kat 1 (Giriş)", 1.45),
        ]
        
        for floor_idx, (f_name, mult) in enumerate(floor_names):
            actual_f = 7 - floor_idx
            if actual_f < self.current_floor:
                p, t = self.floor_history[actual_f] if actual_f < len(self.floor_history) else (0, 1)
                doors_repr = "".join([" 💎 " if d != t else " 💀 " for d in range(3)])
                tower_lines.append(f"✨ **{f_name}:** `[{doors_repr}]` — **{mult:.2f}x** ✅")
            elif actual_f == self.current_floor:
                if status == "lost":
                    doors_repr = "".join([" 💥 " if d == trap_door else " 💎 " for d in range(3)])
                    tower_lines.append(f"💥 **{f_name}:** `[{doors_repr}]` — **{mult:.2f}x** ❌")
                elif status in ["won", "cashed_out"]:
                    p, t = self.floor_history[actual_f] if actual_f < len(self.floor_history) else (0, 1)
                    doors_repr = "".join([" 💎 " if d != t else " 💀 " for d in range(3)])
                    tower_lines.append(f"👑 **{f_name}:** `[{doors_repr}]` — **{mult:.2f}x** 🏆")
                else:
                    tower_lines.append(f"🏰 **{f_name}:** `[ 🚪 | 🚪 | 🚪 ]` — **{mult:.2f}x** 👈 *(Kapı Seçin)*")
            else:
                tower_lines.append(f"🔒 `{f_name}:` `[ ❓ | ❓ | ❓ ]` — `{mult:.2f}x`")

        tower_display = "\n".join(tower_lines)
        
        curr_mult = self.multipliers[self.current_floor - 1] if self.current_floor > 0 else 1.00
        curr_win = self.bet_amount * curr_mult

        if status == "lost":
            embed = discord.Embed(
                title="💥 Kule Çöktü! (Tuzak Kapı)",
                description=(
                    f"💀 **Tuzak kapıya bastınız ve kule çöktü!**\n"
                    f"Kaybedilen Bahis: 💸 **{format_money_string(self.bet_amount)}**\n\n"
                    f"{tower_display}"
                ),
                color=discord.Color.red(),
                timestamp=datetime.utcnow()
            )
        elif status == "cashed_out":
            embed = discord.Embed(
                title="💰 Kuleden Güvenle Çekildiniz!",
                description=(
                    f"🎉 **{self.current_floor}. Katta** başarıyla çekildiniz!\n"
                    f"Çarpan: ⚡ **{curr_mult:.2f}x**\n"
                    f"💵 Kazanılan Tutar: 💰 **{format_money_string(curr_win)}** ({curr_win:,.2f})\n\n"
                    f"{tower_display}"
                ),
                color=discord.Color.green(),
                timestamp=datetime.utcnow()
            )
        elif status == "won":
            embed = discord.Embed(
                title="👑 KULENİN ZİRVESİNE ULAŞTINIZ! (JACKPOT)",
                description=(
                    f"🏆 **Tüm 8 katı hatasız geçerek kuleyi fethettiniz!**\n"
                    f"Büyük Çarpan: 🔥 **25.00x**\n"
                    f"💵 Toplam Kazanç: 💰 **{format_money_string(self.bet_amount * 25.00)}**\n\n"
                    f"{tower_display}"
                ),
                color=discord.Color.gold(),
                timestamp=datetime.utcnow()
            )
        else:
            embed = discord.Embed(
                title="🏰 Şanslı Kule (Dragon's Tower)",
                description=(
                    f"💵 **Bahis:** **{format_money_string(self.bet_amount)}**\n"
                    f"📊 **Mevcut Kat:** `{self.current_floor + 1} / 8`\n"
                    f"💰 **Mevcut Kazanç:** **{format_money_string(curr_win)}** ({curr_mult:.2f}x)\n\n"
                    f"{tower_display}\n\n"
                    f"👇 *Bir sonraki kata tırmanmak için 3 kapıdan birini seçin veya paranızı çekin!*"
                ),
                color=discord.Color.blue(),
                timestamp=datetime.utcnow()
            )
        embed.set_footer(text="KolicGamble Şanslı Kule Altyapısı")
        return embed

    async def handle_door_click(self, interaction: discord.Interaction, door_index: int):
        if interaction.user.id != self.user_id:
            await interaction.response.send_message("❌ Bu kule oyunu size ait değil!", ephemeral=True)
            return

        if self.game_over:
            await interaction.response.defer()
            return

        await interaction.response.defer()

        trap_door = self.floor_traps[self.current_floor]
        self.floor_history.append((door_index, trap_door))

        if door_index == trap_door:
            self.game_over = True
            for item in self.children:
                item.disabled = True

            embed = self.render_embed(status="lost", picked_door=door_index, trap_door=trap_door)
            await interaction.message.edit(embed=embed, view=self)

            from utils.security import schedule_message_delete
            import asyncio
            asyncio.create_task(schedule_message_delete(interaction.message, 15.0))
            return

        # Safe door! Advance floor
        self.current_floor += 1

        if self.current_floor == self.max_floors:
            self.game_over = True
            for item in self.children:
                item.disabled = True

            winnings = round(self.bet_amount * 25.00, 2)
            await db.update_balance(self.user_id, winnings, "tower_jackpot", "Kule Zirvesi (25.00x) Jackpot kazanıldı.")

            embed = self.render_embed(status="won")
            await interaction.message.edit(embed=embed, view=self)

            from utils.security import schedule_message_delete
            import asyncio
            asyncio.create_task(schedule_message_delete(interaction.message, 20.0))
            return

        # Enable cashout button with current earnings
        curr_mult = self.multipliers[self.current_floor - 1]
        from utils.security import format_money_string
        self.cashout_btn.disabled = False
        self.cashout_btn.label = f"💰 Çekil ({format_money_string(self.bet_amount * curr_mult)})"

        embed = self.render_embed(status="playing")
        await interaction.message.edit(embed=embed, view=self)

    async def handle_cashout(self, interaction: discord.Interaction):
        if interaction.user.id != self.user_id:
            await interaction.response.send_message("❌ Bu kule oyunu size ait değil!", ephemeral=True)
            return

        if self.game_over or self.current_floor == 0:
            await interaction.response.defer()
            return

        await interaction.response.defer()
        self.game_over = True
        for item in self.children:
            item.disabled = True

        win_mult = self.multipliers[self.current_floor - 1]
        winnings = round(self.bet_amount * win_mult, 2)
        await db.update_balance(self.user_id, winnings, "tower_cashout", f"Kule {self.current_floor}. Kat çekildi ({win_mult}x).")

        embed = self.render_embed(status="cashed_out")
        await interaction.message.edit(embed=embed, view=self)

        from utils.security import schedule_message_delete
        import asyncio
        asyncio.create_task(schedule_message_delete(interaction.message, 15.0))

    async def on_timeout(self):
        if not self.game_over:
            self.game_over = True
            for item in self.children:
                item.disabled = True
            if self.current_floor > 0:
                win_mult = self.multipliers[self.current_floor - 1]
                winnings = round(self.bet_amount * win_mult, 2)
                await db.update_balance(self.user_id, winnings, "tower_timeout", f"Kule zaman aşımı kazanç ({win_mult}x).")
            if self.msg:
                try:
                    await self.msg.edit(view=self)
                except Exception:
                    pass


class CrateSelectionView(discord.ui.View):
    def __init__(self, cog):
        super().__init__(timeout=60.0)
        self.cog = cog

    @discord.ui.button(label="🔥 Kozmik (50m)", style=discord.ButtonStyle.secondary, custom_id="crate_select_cosmic")
    async def cosmic_crate(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.cog._play_crate(interaction, "kozmik")

    @discord.ui.button(label="🔱 Poseidon (100m)", style=discord.ButtonStyle.secondary, custom_id="crate_select_poseidon")
    async def poseidon_crate(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.cog._play_crate(interaction, "poseidon")

    @discord.ui.button(label="💀 Hades (200m)", style=discord.ButtonStyle.secondary, custom_id="crate_select_hades")
    async def hades_crate(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.cog._play_crate(interaction, "hades")

    @discord.ui.button(label="⚡ Zeus (300m)", style=discord.ButtonStyle.secondary, custom_id="crate_select_zeus")
    async def zeus_crate(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.cog._play_crate(interaction, "zeus")

    @discord.ui.button(label="🌌 Kara Delik (500m)", style=discord.ButtonStyle.secondary, custom_id="crate_select_blackhole")
    async def blackhole_crate(self, interaction: discord.Interaction, button: discord.ui.Button):
        await self.cog._play_crate(interaction, "blackhole")


class GambleLobbyView(discord.ui.View):
    def __init__(self):
        super().__init__(timeout=None)

    @discord.ui.button(label="🪙 Coinflip", style=discord.ButtonStyle.success, custom_id="lobby_coinflip", row=0)
    async def coinflip_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(CoinflipModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="🎰 Slots", style=discord.ButtonStyle.primary, custom_id="lobby_slots", row=0)
    async def slots_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(SlotsModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="🃏 Blackjack", style=discord.ButtonStyle.secondary, custom_id="lobby_blackjack", row=0)
    async def blackjack_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(BlackjackModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="📈 Crash", style=discord.ButtonStyle.danger, custom_id="lobby_crash", row=0)
    async def crash_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(CrashModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="🎡 Rulet", style=discord.ButtonStyle.secondary, emoji="🎡", custom_id="lobby_roulette", row=1)
    async def roulette_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(RouletteModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="💣 Mayın Tarlası", style=discord.ButtonStyle.danger, emoji="💣", custom_id="lobby_mines", row=1)
    async def mines_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(MinesModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="🏰 Şanslı Kule", style=discord.ButtonStyle.success, emoji="🏰", custom_id="lobby_tower", row=1)
    async def tower_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            await interaction.response.send_modal(TowerModal(cog))
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)

    @discord.ui.button(label="📦 Kasa Aç", style=discord.ButtonStyle.primary, emoji="📦", custom_id="lobby_crate", row=1)
    async def crate_button(self, interaction: discord.Interaction, button: discord.ui.Button):
        cog = interaction.client.get_cog("Kumar Oyunları")
        if cog:
            embed = discord.Embed(
                title="📦 KolicGamble Kasa Seçimi",
                description=(
                    "Aşağıdaki kutulardan açmak istediğinizi seçin. Her kutunun farklı maliyeti ve ödül havuzu vardır!\n\n"
                    "🔥 **Kozmik Kasa (50m):** Küçük kozmik madenler, başlangıç kutusu.\n"
                    "🔱 **Poseidon Kasası (100m):** Atlantis hazineleri ve Poseidon mızrağı.\n"
                    "💀 **Hades'in Sandığı (200m):** Yeraltı dünyasının zenginlikleri.\n"
                    "⚡ **Zeus'un Yıldırımı (300m):** Olimpos'un en nadide ödülleri.\n"
                    "🌌 **Kara Delik Kasası (500m):** Sonsuzluk boyutu, **5.000.000.000**'a kadar astronomik kazanç!"
                ),
                color=discord.Color.gold()
            )
            await interaction.response.send_message(embed=embed, view=CrateSelectionView(cog), ephemeral=True)
        else:
            await interaction.response.send_message("❌ Kumar oyunları sistemi şu anda aktif değil.", ephemeral=True)


async def setup(bot):
    await bot.add_cog(GamesCog(bot))
