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

const API_URL = window.location.hostname === 'localhost' || window.location.hostname === '127.0.0.1' || window.location.hostname === ''
    ? 'http://localhost:3001'
    : 'https://api.tmn-studio.cloud';

function App() {
    const Icons = window.Icons;
    const OneMoreDice = window.OneMoreDice;
    const CardPath = window.CardPath;
    const AnalyticsDashboard = window.AnalyticsDashboard;
    const Auth = window.Auth;
    const Lobby = window.Lobby;
    const GameOver = window.GameOver;
    const Leaderboard = window.Leaderboard;
    const Unlocks = window.Unlocks;
    const BankerOffer = window.BankerOffer;
    const DailyPopup = window.DailyPopup;
    const Shop = window.Shop;
    const DebtPanel = window.DebtPanel;

    const [activeGame, setActiveGame] = useState('none');
    const [cpStep, setCpStep] = useState(1);
    const [cpPot, setCpPot] = useState(0);
    const [cpStatus, setCpStatus] = useState('none');
    const [cpDeck, setCpDeck] = useState([]);
    const [cpSelection, setCpSelection] = useState([]);
    const [cpKeptIds, setCpKeptIds] = useState([]);
    const [cpDiscardedIds, setCpDiscardedIds] = useState([]);
    const [cpKeepChoice, setCpKeepChoice] = useState(null);
    const [cpRounds, setCpRounds] = useState(10);
    const [cpRemovingIds, setCpRemovingIds] = useState([]);
    const [cpVanishIds, setCpVanishIds] = useState([]);
    const [cpRevealedIds, setCpRevealedIds] = useState([]);
    const [cpRemovedCards, setCpRemovedCards] = useState([]);

    const [lang, setLang] = useState('TR');
    const [gameState, setGameState] = useState('auth');
    const [authMode, setAuthMode] = useState('login');
    const [authLoading, setAuthLoading] = useState(false);
    const [authError, setAuthError] = useState('');
    const [currentUser, setCurrentUser] = useState(null);
    const [token, setToken] = useState(() => localStorage.getItem('luck_token'));
    const [loginData, setLoginData] = useState({ username: '', password: '' });

    const [playerName, setPlayerName] = useState('');
    const [balance, setBalance] = useState(0);
    const [adminStats, setAdminStats] = useState({
        oneMoreDice: { totalGames: 0, avgWin: 0, houseEdge: 0 },
        cardPath: { totalGames: 0, avgPot: 0, winRate: 0, totalCasinoImpact: 0, highScore: 0 }
    });

    const [round, setRound] = useState(1);
    const [currentDice, setCurrentDice] = useState(null);
    const [currentImpact, setCurrentImpact] = useState(null);
    const [currentOffer, setCurrentOffer] = useState(0);
    const [isRolling, setIsRolling] = useState(false);
    const [history, setHistory] = useState([]);
    const [choices, setChoices] = useState([]);
    const [endReason, setEndReason] = useState('');

    const [totalWealth, setTotalWealth] = useState(0);
    const [xp, setXp] = useState(0);
    const [houseBank, setHouseBank] = useState(0);
    const [dailyPlays, setDailyPlays] = useState(0);
    const [leaderboard, setLeaderboard] = useState([]);
    const [lbLoading, setLbLoading] = useState(false);
    const [lbError, setLbError] = useState(null);
    const [lastRank, setLastRank] = useState(null);
    const [lastSubmissionTime, setLastSubmissionTime] = useState(null);
    const [diceSkin, setDiceSkin] = useState('default');
    const [showLeaderboard, setShowLeaderboard] = useState(false);
    const [showUnlocks, setShowUnlocks] = useState(false);
    const [showAdminStats, setShowAdminStats] = useState(false);
    const [adminKey, setAdminKey] = useState('');
    const [sortBy, setSortBy] = useState('score');
    const [sortOrder, setSortOrder] = useState('desc');
    const [showDailyPopup, setShowDailyPopup] = useState(false);
    const [dailyPopupData, setDailyPopupData] = useState({
        tokensGranted: window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3
    });

    const [showShop, setShowShop] = useState(false);
    const [showDebtPanel, setShowDebtPanel] = useState(false);
    const [userProfile, setUserProfile] = useState(null);
    const [diceShieldActive, setDiceShieldActive] = useState(false);
    const [itemAnimation, setItemAnimation] = useState(null);
    const [insuranceSaved, setInsuranceSaved] = useState(0);
    const [hasInteracted, setHasInteracted] = useState(false);

    const [translationsData, setTranslationsData] = useState(null);

    useEffect(() => {
        Promise.all([
            fetch('locales/tr.json').then(r => r.json()),
            fetch('locales/en.json').then(r => r.json())
        ]).then(([tr, en]) => {
            setTranslationsData({ TR: tr, EN: en });
        }).catch(err => {
            console.error("Lokalizasyon yüklenemedi.", err);
        });
    }, []);

    const t = translationsData ? translationsData[lang] : {};

    useEffect(() => {
        if (token) {
            checkAuthStatus();
        } else {
            setGameState('auth');
        }
    }, [token]);

    const syncUserProfile = (userData) => {
        const isAppAdmin = userData.username.toLowerCase() === 'admin';
        const finalUser = {
            ...userData,
            totalWealth: isAppAdmin ? Infinity : userData.totalWealth,
            xp: isAppAdmin ? Infinity : userData.xp
        };

        setCurrentUser(finalUser);
        setUserProfile(finalUser);
        setTotalWealth(finalUser.totalWealth);
        setXp(finalUser.xp);
        setDailyPlays(finalUser.dailyPlays);
        setPlayerName(finalUser.username);

        if (userData.inventory?.diceShield) {
            setDiceShieldActive(true);
        }
    };

    const checkAuthStatus = async () => {
        try {
            const res = await fetch(`${API_URL}/api/auth/me`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
                setGameState('lobby');
                if (json.isNewDay && json.user.username.toLowerCase() !== 'admin') {
                    setDailyPopupData({
                        tokensGranted: json.tokensGranted || (window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3)
                    });
                    setTimeout(() => setShowDailyPopup(true), 800);
                }
            } else {
                handleLogout();
            }
        } catch (err) {
            handleLogout();
        }
    };

    const handleAuth = async (e) => {
        e.preventDefault();
        setAuthLoading(true);
        setAuthError('');
        try {
            const endpoint = authMode === 'login' ? '/api/auth/login' : '/api/auth/register';
            const res = await fetch(`${API_URL}${endpoint}`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify(loginData)
            });
            const json = await res.json();
            if (json.success) {
                setToken(json.token);
                localStorage.setItem('luck_token', json.token);
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
                setGameState('lobby');
                if (json.isNewDay && json.user.username.toLowerCase() !== 'admin') {
                    setDailyPopupData({
                        tokensGranted: json.tokensGranted || (window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3)
                    });
                    setTimeout(() => setShowDailyPopup(true), 800);
                }
            } else {
                setAuthError(json.error || (authMode === 'login' ? t.authError : t.regError));
            }
        } catch (err) {
            setAuthError(t.serverError);
        } finally {
            setAuthLoading(false);
        }
    };

    const handleGameExit = async () => {
        if ((gameState === 'playing' || gameState === 'banker') && hasInteracted) {
            let exitBalance = balance;
            if (activeGame === 'cardPath' && cpPot > 0) {
                exitBalance = balance + cpPot;
            }
            const finalChoices = [...choices, t.exitLogout || "Exit/Logout"];
            await updateProgression(exitBalance, finalChoices, true);
        }
    };

    const handleLogout = async () => {
        await handleGameExit();
        setToken(null);
        setCurrentUser(null);
        setUserProfile(null);
        localStorage.removeItem('luck_token');
        setGameState('auth');
    };

    const returnToHome = async () => {
        if ((gameState === 'playing' || gameState === 'banker') && hasInteracted) {
            if (!confirm(t.confirmBackToHome)) return;
            await handleGameExit();
        }
        resetGame();
        setGameState('lobby');
    };

    const fetchLeaderboard = useCallback(async () => {
        setLbLoading(true);
        setLbError(null);
        try {
            const res = await fetch(`${API_URL}/api/leaderboard`, {
                headers: { 'Authorization': `Bearer ${token}` }
            });
            const json = await res.json();
            if (json.success) {
                const rankedData = json.data.map((entry, index) => ({
                    ...entry,
                    globalRank: index + 1
                }));
                setLeaderboard(rankedData);
                setHouseBank(json.houseBank);
            }
        } catch (err) {
            setLbError(t.serverError);
        } finally {
            setLbLoading(false);
        }
    }, [token, t.serverError]);

    useEffect(() => {
        fetchLeaderboard();
    }, []);

    const fetchAdminStats = async () => {
        let key = adminKey;
        if (currentUser?.username === 'admin') {
            key = 'lucky-admin-2024';
        } else {
            key = adminKey || prompt("Enter Admin Key:");
        }

        if (!key) return;
        try {
            const res = await fetch(`${API_URL}/api/admin/stats`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ adminKey: key })
            });
            const json = await res.json();
            if (json.success) {
                setAdminStats(json.stats);
                setAdminKey(key);
                setShowAdminStats(true);
            } else {
                alert("Unauthorized");
            }
        } catch (err) { alert("Server error"); }
    };

    const resetSystem = async () => {
        if (!confirm(lang === 'TR' ? "DİKKAT: Tüm veriler tamamen SİLİNECEK! Emin misiniz?" : "WARNING: All data will be DELETED! Are you sure?")) return;

        try {
            const res = await fetch(`${API_URL}/api/admin/reset`, {
                method: 'DELETE',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ adminKey: adminKey })
            });
            const json = await res.json();
            if (json.success) {
                alert(lang === 'TR' ? "Sistem başarıyla sıfırlandı!" : "System reset successful!");
                handleLogout();
            } else {
                alert("Reset failed: " + (json.error || "Unauthorized"));
            }
        } catch (err) { alert("Server error during reset"); }
    };

    useEffect(() => {
        if (showLeaderboard) {
            fetchLeaderboard();
        }
    }, [showLeaderboard]);

    useEffect(() => {
        const handleBeforeUnload = (e) => {
            if (gameState === 'playing' || gameState === 'banker') {
                handleGameExit();
            }
        };
        window.addEventListener('beforeunload', handleBeforeUnload);
        return () => window.removeEventListener('beforeunload', handleBeforeUnload);
    }, [gameState, balance, cpPot, choices, activeGame]);

    const skins = [
        { id: 'default', name: 'Original', color: 'text-slate-600', req: 0, glow: 'bg-indigo-500/5' },
        { id: 'gold', name: 'Gold Rush', color: 'text-amber-400', req: 1000000, glow: 'bg-amber-500/20' },
        { id: 'platinum', name: 'Platinum Elite', color: 'text-cyan-400', req: 5000000, glow: 'bg-cyan-500/30' },
        { id: 'premium', name: 'Neon Phantom', color: 'text-purple-400', req: -1, glow: 'bg-purple-500/40', isPurchasable: true, neon: true }
    ];

    const formatMoney = (amount) => {
        if (amount === Infinity) return '∞';
        return new Intl.NumberFormat(lang === 'TR' ? 'tr-TR' : 'en-US', {
            style: 'currency',
            currency: 'USD',
            minimumFractionDigits: 0,
            maximumFractionDigits: 0,
        }).format(amount);
    };

    const handleRestart = () => {
        resetGame();
        if (activeGame === 'cardPath') {
            initCardPath();
        }
        setGameState('playing');
    };

    const handleStart = (e) => {
        if (e) e.preventDefault();
        handleRestart();
    };

    const generateCardPathDeck = (applyRemover = false) => {
        const cfg = (window.GAME_CONFIG?.cardPath) || {};
        const mult = cfg.REWARD_MULTIPLIER || 10000;
        const maxR = cfg.MAX_REWARD || 100;
        const minR = cfg.MIN_REWARD || -100;
        const totalRounds = cfg.TOTAL_ROUNDS || 10;
        const totalCards = totalRounds * 2;
        const pos = maxR * mult;
        const half = Math.round((maxR / 2)) * mult;
        const quarter = Math.round((maxR / 4)) * mult;
        const tenth = Math.round((maxR / 10)) * mult;
        const neg = minR * mult;
        const nhalf = Math.round((minR / 2)) * mult;
        const nquarter = Math.round((minR / 4)) * mult;
        const ntenth = Math.round((minR / 10)) * mult;
        const neutralCount = Math.max(2, Math.round(totalCards * 0.2));
        const sideCount = totalCards - neutralCount;
        const posHalf = Math.floor(sideCount / 2);
        const negHalf = sideCount - posHalf;
        const posPool = [pos, pos, half, half, quarter, quarter, tenth, tenth];
        const negPool = [neg, neg, nhalf, nhalf, nquarter, nquarter, ntenth, ntenth];
        const pick = (arr, n) => {
            const result = [];
            for (let i = 0; i < n; i++) result.push(arr[i % arr.length]);
            return result;
        };

        let values = [
            ...pick(posPool, posHalf),
            ...Array(neutralCount).fill(0),
            ...pick(negPool, negHalf)
        ];

        return values.sort(() => Math.random() - 0.5).map((v, i) => ({
            id: `card-${i}-${Math.random().toString(36).substr(2, 9)}`,
            v
        }));
    };

    const initCardPath = async () => {
        let deck = generateCardPathDeck();
        setCpDeck(deck);
        setCpRounds(10);
        setCpStep(1);
        setCpPot(0);
        setCpStatus('selecting');
        setCpSelection([]);
        setCpKeptIds([]);
        setCpDiscardedIds([]);
        setCpVanishIds([]);
        setCpRevealedIds([]);
        setCpRemovedCards([]);

        if (userProfile?.inventory?.cardRemover) {
            setCpStatus('removing');
            const removeCount = window.GAME_CONFIG?.shop?.cardRemover?.REMOVE_COUNT || 2;
            
            // Find bad/neutral cards
            const badPool = deck.filter(card => card.v <= 0);
            const shuffledBad = [...badPool].sort(() => Math.random() - 0.5);
            
            const toRemoveObjects = shuffledBad.slice(0, removeCount);
            const toRemoveIds = toRemoveObjects.map(card => card.id);
            setCpRemovingIds(toRemoveIds);
            setCpRemovedCards(toRemoveObjects);

            setHasInteracted(true);
            handleUseItem('cardRemover');
            setItemAnimation({ type: 'cardRemover', message: t.cleaningCards });

            // Step 2: Sequential Reveal and Vanish
            for (let i = 0; i < toRemoveIds.length; i++) {
                const id = toRemoveIds[i];
                
                // Reveal
                setCpRevealedIds(prev => [...prev, id]);
                await new Promise(r => setTimeout(r, 1200)); // Increased wait to see content
                
                // Vanish
                setCpVanishIds(prev => [...prev, id]);
                await new Promise(r => setTimeout(r, 800));
            }

            // Wait for final animations to finish
            await new Promise(r => setTimeout(r, 1000));
            setItemAnimation(null);
            setCpRevealedIds([]);

            // Step 3: Finalize deck
            const finalDeck = deck.filter(card => !toRemoveIds.includes(card.id));
            setCpDeck(finalDeck);
            setCpRounds(Math.floor(finalDeck.length / 2));
            setCpRemovingIds([]);
            setCpVanishIds([]);
            setCpStatus('selecting');
        }
    };

    const resetGame = () => {
        setBalance(0);
        setRound(1);
        setCurrentDice(null);
        setCurrentImpact(null);
        setHistory([]);
        setChoices([]);
        setEndReason('');
        setCpStep(1);
        setCpPot(0);
        setCpStatus('none');
        setCpDeck([]);
        setCpSelection([]);
        setCpKeptIds([]);
        setCpDiscardedIds([]);
        setCpRevealedIds([]);
        setCpRemovedCards([]);
        setInsuranceSaved(0);
        setHasInteracted(false);
    };

    const calculateOffer = (currentValue, currentRoundOrStep) => {
        const gameCfg = activeGame === 'cardPath'
            ? (window.GAME_CONFIG?.cardPath || {})
            : (window.GAME_CONFIG?.oneMoreDice || {});
        const totalRounds = gameCfg.TOTAL_ROUNDS || 10;
        const mult = gameCfg.REWARD_MULTIPLIER || 10000;
        let offer = 0;

        if (activeGame === 'cardPath') {
            if (currentValue < 0) {
                offer = currentValue * 1.1;
            } else {
                offer = currentValue * 0.9;
            }
        } else {
            if (currentValue < 0) {
                offer = currentValue * 0.7;
            } else {
                const nearEnd = Math.floor(totalRounds * 0.8);
                if (currentRoundOrStep >= nearEnd) {
                    const riskPremium = (5 * mult) * (totalRounds - currentRoundOrStep);
                    offer = currentValue + riskPremium;
                } else {
                    offer = currentValue * 0.9;
                }
            }
        }
        return Math.round(offer / 1000) * 1000;
    };

    const rollDice = () => {
        const cfg = window.GAME_CONFIG?.oneMoreDice || {};
        const totalRounds = cfg.TOTAL_ROUNDS || 10;
        const mult = cfg.REWARD_MULTIPLIER || 10000;
        setIsRolling(true);
        let rolls = 0;
        const maxRolls = 25;

        const rollInterval = setInterval(() => {
            setCurrentDice(Math.floor(Math.random() * 100) + 1);
            rolls++;

            if (rolls >= maxRolls) {
                clearInterval(rollInterval);
                let finalDice = Math.floor(Math.random() * 100) + 1;

                if (finalDice < 50 && diceShieldActive && userProfile?.inventory?.diceShield) {
                    finalDice = 50;
                    setDiceShieldActive(false);
                    setHasInteracted(true);
                    handleUseItem('diceShield');
                    setItemAnimation({ type: 'diceShield', message: t.shieldActivated });
                    setTimeout(() => setItemAnimation(null), 2500);
                }

                setHasInteracted(true);
                setCurrentDice(finalDice);

                const startMult = cfg.STARTING_MULTIPLIER || 5000;
                const growth = cfg.MULTIPLIER_GROWTH_RATE || 1;
                const multiplier = startMult * (1 + (round - 1) * growth);
                const impact = (finalDice - 50) * multiplier;
                setCurrentImpact(impact);

                setBalance(prev => {
                    const newBalance = prev + impact;
                    setHistory(historyPrev => [...historyPrev, {
                        round: round,
                        dice: finalDice,
                        multiplier: multiplier,
                        impact: impact,
                        balanceAfter: newBalance
                    }]);

                    setTimeout(() => {
                        if (round === totalRounds) {
                            transitionToGameOver(t.reasonCompleted, newBalance, choices);
                        } else {
                            const offer = calculateOffer(newBalance, round);
                            setCurrentOffer(offer);
                            setGameState('banker');
                        }
                    }, 1500);

                    return newBalance;
                });
                setIsRolling(false);
            }
        }, 40);
    };

    const [cpRevealing, setCpRevealing] = useState(null);

    const handleCardSelect = (id) => {
        if (cpStatus === 'revealing') return;
        if (cpKeptIds.includes(id) || cpDiscardedIds.includes(id)) return;

        if (cpStatus === 'final') {
            setCpSelection([id]);
            setCpKeepChoice(id);
            return;
        }

        if (cpSelection.includes(id)) {
            setCpKeepChoice(id);
            return;
        }

        if (cpSelection.length < 2) {
            const newSel = [...cpSelection, id];
            setCpSelection(newSel);
            if (newSel.length === 2) setCpKeepChoice(id);
        } else {
            setCpSelection([id]);
            setCpKeepChoice(id);
        }
    };

    const confirmKeepChoice = async () => {
        if (cpStatus === 'revealing' || cpKeepChoice === null) return;
        setHasInteracted(true);
        const keptId = cpKeepChoice;
        const discardedId = cpSelection.find(id => id !== keptId);
        setCpStatus('revealing');

        if (discardedId !== undefined) {
            setCpRevealing('discarded');
            await new Promise(r => setTimeout(r, 750));
        }
        setCpRevealing('kept');
        await new Promise(r => setTimeout(r, 750));

        const keptCard = cpDeck.find(c => c.id === keptId);
        const keptValue = keptCard.v;
        setCpPot(prev => prev + keptValue);
        setCpKeptIds(prev => [...prev, keptId]);
        if (discardedId !== undefined) setCpDiscardedIds(prev => [...prev, discardedId]);

        setHistory(prev => [...prev, {
            round: cpStep,
            choice: 'Card', 
            impact: keptValue,
            potAfter: cpPot + keptValue,
            type: keptValue >= 0 ? 'safe' : 'trap'
        }]);

        setCpRevealing(null);
        setCpSelection([]);
        setCpKeepChoice(null);

        const finalPot = cpPot + keptValue;
        if (cpStep < cpRounds) {
            setTimeout(() => {
                setCurrentOffer(calculateOffer(finalPot, cpStep));
                setGameState('banker');
            }, 1000);
        } else {
            setBalance(prev => prev + finalPot);
            transitionToGameOver(t.gameCompleted, finalPot, choices);
        }
    };

    const nextCardStep = () => {
        if (cpStep === cpRounds - 1) {
            setCpStep(cpRounds);
            setCpStatus('final');
        } else {
            setCpStep(prev => prev + 1);
            setCpStatus('selecting');
        }
    };

    const updateProgression = async (finalBalance, finalChoices, isEmergency = false) => {
        const isCompletedStatus = activeGame === 'cardPath'
            ? (cpStep === 10 && endReason !== t.reasonAccepted)
            : (round === 10 && endReason !== t.reasonAccepted);
        const currentRoundOrStep = activeGame === 'cardPath' ? cpStep : round;

        try {
            const res = await fetch(`${API_URL}/api/leaderboard`, {
                method: 'POST',
                keepalive: isEmergency,
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({
                    score: finalBalance,
                    gameType: activeGame,
                    xp: Math.max(0, Math.floor(finalBalance / 1000)),
                    roundsPlayed: currentRoundOrStep,
                    choices: finalChoices || choices,
                    isCompleted: isCompletedStatus || isEmergency
                })
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
                fetchLeaderboard();
                if (json.insuranceApplied) {
                    const saved = json.insuranceSaved || 0;
                    setInsuranceSaved(saved);
                    setBalance(prev => prev + saved);
                    setItemAnimation({ 
                        type: 'insurance', 
                        message: `${t.insuranceActivated}${saved > 0 ? ` (${formatMoney(saved)})` : ''}` 
                    });
                    setTimeout(() => setItemAnimation(null), 3500);
                }
            } else if (json.error) {
                alert(json.error);
            }
        } catch (err) {
            console.error('Leaderboard submit failed');
        }
    };

    const transitionToGameOver = (reason, finalBalance, finalChoices) => {
        setEndReason(reason);
        updateProgression(finalBalance, finalChoices);
        setGameState('end');
    };

    const acceptOffer = () => {
        const finalBalance = currentOffer;
        if (activeGame === 'cardPath') {
            const finalChoices = [...choices, `Step ${cpStep}: ${t.cashOut}`];
            setChoices(finalChoices);
            setBalance(finalBalance);
            transitionToGameOver(t.reasonAccepted, finalBalance, finalChoices);
        } else {
            const finalChoices = [...choices, `Round ${round}: ${t.acceptOffer}`];
            setChoices(finalChoices);
            setBalance(finalBalance);
            transitionToGameOver(t.reasonAccepted, finalBalance, finalChoices);
        }
    };

    const rejectOffer = () => {
        if (activeGame === 'cardPath') {
            setChoices(prev => [...prev, `Step ${cpStep}: ${t.takeRisk}`]);
            setGameState('playing');
            nextCardStep();
        } else {
            setChoices(prev => [...prev, `Round ${round}: ${t.rejectOffer}`]);
            setRound(prev => prev + 1);
            setCurrentDice(null);
            setCurrentImpact(null);
            setGameState('playing');
        }
    };

    const handlePurchase = async (itemType) => {
        try {
            const res = await fetch(`${API_URL}/api/shop/buy`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ itemType })
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error || t.notEnoughMoney);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const handleEquip = async (itemType) => {
        try {
            const res = await fetch(`${API_URL}/api/shop/equip`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ itemType })
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                if (itemType.includes('Skin')) {
                    setDiceSkin(itemType.replace('Skin', '').toLowerCase());
                }
            }
        } catch (err) {
            console.error('Item equip failed');
        }
    };

    const handleUseItem = async (itemType) => {
        try {
            const res = await fetch(`${API_URL}/api/shop/use`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ itemType })
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
            }
        } catch (err) {
            console.error('Item use failed');
        }
    };

    const handleBuyShare = async () => {
        try {
            const res = await fetch(`${API_URL}/api/shares/buy`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error || t.notEnoughMoney);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const handleClaimDividend = async () => {
        try {
            const res = await fetch(`${API_URL}/api/shares/claim`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error || t.sharesNoDividend);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const handleAdWatch = async () => {
        try {
            const res = await fetch(`${API_URL}/api/debt/ad-watch`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const handleClickerSubmit = async (clicks) => {
        try {
            const res = await fetch(`${API_URL}/api/debt/clicker`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                },
                body: JSON.stringify({ clicks })
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const handleSalaryClaim = async () => {
        try {
            const res = await fetch(`${API_URL}/api/debt/salary`, {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    'Authorization': `Bearer ${token}`
                }
            });
            const json = await res.json();
            if (json.success) {
                syncUserProfile(json.user);
                setHouseBank(json.houseBank);
            } else {
                alert(json.error);
            }
        } catch (err) {
            alert(t.serverError);
        }
    };

    const downloadLogFile = () => {
        const timestamp = new Date().toLocaleString(lang === 'TR' ? 'tr-TR' : 'en-US');
        let logContent = `--- ${t.title} LOG ---\n`;
        logContent += `${lang === 'TR' ? 'Oyuncu' : 'Player'}: ${playerName}\n`;
        logContent += `${lang === 'TR' ? 'Tarih' : 'Date'}: ${timestamp}\n`;
        logContent += `${lang === 'TR' ? 'Son Bakiye' : 'Final Balance'}: ${formatMoney(balance)}\n`;
        logContent += `${lang === 'TR' ? 'Bitiş Sebebi' : 'End Reason'}: ${endReason}\n\n`;
        logContent += `--- ${lang === 'TR' ? 'GEÇMİŞ' : 'HISTORY'} ---\n`;
        history.forEach(h => {
            logContent += `Round ${h.round}: Dice=${h.dice} | Multiplier=${formatMoney(h.multiplier)} | Impact=${formatMoney(h.impact)} | Balance=${formatMoney(h.balanceAfter)}\n`;
        });
        const blob = new Blob([logContent], { type: 'text/plain;charset=utf-8' });
        const url = URL.createObjectURL(blob);
        const link = document.createElement('a');
        link.href = url;
        link.download = `TrustYourLuck_Log_${playerName}_${Date.now()}.txt`;
        document.body.appendChild(link);
        link.click();
        document.body.removeChild(link);
    };

    const getBalanceColor = (amount) => {
        if (amount === Infinity) return 'text-amber-400';
        if (amount > 0) return 'text-emerald-400';
        if (amount < 0) return 'text-rose-500';
        return 'text-slate-200';
    };

    if (!translationsData) return (
        <div className="min-h-screen bg-slate-950 flex flex-col items-center justify-center p-6 text-white text-center">
            <Icons.Loader size={48} className="text-emerald-400 mb-6" />
            <p className="text-xl mb-4 text-emerald-400 font-bold tracking-widest uppercase">Initializing Modules</p>
            <p className="text-slate-500 max-w-md text-sm">Please ensure you are loading this application via a local web server (HTTP/HTTPS).</p>
        </div>
    );

    return (
        <div className="min-h-screen text-slate-100 flex flex-col relative overflow-hidden">
            <div className="absolute top-[-20%] left-[-10%] w-[60%] h-[60%] bg-indigo-600/10 blur-[120px] rounded-full pointer-events-none"></div>
            <div className="absolute bottom-[-20%] right-[-10%] w-[60%] h-[60%] bg-cyan-600/10 blur-[120px] rounded-full pointer-events-none"></div>

            <AnimatePresence>
                {itemAnimation && (
                    <motion.div initial={{ opacity: 0 }} animate={{ opacity: 1 }} exit={{ opacity: 0 }} className="fixed inset-0 z-50 flex flex-col items-center justify-center pointer-events-none bg-slate-950/40 backdrop-blur-[2px]">
                        <motion.div initial={{ scale: 0.5, rotate: -15 }} animate={{ scale: 1, rotate: 0 }} exit={{ scale: 1.2, opacity: 0 }} transition={{ type: 'spring', bounce: 0.5 }} className="flex flex-col items-center">
                            <div className={`p-8 rounded-[2rem] shadow-[0_0_100px_rgba(255,255,255,0.4)] ${itemAnimation.type === 'diceShield' ? 'bg-sky-500 text-white' : itemAnimation.type === 'insurance' ? 'bg-emerald-500 text-white' : 'bg-amber-500 text-white'}`}>
                                {itemAnimation.type === 'diceShield' ? <Icons.ShieldCheck size={80} /> : itemAnimation.type === 'insurance' ? <Icons.Briefcase size={80} /> : <Icons.Ban size={80} />}
                            </div>
                            <h2 className={`text-4xl md:text-5xl font-black mt-8 tracking-widest text-center uppercase drop-shadow-[0_0_20px_rgba(255,255,255,1)] ${itemAnimation.type === 'diceShield' ? 'text-sky-400' : itemAnimation.type === 'insurance' ? 'text-emerald-400' : 'text-amber-400'}`}>
                                {itemAnimation.message}
                            </h2>
                        </motion.div>
                    </motion.div>
                )}
            </AnimatePresence>

            <DailyPopup showDailyPopup={showDailyPopup} setShowDailyPopup={setShowDailyPopup} dailyPopupData={dailyPopupData} t={t} formatMoney={formatMoney} Icons={Icons} />

            <div className={`fixed inset-0 pointer-events-none z-50 transition-all duration-1000 ${balance >= 100000 ? 'opacity-100' : 'opacity-0'}`}>
                <div className="absolute inset-0 shadow-[inset_0_0_200px_rgba(245,158,11,0.25)] mix-blend-screen"></div>
                <div className="absolute inset-0 bg-amber-500/[0.02]"></div>
            </div>
            <div className={`fixed inset-0 pointer-events-none z-50 transition-all duration-1000 ${balance < 0 ? 'opacity-100' : 'opacity-0'}`}>
                <div className="absolute inset-0 shadow-[inset_0_0_200px_rgba(225,29,72,0.25)] mix-blend-hard-light"></div>
                <div className="absolute inset-0 bg-rose-500/[0.02] border-[12px] border-rose-500/5"></div>
            </div>

            <header className="flex justify-between items-center p-6 relative z-10 border-b border-white/5 bg-slate-900/40 backdrop-blur-xl">
                <button 
                    onClick={returnToHome} 
                    className="flex items-center gap-3 hover:opacity-80 transition-all active:scale-95 group"
                    title={lang === 'TR' ? 'Ana Menüye Dön' : 'Return to Home'}
                    aria-label="Home"
                >
                    <div className="p-2.5 bg-gradient-to-br from-indigo-500 to-cyan-500 rounded-xl text-white shadow-lg shadow-indigo-500/20 group-hover:rotate-12 transition-transform">
                        <Icons.DollarSign size={24} />
                    </div>
                    <h1 className="text-2xl font-black bg-gradient-to-r from-white to-slate-400 bg-clip-text text-transparent">{t.title}</h1>
                </button>

                <div className="flex items-center gap-6">
                    <div className="hidden lg:flex flex-col items-end px-4 py-1.5 bg-amber-500/10 rounded-xl border border-amber-500/20" title={t.houseBankDesc || (lang === 'TR' ? 'Kasadaki toplam para' : 'Total money in house')}>
                        <p className="text-[10px] font-black text-amber-600 uppercase tracking-widest leading-none mb-1">{t.houseBank}</p>
                        <p className="text-sm font-black text-amber-500 leading-none">{formatMoney(houseBank)}</p>
                    </div>

                    {currentUser && (
                        <div className="hidden md:flex items-center gap-6 px-6 py-3 bg-slate-900/60 rounded-[2rem] border border-white/5 backdrop-blur-md shadow-2xl relative overflow-hidden group">
                            <div className="absolute inset-0 bg-gradient-to-r from-emerald-500/5 to-indigo-500/5 opacity-0 group-hover:opacity-100 transition-opacity duration-700"></div>

                            <div className="flex flex-col items-start gap-1 relative z-10" title={t.totalWealthDesc || (lang === 'TR' ? 'Toplam servetiniz' : 'Your total wealth')}>
                                <div className="flex items-center gap-2">
                                    <Icons.DollarSign size={14} className="text-emerald-400 group-hover:scale-110 transition-transform" />
                                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest leading-none">{t.totalWealth}</p>
                                </div>
                                <p className={`text-2xl font-black leading-none tabular-nums ${totalWealth === Infinity ? 'text-amber-400 drop-shadow-[0_0_8px_rgba(251,191,36,0.6)]' : (totalWealth >= 0 ? 'text-emerald-400' : 'text-rose-500')}`}>
                                    {formatMoney(totalWealth)}
                                </p>
                            </div>

                            <div className="w-px h-10 bg-white/10 relative z-10"></div>

                            <div className="flex flex-col items-center gap-1 relative z-10" title={t.playsLeftDesc || (lang === 'TR' ? 'Kalan oyun hakkınız' : 'Your remaining play tokens')}>
                                <div className="flex items-center gap-2">
                                    <Icons.Zap size={14} className="text-amber-400" />
                                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-widest leading-none">{t.playsLeft}</p>
                                </div>
                                <AnimatePresence mode="wait">
                                    <motion.p key={dailyPlays} initial={{ scale: 1.4, opacity: 0 }} animate={{ scale: 1, opacity: 1 }} className={`text-2xl font-black leading-none tabular-nums ${currentUser?.username === 'admin' ? 'text-amber-400' : ((window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3) - dailyPlays) === 0 ? 'text-rose-500' : 'text-indigo-400'}`}>
                                        {currentUser?.username === 'admin' ? '∞' : (window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3) - dailyPlays}
                                    </motion.p>
                                </AnimatePresence>
                            </div>
                        </div>
                    )}

                    {currentUser && (
                        <div 
                            className="flex items-center gap-4 pl-2 pr-4 py-2 bg-slate-900/40 rounded-[1.5rem] border border-white/5 hover:border-rose-500/30 transition-all duration-500 cursor-pointer group" 
                            onClick={handleLogout}
                            title={lang === 'TR' ? 'Çıkış Yap' : 'Log Out'}
                        >
                            <div className={`w-10 h-10 rounded-xl flex items-center justify-center font-black text-sm shadow-xl shadow-indigo-600/20 transition-all group-hover:scale-110 ${userProfile?.isDebtor ? 'bg-rose-600 text-white' : 'bg-gradient-to-br from-indigo-500 to-indigo-700 text-white'}`}>
                                {currentUser.username[0].toUpperCase()}
                            </div>
                            <div className="hidden lg:block">
                                <p className="text-[9px] font-black text-slate-500 uppercase tracking-[0.2em] mb-1">{lang === 'TR' ? 'Oturum' : 'Session'}</p>
                                <p className={`text-sm font-black leading-none ${userProfile?.isDebtor ? 'text-rose-400' : 'text-white group-hover:text-rose-400 transition-colors'}`}>{currentUser.username}</p>
                            </div>
                            <Icons.LogOut size={16} className="text-slate-600 group-hover:text-rose-500 transition-colors ml-2" />
                        </div>
                    )}
                    <button 
                        onClick={() => setShowShop(true)}
                        className="p-3 rounded-xl bg-slate-900/60 hover:bg-slate-800 transition-all border border-white/5 shadow-2xl group active:scale-95"
                        title={t.market}
                    >
                        <Icons.Store size={20} className="text-purple-400 group-hover:scale-110 transition-transform" />
                    </button>

                    <button onClick={() => setLang(lang === 'TR' ? 'EN' : 'TR')} className="flex items-center gap-3 px-6 py-3 rounded-full bg-slate-900/60 hover:bg-slate-800 transition-all text-[11px] font-black uppercase tracking-[0.2em] border border-white/5 shadow-2xl group active:scale-95">
                        <Icons.Globe size={16} className="text-indigo-400 group-hover:rotate-12 transition-transform" />
                        <span className="text-slate-300 group-hover:text-white transition-colors">{lang === 'TR' ? 'English' : 'Türkçe'}</span>
                    </button>
                </div>
            </header>

            <main className="flex-1 flex flex-col items-center justify-center p-4 sm:p-8 relative z-10">
                {gameState === 'auth' && <Auth authMode={authMode} setAuthMode={setAuthMode} loginData={loginData} setLoginData={setLoginData} handleAuth={handleAuth} authLoading={authLoading} authError={authError} t={t} Icons={Icons} />}

                {gameState === 'lobby' && <Lobby t={t} lang={lang} setActiveGame={setActiveGame} setGameState={setGameState} Icons={Icons} userProfile={userProfile} setShowShop={setShowShop} setShowDebtPanel={setShowDebtPanel} />}

                {gameState === 'start' && (
                    <div className="w-full max-w-md glass-card p-10 rounded-[2.5rem] shadow-2xl flex flex-col items-center">
                        <div className="w-24 h-24 bg-gradient-to-br from-indigo-500 to-indigo-600 text-white rounded-[2rem] flex items-center justify-center mb-8 shadow-2xl shadow-indigo-500/40 rotate-3 transition-transform hover:rotate-0">
                            {activeGame === 'cardPath' ? <Icons.DollarSign size={48} /> : <Icons.Dices size={48} />}
                        </div>
                        <h2 className="text-4xl font-black mb-2 text-center text-white">{activeGame === 'cardPath' ? t.cardPathTitle : t.oneMoreDiceTitle}</h2>
                        <p className="text-slate-400 mb-10 text-center font-medium">{t.subtitle}</p>

                        <div className="w-full space-y-6">
                            <div className="grid grid-cols-2 gap-4 mb-6">
                                <div className="bg-slate-900/50 rounded-2xl p-4 border border-white/5">
                                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-wider">{t.totalWealth}</p>
                                    <p className="text-lg font-black text-amber-500">{formatMoney(totalWealth)}</p>
                                </div>
                                <div className="bg-slate-900/50 rounded-2xl p-4 border border-white/5">
                                    <p className="text-[10px] font-black text-slate-500 uppercase tracking-wider">{t.playsLeft}</p>
                                    <p className={`text-lg font-black ${dailyPlays >= (window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3) && currentUser?.username !== 'admin' ? 'text-rose-500' : 'text-indigo-400'}`}>
                                        {currentUser?.username === 'admin' ? (lang === 'TR' ? 'Sınırsız ♾️' : 'Unlimited ♾️') : `${(window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3) - dailyPlays} / ${window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3}`}
                                    </p>
                                </div>
                            </div>

                            {userProfile?.inventory && (Object.values(userProfile.inventory).some(v => v)) && (
                                <div className="bg-purple-500/10 border border-purple-500/20 rounded-2xl p-4">
                                    <p className="text-[10px] font-black text-purple-400 uppercase tracking-wider mb-2">{t.active} {lang === 'TR' ? 'E\u015EYALAR' : 'ITEMS'}</p>
                                    <div className="flex gap-2 flex-wrap">
                                        {userProfile.inventory.diceShield && <span title={t.diceShieldDesc || "Zarda 50 altı gelmesini bir kez önler."} className="px-2 py-1 bg-sky-500/20 text-sky-400 text-[10px] font-black rounded-lg border border-sky-500/20 cursor-help">🛡️ {t.diceShieldName}</span>}
                                        {userProfile.inventory.cardRemover && <span title={t.cardRemoverDesc || "Kart yolundaki en kötü 2 kartı siler."} className="px-2 py-1 bg-amber-500/20 text-amber-400 text-[10px] font-black rounded-lg border border-amber-500/20 cursor-help">🃏 {t.cardRemoverName}</span>}
                                        {userProfile.inventory.insurance && <span title={t.insuranceDesc || "Borcun yarısını kasa karşılar."} className="px-2 py-1 bg-emerald-500/20 text-emerald-400 text-[10px] font-black rounded-lg border border-emerald-500/20 cursor-help">🔒 {t.insuranceName}</span>}
                                    </div>
                                </div>
                            )}

                            <div className="flex gap-2 w-full">
                                <button type="button" onClick={() => setShowLeaderboard(true)} className="flex-1 py-4 rounded-xl bg-slate-800 hover:bg-slate-700 transition-colors text-white font-bold text-sm flex items-center justify-center gap-2"><Icons.User size={18} /> {t.leaderboard}</button>
                                <button type="button" onClick={() => setShowUnlocks(true)} className="flex-1 py-4 rounded-xl bg-indigo-600/20 hover:bg-indigo-600/30 transition-colors text-indigo-400 font-bold text-sm flex items-center justify-center gap-2"><Icons.Dices size={18} /> {t.unlocks}</button>
                            </div>

                            {currentUser?.username === 'admin' && (
                                <button type="button" onClick={fetchAdminStats} className="w-full flex items-center justify-center p-3 bg-slate-500/5 hover:bg-slate-500/10 border border-white/5 rounded-2xl transition-all opacity-40 hover:opacity-100 gap-2 mb-2"><Icons.Activity size={14} className="text-slate-500" /><span className="text-[10px] font-black text-slate-500 uppercase tracking-widest leading-none">Admin Insights</span></button>
                            )}

                            <button onClick={handleStart} disabled={((dailyPlays >= (window.GAME_CONFIG?.DAILY_MAX_PLAYS || 3)) && currentUser?.username !== 'admin') || houseBank <= 0} className="w-full py-5 rounded-2xl bg-gradient-to-r from-indigo-600 to-indigo-500 hover:from-indigo-500 hover:to-indigo-400 text-white font-black text-xl shadow-xl shadow-indigo-600/20 hover:scale-[1.02] active:scale-95 transition-all flex items-center justify-center gap-3 disabled:opacity-50 disabled:grayscale"><Icons.Play size={24} /> {t.startBtn}</button>
                        </div>
                    </div>
                )}

                {(gameState === 'playing' || gameState === 'banker') && (
                    <>
                        {activeGame === 'oneMoreDice' && <OneMoreDice t={t} round={round} balance={balance} currentDice={currentDice} currentImpact={currentImpact} isRolling={isRolling} rollDice={rollDice} skins={skins} diceSkin={diceSkin} formatMoney={formatMoney} getBalanceColor={getBalanceColor} history={history} />}
                        {activeGame === 'cardPath' && <CardPath t={t} cpStep={cpStep} cpRounds={cpRounds} cpPot={cpPot} cpStatus={cpStatus} cpRevealing={cpRevealing} cpDeck={cpDeck} cpSelection={cpSelection} cpKeptIds={cpKeptIds} cpDiscardedIds={cpDiscardedIds} cpKeepChoice={cpKeepChoice} cpRemovingIds={cpRemovingIds} cpVanishIds={cpVanishIds} cpRevealedIds={cpRevealedIds} cpRemovedCards={cpRemovedCards} handleCardSelect={handleCardSelect} confirmKeepChoice={confirmKeepChoice} formatMoney={formatMoney} diceSkin={diceSkin} skins={skins} lang={lang} adminStats={adminStats.cardPath} isAdmin={currentUser?.username === 'admin'} />}
                    </>
                )}

                <Leaderboard showLeaderboard={showLeaderboard} setShowLeaderboard={setShowLeaderboard} t={t} lastRank={lastRank} playerName={playerName} lbLoading={lbLoading} lbError={lbError} leaderboard={leaderboard} fetchLeaderboard={fetchLeaderboard} sortBy={sortBy} setSortBy={setSortBy} sortOrder={sortOrder} setSortOrder={setSortOrder} currentUser={currentUser} lastSubmissionTime={lastSubmissionTime} getBalanceColor={getBalanceColor} formatMoney={formatMoney} lang={lang} Icons={Icons} />

                <Unlocks showUnlocks={showUnlocks} setShowUnlocks={setShowUnlocks} t={t} skins={skins} totalWealth={totalWealth} currentUser={currentUser} diceSkin={diceSkin} setDiceSkin={setDiceSkin} formatMoney={formatMoney} lang={lang} Icons={Icons} />

                <BankerOffer gameState={gameState} t={t} activeGame={activeGame} cpPot={cpPot} cpStep={cpStep} balance={balance} round={round} currentOffer={currentOffer} rejectOffer={rejectOffer} acceptOffer={acceptOffer} formatMoney={formatMoney} Icons={Icons} lang={lang} />

                {gameState === 'end' && <GameOver t={t} lang={lang} playerName={playerName} endReason={endReason} balance={balance} insuranceSaved={insuranceSaved} formatMoney={formatMoney} getBalanceColor={getBalanceColor} handleRestart={handleRestart} returnToHome={returnToHome} downloadLogFile={downloadLogFile} Icons={Icons} />}

                {showAdminStats && adminStats && adminStats.overview && <AnalyticsDashboard adminStats={adminStats} formatMoney={formatMoney} onClose={() => setShowAdminStats(false)} onReset={resetSystem} t={t} lang={lang} />}

                <Shop showShop={showShop} setShowShop={setShowShop} t={t} userProfile={userProfile} formatMoney={formatMoney} onPurchase={handlePurchase} onEquip={handleEquip} onBuyShare={handleBuyShare} onClaimDividend={handleClaimDividend} lang={lang} Icons={Icons} />

                <DebtPanel showDebtPanel={showDebtPanel} setShowDebtPanel={setShowDebtPanel} t={t} userProfile={userProfile} formatMoney={formatMoney} onAdWatch={handleAdWatch} onClickerSubmit={handleClickerSubmit} onSalaryClaim={handleSalaryClaim} lang={lang} Icons={Icons} />
            </main>
        </div>
    );
}

const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);