using Unity.Netcode;
using UnityEngine;
using UnityEngine.InputSystem;
using Unity.Cinemachine;

public class NetworkPlayerController : NetworkBehaviour
{
    [Header("Movement Settings")]
    public float moveSpeed = 5f;
    public float rotationSpeed = 10f;

    private Vector2 _moveInput;
    private CharacterController _controller;
    private PlayerInputActions _inputActions;
    private Animator _animator;

    void Awake()
    {
        _controller = GetComponent<CharacterController>();
        _animator = GetComponent<Animator>();
    }

    public override void OnNetworkSpawn()
    {
        if (!IsOwner) return;

        var vcam = GameObject.FindFirstObjectByType<CinemachineCamera>();

        if (vcam != null)
        {
            vcam.Follow = transform;
            vcam.LookAt = transform;
            Debug.Log("<color=green>[Camera] 로컬 플레이어에게 카메라가 연결되었습니다.</color>");
        }

        _inputActions = new PlayerInputActions();
        _inputActions.Enable();
    }

    public override void OnNetworkDespawn()
    {
        if (IsOwner && _inputActions != null)
        {
            _inputActions.Disable();
        }
    }

    void Update()
    {
        if (!IsOwner) return;

        _moveInput = _inputActions.Player.Move.ReadValue<Vector2>();
        Vector3 move = new Vector3(_moveInput.x, 0, _moveInput.y).normalized;

        if (move.magnitude >= 0.1f)
        {
            Quaternion targetRotation = Quaternion.LookRotation(move);
            transform.rotation = Quaternion.Slerp(transform.rotation, targetRotation, rotationSpeed * Time.deltaTime);

            if (_controller != null)
            {
                _controller.Move(move * moveSpeed * Time.deltaTime);
            }
        }

        if (_animator != null)
        {
            _animator.SetFloat("MoveSpeed", move.magnitude);
        }
    }
}
