using UnityEngine;

public class PlayerHeadController : MonoBehaviour
{
    public Transform Head;
    public Transform CameraTransform;

    public float ThrowForce = 10f;
    public float PickupDistance = 3f;

    public bool isHoldingHead = true;

    private Rigidbody m_headRigidbody;

    private Vector3 m_headInitialLocalPos;
    private Quaternion m_headInitialLocalRot;

    private Animator animator;
    private PlayerInputController input;

    private void Awake()
    {
        animator = GetComponent<Animator>();
        input = GetComponent<PlayerInputController>();
    }

    void Start()
    {
        Cursor.lockState = CursorLockMode.Locked;

        m_headInitialLocalPos = Head.localPosition;
        m_headInitialLocalRot = Head.localRotation;
    }

    void Update()
    {
        if (input.HeadInteractionPressed)
        {
            InteractHead();
        }

        if (input.ThrowPressed)
        {
            ThrowHead();
        }
    }

    private void InteractHead()
    {
        if (!isHoldingHead)
            TryPickupHead();
        else
            DropHead();
    }

    private void DropHead()
    {
        animator.SetTrigger("Throw");

        isHoldingHead = false;

        Head.SetParent(null);

        m_headRigidbody = Head.gameObject.AddComponent<Rigidbody>();
        m_headRigidbody.mass = 1f;

        m_headRigidbody.constraints =
            RigidbodyConstraints.FreezeRotationX |
            RigidbodyConstraints.FreezeRotationZ |
            RigidbodyConstraints.FreezeRotationY;
    }

    private void ThrowHead()
    {
        if (!isHoldingHead)
            return;

        DropHead();

        m_headRigidbody.AddForce(CameraTransform.forward * ThrowForce, ForceMode.Impulse);
    }

    private void TryPickupHead()
    {
        if (isHoldingHead)
            return;

        float distance = Vector3.Distance(transform.position, Head.position);

        if (distance <= PickupDistance)
        {
            PickupHead();
        }
    }

    private void PickupHead()
    {
        isHoldingHead = true;

        if (m_headRigidbody != null)
        {
            Destroy(m_headRigidbody);
        }

        Head.SetParent(transform);

        Head.localPosition = m_headInitialLocalPos;
        Head.localRotation = m_headInitialLocalRot;
    }
} 