import 'package:mypoint_flutter_app/core/network/restful_api_client_all_request.dart';
import 'package:mypoint_flutter_app/features/popup_manager/popup_manager_model.dart';
import '../../core/network/restful_api_viewmodel.dart';

class PopupManagerViewModel extends RestfulApiViewModel {
  PopupManagerViewModel._();
  static final PopupManagerViewModel instance = PopupManagerViewModel._();

  final Set<String> _shownIds = {};
  List<PopupManagerModel>? _popupData;
  bool _loaded = false;
  Future<void>? _loadingFuture;

  Future<void> ensureLoaded() async {
    if (_loaded) return;
    if (_loadingFuture != null) {
      return _loadingFuture;
    }
    _loadingFuture = _getPopupManagerDataInternal();
    await _loadingFuture;
  }

  Future<void> _getPopupManagerDataInternal() async {
    try {
      final response = await client.getPopupManagerCommonScreen();
      _popupData = response.data ?? [];
      _loaded = true;
    } catch (e) {
      _popupData = [];
      _loaded = true;
      rethrow;
    } finally {
      _loadingFuture = null;
    }
  }

  PopupManagerModel? getForScreen(String screenName) {
    if (_popupData == null || _popupData!.isEmpty) return null;
    final idx = _popupData!.indexWhere(
      (e) => (e.screenToShow ?? '').trim().toUpperCase() == screenName.trim().toUpperCase(),
    );
    if (idx < 0) return null;
    final found = _popupData![idx];
    if (_shownIds.contains(found.id)) return null;
    return found;
  }

  Future<void> markShownOnce(String popupId) async {
    _shownIds.add(popupId);
  }

  Future<void> reset() async {
    _shownIds.clear();
    _popupData = [];
    _loaded = false;
    _loadingFuture = null;
  }
}
