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

namespace UVC.Twin.MonitoringUI
{
    public class EquipmentCardsRowController
    {
        private readonly VisualElement _root;
        private readonly ScrollView _scrollView;
        private readonly List<EquipmentCardController> _cards = new();
        private EquipmentCardController _activeCard;
        private bool _isValid;

        public event Action<string> OnCardClicked;

        public EquipmentCardsRowController(VisualElement root)
        {
            _root = root;
            _scrollView = root.Q<ScrollView>(ElementIds.EquipmentCardsScrollView);

            if (_scrollView == null)
            {
                Debug.LogError("[MonitoringUI] EquipmentCardsRow: ScrollView not found");
                return;
            }

            _isValid = true;
        }

        public void SetCards(IReadOnlyList<EquipmentCardData> cardsData)
        {
            if (!_isValid) return;

            _scrollView.Clear();
            _cards.Clear();
            _activeCard = null;

            foreach (var data in cardsData)
            {
                var card = new EquipmentCardController(data);

                var capturedCard = card;
                card.OnClicked += id =>
                {
                    SetActiveCard(capturedCard);
                    OnCardClicked?.Invoke(id);
                };

                _scrollView.Add(card.Root);
                _cards.Add(card);
            }
        }

        private void SetActiveCard(EquipmentCardController card)
        {
            _activeCard?.SetActive(false);
            card.SetActive(true);
            _activeCard = card;
        }
    }
}
