using System.Collections;
using UnityEngine;

public class TrapBlock : MonoBehaviour
{
    [SerializeField] private int damage = 10;
    [SerializeField] private float activationTime = 2f;
    [SerializeField] private float damageInterval = 1f;

    private Coroutine trapCoroutine;

    private void OnCollisionEnter2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
            Player player = collision.gameObject.GetComponent<Player>();
            if (player != null)
            {
                if (trapCoroutine != null)
                {
                    StopCoroutine(trapCoroutine);
                }

                trapCoroutine = StartCoroutine(ProcessTrapDamage(player));
            }
        }
    }

    private void OnCollisionExit2D(Collision2D collision)
    {
        if (collision.gameObject.CompareTag("Player"))
        {
                StopCoroutine(trapCoroutine);
                trapCoroutine = null;
        }
    }

    private IEnumerator ProcessTrapDamage(Player player)
    {
        yield return new WaitForSeconds(activationTime);
        while (player != null)
        {
            player.TakeDamage(damage);
            yield return new WaitForSeconds(damageInterval);
        }
    }
}