using UnityEngine;

[RequireComponent(typeof(Rigidbody2D))]
[RequireComponent(typeof(Collider2D))]
public class DraggableObject : MonoBehaviour
{
    [Header("Přetahování")]
    public float dragSmoothness = 15f;

    [Header("Vizuální zpětná vazba")]
    public SpriteRenderer spriteRenderer;
    public Color normalColor = Color.white;
    public Color dragColor = new Color(1f, 1f, 0.5f);
    public float scaleOnDrag = 1.15f;

    private Rigidbody2D rb;
    private Camera mainCamera;
    private bool isDragging = false;
    private Vector3 targetPosition;
    private Vector3 originalScale;
    private bool hasBeenScored = false;

    void Awake()
    {
        rb = GetComponent<Rigidbody2D>();
        mainCamera = Camera.main;
        originalScale = transform.localScale;

        if (spriteRenderer == null)
            spriteRenderer = GetComponent<SpriteRenderer>();
    }

    void Start()
    {
        rb.gravityScale = 0f;
        rb.constraints = RigidbodyConstraints2D.FreezeRotation;
        targetPosition = transform.position;
    }

    void Update()
    {
        HandleInput();

        if (isDragging)
            transform.position = Vector3.Lerp(transform.position, targetPosition, Time.deltaTime * dragSmoothness);
    }

    void HandleInput()
    {

        if (Input.touchCount > 0)
        {
            Touch touch = Input.GetTouch(0);
            Vector3 worldPos = mainCamera.ScreenToWorldPoint(new Vector3(touch.position.x, touch.position.y, 10f));

            if (touch.phase == TouchPhase.Began)           TryStartDrag(worldPos);
            else if (touch.phase == TouchPhase.Moved ||
                     touch.phase == TouchPhase.Stationary) { if (isDragging) targetPosition = worldPos; }
            else if (touch.phase == TouchPhase.Ended ||
                     touch.phase == TouchPhase.Canceled)   { if (isDragging) EndDrag(); }
        }
        // na twest pro myŠ
        else
        {
            Vector3 worldPos = mainCamera.ScreenToWorldPoint(new Vector3(Input.mousePosition.x, Input.mousePosition.y, 10f));

            if (Input.GetMouseButtonDown(0))      TryStartDrag(worldPos);
            else if (Input.GetMouseButton(0) && isDragging) targetPosition = worldPos;
            else if (Input.GetMouseButtonUp(0) && isDragging) EndDrag();
        }
    }

    void TryStartDrag(Vector3 worldPos)
    {
        if (GetComponent<Collider2D>().OverlapPoint(worldPos))
            StartDrag(worldPos);
    }

    void StartDrag(Vector3 worldPos)
    {
        isDragging = true;
        rb.linearVelocity = Vector2.zero;
        targetPosition = worldPos;

        transform.localScale = originalScale * scaleOnDrag;
        if (spriteRenderer != null)
        {
            spriteRenderer.color = dragColor;
            spriteRenderer.sortingOrder = 10;
        }
    }

    void EndDrag()
    {
        isDragging = false;
        transform.localScale = originalScale;
        if (spriteRenderer != null)
        {
            spriteRenderer.color = normalColor;
            spriteRenderer.sortingOrder = 0;
        }
    }

    public void OnScored()
    {
        if (hasBeenScored) return;
        hasBeenScored = true;
        isDragging = false;

        StartCoroutine(SinkIntoHole());
    }

    System.Collections.IEnumerator SinkIntoHole()
    {
        float duration = 0.35f;
        float elapsed = 0f;
        Vector3 startScale = transform.localScale;

        while (elapsed < duration)
        {
            elapsed += Time.deltaTime;
            float t = elapsed / duration;
            transform.localScale = Vector3.Lerp(startScale, Vector3.zero, t);
            if (spriteRenderer != null)
                spriteRenderer.color = new Color(normalColor.r, normalColor.g, normalColor.b, 1f - t);
            yield return null;
        }

        gameObject.SetActive(false);

        LevelManager.Instance?.RegisterItem();
    }
}
