// ignore_for_file: avoid_web_libraries_in_flutter, deprecated_member_use
import 'package:web/web.dart' as web;
import 'package:flutter/foundation.dart';
import 'dart:async';

class WebWindow {
  void setTitle(String title) {
    try {
      web.document.title = title;
    } catch (_) {}
  }

  void redirectTo(String url) {
    final currentHref = web.window.location.href;

    debugPrint(
      "[WebWindow] redirectTo start: current=$currentHref, target=$url",
    );

    // Most direct and safe way for WASM: location.href assignment via package:web
    Future.delayed(Duration.zero, () {
      try {
        web.window.location.href = url;
      } catch (e) {
        debugPrint("[WebWindow] CRITICAL JS ERROR: $e");
      }
    });

    // Check after delay
    Future<void>.delayed(const Duration(milliseconds: 800), () {
      final nowHref = web.window.location.href;
      if (nowHref == currentHref) {
        debugPrint(
          "[WebWindow] redirectTo no-op detected: current URL did not change",
        );
      }
    });
  }

  String currentHref() {
    return web.window.location.href;
  }

  String currentSearch() {
    return web.window.location.search;
  }

  void alert(String message) {
    try {
      web.window.alert(message);
    } catch (_) {}
  }

  void close() {
    try {
      web.window.close();
    } catch (_) {}
  }

  bool hasOpener() {
    try {
      return web.window.opener != null;
    } catch (_) {
      return false;
    }
  }

  bool redirectOpenerTo(String url) {
    try {
      final opener = web.window.opener;
      if (opener == null) return false;
      // In package:web, Window is not directly accessible from JSObject opener
      // This is a known tricky part for WASM. We'll use a safer approach.
      (opener as web.Window).location.href = url;
      return true;
    } catch (_) {
      return false;
    }
  }
}

final webWindow = WebWindow();
