using System.Collections;
using System.Collections.Generic;
using UnityEngine;

public class Floater : MonoBehaviour
{
    public Rigidbody2D body;
    public LayerMask waterLayer;
    public bool enableFloating;

    [Header("Float Height")]
    public float floatOffset;

    [Header("Rotation")]
    public bool alignToWaves;
    public float originalAngle;

    [Header("Control")]
    public bool controllable;
    public float sailSpeed;
    public Vector2 jumpForce;
    public float jumpGravityScale;

    [Header("Auto Move")]
    public bool autoMove;
    public float autoMoveSpeed;
   

    private float rayDistance = 25f;
    private Vector2 raycastOrigin = new Vector2(0f, 5f);


    void Start()
    {
        raycastOrigin.x = transform.position.x;
    }

    void Update()
    {
        if (enableFloating)
        {
            Float();
        }
        if (alignToWaves)
        {
            AdjustRotation(originalAngle);
        }
    }
        
    public void Float()
    {
        raycastOrigin.x = transform.position.x;

        if (controllable)
        {
            raycastOrigin.x += Input.GetAxis("Horizontal") * sailSpeed * Time.deltaTime;
        }
        if (autoMove)
        {
            raycastOrigin.x += autoMoveSpeed * Time.deltaTime;
        }

        Debug.DrawRay(raycastOrigin, Vector2.down * rayDistance, Color.green);
        RaycastHit2D raycastHit = Physics2D.Raycast(raycastOrigin, Vector2.down, rayDistance, waterLayer);
        var raycastHitPoint = raycastHit.point;
        raycastHitPoint.y += floatOffset;
        transform.position = raycastHitPoint;
    }

    private void AdjustRotation(float originalAngle = 0f)
    {
        var leftAnchor = raycastOrigin;
        leftAnchor.x -= 0.1f;

        var rightAnchor = raycastOrigin;
        rightAnchor.x += 0.1f;

        var rightAnchorRaycastHit = Physics2D.Raycast(rightAnchor, Vector2.down, rayDistance, waterLayer);
        var leftAnchorRaycastHit = Physics2D.Raycast(leftAnchor, Vector2.down, rayDistance, waterLayer);
        var directionVector = rightAnchorRaycastHit.point - leftAnchorRaycastHit.point;

        var angle = Mathf.Atan2(directionVector.y, directionVector.x) * Mathf.Rad2Deg;

        transform.localRotation = Quaternion.Euler(transform.localRotation.x, transform.localRotation.y, originalAngle + angle);
    }
}
