﻿using UdonSharp;
using UnityEngine;
using VRC.SDKBase;
using VRC.Udon;
using VRC.SDK3.Persistence;
using System;

[UdonBehaviourSyncMode(BehaviourSyncMode.None)]
public class BettingUi : UdonSharpBehaviour
{
    public GameObject[] buttons;
    public int[] denominations;
    public Transform[] positions;
    public GameObject resetButton;

    private int MULTIPLIER = 2;

    public void HideBettingControls()
    {
        for (int i = 0; i < buttons.Length; i++)
        {
            buttons[i].SetActive(false);
        }
        if (resetButton != null) resetButton.SetActive(false);
    }

    public void AdjustButtons(int chips)
    {
        if (resetButton != null) resetButton.SetActive(true);

        // Find the largest denomination where denomination * 2 < chips
        int targetIndex = -1;
        for (int i = denominations.Length - 1; i >= 0; i--)
        {
            if (denominations[i] * MULTIPLIER < chips)
            {
                targetIndex = i;
                break;
            }
        }

        // Set all buttons to false
        for (int i = 0; i < buttons.Length; i++)
        {
            buttons[i].SetActive(false);
        }

        // Check if we have enough smaller denominations
        if (targetIndex >= positions.Length - 1)
        {
            // Place target at last position, then fill with two smaller denominations
            for (int i = 0; i < positions.Length; i++)
            {
                int buttonIndex = targetIndex - (positions.Length - 1 - i);
                buttons[buttonIndex].transform.position = positions[i].position;
                buttons[buttonIndex].transform.rotation = positions[i].rotation;
                buttons[buttonIndex].SetActive(true);
            }
        }
        else
        {
            // Not enough smaller denominations, start from the first one
            for (int i = 0; i < positions.Length; i++)
            {
                buttons[i].transform.position = positions[i].position;
                buttons[i].transform.rotation = positions[i].rotation;
                buttons[i].SetActive(true);
            }
        }
    }

}