@using Sandbox
@using Sandbox.UI
@using GravCoin
@using System
@inherits Panel

<root class="upgrade-panel">

    <div class="panel-title">âš¡ Upgrades</div>

    <div class="upgrade-intro">Clear upgrades with current and next effects.</div>

    <div class="upgrade-scroll-container">
        <div class="upgrade-category-title">ðŸŒ Network & Bots</div>
        <div class="upgrade-grid">
            <div class="upgrade-card @UpgClass(Upgrades?.GasLevel >= 5, VpnCost)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">VPN</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Anonymous VPN</span>
                        <span class="upgrade-desc">Reduces sell fees on every trade.</span>
                    </div>
                    <span class="upgrade-pill">@LevelPill(Upgrades?.GasLevel ?? 0, 5)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Current</span>
                        <span class="upgrade-line-value">@GasCurrentText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Next</span>
                        <span class="upgrade-line-value">@GasNextText</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.GasLevel >= 5, VpnCost)"
                        onclick="@(() => AskConfirm("Upgrade VPN", $"Reduces transaction fees to the next level. Cost: ${FmtM(VpnCost)}", () => Upgrades?.TryUpgradeVpn()))">
                    @(Upgrades?.GasLevel >= 5 ? "MAX" : CanAfford(VpnCost) ? $"Buy ${FmtM(VpnCost)}" : $"Need ${FmtM(VpnCost)}")
                </button>
            </div>

            <div class="upgrade-card @UpgClass(Upgrades?.CoolingLevel >= 3, ServerCost)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">SRV</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Server Farm</span>
                        <span class="upgrade-desc">Increase simultaneous bot capacity.</span>
                    </div>
                    <span class="upgrade-pill">@LevelPill(Upgrades?.CoolingLevel ?? 0, 3)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Current</span>
                        <span class="upgrade-line-value">@ServerCurrentText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Next</span>
                        <span class="upgrade-line-value">@ServerNextText</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.CoolingLevel >= 3, ServerCost)"
                        onclick="@(() => AskConfirm("Upgrade Servers", $"Increases maximum bot capacity. Cost: ${FmtM(ServerCost)}", () => Upgrades?.TryUpgradeServer()))">
                    @(Upgrades?.CoolingLevel >= 3 ? "MAX" : CanAfford(ServerCost) ? $"Buy ${FmtM(ServerCost)}" : $"Need ${FmtM(ServerCost)}")
                </button>
            </div>

            <div class="upgrade-card @UpgClass(Upgrades?.GpuUnlocked == true, 50_000)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">GPU</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">GPU Cluster</span>
                        <span class="upgrade-desc">Unlocks Tier 3 bots (ML Predictor).</span>
                    </div>
                    <span class="upgrade-pill">@UnlockPill(Upgrades?.GpuUnlocked == true)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Status</span>
                        <span class="upgrade-line-value">@GpuStatusText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Unlocks</span>
                        <span class="upgrade-line-value">Tier 3 bots</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.GpuUnlocked == true, 50_000)"
                        onclick="@(() => AskConfirm("Buy GPU Cluster", "Unlocks Tier 3 bots (ML Predictor). Cost: $50k", () => Upgrades?.TryUnlockGpu()))">
                    @(Upgrades?.GpuUnlocked == true ? "Unlocked" : CanAfford(50_000) ? "Buy $50k" : "Need $50k")
                </button>
            </div>

            <div class="upgrade-card @UpgClass(Upgrades?.SatelliteUnlocked == true, 500_000)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">SAT</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Satellite Link</span>
                        <span class="upgrade-desc">Unlocks Tier 4 bots (Quantum AI).</span>
                    </div>
                    <span class="upgrade-pill">@UnlockPill(Upgrades?.SatelliteUnlocked == true)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Status</span>
                        <span class="upgrade-line-value">@SatelliteStatusText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Unlocks</span>
                        <span class="upgrade-line-value">Tier 4 bots</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.SatelliteUnlocked == true, 500_000)"
                        onclick="@(() => AskConfirm("Buy Satellite Link", "Unlocks Tier 4 bots (Quantum AI). Cost: $500k", () => Upgrades?.TryUnlockSatellite()))">
                    @(Upgrades?.SatelliteUnlocked == true ? "Unlocked" : CanAfford(500_000) ? "Buy $500k" : "Need $500k")
                </button>
            </div>
        </div>

        <div class="upgrade-category-title">ðŸ’° Earn Operations</div>
        <div class="upgrade-grid">
            <div class="upgrade-card @UpgClass(Upgrades?.HashLevel >= 3, HashCost)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">HASH</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Hashrate Boost</span>
                        <span class="upgrade-desc">Reduces clicks needed per block.</span>
                    </div>
                    <span class="upgrade-pill">@LevelPill(Upgrades?.HashLevel ?? 0, 3)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Current</span>
                        <span class="upgrade-line-value">@HashCurrentText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Next</span>
                        <span class="upgrade-line-value">@HashNextText</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.HashLevel >= 3, HashCost)"
                        onclick="@(() => AskConfirm("Upgrade Hashrate", $"Improves Classic mode efficiency. Cost: ${FmtM(HashCost)}", () => Upgrades?.TryUpgradeHash()))">
                    @(Upgrades?.HashLevel >= 3 ? "MAX" : CanAfford(HashCost) ? $"Buy ${FmtM(HashCost)}" : $"Need ${FmtM(HashCost)}")
                </button>
            </div>

            <div class="upgrade-card @UpgClass(Upgrades?.RewardLevel >= 3, RewardCostVal)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">REWARD</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Block Reward</span>
                        <span class="upgrade-desc">Raises minimum payouts across Earn games.</span>
                    </div>
                    <span class="upgrade-pill">@LevelPill(Upgrades?.RewardLevel ?? 0, 3)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Current</span>
                        <span class="upgrade-line-value">@RewardCurrentText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Next</span>
                        <span class="upgrade-line-value">@RewardNextText</span>
                    </div>
                </div>
                <button class="upgrade-btn @BtnClass(Upgrades?.RewardLevel >= 3, RewardCostVal)"
                        onclick="@(() => AskConfirm("Upgrade Payout Floor", $"Increases minimum payouts for Earn games. Cost: ${FmtM(RewardCostVal)}", () => Upgrades?.TryUpgradeReward()))">
                    @(Upgrades?.RewardLevel >= 3 ? "MAX" : CanAfford(RewardCostVal) ? $"Buy ${FmtM(RewardCostVal)}" : $"Need ${FmtM(RewardCostVal)}")
                </button>
            </div>
        </div>

        <div class="upgrade-category-title">ðŸ“ˆ Trading Tools</div>
        <div class="upgrade-grid">
            <div class="upgrade-card @UpgClass(Upgrades?.InsiderUnlocked == true, 50_000)">
                <div class="upgrade-card-head">
                    <span class="upgrade-icon">INSIDER</span>
                    <div class="upgrade-info">
                        <span class="upgrade-name">Insider Trading</span>
                        <span class="upgrade-desc">Predicts market direction 30 seconds ahead.</span>
                    </div>
                    <span class="upgrade-pill">@UnlockPill(Upgrades?.InsiderUnlocked == true)</span>
                </div>
                <div class="upgrade-lines">
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Status</span>
                        <span class="upgrade-line-value">@InsiderStatusText</span>
                    </div>
                    <div class="upgrade-line">
                        <span class="upgrade-line-label">Cooldown</span>
                        <span class="upgrade-line-value">Every 2h</span>
                    </div>

    @if (Upgrades?.InsiderUnlocked == true)
                {
                    <button class="upgrade-btn @(!(Upgrades?.InsiderReady ?? false) ? "disabled" : "")"
                            onclick="@(() => Upgrades?.UseInsiderTip())">
                        @((Upgrades?.InsiderReady ?? false) ? "Use Insider Tip" : "Cooldown")
                    </button>
                }
                else
                {
                    <button class="upgrade-btn @BtnClass(false, 50_000)"
                            onclick="@(() => AskConfirm("Buy Insider Trading", "Predict market direction 30s ahead, once every 2 hours. Cost: $50k", () => Upgrades?.TryUnlockInsider()))">
                        @(CanAfford(50_000) ? "Buy $50k" : "Need $50k")
                    </button>
                }
            </div>
        </div>
