const { useState, useEffect, useRef, useMemo, useCallback } = React;

class SoundFX {
    constructor() {
        this.ctx = null;
        this.muted = false;
    }

    init() {
        if (!this.ctx) {
            const AudioContext = window.AudioContext || window.webkitAudioContext;
            this.ctx = new AudioContext();
        }
        if (this.ctx.state === 'suspended') {
            this.ctx.resume();
        }
    }

    playTone(freq, type, duration, gainVal = 0.1) {
        if (this.muted) return;
        this.init();
        try {
            const osc = this.ctx.createOscillator();
            const gain = this.ctx.createGain();
            osc.type = type;
            osc.frequency.setValueAtTime(freq, this.ctx.currentTime);
            
            gain.gain.setValueAtTime(gainVal, this.ctx.currentTime);
            gain.gain.exponentialRampToValueAtTime(0.0001, this.ctx.currentTime + duration);
            
            osc.connect(gain);
            gain.connect(this.ctx.destination);
            
            osc.start();
            osc.stop(this.ctx.currentTime + duration);
        } catch(e) {}
    }

    mine() { this.playTone(650, 'triangle', 0.08, 0.12); }
    click() { this.playTone(900, 'sine', 0.04, 0.05); }
    success() { this.playTone(1046.5, 'sine', 0.2, 0.15); }
    powerup() { this.playTone(784, 'square', 0.2, 0.15); }
    error() { this.playTone(120, 'sawtooth', 0.25, 0.15); }
    start() {
        this.playTone(523.25, 'square', 0.1, 0.1);
        setTimeout(() => this.playTone(1046.5, 'square', 0.2, 0.1), 100);
    }
}

const soundFX = new SoundFX();

class ErrorBoundary extends React.Component {
    constructor(props) {
        super(props);
        this.state = { hasError: false, error: null };
    }
    static getDerivedStateFromError(error) {
        return { hasError: true, error };
    }
    componentDidCatch(error, errorInfo) {
        console.error("ErrorBoundary caught an error", error, errorInfo);
    }
    render() {
        if (this.state.hasError) {
            return (
                <div className="min-h-screen bg-onyx-950 text-neon-magenta flex flex-col items-center justify-center p-6 text-center font-mono">
                    <div className="w-16 h-16 rounded-full bg-neon-magenta/20 border border-neon-magenta flex items-center justify-center text-neon-magenta text-2xl mb-4 shadow-glow-magenta">
                        <i className="fa-solid fa-triangle-exclamation"></i>
                    </div>
                    <h2 className="text-2xl font-extrabold mb-2 text-glow-magenta">MINING RIG EXCEPTION DETECTED</h2>
                    <p className="text-xs text-slate-400 mb-6 max-w-md bg-onyx-900 p-4 rounded-xl border border-slate-800">{this.state.error?.toString()}</p>
                    <button onClick={() => window.location.reload()} className="px-8 py-3 rounded-xl bg-neon-cyan text-onyx-950 font-extrabold text-xs shadow-glow-cyan cyber-button">
                        REBOOT MINING CORE
                    </button>
                </div>
            );
        }
        return this.props.children;
    }
}

