using UnityEngine;
using UnityEngine.InputSystem;
using System.Collections;

public class Player : MonoBehaviour
{
    public GameObject gameBoard;

    public AudioClip flip;

    public AudioClip normalShoot;

    public AudioClip laserCharge;

    public AudioClip laserDischarge;

    public AudioClip laserShoot;

    public AudioClip magnetIdle;

    public AudioClip magnetShoot;

    public AudioClip death;

    public AudioClip killed;

    public AudioClip defeat;

    public MusicManager musicManager;

    public Fader fader;

    private bool flipped = false;

    private bool gameOver = false;

    private AudioSource audioSource;

    // Start is called once before the first execution of Update after the MonoBehaviour is created
    void Start()
    {
        audioSource = GetComponent<AudioSource>();
        Cursor.visible = false;
    }

    // Update is called once per frame
    void Update()
    {
        if (gameBoard == null || Camera.main == null || Mouse.current == null)
        {
            return;
        }

        if (!TryGetWorldBounds(gameBoard, out Bounds boardBounds) || !TryGetWorldBounds(gameObject, out Bounds playerBounds))
        {
            Debug.LogWarning("Could not get world bounds for gameBoard or player.");
            return;
        }

        Vector2 mouseScreen = Mouse.current.position.ReadValue();
        Camera cam = Camera.main;

        // Keep movement on the same depth plane as the current player position.
        float screenZ = cam.WorldToScreenPoint(transform.position).z;
        Vector3 mouseWorld = cam.ScreenToWorldPoint(new Vector3(mouseScreen.x, mouseScreen.y, screenZ));

        Vector3 extents = playerBounds.extents;
        float clampedX = Mathf.Clamp(mouseWorld.x, boardBounds.min.x + extents.x, boardBounds.max.x - extents.x);
        float clampedY = Mathf.Clamp(mouseWorld.y, boardBounds.min.y + extents.y, boardBounds.max.y - extents.y);

        transform.position = new Vector3(clampedX, clampedY, transform.position.z);

        if (Keyboard.current != null)
        {
            if (Keyboard.current.spaceKey.wasPressedThisFrame)
            {
                flipped = !flipped;
                transform.eulerAngles = new Vector3(0, 0, flipped ? 90 : 0);
                audioSource.PlayOneShot(flip);
            }

            if (Keyboard.current.escapeKey.wasPressedThisFrame)
            {
                gameOver = true;
            }
        }

        if (gameOver)
        {
            StartCoroutine(EndGame());
            gameOver = false; // Reset gameOver to prevent multiple coroutine starts
        }
    }

    private static bool TryGetWorldBounds(GameObject target, out Bounds bounds)
    {
        Collider2D collider2D = target.GetComponent<Collider2D>();
        if (collider2D != null)
        {
            bounds = collider2D.bounds;
            return true;
        }

        Renderer renderer = target.GetComponent<Renderer>();
        if (renderer != null)
        {
            bounds = renderer.bounds;
            return true;
        }

        Collider collider3D = target.GetComponent<Collider>();
        if (collider3D != null)
        {
            bounds = collider3D.bounds;
            return true;
        }

        bounds = default;
        return false;
    }

    private IEnumerator EndGame()
    {
        musicManager.pauseMusic();
        audioSource.PlayOneShot(defeat);
        yield return new WaitForSeconds(1.3f);
        fader.resetFader();
    }
}
