import 'dart:async';
import 'dart:io';
import 'package:flutter/foundation.dart';
import 'package:universal_html/html.dart' as html;

class NetworkConnectivity {
  NetworkConnectivity._();
  static final NetworkConnectivity _ins = NetworkConnectivity._();
  factory NetworkConnectivity() => _ins;

  /// Kiểm tra nhanh có Internet hay không bằng DNS lookup.
  /// Mặc định ping DNS Cloudflare: one.one.one.one
  Future<bool> hasInternet({
    String host = 'one.one.one.one',
    Duration timeout = const Duration(seconds: 2),
  }) async {
    if (kIsWeb) {
      try {
        final online = html.window.navigator.onLine;
        return online ?? true;
      } catch (_) {
        return true;
      }
    }
    try {
      final res = await InternetAddress.lookup(host).timeout(timeout);
      return res.isNotEmpty && res.first.rawAddress.isNotEmpty;
    } on SocketException catch (_) {
      return false;
    } on TimeoutException catch (_) {
      return false;
    } catch (_) {
      return false;
    }
  }

  /// Tiện ích: đảm bảo online trước khi làm việc.
  /// Nếu offline -> gọi `showRetryDialog()` (trả về true nếu người dùng chọn Retry),
  /// rồi kiểm tra lại 1 lần nữa.
  Future<bool> ensureOnlineWithRetry({
    required Future<bool> Function() showRetryDialog,
    String host = 'one.one.one.one',
    Duration timeout = const Duration(seconds: 2),
  }) async {
    if (await hasInternet(host: host, timeout: timeout)) return true;

    final retry = await showRetryDialog();
    if (!retry) return false;

    return await hasInternet(host: host, timeout: timeout);
  }
}