function App() {
    const [siteData, setSiteData] = useState(null);
    const [activeTab, setActiveTab] = useState('mine');
    const [soundMuted, setSoundMuted] = useState(false);
    
    // Game Miner Idle State
    const [shards, setShards] = useState(0);
    const [totalMined, setTotalMined] = useState(0);
    const [clickPower, setClickPower] = useState(1);
    const [autoRate, setAutoRate] = useState(0);
    const [critChance, setCritChance] = useState(0.05);
    const [floatingTexts, setFloatingTexts] = useState([]);
    
    const [upgrades, setUpgrades] = useState([
        { id: 'gpu_basic', name: 'GTX-9000 Rig', cost: 15, cps: 1, count: 0, icon: 'fa-microchip', desc: 'Entry-level mining card' },
        { id: 'asic_miner', name: 'Quantum ASIC Miner', cost: 120, cps: 8, count: 0, icon: 'fa-server', desc: 'Dedicated high-speed hash engine' },
        { id: 'botnet_net', name: 'Botnet Cluster', cost: 1100, cps: 45, count: 0, icon: 'fa-network-wired', desc: 'Distributed zombie node network' },
        { id: 'ai_core', name: 'Sentient AI Core', cost: 12500, cps: 260, count: 0, icon: 'fa-brain', desc: 'Neural crypto prediction matrix' },
        { id: 'orbital_sat', name: 'Orbital Sat Rig', cost: 140000, cps: 1400, count: 0, icon: 'fa-satellite', desc: 'Deep-space zero-latency mining' }
    ]);

    const [clickUpgrades, setClickUpgrades] = useState([
        { id: 'click_1', name: 'Overclock ASIC', cost: 50, powerAdd: 1, count: 0, icon: 'fa-bolt', desc: '+1 Shard per click' },
        { id: 'click_2', name: 'Hydro Cooling', cost: 350, powerAdd: 5, count: 0, icon: 'fa-snowflake', desc: '+5 Shards per click' },
        { id: 'click_3', name: 'Quantum Overdrive', cost: 2500, powerAdd: 25, count: 0, icon: 'fa-fire', desc: '+25 Shards per click' },
        { id: 'click_4', name: 'Singularity Tap', cost: 20000, powerAdd: 120, count: 0, icon: 'fa-radiation', desc: '+120 Shards per click' }
    ]);

    const [achievements, setAchievements] = useState([
        { id: 'ach_1', name: 'First Shard', desc: 'Mine your very first crypto shard', target: 1, type: 'total', unlocked: false, icon: 'fa-cube' },
        { id: 'ach_2', name: 'Rig Operator', desc: 'Reach 10 Shards per second', target: 10, type: 'cps', unlocked: false, icon: 'fa-server' },
        { id: 'ach_3', name: 'Crypto Tycoon', desc: 'Amass 10,000 total mined shards', target: 10000, type: 'total', unlocked: false, icon: 'fa-gem' },
        { id: 'ach_4', name: 'Matrix Overlord', desc: 'Reach 1,000 Shards per second', target: 1000, type: 'cps', unlocked: false, icon: 'fa-globe' }
    ]);

    useEffect(() => {
        fetch('data.json')
            .then(res => res.json())
            .then(data => setSiteData(data))
            .catch(err => {
                setSiteData({
                    brand: { name: "GAME MINER", tagline: "ULTIMATE CRYPTO RIG IDLE PROTOCOL", version: "v5.2-PROD" },
                    stats: [
                        { label: "HASH RATE", value: "14.8 GH/s", change: "Optimal", color: "text-neon-cyan" },
                        { label: "CORE TEMP", value: "48.2°C", change: "Stable", color: "text-neon-green" },
                        { label: "POWER DRAW", value: "420W", change: "Green Energy", color: "text-neon-yellow" },
                        { label: "POOL STATUS", value: "ONLINE", change: "99.9% Uptime", color: "text-neon-magenta" }
                    ]
                });
            });

        // Load saved game
        const savedShards = localStorage.getItem('game_miner_shards');
        const savedTotal = localStorage.getItem('game_miner_total');
        const savedClickPower = localStorage.getItem('game_miner_clickpower');
        const savedUpgrades = localStorage.getItem('game_miner_upgrades');
        const savedClickUpg = localStorage.getItem('game_miner_clickupg');
        const savedAch = localStorage.getItem('game_miner_achievements');

        if (savedShards) setShards(parseFloat(savedShards));
        if (savedTotal) setTotalMined(parseFloat(savedTotal));
        if (savedClickPower) setClickPower(parseInt(savedClickPower, 10));
        if (savedUpgrades) { try { setUpgrades(JSON.parse(savedUpgrades)); } catch(e){} }
        if (savedClickUpg) { try { setClickUpgrades(JSON.parse(savedClickUpg)); } catch(e){} }
        if (savedAch) { try { setAchievements(JSON.parse(savedAch)); } catch(e){} }
    }, []);

    // Auto Miner Loop (10 ticks per second)
    useEffect(() => {
        const currentCps = upgrades.reduce((acc, u) => acc + (u.count * u.cps), 0);
        setAutoRate(currentCps);
        if (currentCps <= 0) return;

        const interval = setInterval(() => {
            const added = currentCps / 10;
            setShards(prev => {
                const next = prev + added;
                localStorage.setItem('game_miner_shards', next.toString());
                return next;
            });
            setTotalMined(prev => {
                const next = prev + added;
                localStorage.setItem('game_miner_total', next.toString());
                return next;
            });
        }, 100);

        return () => clearInterval(interval);
    }, [upgrades]);

    // Achievement Checker
    useEffect(() => {
        const currentCps = upgrades.reduce((acc, u) => acc + (u.count * u.cps), 0);
        let updated = false;
        const newAch = achievements.map(ach => {
            if (!ach.unlocked) {
                if (ach.type === 'total' && totalMined >= ach.target) {
                    updated = true;
                    soundFX.success();
                    window.confetti && window.confetti({ particleCount: 70, spread: 80, origin: { y: 0.6 } });
                    return { ...ach, unlocked: true };
                }
                if (ach.type === 'cps' && currentCps >= ach.target) {
                    updated = true;
                    soundFX.success();
                    window.confetti && window.confetti({ particleCount: 70, spread: 80, origin: { y: 0.6 } });
                    return { ...ach, unlocked: true };
                }
            }
            return ach;
        });
        if (updated) {
            setAchievements(newAch);
            localStorage.setItem('game_miner_achievements', JSON.stringify(newAch));
        }
    }, [totalMined, upgrades, achievements]);

    const handleManualMine = (e) => {
        soundFX.mine();
        const isCrit = Math.random() < critChance;
        const multiplier = isCrit ? 3 : 1;
        const earned = clickPower * multiplier;

        const nextShards = shards + earned;
        const nextTotal = totalMined + earned;
        setShards(nextShards);
        setTotalMined(nextTotal);
        localStorage.setItem('game_miner_shards', nextShards.toString());
        localStorage.setItem('game_miner_total', nextTotal.toString());

        // Floating text
        const rect = e.currentTarget.getBoundingClientRect();
        const x = e.clientX || (rect.left + rect.width / 2);
        const y = e.clientY || (rect.top + rect.height / 2);
        const newFloat = { id: Date.now() + Math.random(), text: `+${earned.toLocaleString()}${isCrit ? ' CRIT!' : ''}`, x, y, isCrit };
        setFloatingTexts(prev => [...prev.slice(-15), newFloat]);
    };

    const buyUpgrade = (id) => {
        const upg = upgrades.find(u => u.id === id);
        if (shards < upg.cost) {
            soundFX.error();
            return;
        }

        soundFX.powerup();
        const nextShards = shards - upg.cost;
        const nextUpgrades = upgrades.map(u => {
            if (u.id === id) {
                return { ...u, count: u.count + 1, cost: Math.floor(u.cost * 1.15) };
            }
            return u;
        });

        setShards(nextShards);
        setUpgrades(nextUpgrades);
        localStorage.setItem('game_miner_shards', nextShards.toString());
        localStorage.setItem('game_miner_upgrades', JSON.stringify(nextUpgrades));
    };

    const buyClickUpgrade = (id) => {
        const cupg = clickUpgrades.find(u => u.id === id);
        if (shards < cupg.cost) {
            soundFX.error();
            return;
        }

        soundFX.powerup();
        const nextShards = shards - cupg.cost;
        const nextClickPower = clickPower + cupg.powerAdd;
        const nextClickUpgs = clickUpgrades.map(u => {
            if (u.id === id) {
                return { ...u, count: u.count + 1, cost: Math.floor(u.cost * 1.25) };
            }
            return u;
        });

        setShards(nextShards);
        setClickPower(nextClickPower);
        setClickUpgrades(nextClickUpgs);
        localStorage.setItem('game_miner_shards', nextShards.toString());
        localStorage.setItem('game_miner_clickpower', nextClickPower.toString());
        localStorage.setItem('game_miner_clickupg', JSON.stringify(nextClickUpgs));
    };

    const toggleSound = () => {
        const next = !soundMuted;
        setSoundMuted(next);
        soundFX.muted = next;
        soundFX.click();
    };

    if (!siteData) {
        return (
            <div className="min-h-screen bg-onyx-950 flex flex-col items-center justify-center">
                <div className="w-16 h-16 border-4 border-neon-cyan border-t-transparent rounded-full animate-spin mb-4 shadow-glow-cyan"></div>
                <p className="font-mono text-neon-cyan tracking-widest text-sm animate-pulse">INITIALIZING GAME MINER...</p>
            </div>
        );
    }

    return (
        <div className="min-h-screen matrix-bg text-slate-100 flex flex-col relative">
            <div className="absolute inset-0 scanline pointer-events-none z-50 opacity-20"></div>

            {/* Floating text layer */} 
            <div className="fixed inset-0 pointer-events-none z-40 overflow-hidden">
                {floatingTexts.map(f => (
                    <div
                        key={f.id}
                        className={`absolute font-mono font-extrabold text-sm sm:text-lg animate-float-up ${f.isCrit ? 'text-neon-yellow text-glow-yellow scale-125' : 'text-neon-cyan text-glow-cyan'}`}
                        style={{ left: f.x - 30, top: f.y - 30 }}
                    >
                        {f.text}
                    </div>
                ))}
            </div>

            {/* Header / Navbar */}
            <header className="border-b border-neon-cyan/25 glass-panel sticky top-0 z-40 px-4 lg:px-12 py-4 flex flex-col md:flex-row items-center justify-between gap-4">
                <div className="flex items-center gap-3 cursor-pointer" onClick={() => { soundFX.click(); setActiveTab('mine'); }}>
                    <div className="w-12 h-12 rounded-xl bg-neon-cyan/10 border border-neon-cyan flex items-center justify-center text-neon-cyan shadow-glow-cyan">
                        <i className="fa-solid fa-cubes text-xl"></i>
                    </div>
                    <div>
                        <h1 className="font-extrabold tracking-wider text-xl text-glow-cyan font-mono">
                            GAME MINER <span className="text-neon-magenta">// IDLE RIG</span>
                        </h1>
                        <p className="text-xs text-slate-400 font-mono">{siteData.brand.tagline}</p>
                    </div>
                </div>

                <nav className="flex items-center gap-1 sm:gap-2 bg-onyx-900/90 p-2 rounded-2xl border border-slate-800 flex-wrap justify-center shadow-lg">
                    {[
                        { id: 'mine', label: 'Mining Core', icon: 'fa-microchip' },
                        { id: 'rigs', label: 'GPU Rigs', icon: 'fa-server' },
                        { id: 'overclock', label: 'Overclock', icon: 'fa-bolt' },
                        { id: 'achievements', label: 'Badges', icon: 'fa-trophy' },
                    ].map(tab => (
                        <button
                            key={tab.id}
                            onClick={() => {
                                soundFX.click();
                                setActiveTab(tab.id);
                            }}
                            className={`px-4 py-2.5 rounded-xl font-mono text-xs transition-all flex items-center gap-2 ${ 
                                activeTab === tab.id
                                    ? 'bg-neon-cyan text-onyx-950 font-bold shadow-glow-cyan scale-105'
                                    : 'text-slate-400 hover:text-white hover:bg-slate-800/60'
                            }`}
                        >
                            <i className={`fa-solid ${tab.icon} ${activeTab === tab.id ? 'text-onyx-950' : 'text-neon-cyan'}`}></i>
                            <span className="hidden sm:inline">{tab.label}</span>
                        </button>
                    ))}
                </nav>

                <div className="flex items-center gap-3">
                    <button
                        onClick={toggleSound}
                        className="w-11 h-11 rounded-xl glass-panel flex items-center justify-center text-neon-cyan hover:border-neon-cyan transition shadow-md"
                        title={soundMuted ? "Unmute Audio" : "Mute Audio"}
                    >
                        <i className={`fa-solid ${soundMuted ? 'fa-volume-xmark text-slate-500' : 'fa-volume-high text-neon-cyan'}`}></i>
                    </button>
                    <div className="hidden xl:flex items-center gap-2 px-3.5 py-2 rounded-xl bg-neon-green/10 border border-neon-green/30 text-neon-green font-mono text-xs shadow-glow-green">
                        <span className="w-2.5 h-2.5 rounded-full bg-neon-green animate-ping"></span>
                        <span>HASH ACTIVE</span>
                    </div>
                </div>
            </header>

            {/* Main Content Area */}
            <main className="flex-1 max-w-7xl w-full mx-auto p-4 lg:p-8 space-y-8">
                {/* Stats bar */}
                <div className="grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-4 gap-4">
                    <div className="glass-panel rounded-2xl p-5 border-l-4 border-l-neon-cyan shadow-lg">
                        <p className="text-xs font-mono text-slate-400 mb-1">TOTAL SHARDS MINED</p>
                        <span className="text-2xl sm:text-3xl font-extrabold font-mono text-neon-cyan">{Math.floor(shards).toLocaleString()}</span>
                    </div>
                    <div className="glass-panel rounded-2xl p-5 border-l-4 border-l-neon-green shadow-lg">
                        <p className="text-xs font-mono text-slate-400 mb-1">HASH RATE (AUTO)</p>
                        <span className="text-2xl sm:text-3xl font-extrabold font-mono text-neon-green">+{autoRate.toFixed(1)} /s</span>
                    </div>
                    <div className="glass-panel rounded-2xl p-5 border-l-4 border-l-neon-yellow shadow-lg">
                        <p className="text-xs font-mono text-slate-400 mb-1">CLICK POWER</p>
                        <span className="text-2xl sm:text-3xl font-extrabold font-mono text-neon-yellow">+{clickPower}</span>
                    </div>
                    <div className="glass-panel rounded-2xl p-5 border-l-4 border-l-neon-magenta shadow-lg">
                        <p className="text-xs font-mono text-slate-400 mb-1">ALL-TIME EXTRACTED</p>
                        <span className="text-2xl sm:text-3xl font-extrabold font-mono text-neon-magenta">{Math.floor(totalMined).toLocaleString()}</span>
                    </div>
                </div>

                {activeTab === 'mine' && (
                    <div className="grid grid-cols-1 lg:grid-cols-12 gap-8 items-start">
                        {/* Big Clicker Core */}
                        <div className="lg:col-span-6 glass-panel rounded-3xl p-8 flex flex-col items-center justify-center text-center space-y-8 shadow-2xl relative overflow-hidden">
                            <div className="absolute top-0 right-0 w-[300px] h-[300px] bg-neon-cyan/10 rounded-full blur-[80px] pointer-events-none"></div>
                            
                            <div className="space-y-2">
                                <span className="px-3.5 py-1.5 rounded-full bg-neon-cyan/10 border border-neon-cyan/40 text-neon-cyan font-mono text-xs shadow-glow-cyan">
                                    <i className="fa-solid fa-microchip mr-1.5"></i> GAME MINER CORE v5.2
                                </span>
                                <h2 className="text-3xl font-extrabold font-mono text-white">TAP TO MINE SHARDS</h2>
                                <p className="text-xs text-slate-400 font-mono">Extract crypto shards manually or let your GPU rigs automate the hash rate.</p>
                            </div>

                            <div 
                                onClick={handleManualMine}
                                className="w-56 h-56 rounded-full bg-onyx-900 border-4 border-neon-cyan flex items-center justify-center shadow-glow-cyan cursor-pointer active:scale-95 transition group relative overflow-hidden my-6 select-none"
                            >
                                <div className="absolute inset-0 bg-neon-cyan/10 group-hover:bg-neon-cyan/25 transition animate-pulse-slow"></div>
                                <div className="absolute inset-4 rounded-full border border-neon-cyan/30 flex items-center justify-center">
                                    <div className="absolute inset-4 rounded-full border border-dashed border-neon-cyan/40 animate-spin" style={{ animationDuration: '20s' }}></div>
                                </div>
                                <i className="fa-solid fa-cubes text-7xl text-neon-cyan group-hover:scale-110 transition relative z-10 text-glow-cyan"></i>
                            </div>

                            <div className="w-full space-y-3">
                                <button
                                    onClick={handleManualMine}
                                    className="w-full py-4 rounded-2xl bg-neon-cyan text-onyx-950 font-extrabold font-mono text-sm cyber-button shadow-glow-cyan flex items-center justify-center gap-3"
                                >
                                    <i className="fa-solid fa-hammer text-lg"></i> MINE SHARD (+{clickPower})
                                </button>
                            </div>
                        </div>

                        {/* Quick Upgrades Sidebar */}
                        <div className="lg:col-span-6 space-y-6">
                            <div className="glass-panel rounded-3xl p-6 space-y-4 shadow-2xl">
                                <div className="flex items-center justify-between">
                                    <h3 className="font-mono font-bold text-sm text-neon-cyan flex items-center gap-2">
                                        <i className="fa-solid fa-server"></i> QUICK GPU RIGS
                                    </h3>
                                    <span className="text-xs font-mono text-slate-400">AUTO HASHING</span>
                                </div>

                                <div className="space-y-3">
                                    {upgrades.slice(0, 3).map(u => {
                                        const canAfford = shards >= u.cost;
                                        return (
                                            <div key={u.id} className="p-4 rounded-2xl bg-onyx-900 border border-slate-800 flex items-center justify-between gap-4 transition hover:border-slate-700">
                                                <div className="flex items-center gap-3.5">
                                                    <div className="w-12 h-12 rounded-xl bg-slate-800 border border-slate-700 flex items-center justify-center text-neon-cyan text-lg shadow-md">
                                                        <i className={`fa-solid ${u.icon}`}></i>
                                                    </div>
                                                    <div>
                                                        <h5 className="font-mono font-bold text-sm text-white">{u.name} <span className="text-xs text-neon-magenta font-mono ml-1">(x{u.count})</span></h5>
                                                        <p className="text-xs font-mono text-slate-400">+{u.cps} shards/sec • {u.desc}</p>
                                                    </div>
                                                </div>
                                                <button
                                                    onClick={() => buyUpgrade(u.id)}
                                                    disabled={!canAfford}
                                                    className={`px-5 py-2.5 rounded-xl font-mono text-xs font-extrabold transition shrink-0 ${ 
                                                        canAfford
                                                            ? 'bg-neon-cyan text-onyx-950 shadow-glow-cyan hover:scale-105'
                                                            : 'bg-slate-800 text-slate-500 cursor-not-allowed border border-slate-700'
                                                    }`}
                                                >
                                                    {u.cost.toLocaleString()} SHARDS
                                                </button>
                                            </div>
                                        );
                                    })}
                                </div>
                                <button
                                    onClick={() => setActiveTab('rigs')}
                                    className="w-full py-3 rounded-xl bg-onyx-900 border border-slate-800 text-neon-cyan font-mono text-xs font-bold hover:bg-slate-800 transition text-center block"
                                >
                                    VIEW ALL GPU RIGS & AI CORES <i className="fa-solid fa-arrow-right ml-1.5"></i>
                                </button>
                            </div>

                            <div className="glass-panel rounded-3xl p-6 space-y-4 shadow-2xl">
                                <div className="flex items-center justify-between">
                                    <h3 className="font-mono font-bold text-sm text-neon-yellow flex items-center gap-2">
                                        <i className="fa-solid fa-bolt"></i> OVERCLOCK CLICKS
                                    </h3>
                                    <span className="text-xs font-mono text-slate-400">TAP POWER</span>
                                </div>

                                <div className="space-y-3">
                                    {clickUpgrades.slice(0, 2).map(u => {
                                        const canAfford = shards >= u.cost;
                                        return (
                                            <div key={u.id} className="p-4 rounded-2xl bg-onyx-900 border border-slate-800 flex items-center justify-between gap-4 transition hover:border-slate-700">
                                                <div className="flex items-center gap-3.5">
                                                    <div className="w-12 h-12 rounded-xl bg-slate-800 border border-slate-700 flex items-center justify-center text-neon-yellow text-lg shadow-md">
                                                        <i className={`fa-solid ${u.icon}`}></i>
                                                    </div>
                                                    <div>
                                                        <h5 className="font-mono font-bold text-sm text-white">{u.name} <span className="text-xs text-neon-yellow font-mono ml-1">(x{u.count})</span></h5>
                                                        <p className="text-xs font-mono text-slate-400">+{u.powerAdd} click power • {u.desc}</p>
                                                    </div>
                                                </div>
                                                <button
                                                    onClick={() => buyClickUpgrade(u.id)}
                                                    disabled={!canAfford}
                                                    className={`px-5 py-2.5 rounded-xl font-mono text-xs font-extrabold transition shrink-0 ${ 
                                                        canAfford
                                                            ? 'bg-neon-yellow text-onyx-950 shadow-glow-yellow hover:scale-105'
                                                            : 'bg-slate-800 text-slate-500 cursor-not-allowed border border-slate-700'
                                                    }`}
                                                >
                                                    {u.cost.toLocaleString()} SHARDS
                                                </button>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>
                    </div>
                )}

                {activeTab === 'rigs' && (
                    <div className="max-w-4xl mx-auto space-y-6">
                        <div className="glass-panel rounded-3xl p-6 flex items-center justify-between shadow-xl">
                            <div>
                                <h3 className="text-2xl font-bold font-mono text-glow-cyan flex items-center gap-3">
                                    <i className="fa-solid fa-server text-neon-cyan"></i> GPU RIGS & AI CORES SHOP
                                </h3>
                                <p className="text-xs text-slate-400 font-mono">Deploy automated hardware clusters to extract shards continuously.</p>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 gap-4">
                            {upgrades.map(u => {
                                const canAfford = shards >= u.cost;
                                return (
                                    <div key={u.id} className="glass-panel rounded-3xl p-6 flex flex-col sm:flex-row items-center justify-between gap-6 shadow-xl">
                                        <div className="flex items-center gap-4 w-full sm:w-auto">
                                            <div className="w-16 h-16 rounded-2xl bg-onyx-900 border border-slate-800 flex items-center justify-center text-neon-cyan text-2xl shadow-glow-cyan shrink-0">
                                                <i className={`fa-solid ${u.icon}`}></i>
                                            </div>
                                            <div>
                                                <div className="flex items-center gap-2">
                                                    <h4 className="font-mono font-bold text-lg text-white">{u.name}</h4>
                                                    <span className="px-2.5 py-0.5 rounded-lg bg-neon-magenta/10 border border-neon-magenta/30 text-neon-magenta font-mono text-xs font-bold">
                                                        Owned: {u.count}
                                                    </span>
                                                </div>
                                                <p className="text-xs font-mono text-slate-300 mt-1">{u.desc}</p>
                                                <p className="text-xs font-mono text-neon-green mt-1 font-bold">Yield: +{u.cps} shards/sec</p>
                                            </div>
                                        </div>

                                        <button
                                            onClick={() => buyUpgrade(u.id)}
                                            disabled={!canAfford}
                                            className={`w-full sm:w-auto px-8 py-3.5 rounded-2xl font-mono text-xs font-extrabold transition ${ 
                                                canAfford
                                                    ? 'bg-neon-cyan text-onyx-950 shadow-glow-cyan hover:scale-105'
                                                    : 'bg-slate-800 text-slate-500 cursor-not-allowed border border-slate-700'
                                            }`}
                                        >
                                            BUY FOR {u.cost.toLocaleString()} SHARDS
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {activeTab === 'overclock' && (
                    <div className="max-w-4xl mx-auto space-y-6">
                        <div className="glass-panel rounded-3xl p-6 flex items-center justify-between shadow-xl">
                            <div>
                                <h3 className="text-2xl font-bold font-mono text-glow-yellow flex items-center gap-3">
                                    <i className="fa-solid fa-bolt text-neon-yellow"></i> OVERCLOCK & CLICK POWER
                                </h3>
                                <p className="text-xs text-slate-400 font-mono">Boost manual mining efficiency with advanced hardware cooling and overclocking.</p>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 gap-4">
                            {clickUpgrades.map(u => {
                                const canAfford = shards >= u.cost;
                                return (
                                    <div key={u.id} className="glass-panel rounded-3xl p-6 flex flex-col sm:flex-row items-center justify-between gap-6 shadow-xl">
                                        <div className="flex items-center gap-4 w-full sm:w-auto">
                                            <div className="w-16 h-16 rounded-2xl bg-onyx-900 border border-slate-800 flex items-center justify-center text-neon-yellow text-2xl shadow-glow-yellow shrink-0">
                                                <i className={`fa-solid ${u.icon}`}></i>
                                            </div>
                                            <div>
                                                <div className="flex items-center gap-2">
                                                    <h4 className="font-mono font-bold text-lg text-white">{u.name}</h4>
                                                    <span className="px-2.5 py-0.5 rounded-lg bg-neon-yellow/10 border border-neon-yellow/30 text-neon-yellow font-mono text-xs font-bold">
                                                        Owned: {u.count}
                                                    </span>
                                                </div>
                                                <p className="text-xs font-mono text-slate-300 mt-1">{u.desc}</p>
                                            </div>
                                        </div>

                                        <button
                                            onClick={() => buyClickUpgrade(u.id)}
                                            disabled={!canAfford}
                                            className={`w-full sm:w-auto px-8 py-3.5 rounded-2xl font-mono text-xs font-extrabold transition ${ 
                                                canAfford
                                                    ? 'bg-neon-yellow text-onyx-950 shadow-glow-yellow hover:scale-105'
                                                    : 'bg-slate-800 text-slate-500 cursor-not-allowed border border-slate-700'
                                            }`}
                                        >
                                            UPGRADE FOR {u.cost.toLocaleString()} SHARDS
                                        </button>
                                    </div>
                                );
                            })}
                        </div>
                    </div>
                )}

                {activeTab === 'achievements' && (
                    <div className="max-w-4xl mx-auto space-y-6">
                        <div className="glass-panel rounded-3xl p-6 flex items-center justify-between shadow-xl">
                            <div>
                                <h3 className="text-2xl font-bold font-mono text-glow-cyan flex items-center gap-3">
                                    <i className="fa-solid fa-trophy text-neon-cyan"></i> MINING BADGES & ACHIEVEMENTS
                                </h3>
                                <p className="text-xs text-slate-400 font-mono">Unlock milestones as your mining empire scales.</p>
                            </div>
                        </div>

                        <div className="grid grid-cols-1 sm:grid-cols-2 gap-4">
                            {achievements.map(ach => (
                                <div key={ach.id} className={`glass-panel rounded-3xl p-6 flex items-center gap-4 transition shadow-xl ${ach.unlocked ? 'border-neon-cyan/60 bg-onyx-900/90' : 'opacity-60'}`}>
                                    <div className={`w-14 h-14 rounded-2xl border flex items-center justify-center text-xl shrink-0 ${ach.unlocked ? 'bg-neon-cyan/20 border-neon-cyan text-neon-cyan shadow-glow-cyan' : 'bg-onyx-900 border-slate-800 text-slate-500'}`}>
                                        <i className={`fa-solid ${ach.icon}`}></i>
                                    </div>
                                    <div>
                                        <div className="flex items-center gap-2">
                                            <h4 className="font-mono font-bold text-base text-white">{ach.name}</h4>
                                            <span className={`px-2 py-0.5 rounded-md font-mono text-[10px] font-bold ${ach.unlocked ? 'bg-neon-green/20 text-neon-green border border-neon-green/40' : 'bg-slate-800 text-slate-400 border border-slate-700'}`}>
                                                {ach.unlocked ? 'UNLOCKED' : 'LOCKED'}
                                            </span>
                                        </div>
                                        <p className="text-xs font-mono text-slate-300 mt-1">{ach.desc}</p>
                                    </div>
                                </div>
                            ))}
                        </div>
                    </div>
                )}
            </main>

            {/* Footer */}
            <footer className="border-t border-slate-800/80 bg-onyx-900/60 py-8 px-6 text-center text-xs font-mono text-slate-500 flex flex-col sm:flex-row items-center justify-between gap-4 max-w-7xl mx-auto w-full">
                <p>© GAME MINER PROTOCOL. ALL RIGHTS RESERVED. SECURE CRYPTO MINING ENGINE.</p>
                <div className="flex items-center gap-4 text-neon-cyan">
                    <span><i className="fa-solid fa-shield-halved mr-1.5"></i> HASH ENCRYPTION</span>
                    <span><i className="fa-solid fa-bolt mr-1.5"></i> OPTIMAL EFFICIENCY</span>
                </div>
            </footer>
        </div>
    );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ErrorBoundary><App /></ErrorBoundary>);