using UnityEngine;
using DG.Tweening;
using ScrambleKit;

public class Umbrella : MonoBehaviour
{
	public float MaxFallSpeed = -0.5f;
	public float FallSpeedWobbleFactor = 0.1f;
	public float FallSpeedWobbleHz = 3f;

	public Vector3 ClosedPosition;
	public Vector3 ClosedEulers;
	public Vector3 OpenPosition;
	public Vector3 OpenEulers;
	public Sprite OpenSprite;
	public Sprite ClosedSprite;
	public float ChangeTime = 0.075f;

	public FXTrigger OpenFX;
	public FXTrigger CloseFX;

	private SpriteRenderer rend;
	private Rigidbody2D rb;
	private bool isOpen;

	void Update()
	{
		if (Scoreboard.instance.playerDied)
		{
			if (isOpen)
			{
				Close();
			}
			return;
		}

		bool keyHeld = Input.GetKey(KeyCode.Space) || Input.GetKey(KeyCode.W) || Input.GetKey(KeyCode.Z) || Input.GetKey(KeyCode.UpArrow);
		if (keyHeld && !isOpen)
		{
			Open();
		}
		else if (!keyHeld && isOpen)
		{
			Close();
		}
	}

	void FixedUpdate()
	{
		if (isOpen)
		{
			LimitFallSpeed();
		}
	}

	private void Close()
	{
		isOpen = false;
		transform.DOKill();
		transform.DOLocalMove(ClosedPosition, ChangeTime);
		transform.DOLocalRotate(ClosedEulers, ChangeTime);
		rend.sprite = ClosedSprite;
		CloseFX.Trigger(transform);
	}

	private void Open()
	{
		isOpen = true;
		transform.DOKill();
		transform.DOLocalMove(OpenPosition, ChangeTime);
		transform.DOLocalRotate(OpenEulers, ChangeTime * 0.3f).OnComplete(() => rend.sprite = OpenSprite);
		OpenFX.Trigger(transform);
	}

	private void LimitFallSpeed()
	{
		float wobble = Mathf.Sin(Time.fixedTime * FallSpeedWobbleHz * 2f * Mathf.PI) * FallSpeedWobbleFactor;
		float wobbledMaxFallSpeed = MaxFallSpeed * (1 + wobble);

		if (rb.velocity.y > wobbledMaxFallSpeed)
			return;

		float overfall = wobbledMaxFallSpeed - rb.velocity.y;  // ex: (-3) - (-5) = -3 + 5 = 2
		Vector3 accel = new Vector3(0, overfall, 0);
		Vector3 force = rb.mass * accel / Time.fixedDeltaTime;
		rb.AddForce(force);
	}

	void Start()
    {
		rend = GetComponent<SpriteRenderer>();
		rb = transform.root.GetComponent<Rigidbody2D>();
		isOpen = false;
		transform.localPosition = ClosedPosition;
		transform.localEulerAngles = ClosedEulers;
		rend.sprite = ClosedSprite;
    }

}
