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

// 旧版 H5 相机兼容层 JavaScript 代码
// 通过替换 `window.openCamera` / `capturePhoto` 的方式兼容老页面。

const String _legacyCameraCompatScript = '''
  if (!window.__appShellLegacyCameraCompatInstalled) {
    window.__appShellLegacyCameraCompatInstalled = true;

    const installLegacyCameraCompat = () => {
      if (typeof window.openCamera !== 'function') {
        return false;
      }
      if (window.openCamera.__appShellCompatWrapped) {
        return true;
      }

      const originalOpenCamera = window.openCamera.bind(window);
      const originalCapturePhoto =
        typeof window.capturePhoto === 'function'
          ? window.capturePhoto.bind(window)
          : null;

      const deliverCaptureResult = (args, result) => {
        const detail = {
          args: Array.from(args),
          result,
        };

        if (typeof window.handleNativeCapture === 'function') {
          window.handleNativeCapture(detail);
          return true;
        }

        const targetId =
          detail.args[0] ??
          window.currentUploadId ??
          null;

        if (
          targetId != null &&
          result &&
          result.dataUrl &&
          typeof window.addPreview === 'function'
        ) {
          window.currentUploadId = targetId;
          window.addPreview(targetId, result.dataUrl);
          return true;
        }

        window.dispatchEvent(
          new CustomEvent('app-shell-image-captured', {
            detail,
          }),
        );
        return false;
      };

      const closeLegacyCameraModal = () => {
        if (typeof window.closeCamera === 'function') {
          try {
            window.closeCamera();
          } catch (_) {}
        }
      };

      const wrappedOpenCamera = async function(...args) {
        try {
          const result = await window.AppShell.captureImage({
            responseType: 'dataUrl',
          });
          const delivered = deliverCaptureResult(args, result);
          if (!delivered) {
            return result;
          }
          closeLegacyCameraModal();
          return result;
        } catch (error) {
          console.warn(
            '[AppShell] legacy openCamera fallback to page implementation',
            error,
          );
          return originalOpenCamera(...args);
        }
      };

      wrappedOpenCamera.__appShellCompatWrapped = true;
      window.openCamera = wrappedOpenCamera;

      if (originalCapturePhoto) {
        const wrappedCapturePhoto = function(...args) {
          if (
            window.currentUploadId != null &&
            window.__lastAppShellCaptureResult &&
            window.__lastAppShellCaptureResult.dataUrl &&
            typeof window.addPreview === 'function'
          ) {
            window.addPreview(
              window.currentUploadId,
              window.__lastAppShellCaptureResult.dataUrl,
            );
            closeLegacyCameraModal();
            return;
          }
          return originalCapturePhoto(...args);
        };
        wrappedCapturePhoto.__appShellCompatWrapped = true;
        window.capturePhoto = wrappedCapturePhoto;
      }

      return true;
    };

    const originalCaptureImage = window.AppShell.captureImage;
    window.AppShell.captureImage = async function(options = {}) {
      const result = await originalCaptureImage(options);
      window.__lastAppShellCaptureResult = result;
      return result;
    };

    installLegacyCameraCompat();

    let attempts = 0;
    const compatTimer = setInterval(() => {
      attempts += 1;
      const installed = installLegacyCameraCompat();
      if (installed || attempts >= 20) {
        clearInterval(compatTimer);
      }
    }, 500);
  }
''';
