﻿using UnityEngine;
using UnityEngine.InputSystem;

/// <summary>
/// Lit les inputs via le New Input System (pattern C# Generated Class).
/// Instancie directement PlayerAction (classe générée depuis l'Input Action Asset)
/// et s'abonne aux callbacks — aucun composant PlayerInput nécessaire sur le GameObject.
/// N'applique aucune physique : responsabilité unique = gérer les entrées.
/// </summary>
[RequireComponent(typeof(PlayerMotor))]
public class PlayerController : MonoBehaviour
{
    // ── Références ────────────────────────────────────────────────────────────
    private PlayerMotor _motor;
    private PlayerAction _actions;

    // ── État des inputs (mis à jour par les callbacks) ────────────────────────
    private Vector2 _moveInput;
    private Vector2 _lookInput;

    // ─────────────────────────────────────────────────────────────────────────
    // Lifecycle
    // ─────────────────────────────────────────────────────────────────────────

    private void Awake()
    {
        _motor = GetComponent<PlayerMotor>();
        _actions = new PlayerAction();

        // ── Move ──────────────────────────────────────────────────────────────
        _actions.Player.Move.performed += ctx =>
        {
            Vector2 raw = ctx.ReadValue<Vector2>();
            _moveInput = raw.sqrMagnitude > 1f ? raw.normalized : raw;
        };
        _actions.Player.Move.canceled += _ => _moveInput = Vector2.zero;

        // ── Look ──────────────────────────────────────────────────────────────
        _actions.Player.Look.performed += ctx => _lookInput = ctx.ReadValue<Vector2>();
        _actions.Player.Look.canceled += _ => _lookInput = Vector2.zero;

        // ── Jump ──────────────────────────────────────────────────────────────
        _actions.Player.Jump.performed += _ => _motor.Jump();

        // ── ToggleCursor ──────────────────────────────────────────────────────
        _actions.Player.ToggleCursor.performed += _ =>
            LockCursor(Cursor.lockState != CursorLockMode.Locked);
    }

    private void Start()
    {
        LockCursor(true);
    }

    private void OnEnable() => _actions.Player.Enable();
    private void OnDisable() => _actions.Player.Disable();

    // ─────────────────────────────────────────────────────────────────────────
    // Update — transmet les inputs continus au Motor
    // ─────────────────────────────────────────────────────────────────────────

    private void Update()
    {
        _motor.Move(_moveInput);

        if (Cursor.lockState == CursorLockMode.Locked)
            _motor.RotateCamera(_lookInput);
    }

    // ─────────────────────────────────────────────────────────────────────────
    // Utilitaires
    // ─────────────────────────────────────────────────────────────────────────

    private void LockCursor(bool locked)
    {
        Cursor.lockState = locked ? CursorLockMode.Locked : CursorLockMode.None;
        Cursor.visible = !locked;
    }
}