using Core;
using UnityEngine;
using Script.Gameplay.Interface;
using Script.Gameplay.Input;

namespace Script.Gameplay.Player
{
    public class PlayerEditController:MonoBehaviour
    {
        [SerializeField] private FirstPersonRaycaster raycaster; // 新增：第一人称射线检测器

        private IEditable currentTarget; // 射线命中的当前可编辑对象（用于按键交互）
        private IEditable previousGazedTarget; // 上一次注视的对象（用于注视进入/离开事件）
        
        private InputManager inputManager;

        void Start()
        {
            inputManager = InputManager.Instance;
            if (raycaster == null)
                raycaster = GetComponent<FirstPersonRaycaster>() ?? GetComponentInChildren<FirstPersonRaycaster>();
            if (raycaster == null)
                raycaster = FindObjectOfType<FirstPersonRaycaster>();
            if (raycaster == null)
                Debug.LogWarning("FirstPersonRaycaster not found! Please assign or add it to the player.");
            ControllerLocator.Instance.Register(this);

        }

        void Update()
        {
            DetectInteractable();
        }

        void DetectInteractable()
        {
            if (raycaster == null) return;
            GameObject lookAtObj = raycaster.CurrentLookAtObject;
            IEditable hitEditable = lookAtObj != null ? lookAtObj.GetComponent<IEditable>() : null;

            // 如果命中对象与之前注视的不一样，触发进入/离开事件
            if (hitEditable != previousGazedTarget)
            {
                if (previousGazedTarget != null)
                {
                    previousGazedTarget.OnGazeExit(this);
                }

                if (hitEditable != null)
                {
                    hitEditable.OnGazeEnter(this);
                }

                previousGazedTarget = hitEditable;
            }

            currentTarget = hitEditable;
        }

        public IEditable GetCurrentTarget()
        {
            return currentTarget;
        }

        void OnDrawGizmos()
        {
            // 交由 FirstPersonRaycaster 绘制射线
        }
    }
}