import 'dart:async';
import 'dart:js_interop';

import 'package:qpay/config/app_config.dart';
import 'package:web/web.dart' as web;

@JS('Checkout')
external JSAny? _checkout;

@JS('configure')
external void configure(String sessionID);

@JS('showEmbeddedPage')
external void showEmbeddedPage();

Future<void> ensureCheckoutScriptLoaded() async {
  final existing = web.document.querySelector('#mastercard-checkout-script');
  if (existing is web.HTMLScriptElement) {
    await _waitForCheckout();
    return;
  }

  final scriptUrl = AppConfig.gatewayScriptUrl;

  final scriptElement = web.HTMLScriptElement()
    ..id = 'mastercard-checkout-script'
    ..src = scriptUrl
    ..async = true;

  web.document.head?.append(scriptElement);
  await _waitForCheckout();
}

Future<void> _waitForCheckout() async {
  const maxAttempts = 100;
  for (var attempt = 0; attempt < maxAttempts; attempt++) {
    if (_checkout != null) {
      return;
    }
    await Future.delayed(const Duration(milliseconds: 100));
  }

  throw StateError('Mastercard Checkout script failed to load before timeout.');
}
