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

function LiveFeed({ t, lang, formatMoney, Icons, apiUrl })
{
    const [isMinimized, setIsMinimized] = useState(true);
    const [wins, setWins] = useState([]);
    const [isLoading, setIsLoading] = useState(true);
    const [newWinId, setNewWinId] = useState(null);
    const prevWinsRef = useRef([]);

    const FormatTimeAgo = useCallback((timestamp) =>
    {
        if (!timestamp)
        {
            return t.justNow || "Az önce";
        }

        const now = Date.now();
        const past = new Date(timestamp).getTime();
        const diffSeconds = Math.max(0, Math.floor((now - past) / 1000));

        if (diffSeconds < 60)
        {
            return t.justNow || "Az önce";
        }

        const diffMinutes = Math.floor(diffSeconds / 60);
        if (diffMinutes < 60)
        {
            const template = t.minAgo || "{count} dk önce";
            return template.replace("{count}", diffMinutes);
        }

        const diffHours = Math.floor(diffMinutes / 60);
        const template = t.hoursAgo || "{count} sa önce";
        return template.replace("{count}", diffHours);
    }, [t]);

    const GetGameInfo = useCallback((gameType) =>
    {
        switch (gameType)
        {
            case 'cardPath':
                return {
                    name: t.cardPathGameName || "Kart Yolu",
                    icon: <Icons.DollarSign size={14} className="text-emerald-400" />,
                    badgeColor: 'bg-emerald-500/10 text-emerald-400 border-emerald-500/20'
                };
            case 'dotRace':
                return {
                    name: t.dotRaceGameName || "Nokta Yarışı",
                    icon: <Icons.Flag size={14} className="text-purple-400" />,
                    badgeColor: 'bg-purple-500/10 text-purple-400 border-purple-500/20'
                };
            case 'luckySlot':
                return {
                    name: t.luckySlotGameName || "Şanslı Slot",
                    icon: <Icons.SlotMachine size={14} className="text-amber-400" />,
                    badgeColor: 'bg-amber-500/10 text-amber-400 border-amber-500/20'
                };
            case 'dede':
                return {
                    name: t.dedeGameName || "Dede (Gates of Olympus)",
                    icon: <Icons.Zeus size={14} className="text-amber-400" />,
                    badgeColor: 'bg-yellow-500/10 text-yellow-400 border-yellow-500/20'
                };
            case 'customBet':
                return {
                    name: t.customBetGameName || "Özel Bahis",
                    icon: <Icons.Gavel size={14} className="text-purple-400" />,
                    badgeColor: 'bg-purple-500/10 text-purple-400 border-purple-500/20'
                };
            case 'oneMoreDice':
            default:
                return {
                    name: t.diceGameName || "Bir Zar Daha",
                    icon: <Icons.Dices size={14} className="text-indigo-400" />,
                    badgeColor: 'bg-indigo-500/10 text-indigo-400 border-indigo-500/20'
                };
        }
    }, [t, Icons]);

    const FetchRecentWins = useCallback(async () =>
    {
        try
        {
            const res = await fetch(`${apiUrl}/api/feed`);
            const json = await res.json();

            if (json.success && Array.isArray(json.data))
            {
                if (prevWinsRef.current.length > 0 && json.data.length > 0)
                {
                    const latest = json.data[0];
                    const prevLatest = prevWinsRef.current[0];
                    if (latest && prevLatest && latest.id !== prevLatest.id)
                    {
                        setNewWinId(latest.id);
                        setTimeout(() => setNewWinId(null), 3000);
                    }
                }
                prevWinsRef.current = json.data;
                setWins(json.data);
            }
        }
        catch (err)
        {
            console.warn("Live feed fetch error:", err);
        }
        finally
        {
            setIsLoading(false);
        }
    }, [apiUrl]);

    useEffect(() =>
    {
        FetchRecentWins();
        const intervalId = setInterval(FetchRecentWins, 8000);
        return () => clearInterval(intervalId);
    }, [FetchRecentWins]);

    const latestWin = wins.length > 0 ? wins[0] : null;

    return (
        <aside aria-label={t.liveWinsTitle || "Canlı Kazançlar"} className="fixed bottom-6 right-6 z-40 flex flex-col items-end pointer-events-auto select-none font-sans">
            {/* MINIMIZED PILL VIEW */}
            {isMinimized ? (
                <motion.button
                    initial={{ opacity: 0, scale: 0.9, y: 10 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    whileHover={{ scale: 1.05 }}
                    whileTap={{ scale: 0.95 }}
                    onClick={() => setIsMinimized(false)}
                    className="flex items-center gap-3 px-4 py-2.5 rounded-2xl bg-slate-900/90 border border-emerald-500/30 backdrop-blur-xl shadow-[0_8px_32px_rgba(0,0,0,0.4)] text-white hover:border-emerald-400/60 transition-all group"
                >
                    <span className="relative flex h-2.5 w-2.5">
                        <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                        <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                    </span>

                    <span className="text-[11px] font-black tracking-wider text-emerald-400 uppercase">
                        {t.liveBadge || "CANLI"}
                    </span>

                    {latestWin && (
                        <div className="hidden sm:flex items-center gap-2 border-l border-white/10 pl-3">
                            <span className="text-xs font-bold text-slate-200">{latestWin.username}</span>
                            <span className="text-xs font-black text-emerald-400">+{formatMoney(latestWin.amount)}</span>
                        </div>
                    )}

                    <Icons.ChevronUp size={16} className="text-slate-400 group-hover:text-white transition-colors ml-1" />
                </motion.button>
            ) : (
                /* EXPANDED FEED PANEL */
                <motion.div
                    initial={{ opacity: 0, scale: 0.95, y: 20 }}
                    animate={{ opacity: 1, scale: 1, y: 0 }}
                    exit={{ opacity: 0, scale: 0.95, y: 20 }}
                    transition={{ type: "spring", stiffness: 350, damping: 25 }}
                    className="w-80 sm:w-96 rounded-[2rem] bg-slate-950/85 border border-slate-800/80 backdrop-blur-2xl shadow-[0_20px_50px_rgba(0,0,0,0.6)] overflow-hidden flex flex-col relative group"
                >
                    {/* TOP ACCENT GLOW */}
                    <div className="absolute top-0 inset-x-0 h-1 bg-gradient-to-r from-indigo-500 via-emerald-500 to-amber-500 opacity-60"></div>

                    {/* HEADER */}
                    <div className="px-5 py-3.5 flex items-center justify-between border-b border-white/5 bg-slate-900/40">
                        <div className="flex items-center gap-2.5">
                            <span className="relative flex h-2.5 w-2.5">
                                <span className="animate-ping absolute inline-flex h-full w-full rounded-full bg-emerald-400 opacity-75"></span>
                                <span className="relative inline-flex rounded-full h-2.5 w-2.5 bg-emerald-500"></span>
                            </span>
                            <div>
                                <div className="flex items-center gap-2">
                                    <h2 className="text-[12px] font-black tracking-wider text-white uppercase leading-none">
                                        {t.liveWinsTitle || "CANLI KAZANÇLAR"}
                                    </h2>
                                    <span className="px-1.5 py-0.5 rounded text-[9px] font-black bg-emerald-500/20 text-emerald-400 border border-emerald-500/30">
                                        {t.liveBadge || "CANLI"}
                                    </span>
                                </div>
                                <p className="text-[9px] font-bold text-slate-500 uppercase tracking-widest leading-none mt-1">
                                    {t.liveWinsDesc || "Anlık Oyuncu Kazançları"}
                                </p>
                            </div>
                        </div>

                        <div className="flex items-center gap-1">
                            <button
                                onClick={() => setIsMinimized(true)}
                                className="p-1.5 rounded-lg text-slate-400 hover:text-white hover:bg-slate-800/60 transition-all active:scale-95"
                                title={t.minimize || "Küçült"}
                            >
                                <Icons.ChevronDown size={16} />
                            </button>
                        </div>
                    </div>

                    {/* WINS LIST */}
                    <div className="p-3 max-h-[300px] overflow-y-auto custom-scrollbar flex flex-col gap-2">
                        {isLoading && wins.length === 0 ? (
                            <div className="py-8 flex flex-col items-center justify-center text-slate-500 gap-2">
                                <Icons.Loader size={24} className="text-emerald-400 animate-spin" />
                                <span className="text-xs font-bold">{t.loading || "Yükleniyor..."}</span>
                            </div>
                        ) : wins.length === 0 ? (
                            <div className="py-8 text-center text-slate-500 text-xs font-medium">
                                {t.noWinsYet || "Henüz yeni kazanç kaydı yok."}
                            </div>
                        ) : (
                            <AnimatePresence initial={false}>
                                {wins.map((win) =>
                                {
                                    const game = GetGameInfo(win.gameType);
                                    const isNew = newWinId === win.id;

                                    return (
                                        <motion.div
                                            key={win.id}
                                            layout
                                            initial={{ opacity: 0, x: -15, scale: 0.95 }}
                                            animate={{ 
                                                opacity: 1, 
                                                x: 0, 
                                                scale: 1,
                                                backgroundColor: isNew 
                                                    ? 'rgba(16, 185, 129, 0.15)' 
                                                    : win.isBigWin 
                                                        ? 'rgba(245, 158, 11, 0.06)' 
                                                        : 'rgba(15, 23, 42, 0.45)'
                                            }}
                                            exit={{ opacity: 0, scale: 0.9 }}
                                            transition={{ duration: 0.3 }}
                                            className={`p-2.5 rounded-xl border transition-all ${
                                                win.isBigWin 
                                                    ? 'border-amber-500/30 hover:border-amber-500/50' 
                                                    : 'border-white/5 hover:border-slate-700/60'
                                            }`}
                                        >
                                            <div className="flex items-center justify-between gap-3">
                                                {/* USER INFO */}
                                                <div className="flex items-center gap-2.5 min-w-0">
                                                    <div className={`w-8 h-8 rounded-xl flex items-center justify-center font-black text-xs flex-shrink-0 shadow-md ${
                                                        win.isBigWin 
                                                            ? 'bg-gradient-to-br from-amber-500 to-yellow-600 text-black shadow-amber-500/20' 
                                                            : 'bg-gradient-to-br from-slate-800 to-slate-700 text-white'
                                                    }`}>
                                                        {win.username ? win.username[0].toUpperCase() : 'U'}
                                                    </div>

                                                    <div className="min-w-0">
                                                        <div className="flex items-center gap-1.5">
                                                            <span className={`text-xs font-black truncate ${
                                                                win.isBigWin ? 'text-amber-300' : 'text-slate-200'
                                                            }`}>
                                                                {win.username}
                                                            </span>

                                                            {win.title && (
                                                                <span className="hidden sm:inline-block px-1 py-0.2 text-[8px] font-black uppercase tracking-wider rounded bg-indigo-500/20 text-indigo-300 border border-indigo-500/30">
                                                                    {t[`title${win.title.replace(/\s/g, '')}`] || win.title}
                                                                </span>
                                                            )}
                                                        </div>

                                                        <div className="flex items-center gap-1.5 mt-0.5">
                                                            <span className={`inline-flex items-center gap-1 px-1.5 py-0.5 rounded text-[9px] font-bold border ${game.badgeColor}`}>
                                                                {game.icon}
                                                                {game.name}
                                                            </span>
                                                            <span className="text-[9px] font-medium text-slate-500">
                                                                • {FormatTimeAgo(win.timestamp)}
                                                            </span>
                                                        </div>
                                                    </div>
                                                </div>

                                                {/* WIN AMOUNT */}
                                                <div className="flex flex-col items-end flex-shrink-0">
                                                    {win.isBigWin && (
                                                        <span className="flex items-center gap-1 text-[8px] font-black uppercase tracking-wider text-amber-400 bg-amber-500/20 px-1.5 py-0.5 rounded-full border border-amber-500/30 mb-0.5">
                                                            <Icons.Flame size={10} className="text-amber-400 animate-pulse" />
                                                            {t.bigWinBadge || "BÜYÜK KAZANÇ"}
                                                        </span>
                                                    )}
                                                    <span className={`text-sm font-black tabular-nums ${
                                                        win.isBigWin 
                                                            ? 'text-amber-400 drop-shadow-[0_0_8px_rgba(245,158,11,0.5)]' 
                                                            : 'text-emerald-400'
                                                    }`}>
                                                        +{formatMoney(win.amount)}
                                                    </span>
                                                </div>
                                            </div>
                                        </motion.div>
                                    );
                                })}
                            </AnimatePresence>
                        )}
                    </div>

                    {/* FOOTER TICKER INFO */}
                    <div className="px-4 py-2 border-t border-white/5 bg-slate-900/30 flex items-center justify-between text-[10px] text-slate-500 font-bold">
                        <span className="flex items-center gap-1.5">
                            <Icons.Sparkles size={12} className="text-amber-400" />
                            {lang === 'TR' ? 'Her 8 saniyede bir güncellenir' : 'Updates every 8 seconds'}
                        </span>
                        <span className="text-slate-600">
                            {wins.length} {lang === 'TR' ? 'kayıt' : 'entries'}
                        </span>
                    </div>
                </motion.div>
            )}
        </aside>
    );
}

window.LiveFeed = LiveFeed;
