import 'dart:async';
// ignore: avoid_web_libraries_in_flutter
import 'dart:js' as js;
import 'package:flutter/foundation.dart';
import 'package:prosapp_web_app/services/api_service.dart';

class MapsService {
  static bool _loaded = false;
  static Completer<bool>? _completer;

  static Future<bool> load() async {
    if (_loaded) return true;
    if (_completer != null) return _completer!.future;

    _completer = Completer<bool>();

    try {
      final data = await ApiService.instance.get('/settings/maps-key');
      final apiKey = data['api_key'] as String? ?? '';

      if (apiKey.isEmpty) {
        debugPrint('MapsService: API key no configurada');
        _completer!.complete(false);
        return false;
      }

      if (kIsWeb) {
        _injectScript(apiKey);
      }

      _loaded = true;
      _completer!.complete(true);
      return true;
    } catch (e) {
      debugPrint('MapsService: error cargando key — $e');
      _completer!.complete(false);
      return false;
    }
  }

  static void _injectScript(String apiKey) {
    // Verifica si ya está cargado
    final existing = js.context.callMethod('eval', [
      'typeof google !== "undefined" && typeof google.maps !== "undefined"'
    ]);
    if (existing == true) {
      _loaded = true;
      return;
    }

    js.context.callMethod('eval', ['''
      (function() {
        var s = document.createElement('script');
        s.src = 'https://maps.googleapis.com/maps/api/js?key=$apiKey';
        s.async = true;
        document.head.appendChild(s);
      })();
    ''']);
  }
}
