using UnityEngine;
using Photon.Pun;
using UnityEngine.InputSystem;

[RequireComponent(typeof(Collider))]
public class CosmeticButton : MonoBehaviour
{
    [Header("Cosmetic Settings")]
    public string SlotName = "Hat";
    public string CosmeticName = "CoolHat";
    public float HoldDuration = 1f;
    public float MaxDistance = 3f;
    public float MaxAngle = 30f; // max degrees from center of button to count as looking

    private float holdTimer = 0f;
    private Camera playerCam;

    private void Start()
    {
        playerCam = Camera.main;
    }

    private void Update()
    {
        PhotonPlayer localPlayer = FindLocalPlayer();
        if (localPlayer == null || !localPlayer.photonView.IsMine) return;

        if (IsLookingAtButton() && Keyboard.current != null && Keyboard.current.eKey.isPressed)
        {
            holdTimer += Time.deltaTime;

            if (holdTimer >= HoldDuration)
            {
                Debug.Log($"Equipped cosmetic: {CosmeticName} in slot {SlotName}");
                localPlayer.SetCosmetic(SlotName, CosmeticName);
                holdTimer = 0f;
            }
        }
        else
        {
            holdTimer = 0f;
        }
    }

    private bool IsLookingAtButton()
    {
        if (playerCam == null) return false;

        Vector3 toButton = (transform.position - playerCam.transform.position);
        float distance = toButton.magnitude;
        if (distance > MaxDistance) return false;

        float angle = Vector3.Angle(playerCam.transform.forward, toButton);
        if (angle > MaxAngle) return false;

        // Optional: Debug
        Debug.DrawLine(playerCam.transform.position, transform.position, Color.green);

        return true;
    }

    private PhotonPlayer FindLocalPlayer()
    {
        foreach (var p in FindObjectsOfType<PhotonPlayer>())
        {
            if (p.photonView.IsMine)
                return p;
        }
        return null;
    }
}
