import { WorkerFactory as e } from "../common/src/webworker/workerFactory.mjs";
import { WORKER_CDN_URLS as t } from "./workerCDNUrls.mjs";
import { bigIntReplacer as n, reviveBigInts as r } from "./bridge/serialization.utils.mjs";
import { HinkalRNWorker as i } from "./bridge/HinkalRNWorker.mjs";
import { useCallback as a, useEffect as o, useRef as s } from "react";
import { DeviceEventEmitter as c, StyleSheet as l, View as u } from "react-native";
import { WebView as d } from "react-native-webview";
import { jsx as f } from "react/jsx-runtime";
//#region libs/shared/sdk/src/react-native/HinkalWebViewWorker.tsx
var p = `${new URL(Object.values(t)[0]).origin}/`;
e.rnWorkerFactory = (e) => new i(e);
var m = `
if (!window.__hinkalPageBoot) (function(){
  window.__hinkalPageBoot = true;
  var URLS = ${JSON.stringify(t)};
  var BLOBS = {};

  function replacer(_key, value){
    if (typeof value === 'bigint') return { __bigint: value.toString() };
    if (value instanceof Set) return { __set: Array.from(value) };
    if (value instanceof Map) return { __map: Array.from(value.entries()) };
    return value;
  }
  function revive(value){
    if (value === null || typeof value !== 'object') return value;
    var keys = Object.keys(value);
    if (keys.length === 1) {
      if (typeof value.__bigint === 'string') return BigInt(value.__bigint);
      if (Array.isArray(value.__set)) return new Set(value.__set.map(revive));
      if (Array.isArray(value.__map)) return new Map(value.__map.map(function(entry){ return [revive(entry[0]), revive(entry[1])]; }));
    }
    if (Array.isArray(value)) return value.map(revive);
    var out = {}; for (var i = 0; i < keys.length; i++) out[keys[i]] = revive(value[keys[i]]); return out;
  }
  function post(payload){ try { window.ReactNativeWebView.postMessage(JSON.stringify(payload, replacer)); } catch(_){} }
  function describe(error){
    if (!error) return 'worker error';
    if (error.message) return error.message;
    if (error.error && error.error.stack) return error.error.stack;
    try { return JSON.stringify(error); } catch(_){ return String(error); }
  }

  async function blobUrl(url){
    if (BLOBS[url]) return BLOBS[url];
    var response = await fetch(url);
    if (!response.ok) throw new Error('HTTP ' + response.status + ' ' + url);
    var body = await response.text();
    BLOBS[url] = URL.createObjectURL(new Blob([${JSON.stringify("(function(){\n  var post = self.postMessage.bind(self);\n  function describe(error){\n    if (!error) return 'unknown';\n    var parts = [];\n    if (error.message) parts.push(error.message);\n    if (error.error && error.error.stack) parts.push(error.error.stack);\n    if (!parts.length) { try { parts.push(JSON.stringify(error)); } catch(_) { parts.push(String(error)); } }\n    return parts.join(' | ');\n  }\n  self.addEventListener('error', function(event){ try { post({ __hinkalWorkerError: describe(event) }); } catch(_){} });\n  self.addEventListener('unhandledrejection', function(event){ try { post({ __hinkalWorkerError: 'unhandledrejection: ' + describe(event && event.reason) }); } catch(_){} });\n  try { post({ __hinkalWorkerReady: true }); } catch(_){}\n})();")}, body], { type: 'application/javascript' }));
    return BLOBS[url];
  }

  function spawn(url){
    try { return new Worker(url, { type: 'module' }); } catch(_){ return new Worker(url); }
  }

  window.handleMessage = async function(envelope){
    var requestId = envelope && envelope.requestId;
    var variant = envelope && envelope.variant;
    var message = revive(envelope && envelope.message);
    var url = URLS[variant];
    if (!url) return post({ requestId: requestId, type: 'ERROR', error: 'Unknown variant: ' + variant });

    var worker;
    try { worker = spawn(await blobUrl(url)); }
    catch (error) { return post({ requestId: requestId, type: 'ERROR', error: 'spawn failed: ' + describe(error) }); }

    var done = false, ready = false, pending = message;
    function finish(){ if (done) return; done = true; try { worker.terminate(); } catch(_){} }

    worker.onmessage = function(event){
      var data = event && event.data;
      if (data && typeof data === 'object') {
        if (data.__hinkalWorkerReady) {
          ready = true;
          try { worker.postMessage(pending); pending = null; }
          catch (error) { post({ requestId: requestId, type: 'ERROR', error: 'postMessage failed: ' + describe(error) }); finish(); }
          return;
        }
        if (typeof data.__hinkalWorkerError === 'string') {
          post({ requestId: requestId, type: 'ERROR', error: data.__hinkalWorkerError });
          finish();
          return;
        }
      }
      post({ requestId: requestId, type: 'RESULT', data: data });
      finish();
    };
    worker.onerror = function(event){
      post({ requestId: requestId, type: 'ERROR', error: (ready ? 'worker runtime: ' : 'worker startup: ') + describe(event) });
      finish();
    };
  };

  post({ type: 'READY' });
})();
true;`, h = `<!DOCTYPE html><html><head><meta charset="utf-8"/></head><body><script>${m}<\/script></body></html>`, g = l.create({ hiddenHost: {
	position: "absolute",
	height: 1,
	width: 1,
	left: -9999,
	top: -9999,
	opacity: 0
} }), _ = () => {
	let e = s(null), t = s({
		ready: !1,
		queue: []
	}), i = a((t, r, i) => {
		console.log("inject", t, r, i);
		let a;
		try {
			a = JSON.stringify({
				requestId: t,
				variant: r,
				message: i
			}, n);
		} catch (e) {
			c.emit("FROM_WEBVIEW_WORKER", {
				requestId: t,
				type: "ERROR",
				error: `serialize failed: ${e?.message ?? e}`
			});
			return;
		}
		e.current?.injectJavaScript(`window.handleMessage && window.handleMessage(${a}); true;`);
	}, []);
	o(() => {
		let e = c.addListener("TO_WEBVIEW_WORKER", (e) => {
			console.log("TO_WEBVIEW_WORKER", e);
			let n = {
				requestId: e?.__requestId ?? "",
				variant: e?.variant ?? "",
				message: e?.message
			};
			t.current.ready ? i(n.requestId, n.variant, n.message) : t.current.queue.push(n);
		});
		return () => e.remove();
	}, [i]);
	let l = a((e) => {
		console.log("onMessage", e), console.log("event.nativeEvent.data", e.nativeEvent.data);
		let n;
		try {
			n = r(JSON.parse(e.nativeEvent.data));
		} catch (e) {
			c.emit("FROM_WEBVIEW_WORKER", {
				type: "ERROR",
				error: e?.message ?? "parse error"
			});
			return;
		}
		if (n?.type === "READY") {
			t.current.ready = !0;
			let e = t.current.queue;
			t.current.queue = [], e.forEach(({ requestId: e, variant: t, message: n }) => i(e, t, n));
			return;
		}
		c.emit("FROM_WEBVIEW_WORKER", n);
	}, [i]);
	return /* @__PURE__ */ f(u, {
		pointerEvents: "none",
		style: g.hiddenHost,
		children: /* @__PURE__ */ f(d, {
			ref: e,
			source: {
				html: h,
				baseUrl: p
			},
			originWhitelist: ["*"],
			javaScriptEnabled: !0,
			domStorageEnabled: !0,
			androidLayerType: "hardware",
			onMessage: l,
			onLoad: () => e.current?.injectJavaScript(m)
		})
	});
};
//#endregion
export { _ as default };
