﻿using UdonSharp;
using UnityEngine;
using TMPro;

public class PokerChipPile : UdonSharpBehaviour
{
    [Header("Denomination Settings")]
    public int[] denominationValues = new int[] { 10, 50, 100, 500, 1000 };
    public LocalObjectPool[] denominationPools;

    [Header("Chip Settings")]
    public float chipHeight = 0.003f;

    [Header("Stack Settings")]
    public int stackHeight = 10;
    public float hexSpacing = 0.035f;

    [Header("Randomization")]
    public int seed = 12345;
    public float positionJitter = 0.004f;
    public float tiltDegrees = 2f;

    // Internal
    private Vector3[] stackPositions;
    private int maxStacks;
    private int totalActiveChips;
    private int previousTotalValue;

    // Animation (private — not tweakable in inspector)
    private float chipFallOffset = 0.04f;
    private float timeBetweenChipRepositioning = 0.02f;
    private float chipFallDuration = 0.1f;

    // Animation tracking
    private int[] prevCounts;
    private Transform[] animTargets;
    private Vector3[] animStartPositions;
    private Vector3[] animTargetPositions;
    private int animCount;
    private float animStartTime;

    [Header("Value display")]
    public TMP_Text text;
    public GameObject textGameObject;
    public LookAtPlayerYawOnly lookAtPlayer;


    public void UpdateText()
    {
        if (text == null)
            return;

        if (previousTotalValue > 0)
        {
            text.text = $"{previousTotalValue}";
            if (lookAtPlayer != null)
                lookAtPlayer.enabled = true;
        }
        else
        {
            text.text = "";
            if (lookAtPlayer != null)
                lookAtPlayer.enabled = false;
        }
    }

    public void OverrideText(string newValue)
    {
        if (text == null)
            return;

        text.text = newValue;
    }


    public void SetTextVisibility(bool visible)
    {
        if (textGameObject != null)
        {
            textGameObject.SetActive(visible);
        }
    }


    void Start()
    {
        // Validate pools are assigned
        if (denominationPools == null || denominationPools.Length != denominationValues.Length)
        {
            Debug.LogError("PokerChipPile: denominationPools array must match denominationValues length!");
            return;
        }

        for (int i = 0; i < denominationPools.Length; i++)
        {
            if (denominationPools[i] == null)
            {
                Debug.LogError($"PokerChipPile: Pool for denomination {denominationValues[i]} not assigned!");
            }
        }

        // Set a reasonable default for max stacks
        // We'll spawn chips until TryToSpawn returns null, so this is just for grid generation
        maxStacks = 60;

        prevCounts = new int[denominationValues.Length];
        int maxChips = maxStacks * stackHeight;
        animTargets = new Transform[maxChips];
        animStartPositions = new Vector3[maxChips];
        animTargetPositions = new Vector3[maxChips];
        animCount = 0;

        GenerateHexGrid();
        SetTotalChips(0);
        SetTextVisibility(true);
    }

    /* ---------------------------
     * Public API
     * --------------------------- */

    /// <summary>
    /// Set the total chip value to display. Calculates and displays chips by denomination.
    /// </summary>
    public void SetTotalChips(int totalValue)
    {
        if (previousTotalValue == totalValue)
        {
            return;
        }
        previousTotalValue = totalValue;
        UpdateText();
        int[] counts = CalculateDenominationCounts(totalValue);
        UpdateChipDisplay(counts);
    }

    /// <summary>
    /// Calculate how many chips of each denomination are needed for the given total value.
    /// Uses greedy algorithm starting from highest denomination.
    /// </summary>
    private int[] CalculateDenominationCounts(int totalValue)
    {
        int[] counts = new int[denominationValues.Length];
        int remaining = totalValue;

        // Sort denominations in descending order for greedy algorithm
        int[] sortedIndices = new int[denominationValues.Length];
        for (int i = 0; i < denominationValues.Length; i++)
        {
            sortedIndices[i] = i;
        }

        // Bubble sort indices by denomination value (descending)
        for (int i = 0; i < sortedIndices.Length - 1; i++)
        {
            for (int j = 0; j < sortedIndices.Length - i - 1; j++)
            {
                if (denominationValues[sortedIndices[j]] < denominationValues[sortedIndices[j + 1]])
                {
                    int temp = sortedIndices[j];
                    sortedIndices[j] = sortedIndices[j + 1];
                    sortedIndices[j + 1] = temp;
                }
            }
        }

        // Greedy allocation
        for (int i = 0; i < sortedIndices.Length; i++)
        {
            int denomIndex = sortedIndices[i];
            int denomValue = denominationValues[denomIndex];
            if (denomValue > 0)
            {
                counts[denomIndex] = remaining / denomValue;
                remaining = remaining % denomValue;
            }
        }

        return counts;
    }

