// ignore_for_file: avoid_web_libraries_in_flutter, deprecated_member_use

import 'dart:async';
import 'dart:convert';
import 'package:web/web.dart' as web;
import 'package:flutter/foundation.dart';
import 'dart:js_interop';
import 'auth_token_store.dart';
import '../i18n/locale_utils.dart';

void implSendLoginSuccess(String token) {
  var effectiveToken = token;
  if (effectiveToken.isEmpty) {
    effectiveToken = AuthTokenStore.getToken() ?? "";
  }

  final fullUrl = web.window.location.href;
  final uri = Uri.base;

  // Try to find redirect_uri from standard parsing first, then manual string search
  String? redirectUri =
      uri.queryParameters['redirect_uri'] ??
      uri.queryParameters['redirect_url'];

  if (redirectUri == null) {
    // Manual fallback for cases where Uri.base misses params
    final searchParams = web.window.location.search;
    if (searchParams.isNotEmpty) {
      final sUri = Uri.parse(
        '?${searchParams.startsWith('?') ? searchParams.substring(1) : searchParams}',
      );
      redirectUri =
          sUri.queryParameters['redirect_uri'] ??
          sUri.queryParameters['redirect_url'];
    }
  }

  // Final fallback: regex or manual search in fullUrl
  if (redirectUri == null) {
    for (final key in ['redirect_uri=', 'redirect_url=']) {
      if (fullUrl.contains(key)) {
        final start = fullUrl.indexOf(key) + key.length;
        var end = fullUrl.indexOf('&', start);
        if (end == -1) end = fullUrl.length;
        final raw = fullUrl.substring(start, end);
        try {
          redirectUri = Uri.decodeComponent(raw);
          break;
        } catch (_) {}
      }
    }
  }

  if (redirectUri != null && redirectUri.isNotEmpty) {
    // Redirection flow
    final target = Uri.parse(redirectUri);
    final query = Map<String, String>.from(target.queryParameters);
    query['token'] = effectiveToken;
    final finalUri = target.replace(queryParameters: query);

    debugPrint('Redirecting to: ${finalUri.toString()}');
    web.window.location.href = finalUri.toString();
    return;
  }

  final message = {'type': 'LOGIN_SUCCESS', 'token': effectiveToken};
  final opener = web.window.opener;

  if (opener != null) {
    try {
      // Use JSON string for safer cross-origin/WASM messaging if direct object fails
      final jsonMsg = jsonEncode(message);
      (opener as web.Window).postMessage(jsonMsg.toJS, '*'.toJS);
      debugPrint('Sent login success message to opener');
    } catch (e) {
      debugPrint('Failed to postMessage: $e');
    }

    // Close the popup after a short delay to ensure message sending
    Timer(const Duration(milliseconds: 500), () {
      try {
        web.window.close();
      } catch (e) {
        debugPrint('Failed to close window: $e');
      }
    });
    return;
  }

  // No opener and no redirect: fall back to local navigation
  final fallbackTarget = buildLocalizedHomePath(Uri.base);
  debugPrint('No opener found. Redirecting to $fallbackTarget.');
  web.window.location.href = fallbackTarget;
}

bool implIsPopup() {
  return web.window.opener != null;
}