</div>

    @if (_confirmVisible)
    {
        <div class="confirm-overlay">
            <div class="confirm-popup">
                <div class="confirm-title">@_confirmTitle</div>
                <div class="confirm-desc">@_confirmDesc</div>
                <div class="confirm-buttons">
                    <button class="confirm-yes" onclick="@OnConfirmYes">Confirm</button>
                    <button class="confirm-no" onclick="@OnConfirmNo">Cancel</button>
                </div>
            </div>
        </div>
    }

</root>

@code
{
    PlayerTrader  Player   => PlayerTrader.Local;
    UpgradeSystem Upgrades => Player?.Components.Get<UpgradeSystem>( FindMode.InSelf );

    // â”€â”€ Confirmation popup state â”€â”€
    bool   _confirmVisible;
    string _confirmTitle = "";
    string _confirmDesc  = "";
    Action _confirmAction;

    void AskConfirm( string title, string desc, Action action )
    {
        _confirmTitle   = title;
        _confirmDesc    = desc;
        _confirmAction  = action;
        _confirmVisible = true;
        StateHasChanged();
    }

    void OnConfirmYes()
    {
        _confirmVisible = false;
        _confirmAction?.Invoke();
        _confirmAction = null;
        StateHasChanged();
    }

    void OnConfirmNo()
    {
        _confirmVisible = false;
        _confirmAction  = null;
        StateHasChanged();
    }

    double VpnCost   => (Upgrades?.GasLevel  ?? 0) switch { 0=>2000, 1=>10000, 2=>50000, 3=>100000, 4=>1000000, _=>0 };
    double ServerCost  => (Upgrades?.CoolingLevel ?? 0) switch { 0=>10000, 1=>50000, 2=>500000, _=>0 };
    double HashCost    => (Upgrades?.HashLevel ?? 0) switch { 0=>1500, 1=>7500, 2=>30000, _=>0 };
    double RewardCostVal => (Upgrades?.RewardLevel ?? 0) switch { 0=>2000, 1=>8000, 2=>35000, _=>0 };

    static float FeeReductionForLevel( int level ) => level switch { 1=>0.05f, 2=>0.10f, 3=>0.20f, 4=>0.30f, 5=>0.50f, _=>0f };
    static int ExtraSlotsForLevel( int level ) => level switch { 1=>1, 2=>2, 3=>4, _=>0 };
    static int HashClicksForLevel( int level ) => level switch { 1=>18, 2=>14, 3=>10, _=>20 };
    static int RewardMinForLevel( int level ) => level switch { 1=>12, 2=>16, 3=>20, _=>8 };

    string LevelPill( int level, int max ) => level >= max ? "MAX" : $"LV {level}/{max}";
    string UnlockPill( bool unlocked ) => unlocked ? "UNLOCKED" : "LOCKED";

    string GasCurrentText => $"{FeeReductionForLevel(Upgrades?.GasLevel ?? 0) * 100:0}% fee reduction";
    string GasNextText => (Upgrades?.GasLevel ?? 0) >= 5 ? "MAX" : $"{FeeReductionForLevel((Upgrades?.GasLevel ?? 0) + 1) * 100:0}% fee reduction";
    string ServerCurrentText => $"Max bots: {1 + ExtraSlotsForLevel(Upgrades?.CoolingLevel ?? 0)}";
    string ServerNextText => (Upgrades?.CoolingLevel ?? 0) >= 3 ? "MAX" : $"Max bots: {1 + ExtraSlotsForLevel((Upgrades?.CoolingLevel ?? 0) + 1)}";
    string HashCurrentText => $"{HashClicksForLevel(Upgrades?.HashLevel ?? 0)} clicks per block";
    string HashNextText => (Upgrades?.HashLevel ?? 0) >= 3 ? "MAX" : $"{HashClicksForLevel((Upgrades?.HashLevel ?? 0) + 1)} clicks per block";
    string RewardCurrentText => $"Min payout: ${RewardMinForLevel(Upgrades?.RewardLevel ?? 0)}";
    string RewardNextText => (Upgrades?.RewardLevel ?? 0) >= 3 ? "MAX" : $"Min payout: ${RewardMinForLevel((Upgrades?.RewardLevel ?? 0) + 1)}";
    string InsiderStatusText => (Upgrades?.InsiderUnlocked ?? false) ? ((Upgrades?.InsiderReady ?? false) ? "Ready" : "Cooldown") : "Locked";
    string GpuStatusText => (Upgrades?.GpuUnlocked ?? false) ? "Unlocked" : "Locked";
    string SatelliteStatusText => (Upgrades?.SatelliteUnlocked ?? false) ? "Unlocked" : "Locked";

    bool CanAfford( double cost ) => (Player?.Money ?? 0) >= cost;

    string UpgClass( bool maxed, double cost ) => maxed ? "owned" : !CanAfford(cost) ? "locked" : "";
    string BtnClass( bool maxed, double cost ) => maxed || !CanAfford(cost) ? "disabled" : "";

    bool AllMaxed => (Upgrades?.GasLevel ?? 0) >= 5
                  && (Upgrades?.CoolingLevel ?? 0) >= 3
                  && (Upgrades?.GpuUnlocked ?? false)
                  && (Upgrades?.SatelliteUnlocked ?? false)
                  && (Upgrades?.InsiderUnlocked ?? false)
                  && (Upgrades?.HashLevel ?? 0) >= 3
                  && (Upgrades?.RewardLevel ?? 0) >= 3;

    static string FmtM( double v )
        => v >= 1_000_000 ? $"{v/1_000_000:F0}M"
         : v >= 1_000 ? $"{v/1_000:F0}k" : v.ToString("F0");

    protected override int BuildHash() => System.HashCode.Combine(
        Upgrades?.GasLevel, Upgrades?.CoolingLevel,
        Upgrades?.GpuUnlocked, Upgrades?.SatelliteUnlocked,
        Upgrades?.InsiderUnlocked, Upgrades?.InsiderReady,
        System.HashCode.Combine( Player?.Money, Upgrades?.HashLevel, Upgrades?.RewardLevel ) );
}

