part of '../../core_app.dart';

const String _appShellBridgeChannel = 'AppShellBridge';
const String _appShellBridgeVersion = '1.0.0';

Future<void> _injectAppShellBridge(
  WebViewController controller,
  String url,
) async {
  try {
    await controller.runJavaScript(_buildAppShellBridgeScript());
    debugPrint('已为 $url 注入 AppShell 桥接');
  } on Object catch (error, stackTrace) {
    debugPrint('注入 AppShell 桥接失败：$error\n$stackTrace');
  }
}

Future<void> _sendBridgeResponse(
  WebViewController controller, {
  required String requestId,
  required bool success,
  Object? data,
  String? error,
}) async {
  final response = <String, dynamic>{
    'requestId': requestId,
    'success': success,
    'data': data,
    'error': error,
  };

  try {
    await controller.runJavaScript(
      'window.__appShellReceiveResponse(${jsonEncode(response)});',
    );
  } on Object catch (bridgeError, stackTrace) {
    debugPrint(
      '发送 AppShell 桥接响应失败：$bridgeError\n$stackTrace',
    );
  }
}

String _buildAppShellBridgeScript() {
  return '''
(() => {
  const channel = window.$_appShellBridgeChannel;
  if (!channel || typeof channel.postMessage !== 'function') {
    return;
  }

  if (window.AppShell && window.AppShell.__nativeShellVersion === '$_appShellBridgeVersion') {
    return;
  }

  const pending = new Map();

  window.__appShellReceiveResponse = function(response) {
    if (!response || !response.requestId) {
      return;
    }

    const task = pending.get(response.requestId);
    if (!task) {
      return;
    }

    pending.delete(response.requestId);

    if (response.success) {
      task.resolve(response.data ?? null);
      return;
    }

    task.reject(new Error(response.error || 'Native request failed'));
  };

  const send = (action, payload = {}) => new Promise((resolve, reject) => {
    const requestId =
      Date.now().toString(36) + Math.random().toString(36).slice(2);
    pending.set(requestId, { resolve, reject });
    channel.postMessage(JSON.stringify({ requestId, action, payload }));
  });

  window.AppShell = {
    __nativeShellVersion: '$_appShellBridgeVersion',
    isNativeShell: true,
    version: '$_appShellBridgeVersion',
    pickImage: (options = {}) => send('pickImage', options),
    captureImage: (options = {}) => send('captureImage', options),
    pickFile: (options = {}) => send('pickFile', options),
    openExternal: (url) => send('openExternal', { url }),
    requestPermissions: (types = []) => send('requestPermissions', { types }),
    reloadPage: () => send('reloadPage'),
    goBack: () => send('goBack'),
    closeApp: () => send('closeApp'),
    getDeviceInfo: () => send('getDeviceInfo'),
    getNetworkStatus: () => send('getNetworkStatus'),
    showToast: (message, options = {}) => send('showToast', { message, ...options }),
    setStatusBar: (options = {}) => send('setStatusBar', options),
  };

  window.dispatchEvent(new CustomEvent('app-shell-ready', {
    detail: {
      version: '$_appShellBridgeVersion',
      isNativeShell: true,
    },
  }));

$_legacyCameraCompatScript
})();
''';
}
