﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;

/// <summary>
/// Main scoreboard controller. Collects player data, sorts by profit,
/// and updates row displays. Updates every 10 seconds.
/// </summary>
[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class HoldemScoreboard : UdonSharpBehaviour
{
    [Header("Row References")]
    [Tooltip("Assign row prefabs in the order they should appear (rank 1, 2, 3, etc.)")]
    public HoldemRowPrefab[] rows;

    // Set by the world's HoldemAuthority at start
    [HideInInspector] public HoldemAuthority authority;

    [Header("Update Settings")]
    [Tooltip("How often to refresh the scoreboard (in seconds)")]
    public float updateIntervalSeconds = 10f;

    [Header("Player Data Cache")]
    // Arrays to store player data for sorting
    // Max 40 players (world capacity)
    private VRCPlayerApi[] allPlayers = new VRCPlayerApi[40];
    private string[] playerNames = new string[40];
    private int[] playerProfits = new int[40];
    private int[] playerBalances = new int[40];
    private int[] playerHandsPlayed = new int[40];
    private int[] playerHatsGiven = new int[40];
    private int[] playerHatsReceived = new int[40];
    private int[] playerDonationsGiven = new int[40];
    private int[] playerDonationsReceived = new int[40];
    private int playerCount = 0;

    private int[] rowOrder = new int[40];

    private float lastUpdateTime = 0f;
    private bool isInitialized = false;

    void Start()
    {
        isInitialized = rows != null && rows.Length > 0;
        
        // Clear all rows initially
        ClearAllRows();
    }

    void Update()
    {
        if (!isInitialized) return;

        // Update every interval
        if (Time.time - lastUpdateTime >= updateIntervalSeconds)
        {
            lastUpdateTime = Time.time;
            RefreshScoreboard();
        }
    }

    /// <summary>
    /// Main refresh logic - collects data, sorts, and updates display.
    /// </summary>
    public void RefreshScoreboard()
    {
        CollectPlayerData();
        SortByProfit();
        UpdateRowDisplays();
    }

    /// <summary>
    /// Collects player data from all players in the instance.
    /// </summary>
    private void CollectPlayerData()
    {
        playerCount = 0;

        for (int i = 0; i < allPlayers.Length; i++)
        {
            allPlayers[i] = null;
        }

        // Get all players in the instance
        VRCPlayerApi.GetPlayers(allPlayers);

        for (int i = 0; i < allPlayers.Length; i++)
        {
            VRCPlayerApi player = allPlayers[i];
            
            // Skip null/invalid players
            if (player == null || !Utilities.IsValid(player))
                continue;

            // Get player's balance component
            PlayerBalanceComponent balanceComp = PlayerBalanceComponent.GetPlayerBalanceComponent(player);
            
            // Skip players without a ready balance component
            if (balanceComp == null || !balanceComp.IsReady())
                continue;

            // Store player data
            bool flagged = authority != null && authority.IsFlagged(player.displayName);
            playerNames[playerCount] = flagged ? "[FLAGGED] " + player.displayName : player.displayName;
            playerProfits[playerCount] = balanceComp.GetProfit();
            playerBalances[playerCount] = balanceComp.GetBalance();
            playerHandsPlayed[playerCount] = balanceComp.GetHandsPlayed();
            playerHatsGiven[playerCount] = balanceComp.GetHatsGiven();
            playerHatsReceived[playerCount] = balanceComp.GetHatsReceived();
            playerDonationsGiven[playerCount] = balanceComp.GetDonation();
            playerDonationsReceived[playerCount] = balanceComp.GetDonationsReceived();
            
            playerCount++;
            
            // Safety check - don't exceed array bounds
            if (playerCount >= playerNames.Length)
                break;
        }
    }

    /// <summary>
    /// Sorts player data by profit descending (highest profit at top).
    /// Uses simple insertion sort (efficient for small datasets).
    /// </summary>
    private void SortByProfit()
    {
        for (int i = 0; i < playerCount; i++) rowOrder[i] = i;
        if (playerCount <= 1) return;

        // Insertion sort by profit descending
        for (int i = 1; i < playerCount; i++)
        {
            int slot = rowOrder[i];
            int profit = playerProfits[slot];
            int j = i - 1;

            while (j >= 0 && playerProfits[rowOrder[j]] < profit)
            {
                rowOrder[j + 1] = rowOrder[j];
                j--;
            }

            rowOrder[j + 1] = slot;
        }
    }

    /// <summary>
    /// Updates the row displays with sorted data.
    /// Only fills up to the number of available rows.
    /// </summary>
    private void UpdateRowDisplays()
    {
        int rowsToShow = Mathf.Min(playerCount, rows.Length);

        // Update active rows
        for (int i = 0; i < rowsToShow; i++)
        {
            if (rows[i] != null)
            {
                int slot = rowOrder[i];
                rows[i].UpdateDisplay(
                    i + 1, // Rank starts at 1
                    playerNames[slot],
                    playerProfits[slot],
                    playerBalances[slot],
                    playerHandsPlayed[slot],
                    playerHatsGiven[slot],
                    playerHatsReceived[slot],
                    playerDonationsGiven[slot],
                    playerDonationsReceived[slot]
                );
            }
        }

        // Clear unused rows
        for (int i = rowsToShow; i < rows.Length; i++)
        {
            if (rows[i] != null)
            {
                rows[i].Clear();
            }
        }
    }

    /// <summary>
    /// Clears all rows (hides them).
    /// </summary>
    private void ClearAllRows()
    {
        if (rows == null) return;
        
        for (int i = 0; i < rows.Length; i++)
        {
            if (rows[i] != null)
            {
                rows[i].Clear();
            }
        }
    }
}