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

// Web Audio API Sound Synthesizer for rich arcade casino sounds
const SoundEngine = {
    _ctx: null,
    _muted: false,

    _init()
    {
        if (!SoundEngine._ctx && typeof window !== 'undefined')
        {
            const AudioCtx = window.AudioContext || window.webkitAudioContext;
            if (AudioCtx)
            {
                SoundEngine._ctx = new AudioCtx();
            }
        }
        if (SoundEngine._ctx && SoundEngine._ctx.state === 'suspended')
        {
            SoundEngine._ctx.resume();
        }
    },

    setMuted(muted)
    {
        SoundEngine._muted = muted;
    },

    playSpinTick()
    {
        if (SoundEngine._muted) return;
        try
        {
            SoundEngine._init();
            if (!SoundEngine._ctx) return;
            const osc = SoundEngine._ctx.createOscillator();
            const gain = SoundEngine._ctx.createGain();
            osc.type = 'triangle';
            osc.frequency.setValueAtTime(440 + Math.random() * 80, SoundEngine._ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(120, SoundEngine._ctx.currentTime + 0.04);
            gain.gain.setValueAtTime(0.12, SoundEngine._ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.01, SoundEngine._ctx.currentTime + 0.04);
            osc.connect(gain);
            gain.connect(SoundEngine._ctx.destination);
            osc.start();
            osc.stop(SoundEngine._ctx.currentTime + 0.04);
        }
        catch (e) { }
    },

    playReelStop()
    {
        if (SoundEngine._muted) return;
        try
        {
            SoundEngine._init();
            if (!SoundEngine._ctx) return;
            const osc = SoundEngine._ctx.createOscillator();
            const gain = SoundEngine._ctx.createGain();
            osc.type = 'sine';
            osc.frequency.setValueAtTime(180, SoundEngine._ctx.currentTime);
            osc.frequency.exponentialRampToValueAtTime(60, SoundEngine._ctx.currentTime + 0.09);
            gain.gain.setValueAtTime(0.25, SoundEngine._ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.01, SoundEngine._ctx.currentTime + 0.09);
            osc.connect(gain);
            gain.connect(SoundEngine._ctx.destination);
            osc.start();
            osc.stop(SoundEngine._ctx.currentTime + 0.09);
        }
        catch (e) { }
    },

    playWinSound(winType)
    {
        if (SoundEngine._muted) return;
        try
        {
            SoundEngine._init();
            if (!SoundEngine._ctx) return;
            const now = SoundEngine._ctx.currentTime;

            if (winType === 'jackpot' || winType === 'crown')
            {
                // Fanfare arpeggio for Mega / Grand wins
                const notes = [523.25, 659.25, 783.99, 1046.50, 1318.51, 1567.98];
                notes.forEach((freq, i) =>
                {
                    const osc = SoundEngine._ctx.createOscillator();
                    const gain = SoundEngine._ctx.createGain();
                    osc.type = 'triangle';
                    osc.frequency.setValueAtTime(freq, now + i * 0.09);
                    gain.gain.setValueAtTime(0, now + i * 0.09);
                    gain.gain.linearRampToValueAtTime(0.22, now + i * 0.09 + 0.02);
                    gain.gain.exponentialRampToValueAtTime(0.001, now + i * 0.09 + 0.35);
                    osc.connect(gain);
                    gain.connect(SoundEngine._ctx.destination);
                    osc.start(now + i * 0.09);
                    osc.stop(now + i * 0.09 + 0.35);
                });
            }
            else if (winType === 'seven' || winType === 'bell' || winType === 'clover' || winType === 'cherry3')
            {
                // Ascending harmonic chime
                const notes = [587.33, 739.99, 880.00];
                notes.forEach((freq, i) =>
                {
                    const osc = SoundEngine._ctx.createOscillator();
                    const gain = SoundEngine._ctx.createGain();
                    osc.type = 'sine';
                    osc.frequency.setValueAtTime(freq, now + i * 0.08);
                    gain.gain.setValueAtTime(0.18, now + i * 0.08);
                    gain.gain.exponentialRampToValueAtTime(0.001, now + i * 0.08 + 0.25);
                    osc.connect(gain);
                    gain.connect(SoundEngine._ctx.destination);
                    osc.start(now + i * 0.08);
                    osc.stop(now + i * 0.08 + 0.25);
                });
            }
            else if (winType === 'cherry2')
            {
                // Break-even double pip
                [440, 554.37].forEach((freq, i) =>
                {
                    const osc = SoundEngine._ctx.createOscillator();
                    const gain = SoundEngine._ctx.createGain();
                    osc.type = 'sine';
                    osc.frequency.setValueAtTime(freq, now + i * 0.1);
                    gain.gain.setValueAtTime(0.12, now + i * 0.1);
                    gain.gain.exponentialRampToValueAtTime(0.001, now + i * 0.1 + 0.15);
                    osc.connect(gain);
                    gain.connect(SoundEngine._ctx.destination);
                    osc.start(now + i * 0.1);
                    osc.stop(now + i * 0.1 + 0.15);
                });
            }
        }
        catch (e) { }
    }
};

const SYMBOL_MAP = {
    diamond: { id: 'diamond', name: 'Diamond', icon: '💎', color: 'from-sky-400 to-cyan-300', textGlow: 'text-sky-300 drop-shadow-[0_0_15px_rgba(56,189,248,0.8)]' },
    crown: { id: 'crown', name: 'Crown', icon: '👑', color: 'from-amber-400 to-yellow-300', textGlow: 'text-amber-300 drop-shadow-[0_0_15px_rgba(245,158,11,0.8)]' },
    seven: { id: 'seven', name: 'Seven', icon: '7️⃣', color: 'from-rose-500 to-red-400', textGlow: 'text-rose-400 drop-shadow-[0_0_15px_rgba(244,63,94,0.8)]' },
    bell: { id: 'bell', name: 'Bell', icon: '🔔', color: 'from-yellow-400 to-amber-300', textGlow: 'text-yellow-300 drop-shadow-[0_0_12px_rgba(251,191,36,0.7)]' },
    clover: { id: 'clover', name: 'Clover', icon: '🍀', color: 'from-emerald-400 to-teal-300', textGlow: 'text-emerald-300 drop-shadow-[0_0_12px_rgba(16,185,129,0.7)]' },
    cherry: { id: 'cherry', name: 'Cherry', icon: '🍒', color: 'from-pink-500 to-rose-400', textGlow: 'text-pink-400 drop-shadow-[0_0_12px_rgba(236,72,153,0.7)]' },
    lemon: { id: 'lemon', name: 'Lemon', icon: '🍋', color: 'from-amber-300 to-yellow-200', textGlow: 'text-yellow-200 drop-shadow-[0_0_10px_rgba(234,179,8,0.6)]' },
    bar: { id: 'bar', name: 'Bar', icon: '🎰', color: 'from-purple-500 to-indigo-400', textGlow: 'text-purple-300 drop-shadow-[0_0_10px_rgba(168,85,247,0.6)]' }
};

const ALL_SYMBOL_KEYS = ['diamond', 'crown', 'seven', 'bell', 'clover', 'cherry', 'lemon', 'bar'];

function LuckySlot({ t, lang, userProfile, formatMoney, onBalanceUpdate, onBackToLobby, setShowDebtPanel })
{
    const Icons = window.Icons;
    const config = window.GAME_CONFIG?.luckySlot || {};
    const minBet = config.MIN_BET || 100;
    const maxBet = config.MAX_BET || 1000000;
    const presets = config.BET_PRESETS || [100, 250, 500, 1000, 2500, 5000, 10000, 25000, 50000, 100000, 250000, 500000, 1000000];

    const [bet, setBet] = useState(minBet);
    const [reels, setReels] = useState(['seven', 'seven', 'seven']);
    const [isSpinning, setIsSpinning] = useState(false);
    const [reelStates, setReelStates] = useState([false, false, false]); // individual spinning state
    const [lastWin, setLastWin] = useState(null);
    const [autoSpin, setAutoSpin] = useState(false);
    const [turbo, setTurbo] = useState(false);
    const [soundMuted, setSoundMuted] = useState(false);
    const [showPaytable, setShowPaytable] = useState(false);
    const [showJackpotCelebration, setShowJackpotCelebration] = useState(false);
    const [errorMessage, setErrorMessage] = useState('');

    const autoSpinRef = useRef(autoSpin);
    autoSpinRef.current = autoSpin;
    const winTimeoutRef = useRef(null);

    const isDebtor = userProfile?.isDebtor || (userProfile?.totalWealth < 0 && userProfile?.username?.toLowerCase() !== 'admin');
    const maxOverdraft = config.MAX_OVERDRAFT_BET || 1000;

    useEffect(() =>
    {
        SoundEngine.setMuted(soundMuted);
    }, [soundMuted]);

    useEffect(() =>
    {
        return () =>
        {
            if (winTimeoutRef.current)
            {
                clearTimeout(winTimeoutRef.current);
            }
        };
    }, []);

    const maxMultiplier = 100;
    const potentialJackpot = bet * maxMultiplier;

    const handleBetChange = (newBet) =>
    {
        if (isSpinning) return;
        const clamped = Math.min(maxBet, Math.max(minBet, Math.round(newBet)));
        setBet(clamped);
        setErrorMessage('');
    };

    const handleBetStep = (direction) =>
    {
        if (isSpinning) return;
        const currentIndex = presets.indexOf(bet);
        if (currentIndex !== -1)
        {
            const nextIndex = currentIndex + direction;
            if (nextIndex >= 0 && nextIndex < presets.length)
            {
                handleBetChange(presets[nextIndex]);
                return;
            }
        }

        if (direction > 0)
        {
            const nextPreset = presets.find(p => p > bet);
            handleBetChange(nextPreset !== undefined ? nextPreset : Math.min(maxBet, bet * 2));
        }
        else
        {
            const prevPresets = presets.filter(p => p < bet);
            handleBetChange(prevPresets.length > 0 ? prevPresets[prevPresets.length - 1] : minBet);
        }
    };

    const spin = useCallback(async () =>
    {
        if (isSpinning) return;
        if (winTimeoutRef.current)
        {
            clearTimeout(winTimeoutRef.current);
        }
        setErrorMessage('');
        setLastWin(null);

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

        if (!isAdmin)
        {
            if (isDebtor && bet > maxOverdraft)
            {
                setErrorMessage(lang === 'TR' ? `Borçlu statüsünde maksimum ${formatMoney(maxOverdraft)} bahis yapabilirsiniz.` : `Max bet for debtors is ${formatMoney(maxOverdraft)}.`);
                setAutoSpin(false);
                return;
            }
            if (!isDebtor && currentWealth < bet)
            {
                setErrorMessage(t.insufficientBalance || 'Yetersiz Bakiye!');
                setAutoSpin(false);
                return;
            }
        }

        setIsSpinning(true);
        setReelStates([true, true, true]);

        // Sound: initial tick
        SoundEngine.playSpinTick();

        // Intermediate reel jitter interval
        const spinInterval = setInterval(() =>
        {
            setReels([
                ALL_SYMBOL_KEYS[Math.floor(Math.random() * ALL_SYMBOL_KEYS.length)],
                ALL_SYMBOL_KEYS[Math.floor(Math.random() * ALL_SYMBOL_KEYS.length)],
                ALL_SYMBOL_KEYS[Math.floor(Math.random() * ALL_SYMBOL_KEYS.length)]
            ]);
            SoundEngine.playSpinTick();
        }, turbo ? 25 : 75);

        try
        {
            const token = localStorage.getItem('luck_token');
            const res = await fetch(`${window.API_URL}/api/slot/spin`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ bet })
            });

            const data = await res.json();

            if (!data.success)
            {
                clearInterval(spinInterval);
                setIsSpinning(false);
                setReelStates([false, false, false]);
                setErrorMessage(data.error || t.serverError);
                setAutoSpin(false);
                return;
            }

            const targetReels = data.reels;
            const stopDelay1 = turbo ? 80 : 650;
            const stopDelay2 = turbo ? 160 : 1200;
            const stopDelay3 = turbo ? 240 : 1800;

            // Stop Reel 1
            setTimeout(() =>
            {
                setReels(prev => [targetReels[0], prev[1], prev[2]]);
                setReelStates([false, true, true]);
                SoundEngine.playReelStop();
            }, stopDelay1);

            // Stop Reel 2
            setTimeout(() =>
            {
                setReels(prev => [targetReels[0], targetReels[1], prev[2]]);
                setReelStates([false, false, true]);
                SoundEngine.playReelStop();
            }, stopDelay2);

            // Stop Reel 3 and finalize
            setTimeout(() =>
            {
                clearInterval(spinInterval);
                setReels(targetReels);
                setReelStates([false, false, false]);
                setIsSpinning(false);
                SoundEngine.playReelStop();

                // Update progression
                if (data.user)
                {
                    onBalanceUpdate(data.user, data.houseBank);
                }

                if (data.winAmount > 0)
                {
                    setLastWin(data);
                    SoundEngine.playWinSound(data.winType);

                    if (data.winType === 'jackpot' || data.winAmount >= 1000000)
                    {
                        setShowJackpotCelebration(true);
                        setTimeout(() => setShowJackpotCelebration(false), 5000);
                    }
                }
                else
                {
                    setLastWin({ winAmount: 0, winType: 'none', netProfit: -bet });
                }

                // Automatically clear result banner after 3.5 seconds
                winTimeoutRef.current = setTimeout(() =>
                {
                    setLastWin(null);
                }, turbo ? 2000 : 3500);

                // Handle auto spin iteration
                if (autoSpinRef.current)
                {
                    setTimeout(() =>
                    {
                        if (autoSpinRef.current)
                        {
                            spin();
                        }
                    }, turbo ? 150 : 900);
                }
            }, stopDelay3);
        }
        catch (err)
        {
            clearInterval(spinInterval);
            setIsSpinning(false);
            setReelStates([false, false, false]);
            setErrorMessage(t.serverError);
            setAutoSpin(false);
        }
    }, [isSpinning, userProfile, bet, isDebtor, maxOverdraft, turbo, lang, t, onBalanceUpdate]);

    const toggleAutoSpin = () =>
    {
        if (autoSpin)
        {
            setAutoSpin(false);
        }
        else
        {
            setAutoSpin(true);
            if (!isSpinning)
            {
                spin();
            }
        }
    };

    return (
        <div className="w-full max-w-4xl mx-auto px-4 py-4 flex flex-col items-center select-none font-sans">

            {/* JACKPOT CELEBRATION OVERLAY */}
            <AnimatePresence>
                {showJackpotCelebration && (
                    <motion.div
                        initial={{ opacity: 0, scale: 0.8 }}
                        animate={{ opacity: 1, scale: 1 }}
                        exit={{ opacity: 0, scale: 0.8 }}
                        className="fixed inset-0 z-50 flex flex-col items-center justify-center bg-slate-950/85 backdrop-blur-md pointer-events-none"
                    >
                        <motion.div
                            animate={{ rotate: [0, 10, -10, 0], scale: [1, 1.15, 1] }}
                            transition={{ repeat: Infinity, duration: 1.5 }}
                            className="p-10 rounded-[3rem] bg-gradient-to-br from-amber-500 to-yellow-600 border-4 border-yellow-300 shadow-[0_0_120px_rgba(251,191,36,0.9)] text-center text-slate-950"
                        >
                            <div className="text-8xl mb-4 animate-bounce">💎💎💎</div>
                            <h2 className="text-5xl md:text-7xl font-black uppercase tracking-widest text-slate-950 drop-shadow-md">
                                {t.jackpotWin || "🎉 BÜYÜK JACKPOT!"}
                            </h2>
                            <p className="text-4xl md:text-6xl font-black mt-4 text-white drop-shadow-[0_4px_10px_rgba(0,0,0,0.8)]">
                                +{formatMoney(lastWin?.winAmount || 0)}
                            </p>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            {/* TOP NAVIGATION BAR */}
            <div className="w-full flex items-center justify-between mb-6">
                <button
                    onClick={onBackToLobby}
                    disabled={isSpinning}
                    className="flex items-center gap-2 px-5 py-2.5 rounded-2xl bg-slate-900/80 hover:bg-slate-800 border border-white/5 text-slate-300 hover:text-white transition-all active:scale-95 disabled:opacity-50 text-xs font-black uppercase tracking-wider shadow-lg"
                >
                    <Icons.PlayCircle size={16} className="rotate-180 text-indigo-400" />
                    <span>{t.mainMenu || "Lobiye Dön"}</span>
                </button>

                {/* GAME TITLE BADGE */}
                <div className="flex items-center gap-3 px-6 py-2 rounded-2xl bg-gradient-to-r from-amber-500/10 via-purple-500/10 to-amber-500/10 border border-amber-500/20 backdrop-blur-md">
                    <Icons.SlotMachine size={20} className="text-amber-400 animate-pulse" />
                    <h2 className="text-sm md:text-base font-black tracking-widest uppercase bg-gradient-to-r from-amber-300 via-yellow-200 to-amber-400 bg-clip-text text-transparent">
                        {t.luckySlotTitle || (lang === 'TR' ? "Şanslı Slot" : "Lucky Slot")}
                    </h2>
                    <span className="px-2 py-0.5 rounded text-[9px] font-black bg-emerald-500/20 text-emerald-400 border border-emerald-500/30 uppercase">
                        {t.freeEntry || (lang === 'TR' ? "Sınırsız Hak" : "Free / Unlimited")}
                    </span>
                </div>

                <div className="flex items-center gap-2">
                    <button
                        onClick={() => setShowPaytable(true)}
                        className="p-2.5 rounded-xl bg-slate-900/80 hover:bg-slate-800 border border-white/5 text-amber-400 hover:text-amber-300 transition-all shadow-lg active:scale-95"
                        title={t.paytable || "Ödeme Tablosu"}
                    >
                        <Icons.Info size={18} />
                    </button>
                    <button
                        onClick={() => setSoundMuted(!soundMuted)}
                        className={`p-2.5 rounded-xl bg-slate-900/80 hover:bg-slate-800 border border-white/5 transition-all shadow-lg active:scale-95 ${soundMuted ? 'text-rose-400' : 'text-slate-300'}`}
                        title={soundMuted ? t.soundOff : t.soundOn}
                    >
                        {soundMuted ? <Icons.VolumeX size={18} /> : <Icons.Volume2 size={18} />}
                    </button>
                </div>
            </div>

            {/* ERROR BANNER */}
            {errorMessage && (
                <motion.div
                    initial={{ opacity: 0, y: -10 }}
                    animate={{ opacity: 1, y: 0 }}
                    className="w-full mb-4 p-3 rounded-2xl bg-rose-500/15 border border-rose-500/30 text-rose-300 text-xs font-bold text-center flex items-center justify-center gap-2"
                >
                    <Icons.AlertTriangle size={16} className="text-rose-400" />
                    <span>{errorMessage}</span>
                </motion.div>
            )}

            {/* MAIN SLOT CASING */}
            <div className="w-full bg-[#070b19] border-2 border-amber-500/30 rounded-[3rem] p-6 md:p-8 shadow-[0_0_80px_rgba(245,158,11,0.15)] relative overflow-hidden flex flex-col items-center">

                {/* BACKGROUND NEON ACCENTS */}
                <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-transparent via-amber-400 to-transparent opacity-80"></div>
                <div className="absolute -top-24 left-1/2 -translate-x-1/2 w-80 h-80 bg-amber-500/10 blur-[90px] pointer-events-none"></div>

                {/* MULTIPLIER & JACKPOT PREVIEW HEADER */}
                <div className="w-full grid grid-cols-1 md:grid-cols-3 gap-3 mb-6 relative z-10">
                    <div className="p-3.5 rounded-2xl bg-slate-900/80 border border-white/5 flex items-center justify-between px-4">
                        <button
                            onClick={() => handleBetStep(-1)}
                            disabled={isSpinning || bet <= minBet}
                            className="w-9 h-9 rounded-xl bg-slate-800 hover:bg-slate-700 disabled:opacity-30 text-white font-black text-xl flex items-center justify-center transition-all active:scale-95 border border-white/5"
                            title={lang === 'TR' ? "Bahsi Düşür" : "Decrease Bet"}
                        >
                            -
                        </button>
                        <div className="flex flex-col items-center justify-center">
                            <span className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-0.5">
                                {t.betAmount || "Bahis"}
                            </span>
                            <span className="text-lg md:text-xl font-black text-white tabular-nums">
                                {formatMoney(bet)}
                            </span>
                        </div>
                        <button
                            onClick={() => handleBetStep(1)}
                            disabled={isSpinning || bet >= maxBet}
                            className="w-9 h-9 rounded-xl bg-slate-800 hover:bg-slate-700 disabled:opacity-30 text-white font-black text-xl flex items-center justify-center transition-all active:scale-95 border border-white/5"
                            title={lang === 'TR' ? "Bahsi Artır" : "Increase Bet"}
                        >
                            +
                        </button>
                    </div>

                    <div className="p-3.5 rounded-2xl bg-gradient-to-br from-amber-500/20 to-yellow-600/10 border border-amber-500/40 flex flex-col items-center justify-center shadow-lg shadow-amber-500/10">
                        <span className="text-[10px] font-black uppercase tracking-widest text-amber-400 mb-0.5 flex items-center gap-1">
                            <Icons.Flame size={12} className="text-amber-400 animate-pulse" />
                            {t.jackpotMultiplier || (lang === 'TR' ? "En Yüksek Oran" : "Jackpot Multiplier")}
                        </span>
                        <span className="text-2xl font-black text-amber-300 tabular-nums drop-shadow-[0_0_10px_rgba(245,158,11,0.6)]">
                            100x
                        </span>
                    </div>

                    <div className="p-3.5 rounded-2xl bg-slate-900/80 border border-white/5 flex flex-col items-center justify-center">
                        <span className="text-[10px] font-black uppercase tracking-widest text-slate-500 mb-0.5">
                            {t.potentialJackpot || "Maksimum Jackpot"}
                        </span>
                        <span className="text-lg md:text-xl font-black text-emerald-400 tabular-nums">
                            {formatMoney(potentialJackpot)}
                        </span>
                    </div>
                </div>

                {/* REEL WINDOW */}
                <div className="w-full relative py-6 px-4 bg-slate-950/90 rounded-[2.5rem] border-2 border-slate-800 shadow-inner flex items-center justify-center mb-6 overflow-hidden">
                    {/* PAYLINE GLOW LINE */}
                    <div className="absolute inset-x-0 top-1/2 -translate-y-1/2 h-[2px] bg-gradient-to-r from-transparent via-amber-400/50 to-transparent pointer-events-none z-20"></div>

                    {/* 3 REELS CONTAINER */}
                    <div className="grid grid-cols-3 gap-3 sm:gap-6 w-full max-w-xl relative z-10">
                        {reels.map((symKey, index) =>
                        {
                            const sym = SYMBOL_MAP[symKey] || SYMBOL_MAP.lemon;
                            const isReelActive = reelStates[index];

                            return (
                                <div
                                    key={index}
                                    className={`h-36 sm:h-44 rounded-3xl bg-gradient-to-b from-slate-900/90 via-slate-900/50 to-slate-900/90 border flex flex-col items-center justify-center relative overflow-hidden transition-all duration-300 ${isReelActive ? 'border-amber-500/50 shadow-[0_0_25px_rgba(245,158,11,0.25)]' : 'border-white/10'}`}
                                >
                                    {/* TOP/BOTTOM GRADIENT OVERLAYS FOR 3D ROLLER DEPTH */}
                                    <div className="absolute top-0 inset-x-0 h-10 bg-gradient-to-b from-slate-950 to-transparent z-10 pointer-events-none"></div>
                                    <div className="absolute bottom-0 inset-x-0 h-10 bg-gradient-to-t from-slate-950 to-transparent z-10 pointer-events-none"></div>

                                    {/* SYMBOL DISPLAY */}
                                    <motion.div
                                        key={`${symKey}-${index}`}
                                        initial={isReelActive ? { y: -40, opacity: 0.6 } : { scale: 0.85, y: 0, opacity: 1 }}
                                        animate={{ scale: 1, y: 0, opacity: 1 }}
                                        transition={{ type: "spring", stiffness: 450, damping: 20 }}
                                        className="flex flex-col items-center justify-center"
                                    >
                                        <span className={`text-5xl sm:text-6xl select-none filter transition-transform duration-200 ${isReelActive ? 'blur-[1.5px] scale-110' : 'hover:scale-110'} ${sym.textGlow}`}>
                                            {sym.icon}
                                        </span>
                                        <span className="text-[10px] font-black uppercase tracking-widest text-slate-400 mt-2">
                                            {sym.name}
                                        </span>
                                    </motion.div>
                                </div>
                            );
                        })}
                    </div>
                </div>

                {/* WIN / RESULT BANNER */}
                <div className="w-full min-h-[52px] flex items-center justify-center mb-6">
                    <AnimatePresence mode="wait">
                        {lastWin ? (
                            <motion.div
                                key={`${lastWin.winType}-${Date.now()}`}
                                initial={{ opacity: 0, scale: 0.8, y: 5 }}
                                animate={{ opacity: 1, scale: 1, y: 0 }}
                                exit={{ opacity: 0, scale: 0.8 }}
                                className={`px-6 py-2.5 rounded-2xl border text-center flex items-center gap-3 ${lastWin.winAmount > 0 ? (lastWin.winType === 'jackpot' ? 'bg-amber-500/25 border-amber-400 text-amber-300 shadow-[0_0_30px_rgba(245,158,11,0.5)]' : 'bg-emerald-500/20 border-emerald-500/40 text-emerald-300') : 'bg-slate-900/60 border-white/5 text-slate-400'}`}
                            >
                                <span className="text-base font-black">
                                    {lastWin.winType === 'jackpot' && (t.jackpotWin || "🎉 BÜYÜK JACKPOT!")}
                                    {lastWin.winType === 'crown' && (t.bigWin || "👑 GRAND KAZANÇ!")}
                                    {lastWin.winType === 'seven' && (t.miniWin || "🔥 MAJOR KAZANÇ!")}
                                    {lastWin.winType === 'bell' && (t.miniWin || "🔔 5X KAZANÇ!")}
                                    {lastWin.winType === 'clover' && (t.miniWin || "🍀 3X KAZANÇ!")}
                                    {lastWin.winType === 'cherry3' && (t.miniWin || "🍒 2X KAZANÇ!")}
                                    {lastWin.winType === 'cherry2' && (t.refundWin || "🪙 AMORTİ!")}
                                    {lastWin.winType === 'none' && (t.noWin || "Tekrar Dene!")}
                                </span>
                                {lastWin.winAmount > 0 && (
                                    <span className="text-lg font-black text-amber-300 tabular-nums">
                                        +{formatMoney(lastWin.winAmount)}
                                    </span>
                                )}
                            </motion.div>
                        ) : (
                            <div className="text-slate-500 text-xs font-bold uppercase tracking-widest">
                                {lang === 'TR' ? "Bahsini ayarla ve çevir" : "Set your bet and spin"}
                            </div>
                        )}
                    </AnimatePresence>
                </div>

                {/* BET SELECTION CHIPS */}
                <div className="w-full mb-6">
                    <div className="flex items-center justify-between mb-2.5">
                        <span className="text-[11px] font-black uppercase tracking-wider text-slate-400 flex items-center gap-1.5">
                            <Icons.Coins size={14} className="text-amber-400" />
                            {lang === 'TR' ? "Hızlı Bahis Seçimi" : "Quick Bet Selection"}
                        </span>
                        <div className="flex items-center gap-2">
                            <span className="text-[10px] font-bold text-slate-500 hidden sm:inline">
                                Min: {formatMoney(minBet)} | Max: {formatMoney(maxBet)}
                            </span>
                            <div className="flex items-center gap-1">
                                <button
                                    onClick={() => handleBetChange(minBet)}
                                    disabled={isSpinning || bet === minBet}
                                    className="px-2.5 py-1 rounded-lg bg-slate-800/80 hover:bg-slate-700 text-[10px] font-bold text-slate-400 hover:text-white disabled:opacity-30 border border-white/5 transition-all active:scale-95"
                                >
                                    MIN
                                </button>
                                <button
                                    onClick={() => handleBetChange(Math.max(minBet, Math.floor(bet / 2)))}
                                    disabled={isSpinning || bet <= minBet}
                                    className="px-2.5 py-1 rounded-lg bg-slate-800/80 hover:bg-slate-700 text-[10px] font-bold text-slate-400 hover:text-white disabled:opacity-30 border border-white/5 transition-all active:scale-95"
                                >
                                    ½
                                </button>
                                <button
                                    onClick={() => handleBetChange(Math.min(maxBet, bet * 2))}
                                    disabled={isSpinning || bet >= maxBet}
                                    className="px-2.5 py-1 rounded-lg bg-slate-800/80 hover:bg-slate-700 text-[10px] font-bold text-slate-400 hover:text-white disabled:opacity-30 border border-white/5 transition-all active:scale-95"
                                >
                                    2X
                                </button>
                                <button
                                    onClick={() => handleBetChange(maxBet)}
                                    disabled={isSpinning || bet === maxBet}
                                    className="px-2.5 py-1 rounded-lg bg-slate-800/80 hover:bg-slate-700 text-[10px] font-bold text-amber-400 hover:text-amber-300 disabled:opacity-30 border border-white/5 transition-all active:scale-95"
                                >
                                    MAX
                                </button>
                            </div>
                        </div>
                    </div>

                    <div className="flex flex-wrap gap-2 justify-center">
                        {presets.map((presetVal) => (
                            <button
                                key={presetVal}
                                onClick={() => handleBetChange(presetVal)}
                                disabled={isSpinning}
                                className={`px-3.5 py-1.5 rounded-xl text-xs font-black transition-all active:scale-95 disabled:opacity-50 ${bet === presetVal ? 'bg-gradient-to-r from-amber-500 to-yellow-500 text-slate-950 shadow-lg shadow-amber-500/30 scale-105 ring-1 ring-yellow-300' : 'bg-slate-900/80 hover:bg-slate-800 text-slate-300 border border-white/5 hover:border-amber-500/20'}`}
                            >
                                {formatMoney(presetVal)}
                            </button>
                        ))}
                    </div>
                </div>

                {/* ACTION BUTTONS & CONTROLS */}
                <div className="w-full flex flex-col sm:flex-row items-center gap-4 justify-between pt-4 border-t border-white/5">

                    {/* TOGGLE MODES */}
                    <div className="flex items-center gap-3">
                        <button
                            onClick={() => setTurbo(!turbo)}
                            className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border text-xs font-black transition-all active:scale-95 ${turbo ? 'bg-amber-500/20 border-amber-500/50 text-amber-400' : 'bg-slate-900/60 border-white/5 text-slate-400'}`}
                            title={t.turboMode || "Hızlı Mod"}
                        >
                            <Icons.Zap size={15} className={turbo ? "text-amber-400 animate-pulse" : ""} />
                            <span>{t.turboMode || "Hızlı Mod"}</span>
                        </button>

                        <button
                            onClick={toggleAutoSpin}
                            className={`flex items-center gap-2 px-4 py-2.5 rounded-xl border text-xs font-black transition-all active:scale-95 ${autoSpin ? 'bg-rose-500/20 border-rose-500/50 text-rose-400 shadow-lg shadow-rose-500/20' : 'bg-slate-900/60 border-white/5 text-slate-400'}`}
                        >
                            <Icons.Repeat size={15} className={autoSpin ? "animate-spin text-rose-400" : ""} />
                            <span>{autoSpin ? (t.stopAuto || "Durdur") : (t.autoSpin || "Otomatik")}</span>
                        </button>
                    </div>

                    {/* BIG SPIN BUTTON */}
                    <button
                        onClick={spin}
                        disabled={isSpinning || autoSpin}
                        className="w-full sm:w-auto px-10 py-5 rounded-2xl bg-gradient-to-r from-amber-500 via-yellow-400 to-amber-500 hover:from-amber-400 hover:to-yellow-300 text-slate-950 font-black text-xl tracking-wider uppercase shadow-[0_0_40px_rgba(245,158,11,0.4)] hover:scale-105 active:scale-95 transition-all disabled:opacity-50 disabled:grayscale disabled:pointer-events-none flex items-center justify-center gap-3"
                    >
                        <Icons.SlotMachine size={26} />
                        <span>{isSpinning ? (t.spinning || "Çevriliyor...") : (t.spin || "ÇEVİR")}</span>
                    </button>
                </div>
            </div>

            {/* PAYTABLE / RULES MODAL */}
            <AnimatePresence>
                {showPaytable && (
                    <motion.div
                        initial={{ opacity: 0 }}
                        animate={{ opacity: 1 }}
                        exit={{ opacity: 0 }}
                        onClick={() => setShowPaytable(false)}
                        className="fixed inset-0 z-50 flex items-center justify-center p-4 bg-slate-950/80 backdrop-blur-md"
                    >
                        <motion.div
                            initial={{ scale: 0.9, y: 20 }}
                            animate={{ scale: 1, y: 0 }}
                            exit={{ scale: 0.9, y: 20 }}
                            onClick={e => e.stopPropagation()}
                            className="w-full max-w-lg bg-slate-900 border border-amber-500/30 rounded-[2.5rem] p-6 shadow-2xl overflow-hidden flex flex-col"
                        >
                            <div className="flex items-center justify-between pb-4 border-b border-white/10 mb-4">
                                <div className="flex items-center gap-2">
                                    <Icons.Info size={20} className="text-amber-400" />
                                    <h3 className="text-lg font-black text-white uppercase tracking-wider">
                                        {t.paytable || "Ödeme Tablosu"}
                                    </h3>
                                </div>
                                <button
                                    onClick={() => setShowPaytable(false)}
                                    className="p-1.5 rounded-lg text-slate-400 hover:text-white"
                                >
                                    <Icons.XCircle size={20} />
                                </button>
                            </div>

                            <div className="space-y-3 max-h-[60vh] overflow-y-auto pr-1 custom-scrollbar">
                                <div className="p-3 rounded-xl bg-amber-500/10 border border-amber-500/20 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">💎💎💎</span>
                                        <div>
                                            <p className="text-xs font-black text-amber-300">3x {lang === 'TR' ? 'Elmas (Jackpot)' : 'Diamond (Jackpot)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '100x Bahis Kazancı' : '100x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-amber-300 tabular-nums">100x ({formatMoney(bet * 100)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">👑👑👑</span>
                                        <div>
                                            <p className="text-xs font-black text-yellow-400">3x {lang === 'TR' ? 'Taç (Grand)' : 'Crown (Grand)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '50x Bahis Kazancı' : '50x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-yellow-400 tabular-nums">50x ({formatMoney(bet * 50)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">7️⃣7️⃣7️⃣</span>
                                        <div>
                                            <p className="text-xs font-black text-rose-400">3x {lang === 'TR' ? 'Yedi (Major)' : 'Seven (Major)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '25x Bahis Kazancı' : '25x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-rose-400 tabular-nums">25x ({formatMoney(bet * 25)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">🔔🔔🔔</span>
                                        <div>
                                            <p className="text-xs font-black text-yellow-300">3x {lang === 'TR' ? 'Zil (Minor)' : 'Bell (Minor)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '10x Bahis Kazancı' : '10x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-yellow-300 tabular-nums">10x ({formatMoney(bet * 10)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">🍀🍀🍀</span>
                                        <div>
                                            <p className="text-xs font-black text-emerald-400">3x {lang === 'TR' ? 'Yonca (Mini)' : 'Clover (Mini)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '5x Bahis Kazancı' : '5x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-emerald-400 tabular-nums">5x ({formatMoney(bet * 5)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">🍒🍒🍒</span>
                                        <div>
                                            <p className="text-xs font-black text-pink-400">3x {lang === 'TR' ? 'Kiraz' : 'Cherry'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? '3x Bahis Kazancı' : '3x Bet Win'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-pink-400 tabular-nums">3x ({formatMoney(bet * 3)})</span>
                                </div>

                                <div className="p-3 rounded-xl bg-slate-800/60 border border-white/5 flex items-center justify-between">
                                    <div className="flex items-center gap-3">
                                        <span className="text-2xl">🍒🍒❌</span>
                                        <div>
                                            <p className="text-xs font-black text-pink-300">2x {lang === 'TR' ? 'Kiraz (Amorti)' : 'Cherry (Break-Even)'}</p>
                                            <p className="text-[10px] text-slate-400">{lang === 'TR' ? 'Bahis İadesi' : 'Bet Refund'}</p>
                                        </div>
                                    </div>
                                    <span className="text-xs font-black text-pink-300 tabular-nums">1x ({formatMoney(bet)})</span>
                                </div>
                            </div>

                            <div className="mt-4 p-3 rounded-xl bg-slate-950/80 border border-white/5 text-[11px] text-slate-400">
                                <p>ℹ️ {t.slotOddsNote || "Çarpan arttıkça jackpot ikramiyesi büyür, kazanma olasılığı orantılı olarak dengelenir."}</p>
                            </div>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>
        </div>
    );
}

window.LuckySlot = LuckySlot;
