import 'package:flutter/material.dart';
import 'package:url_launcher/url_launcher.dart';

import '../widgets/app_toast.dart';
import '../widgets/outbound_service_sheet.dart';

Future<void> openExternalUrl(
  BuildContext context,
  String url, {
  String title = '即将打开外部服务',
  String description = '你将离开金值，进入第三方服务页面。外部内容由对应服务提供。\n价格与资讯仅供参考，不构成投资建议。',
  String fallbackToast = '链接即将上线',
}) async {
  if (url.isEmpty) {
    toastInfo(msg: fallbackToast);
    return;
  }

  final uri = Uri.tryParse(url);
  if (uri == null || !uri.hasScheme) {
    toastInfo(msg: fallbackToast);
    return;
  }

  final ok = await showOutboundServiceSheet(
    context,
    title: title,
    description: description,
  );
  if (ok != true || !context.mounted) return;

  final launched = await launchUrl(uri, mode: LaunchMode.externalApplication);
  if (!launched && context.mounted) {
    toastInfo(msg: fallbackToast);
  }
}