    /// <summary>
    /// Return all currently spawned chips to their pools.
    /// Iterates denomination pools and returns each chip to the pool that owns it.
    /// </summary>
    private void ReturnAllChips()
    {
        // Iterate through all children and return them to their owning pools
        int childCount = transform.childCount;
        for (int i = childCount - 1; i >= 0; i--)
        {
            Transform child = transform.GetChild(i);
            if (child != null)
            {
                GameObject chip = child.gameObject;

                // Try each denomination pool to find which one owns this chip
                bool returned = false;
                if (denominationPools != null)
                {
                    for (int p = 0; p < denominationPools.Length; p++)
                    {
                        if (denominationPools[p] != null && denominationPools[p].OwnsObject(chip))
                        {
                            denominationPools[p].Return(chip);
                            returned = true;
                            break;
                        }
                    }
                }

                if (!returned)
                {
                    Debug.LogWarning($"PokerChipPile: Chip {chip.name} could not be returned to any pool!");
                }
            }
        }
    }

    /// <summary>
    /// Update the visual chip display based on denomination counts.
    /// Compares against previous counts; only newly-added chips get the
    /// fall-in animation. Existing chips are placed silently at their
    /// final positions.
    /// </summary>
    private void UpdateChipDisplay(int[] counts)
    {
        // Snap any in-progress animation so we start fresh.
        // ReturnAllChips sends everything back to pools (silent).
        animCount = 0;
        ReturnAllChips();

        // Sort denominations by value (descending) for placement order
        int[] sortedIndices = new int[denominationValues.Length];
        for (int i = 0; i < denominationValues.Length; i++)
        {
            sortedIndices[i] = i;
        }

        for (int i = 0; i < sortedIndices.Length - 1; i++)
        {
            for (int j = 0; j < sortedIndices.Length - i - 1; j++)
            {
                if (denominationValues[sortedIndices[j]] < denominationValues[sortedIndices[j + 1]])
                {
                    int temp = sortedIndices[j];
                    sortedIndices[j] = sortedIndices[j + 1];
                    sortedIndices[j + 1] = temp;
                }
            }
        }

        // Find the first (highest-value) sorted index where count changed.
        // Because sortedIndices is descending by value, an index of 2 means
        // "the 3rd-highest denom and everything below it changed".
        int firstChangedSortedIndex = int.MaxValue;
        int oldCountForChanged = 0;
        if (prevCounts != null)
        {
            for (int idx = 0; idx < sortedIndices.Length; idx++)
            {
                int d = sortedIndices[idx];
                if (counts[d] != prevCounts[d])
                {
                    firstChangedSortedIndex = idx;
                    oldCountForChanged = prevCounts[d];
                    break;
                }
            }
        }

        // Place chips starting from center (highest denomination first).
        // Sorted indices are descending by value.
        // - The denomination that changed: only the *new* chips animate
        //   (existing chips stay put).
        // - Lower-value denominations: *all* chips animate (they get
        //   pushed up by the new chips above).
        // - Higher-value denominations: no animation.
        int globalChipIndex = 0;
        for (int i = 0; i < sortedIndices.Length; i++)
        {
            int denomIndex = sortedIndices[i];
            int chipCount = counts[denomIndex];

            // Safety check: ensure pool exists
            if (denominationPools[denomIndex] == null)
            {
                Debug.LogWarning($"PokerChipPile: Pool for denomination {denominationValues[denomIndex]} is null, skipping.");
                continue;
            }

            // Determine animation policy for this denomination
            //  i < firstChangedSortedIndex  → above, no animation
            //  i == firstChangedSortedIndex → changed denom, only new chips
            //  i > firstChangedSortedIndex  → below, all chips cascade
            int firstNewIndex = 0;
            if (i == firstChangedSortedIndex)
            {
                firstNewIndex = oldCountForChanged;   // c >= this → new
            }
            if (i > firstChangedSortedIndex)
            {
                firstNewIndex = 0;                    // all chips cascade
            }

            for (int c = 0; c < chipCount; c++)
            {
                int stackIndex = globalChipIndex / stackHeight;
                if (stackIndex >= stackPositions.Length)
                {
                    Debug.LogWarning($"PokerChipPile: Exceeded maximum stack positions ({maxStacks}). Some chips may not be displayed.");
                    break;
                }

                // Spawn chip from pool
                GameObject chip = denominationPools[denomIndex].TryToSpawn();

                if (chip == null)
                {
                    Debug.Log($"PokerChipPile: Pool for denomination {denominationValues[denomIndex]} exhausted after {c} chips.");
                    break;
                }

                chip.transform.SetParent(transform);
                PlaceChip(chip.transform, denomIndex, c, globalChipIndex);

                if (i >= firstChangedSortedIndex && c >= firstNewIndex && animCount < animTargets.Length)
                {
                    // Save final position as target, then lift chip up
                    Vector3 finalPos = chip.transform.localPosition;
                    animTargets[animCount] = chip.transform;
                    animStartPositions[animCount] = finalPos + Vector3.up * chipFallOffset;
                    animTargetPositions[animCount] = finalPos;
                    chip.transform.localPosition = animStartPositions[animCount];
                    animCount++;
                }

                globalChipIndex++;
            }
        }

        totalActiveChips = globalChipIndex;

        // Copy counts for next diff
        if (prevCounts == null) prevCounts = new int[denominationValues.Length];
        for (int i = 0; i < counts.Length; i++)
        {
            prevCounts[i] = counts[i];
        }

        animStartTime = Time.time;
    }

