using UnityEngine;

namespace AlterchaseSDK
{
    public class PlayerSpawnReference : MonoBehaviour
    {
        [Header("Spawn Info")]
        [Tooltip("The position where the player will spawn (read-only)")]
        public Vector3 SpawnPosition => transform.position;
        
        [Tooltip("The rotation the player will face when spawned (read-only)")]
        public Quaternion SpawnRotation => transform.rotation;

        [Header("Gizmo Settings")]
        [SerializeField] private Color gizmoColor = new Color(0.2f, 0.8f, 1f, 0.8f);
        [SerializeField] private float gizmoHeight = 2f;
        [SerializeField] private float gizmoRadius = 0.5f;
        [SerializeField] private bool showDirectionArrow = true;

        private void OnDrawGizmos()
        {
            Gizmos.color = gizmoColor;
            
            Vector3 position = transform.position;
            
            Gizmos.DrawWireSphere(position + Vector3.up * gizmoHeight * 0.5f, gizmoRadius);
            Gizmos.DrawWireSphere(position, gizmoRadius * 0.5f);
            
            Gizmos.DrawLine(position, position + Vector3.up * gizmoHeight);
            
            if (showDirectionArrow)
            {
                Vector3 forward = transform.forward;
                Vector3 arrowStart = position + Vector3.up * 0.1f;
                Vector3 arrowEnd = arrowStart + forward * 1.5f;
                
                Gizmos.color = Color.yellow;
                Gizmos.DrawLine(arrowStart, arrowEnd);
                
                Vector3 right = transform.right * 0.3f;
                Vector3 arrowTip = arrowEnd;
                Gizmos.DrawLine(arrowTip, arrowTip - forward * 0.3f + right);
                Gizmos.DrawLine(arrowTip, arrowTip - forward * 0.3f - right);
            }
        }

        private void OnDrawGizmosSelected()
        {
            Gizmos.color = new Color(gizmoColor.r, gizmoColor.g, gizmoColor.b, 1f);
            
            Vector3 position = transform.position;
            
            Gizmos.DrawSphere(position + Vector3.up * gizmoHeight * 0.5f, gizmoRadius);
            Gizmos.DrawSphere(position, gizmoRadius * 0.5f);
            
            for (int i = 0; i < 8; i++)
            {
                float angle = i * 45f * Mathf.Deg2Rad;
                Vector3 offset = new Vector3(Mathf.Cos(angle), 0, Mathf.Sin(angle)) * gizmoRadius;
                Gizmos.DrawLine(position + offset, position + offset + Vector3.up * gizmoHeight);
            }
        }

        public static PlayerSpawnReference FindSpawnReference()
        {
            return FindFirstObjectByType<PlayerSpawnReference>();
        }
    }
}
