using System;

namespace Core.Domain
{
    public class Tile
    {
        public string Id { get; }
        public int Floor { get; }
        public TileType Type { get; }

        public TileState CurrentState { get; private set; }

        private readonly float _warningDuration;
        private readonly float _fallingDuration;

        private float _stateTimer;

        public event Action<Tile> OnStateChanged;

        public Tile(string id, int floor, float warningDuration, float fallingDuration, TileType type = TileType.Normal)
        {
            Id = id;
            Floor = floor;
            Type = type;

            _warningDuration = warningDuration;
            _fallingDuration = fallingDuration;
            CurrentState = TileState.Stable;
        }

        public void StepOn()
        {
            if (CurrentState == TileState.Stable)
            {
                if (Type == TileType.Fragile)
                {
                    TransitionTo(TileState.Falling);
                }
                else
                {
                    TransitionTo(TileState.Warning);
                }
            }
        }

        public void Tick(float deltaTime)
        {
            if (CurrentState == TileState.Stable || CurrentState == TileState.Destroyed) return;

            _stateTimer += deltaTime;

            if (CurrentState == TileState.Warning && _stateTimer >= _warningDuration)
            {
                TransitionTo(TileState.Falling);
            }
            else if (CurrentState == TileState.Falling && _stateTimer >= _fallingDuration)
            {
                TransitionTo(TileState.Destroyed);
            }
        }

        private void TransitionTo(TileState newState)
        {
            CurrentState = newState;
            _stateTimer = 0f;
            OnStateChanged?.Invoke(this);
        }
    }
}