    /// <summary>
    /// Every frame, interpolate queued chips from their elevated start
    /// position down to their final position using a cubic ease-out
    /// curve that mimics gravity settling. Chips are staggered by
    /// timeBetweenChipRepositioning so the bottom chip lands first.
    /// </summary>
    void Update()
    {
        if (animCount == 0) return;

        for (int i = 0; i < animCount; i++)
        {
            float delay = i * timeBetweenChipRepositioning;
            float elapsed = Time.time - animStartTime - delay;
            if (elapsed <= 0f) continue;

            Transform t = animTargets[i];
            if (t == null) continue;

            float progress = elapsed / chipFallDuration;
            if (progress >= 1f)
            {
                t.localPosition = animTargetPositions[i];
                continue;
            }

            // Cubic ease-out: starts fast, decelerates smoothly
            float oneMinusT = 1f - progress;
            float eased = 1f - (oneMinusT * oneMinusT * oneMinusT);
            t.localPosition = Vector3.Lerp(animStartPositions[i], animTargetPositions[i], eased);
        }
    }

    /* ---------------------------
     * Initialization
     * --------------------------- */

    private void GenerateHexGrid()
    {
        stackPositions = new Vector3[maxStacks];
        stackPositions[0] = Vector3.zero;

        int index = 1;

        Vector3[] dirs = new Vector3[]
        {
            new Vector3(1f, 0f, 0f),
            new Vector3(0.5f, 0f, 0.866f),
            new Vector3(-0.5f, 0f, 0.866f),
            new Vector3(-1f, 0f, 0f),
            new Vector3(-0.5f, 0f, -0.866f),
            new Vector3(0.5f, 0f, -0.866f)
        };

        for (int ring = 1; index < maxStacks; ring++)
        {
            Vector3 pos = dirs[4] * ring * hexSpacing;

            for (int dir = 0; dir < 6; dir++)
            {
                for (int step = 0; step < ring; step++)
                {
                    if (index >= maxStacks) return;

                    stackPositions[index++] = pos;
                    pos += dirs[dir] * hexSpacing;
                }
            }
        }
    }

    /* ---------------------------
     * Chip Placement
     * --------------------------- */

    private void PlaceChip(Transform chipTransform, int denomIndex, int chipIndexInDenom, int globalStackIndex)
    {
        int stackIndex = globalStackIndex / stackHeight;
        int heightIndex = globalStackIndex % stackHeight;

        Vector3 basePos = stackPositions[stackIndex];
        Vector3 pos = basePos;
        pos.y += heightIndex * chipHeight;

        // Create unique hash based on denomination and chip index for consistent randomization
        int h = (denomIndex * 1000) + chipIndexInDenom + seed;

        float ox = Hash01(h) * positionJitter;
        float oz = Hash01(h + 17) * positionJitter;

        pos.x += ox;
        pos.z += oz;

        float yaw = Hash01(h + 43) * 360f;
        //float tiltX = (Hash01(h + 91) - 0.5f) * tiltDegrees;
        //float tiltZ = (Hash01(h + 137) - 0.5f) * tiltDegrees;
        float tiltX = -90f;
        float tiltZ = 0f;

        Quaternion rot = Quaternion.Euler(tiltX, yaw, tiltZ);

        chipTransform.localPosition = pos;
        chipTransform.localRotation = rot;
    }


    private float Hash01(int x)
    {
        x = (x << 13) ^ x;
        int n = (x * (x * x * 15731 + 789221) + 1376312589);
        return 1f - ((n & 0x7fffffff) / 1073741824f);
    }
}