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

namespace Infrastructure.Unity
{
    public class FloorVisibilityManager : MonoBehaviour
    {
        [SerializeField] private float fadeSpeed = 5f;
        [SerializeField] private float hiddenAlpha = 0.1f;
        [SerializeField] private float visibleAlpha = 1.0f;

        private List<List<TileViewAdapter>> _floors;
        private int _currentFloorIndex = -1;

        public void Initialize(TileRegistry registry, int totalFloors)
        {
            _floors = registry.GroupViewsByFloor(totalFloors);
        }

        // Call this from GameBootstrap.Update()
        public void UpdateFloorVisibility(int playerFloorIndex)
        {
            if (_currentFloorIndex == playerFloorIndex) return;

            _currentFloorIndex = playerFloorIndex;
            StopAllCoroutines();
            StartCoroutine(UpdateFloorsRoutine(playerFloorIndex));
        }

        private IEnumerator UpdateFloorsRoutine(int playerFloor)
        {
            for (var i = 0; i < _floors.Count; i++)
            {
                var targetAlpha = (i < playerFloor) ? hiddenAlpha : visibleAlpha;

                if (_floors[i].Count == 0) continue;

                foreach (var tile in _floors[i])
                {
                    if (tile && tile.gameObject.activeInHierarchy)
                    {
                        tile.SetAlpha(targetAlpha);
                    }
                }

                if (i % 2 == 0) yield return null;
            }
        }
    }
}
