using ScrambleKit;
using UnityEngine;

public class MouseMovement : MonoBehaviour
{
    public FXTrigger stepFX;

    public Transform targetX;

    public float wiggleHz = 2f;
    public float wiggleScale = 0.1f;
    public Transform bodyToWiggle;

    public float ArrivalRadius = 0.05f;
    private TopDownMovement move;
    private Vector2 moveToPos;

    private bool wigglingUp = false;

    void Start()
    {
        move = GetComponent<TopDownMovement>();
        moveToPos = transform.position;
    }

    private Vector2 ClampToGameplayArea(Vector2 raw)
    {
        float x = Mathf.Clamp(raw.x, -10.67f, 10.67f);
        float y = Mathf.Clamp(raw.y, -6f, 6f);
        return new Vector2(x, y);
    }

    void WalkWiggle()
    {
        // use a sin curve to squash the y scale of the player
        // to make it look like they're walking
        float wiggle = Mathf.Sin(Time.time * wiggleHz * 2* Mathf.PI);
        bodyToWiggle.localScale = new Vector3(1f + wiggle* wiggleScale, 1f - wiggle* wiggleScale, 1f);

        float turn = Mathf.Sin(Time.time * 2 * wiggleHz * 2 * Mathf.PI);
        bodyToWiggle.localEulerAngles = new Vector3(0, 0, turn * 2f);

        if(wiggle > 0 && !wigglingUp)
        {
            wigglingUp = true;
            stepFX.Trigger(transform);
        }
        else if(wiggle < 0 && wigglingUp)
        {
            wigglingUp = false;
            stepFX.Trigger(transform);
        }
    }

    void ResetWiggle()
    {
        bodyToWiggle.localScale = Vector3.one;
        bodyToWiggle.localEulerAngles = Vector3.zero;
    }

    void Update()
    {
        if (Input.GetMouseButtonDown(0))
        {
            moveToPos = ClampToGameplayArea(Camera.main.ScreenToWorldPoint(Input.mousePosition));
            targetX.gameObject.SetActive(true);
            targetX.position = moveToPos;
        }

        if(Vector2.Distance(transform.position, moveToPos) < ArrivalRadius)
        {
            move.moveDir = Vector2.zero;
            targetX.gameObject.SetActive(false);
            ResetWiggle();
            return;
        }

        move.moveDir = (moveToPos - (Vector2)transform.position).normalized;
        WalkWiggle();
    }
}
