import 'package:flutter/foundation.dart';
import 'package:mypoint_flutter_app/configs/url_params.dart';
import 'web_helper.dart';

/// Web-specific initialization and configuration
class WebAppInitializer {
  static final WebAppInitializer _instance = WebAppInitializer._internal();
  factory WebAppInitializer() => _instance;
  WebAppInitializer._internal();

  // Ensure web initialization runs only once per app lifecycle
  static bool _didInit = false;
  // Ensure we only start one polling sequence for SDK data
  static bool _startedSdkPolling = false;

  /// Initialize all web-specific features
  static Future<void> initialize() async {
    if (!kIsWeb) return;
    if (_didInit) {
      // Prevent re-initialization on hot reload / route changes
      return;
    }
    _didInit = true;

    print('🌐 Initializing web-specific features...');
    
    // Handle URL parameters
    _handleWebUrlParams();
    
    // Initialize x-app-sdk
    _initializeXAppSDK();
  }

  /// Handle URL parameters for web
  static void _handleWebUrlParams() {
    print('🔍 Handling web URL parameters...');
    final uri = Uri.base;
    print('🔍 Current URI: ${uri.toString()}');
    
    final token = uri.queryParameters['token'];
    final userId = uri.queryParameters['userId'];
    print('🔍 Web URL Params: {token: $token, user_id: $userId}');
    
    if (token != null && token.isNotEmpty) {
      UrlParams.setToken(token);
      UrlParams.setUserId(userId);
      print('✅ Token set from URL: $token');
      print('🔍 UrlParams after set: ${UrlParams.allParams}');
      // Clean URL to remove query params
      webReplaceUrl('/');
    } else {
      print('❌ No token found in URL parameters');
    }
  }

  /// Initialize x-app-sdk service
  static void _initializeXAppSDK() {
    print('🔍 Initializing x-app-sdk...');
    
    // Check if x-app-sdk is available from Super App
    final isSDKAvailable = webIsSDKAvailable();
    print('🔍 XAppSDK available from Super App: $isSDKAvailable');
    
    // Always try to initialize once (no-op on non-web/stub)
    webInitializeXAppSDK().then((_) {
      print('✅ XAppSDK service initialized');
      // Only poll for data if SDK is actually available from host
      if (isSDKAvailable) {
        if (_startedSdkPolling) return;
        _startedSdkPolling = true;
        // Wait a bit for JavaScript to initialize and then check for data
        _checkForAppHostData(0); // Start with retry count 0
      } else {
        print('ℹ️ XAppSDK not available – skipping polling outside Super App.');
        print('💡 Tip: Test with URL params, e.g. ?token=test123&userId=user123');
      }
    }).catchError((error) {
      print('❌ Error initializing XAppSDK: $error');
    });
  }

  /// Check for app host data with retry mechanism (max 3 retries)
  static void _checkForAppHostData(int retryCount) {
    print('🔍 Checking for app host data... (attempt ${retryCount + 1}/4)');
    
    // Wait a bit for JavaScript to initialize
    Future.delayed(const Duration(milliseconds: 1000), () {
      final token = webGetAppHostToken();
      final user = webGetAppHostUser();
      final error = webGetAppHostError();
      final isReady = webIsAppHostDataReady();
      
      print('🔍 Data check result:');
      print('   Token: ${token != null ? '***${token.substring(0, 8)}...' : 'null'}');
      print('   User: ${user?.toString() ?? 'null'}');
      print('   Error: ${error ?? 'null'}');
      print('   Ready: $isReady');
      
      if (token != null && token.isNotEmpty) {
        print('✅ Token from Super App: ${token.substring(0, 8)}...');
        UrlParams.setToken(token);
        
        if (user != null) {
          print('✅ User from Super App: $user');
          UrlParams.setUserId(user['id']?.toString());
          // Store user data for later use
          webStoreAppHostData(token, user);
        }
      } else if (error != null) {
        print('❌ Error from Super App: $error');
      } else if (!isReady && retryCount < 3) {
        print('⏳ App host data not ready yet, will retry... (${retryCount + 1}/3)');
        // Retry after a longer delay
        Future.delayed(const Duration(milliseconds: 2000), () {
          _checkForAppHostData(retryCount + 1);
        });
      } else if (retryCount >= 3) {
        print('❌ Max retries reached (3), giving up on Super App data');
        print('💡 You can test with URL parameters: ?token=test123&user={"id":"user123"}');
      } else {
        print('❌ No token found from Super App');
      }
    });
  }
}
