import { builtinEnvironments } from "vitest/environments";
import events from "events";
import { Console } from "console";
function util_define(object, properties) {
    for (const name of Object.getOwnPropertyNames(properties)){
        const propDesc = Object.getOwnPropertyDescriptor(properties, name);
        Object.defineProperty(object, name, propDesc);
    }
}
function installOwnProperties(globalThis1) {
    util_define(globalThis1, {
        get globalThis () {
            return globalThis1._globalProxy;
        }
    });
}
const createGlobalThis = ()=>{
    const globalThis1 = {};
    globalThis1._globalObject = globalThis1._globalProxy = globalThis1;
    installOwnProperties(globalThis1);
    return globalThis1;
};
function _define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
const initElementTree = ()=>{
    let uiSignNext = 0;
    return new class {
        countElement(element, parentComponentUniqueId) {
            element.$$uiSign = uiSignNext++;
            this.uniqueId2Element.set(element.$$uiSign, element);
            element.parentComponentUniqueId = parentComponentUniqueId;
        }
        __CreatePage(_tag, parentComponentUniqueId) {
            const page = this.__CreateElement('page', parentComponentUniqueId);
            this.root = page;
            lynxTestingEnv.jsdom.window.document.body.appendChild(page);
            return page;
        }
        __CreateRawText(text) {
            const element = lynxTestingEnv.jsdom.window.document.createTextNode(text);
            this.countElement(element, 0);
            return element;
        }
        __GetElementUniqueID(e) {
            return e.$$uiSign;
        }
        __SetClasses(e, cls) {
            e.className = cls;
        }
        __CreateElement(tag, parentComponentUniqueId) {
            if ('raw-text' === tag) return this.__CreateRawText('');
            const element = lynxTestingEnv.jsdom.window.document.createElement(tag);
            this.countElement(element, parentComponentUniqueId);
            return element;
        }
        __CreateView(parentComponentUniqueId) {
            return this.__CreateElement('view', parentComponentUniqueId);
        }
        __CreateScrollView(parentComponentUniqueId) {
            return this.__CreateElement('scroll-view', parentComponentUniqueId);
        }
        __FirstElement(e) {
            return e.firstChild;
        }
        __CreateText(parentComponentUniqueId) {
            return this.__CreateElement('text', parentComponentUniqueId);
        }
        __CreateImage(parentComponentUniqueId) {
            return this.__CreateElement('image', parentComponentUniqueId);
        }
        __CreateWrapperElement(parentComponentUniqueId) {
            return this.__CreateElement('wrapper', parentComponentUniqueId);
        }
        __AddInlineStyle(e, key, value) {
            e.style[key] = value;
        }
        __AppendElement(parent, child) {
            parent.appendChild(child);
        }
        __SetCSSId(e, id, entryName) {
            const cssId = `${entryName ?? '__Card__'}:${id}`;
            if (Array.isArray(e)) e.forEach((item)=>{
                item.cssId = cssId;
            });
            else e.cssId = cssId;
        }
        __SetAttribute(e, key, value) {
            if ('style' === key || 'class' === key || 'className' === key || 'key' === key || 'id' === key || 'ref' === key || /^data-/.exec(key) || /^(bind|catch|global-bind|capture-bind|capture-catch)[A-Za-z]/.exec(key)) throw new Error(`Cannot use __SetAttribute for "${key}"`);
            if ('update-list-info' === key) {
                let listInfoStr = e.getAttribute(key);
                let listInfo = listInfoStr ? JSON.parse(listInfoStr) : [];
                listInfo.push(value);
                e.setAttribute(key, JSON.stringify(listInfo));
                return;
            }
            if ('text' === key) {
                e.textContent = value;
                return;
            }
            if (null === value) return void e.removeAttribute(key);
            if ('string' == typeof value) return void e.setAttribute(key, value);
            e.setAttribute(key, JSON.stringify(value));
        }
        __AddEvent(e, eventType, eventName, eventHandler) {
            var _e_eventMap;
            if (null == (_e_eventMap = e.eventMap) ? void 0 : _e_eventMap[`${eventType}:${eventName}`]) {
                e.removeEventListener(`${eventType}:${eventName}`, e.eventMap[`${eventType}:${eventName}`]);
                delete e.eventMap[`${eventType}:${eventName}`];
            }
            if (void 0 === eventHandler) return;
            if ('string' != typeof eventHandler && void 0 === eventHandler['type']) throw new Error(`event must be string, but got ${typeof eventHandler}`);
            const listener = (evt)=>{
                if ('object' == typeof eventHandler && 'worklet' === eventHandler['type']) {
                    const isBackground = !__MAIN_THREAD__;
                    globalThis.lynxTestingEnv.switchToMainThread();
                    runWorklet(eventHandler.value, [
                        Object.assign({}, evt)
                    ]);
                    if (isBackground) globalThis.lynxTestingEnv.switchToBackgroundThread();
                } else {
                    if ('catchEvent' === eventType || 'capture-catch' === eventType) evt.stopPropagation();
                    globalThis.lynxCoreInject.tt.publishEvent(eventHandler, evt);
                }
            };
            e.eventMap = e.eventMap ?? {};
            e.eventMap[`${eventType}:${eventName}`] = listener;
            e.addEventListener(`${eventType}:${eventName}`, listener, {
                capture: 'capture-bind' === eventType || 'capture-catch' === eventType
            });
        }
        __GetEvent(e, eventType, eventName) {
            var _e_eventMap;
            const jsFunction = null == (_e_eventMap = e.eventMap) ? void 0 : _e_eventMap[`${eventType}:${eventName}`];
            if (void 0 !== jsFunction) return {
                type: eventType,
                name: eventName,
                jsFunction
            };
        }
        __SetID(e, id) {
            e.id = id;
        }
        __SetInlineStyles(e, styles) {
            if ('string' == typeof styles) e.setAttributeNS(null, 'style', styles);
            else Object.assign(e.style, styles);
        }
        __AddDataset(e, key, value) {
            e.dataset[key] = value;
        }
        __SetDataset(e, dataset) {
            Object.assign(e.dataset, dataset);
        }
        __SetGestureDetector(e, id, type, config, relationMap) {
            e.gesture = {
                id,
                type,
                config,
                relationMap
            };
        }
        __GetDataset(e) {
            return e.dataset;
        }
        __RemoveElement(parent, child) {
            let ch = parent.firstChild;
            while(ch){
                if (ch === child) {
                    parent.removeChild(ch);
                    break;
                }
                ch = ch.nextSibling;
            }
        }
        __InsertElementBefore(parent, child, ref) {
            if (void 0 === ref) parent.appendChild(child);
            else parent.insertBefore(child, ref);
        }
        __ReplaceElement(newElement, oldElement) {
            const parent = oldElement.parentNode;
            if (!parent) throw new Error('unreachable');
            parent.replaceChild(newElement, oldElement);
        }
        __FlushElementTree() {}
        __UpdateListComponents(_list, _components) {}
        __UpdateListCallbacks(list, componentAtIndex, enqueueComponent) {
            Object.defineProperties(list, {
                componentAtIndex: {
                    enumerable: false,
                    configurable: true,
                    value: componentAtIndex
                },
                enqueueComponent: {
                    enumerable: false,
                    configurable: true,
                    value: enqueueComponent
                }
            });
        }
        __CreateList(parentComponentUniqueId, componentAtIndex, enqueueComponent) {
            const e = this.__CreateElement('list', parentComponentUniqueId);
            Object.defineProperties(e, {
                componentAtIndex: {
                    enumerable: false,
                    configurable: true,
                    value: componentAtIndex
                },
                enqueueComponent: {
                    enumerable: false,
                    configurable: true,
                    value: enqueueComponent
                }
            });
            return e;
        }
        __GetTag(ele) {
            return ele.nodeName;
        }
        __GetAttributeByName(ele, name) {
            return ele.getAttribute(name);
        }
        clear() {
            this.root = void 0;
        }
        toTree() {
            return this.root;
        }
        enterListItemAtIndex(e, index, ...args) {
            const { componentAtIndex, $$uiSign } = e;
            return componentAtIndex(e, $$uiSign, index, ...args);
        }
        leaveListItem(e, uiSign) {
            const { enqueueComponent, $$uiSign } = e;
            enqueueComponent(e, $$uiSign, uiSign);
        }
        toJSON() {
            return this.toTree();
        }
        __GetElementByUniqueId(uniqueId) {
            return this.uniqueId2Element.get(uniqueId);
        }
        constructor(){
            _define_property(this, "uniqueId2Element", new Map());
            _define_property(this, "root", void 0);
        }
    }();
};
function GlobalEventEmitter_define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
class GlobalEventEmitter {
    addListener(eventName, listener) {
        this.listeners[eventName] ??= [];
        this.listeners[eventName].push(listener);
    }
    removeListener(eventName, listener) {
        if (!this.listeners[eventName]) return;
        this.listeners[eventName] = this.listeners[eventName].filter((l)=>l !== listener);
    }
    emit(eventName, args) {
        if (!this.listeners[eventName]) return;
        this.listeners[eventName].forEach((listener)=>args ? listener(...args) : listener());
    }
    clear() {
        this.listeners = {};
    }
    removeAllListeners(eventName) {
        if (eventName) delete this.listeners[eventName];
        else this.clear();
    }
    trigger(eventName, params) {
        this.emit(eventName, [
            params
        ]);
    }
    toggle(eventName, ...data) {
        this.emit(eventName, data);
    }
    constructor(){
        GlobalEventEmitter_define_property(this, "listeners", {});
    }
}
function dist_define_property(obj, key, value) {
    if (key in obj) Object.defineProperty(obj, key, {
        value: value,
        enumerable: true,
        configurable: true,
        writable: true
    });
    else obj[key] = value;
    return obj;
}
function __injectElementApi(target) {
    const elementTree1 = initElementTree();
    target.elementTree = elementTree1;
    if (void 0 === target) target = globalThis;
    for (const k of Object.getOwnPropertyNames(elementTree1.constructor.prototype))if (k.startsWith('__')) target[k] = elementTree1[k].bind(elementTree1);
    target.$kTemplateAssembler = {};
    target.registerDataProcessor = ()=>{
        console.error('registerDataProcessor is not implemented');
    };
    target.__OnLifecycleEvent = (...args)=>{
        const isMainThread = __MAIN_THREAD__;
        globalThis.lynxTestingEnv.switchToBackgroundThread();
        globalThis.lynxCoreInject.tt.OnLifecycleEvent(...args);
        if (isMainThread) globalThis.lynxTestingEnv.switchToMainThread();
    };
    target._ReportError = ()=>{};
}
function createPolyfills() {
    const app = {
        callLepusMethod: (...rLynxChange)=>{
            var _rLynxChange_;
            const isBackground = !__MAIN_THREAD__;
            globalThis.lynxTestingEnv.switchToMainThread();
            globalThis[rLynxChange[0]](rLynxChange[1]);
            globalThis.lynxTestingEnv.switchToBackgroundThread();
            null == (_rLynxChange_ = rLynxChange[2]) || _rLynxChange_.call(rLynxChange);
            globalThis.lynxTestingEnv.switchToMainThread();
            if (isBackground) globalThis.lynxTestingEnv.switchToBackgroundThread();
        },
        markTiming: ()=>{},
        createJSObjectDestructionObserver: ()=>({})
    };
    const performance = {
        __functionCallHistory: [],
        _generatePipelineOptions: ()=>{
            performance.__functionCallHistory.push([
                '_generatePipelineOptions'
            ]);
            return {
                pipelineID: 'pipelineID',
                needTimestamps: false
            };
        },
        _onPipelineStart: (id)=>{
            performance.__functionCallHistory.push([
                '_onPipelineStart',
                id
            ]);
        },
        _markTiming: (id, key)=>{
            performance.__functionCallHistory.push([
                '_markTiming',
                id,
                key
            ]);
        },
        _bindPipelineIdWithTimingFlag: (id, flag)=>{
            performance.__functionCallHistory.push([
                '_bindPipelineIdWithTimingFlag',
                id,
                flag
            ]);
        }
    };
    const ee = new events();
    ee.dispatchEvent = ({ type, data })=>{
        const origin = __MAIN_THREAD__ ? 'CoreContext' : 'JSContext';
        if ('CoreContext' === origin) lynxTestingEnv.switchToBackgroundThread();
        else lynxTestingEnv.switchToMainThread();
        ee.emit(type, {
            data: data,
            origin
        });
        if ('CoreContext' === origin) lynxTestingEnv.switchToMainThread();
        else lynxTestingEnv.switchToBackgroundThread();
    };
    ee.addEventListener = ee.addListener;
    ee.removeEventListener = ee.removeListener;
    const CoreContext = ee;
    const JsContext = ee;
    function __LoadLepusChunk(chunkName, _options) {
        const isBackground = !__MAIN_THREAD__;
        globalThis.lynxTestingEnv.switchToMainThread();
        let ans;
        if ('worklet-runtime' === chunkName) {
            var _globalThis_onInitWorkletRuntime, _globalThis;
            ans = null == (_globalThis_onInitWorkletRuntime = (_globalThis = globalThis).onInitWorkletRuntime) ? void 0 : _globalThis_onInitWorkletRuntime.call(_globalThis);
        } else throw new Error(`__LoadLepusChunk: Unknown chunk name: ${chunkName}`);
        if (isBackground) globalThis.lynxTestingEnv.switchToBackgroundThread();
        return ans;
    }
    return {
        app,
        performance,
        CoreContext,
        JsContext,
        __LoadLepusChunk
    };
}
function createPreconfiguredConsole() {
    const console1 = new Console(process.stdout, process.stderr);
    console1.profile = ()=>{};
    console1.profileEnd = ()=>{};
    console1.alog = ()=>{};
    return console1;
}
function injectMainThreadGlobals(target, polyfills) {
    var _globalThis_onInjectMainThreadGlobals, _globalThis;
    __injectElementApi(target);
    const { performance, CoreContext, JsContext, __LoadLepusChunk } = polyfills || {};
    if (void 0 === target) target = globalThis;
    target.__DEV__ = true;
    target.__PROFILE__ = true;
    target.__ALOG__ = true;
    target.__JS__ = false;
    target.__LEPUS__ = true;
    target.__BACKGROUND__ = false;
    target.__MAIN_THREAD__ = true;
    target.__REF_FIRE_IMMEDIATELY__ = false;
    target.__FIRST_SCREEN_SYNC_TIMING__ = 'immediately';
    target.__TESTING_FORCE_RENDER_TO_OPCODE__ = false;
    target.__ENABLE_SSR__ = false;
    target.globDynamicComponentEntry = '__Card__';
    target.lynx = {
        performance,
        getCoreContext: ()=>CoreContext,
        getJSContext: ()=>JsContext,
        reportError: (e)=>{
            throw e;
        }
    };
    target.requestAnimationFrame = setTimeout;
    target.cancelAnimationFrame = clearTimeout;
    target.console = createPreconfiguredConsole();
    target.__LoadLepusChunk = __LoadLepusChunk;
    null == (_globalThis_onInjectMainThreadGlobals = (_globalThis = globalThis).onInjectMainThreadGlobals) || _globalThis_onInjectMainThreadGlobals.call(_globalThis, target);
}
const IGNORE_LIST_GLOBALS = [
    'globalThis',
    'global'
];
class NodesRef {
    invoke() {
        throw new Error('not implemented');
    }
    path() {
        throw new Error('not implemented');
    }
    fields() {
        throw new Error('not implemented');
    }
    setNativeProps(props) {
        return {
            exec: ()=>{
                const element = elementTree.uniqueId2Element.get(Number(this._nodeSelectToken.identifier));
                if (!element) throw new Error(`[NodesRef.setNativeProps] Element not found for identifier=${this._nodeSelectToken.identifier}`);
                if (element) for(const key in props)element.setAttributeNS(null, key, props[key]);
            }
        };
    }
    constructor(selectorQuery, nodeSelectToken){
        dist_define_property(this, "_nodeSelectToken", void 0);
        dist_define_property(this, "_selectorQuery", void 0);
        this._nodeSelectToken = nodeSelectToken;
        this._selectorQuery = selectorQuery;
    }
}
function injectBackgroundThreadGlobals(target, polyfills) {
    var _globalThis_onInjectBackgroundThreadGlobals, _globalThis;
    const { app, performance, CoreContext, JsContext, __LoadLepusChunk } = polyfills || {};
    if (void 0 === target) target = globalThis;
    target.__DEV__ = true;
    target.__PROFILE__ = true;
    target.__ALOG__ = true;
    target.__JS__ = true;
    target.__LEPUS__ = false;
    target.__BACKGROUND__ = true;
    target.__MAIN_THREAD__ = false;
    target.__ENABLE_SSR__ = false;
    target.globDynamicComponentEntry = '__Card__';
    target.lynxCoreInject = {};
    target.lynxCoreInject.tt = {
        _params: {
            initData: {},
            updateData: {}
        }
    };
    const globalEventEmitter = new GlobalEventEmitter();
    target.lynx = {
        getNativeApp: ()=>app,
        performance,
        createSelectorQuery: ()=>({
                selectUniqueID: function(uniqueId) {
                    return new NodesRef({}, {
                        type: 2,
                        identifier: uniqueId.toString()
                    });
                },
                select: function(selector) {
                    const el = lynxTestingEnv.jsdom.window.document.querySelector(selector);
                    if (!el) throw new Error(`[createSelectorQuery.select] No element matches selector: ${selector}`);
                    return new NodesRef({}, {
                        type: 0,
                        identifier: el.$$uiSign.toString()
                    });
                }
            }),
        getCoreContext: ()=>CoreContext,
        getJSContext: ()=>JsContext,
        getJSModule: (moduleName)=>{
            if ('GlobalEventEmitter' === moduleName) return globalEventEmitter;
            throw new Error(`getJSModule(${moduleName}) not implemented`);
        },
        reportError: (e)=>{
            throw e;
        }
    };
    target.requestAnimationFrame = setTimeout;
    target.cancelAnimationFrame = clearTimeout;
    target.console = createPreconfiguredConsole();
    target.SystemInfo = {
        platform: 'iOS',
        pixelRatio: 3,
        pixelWidth: 1170,
        pixelHeight: 2532,
        osVersion: '17.0.2',
        enableKrypton: true,
        runtimeType: 'quickjs',
        lynxSdkVersion: '3.0'
    };
    target.__LoadLepusChunk = __LoadLepusChunk;
    null == (_globalThis_onInjectBackgroundThreadGlobals = (_globalThis = globalThis).onInjectBackgroundThreadGlobals) || _globalThis_onInjectBackgroundThreadGlobals.call(_globalThis, target);
}
class LynxTestingEnv {
    injectGlobals() {
        const polyfills = createPolyfills();
        injectBackgroundThreadGlobals(this.backgroundThread.globalThis, polyfills);
        injectMainThreadGlobals(this.mainThread.globalThis, polyfills);
    }
    switchToBackgroundThread() {
        var _globalThis_onSwitchedToBackgroundThread, _globalThis;
        this.originals = new Map();
        Object.getOwnPropertyNames(this.backgroundThread.globalThis).forEach((key)=>{
            if (IGNORE_LIST_GLOBALS.includes(key)) return;
            this.originals.set(key, global[key]);
            global[key] = this.backgroundThread.globalThis[key];
        });
        null == (_globalThis = globalThis) || null == (_globalThis_onSwitchedToBackgroundThread = _globalThis.onSwitchedToBackgroundThread) || _globalThis_onSwitchedToBackgroundThread.call(_globalThis);
    }
    switchToMainThread() {
        var _globalThis_onSwitchedToMainThread, _globalThis;
        this.originals = new Map();
        Object.getOwnPropertyNames(this.mainThread.globalThis).forEach((key)=>{
            if (IGNORE_LIST_GLOBALS.includes(key)) return;
            this.originals.set(key, global[key]);
            global[key] = this.mainThread.globalThis[key];
        });
        null == (_globalThis = globalThis) || null == (_globalThis_onSwitchedToMainThread = _globalThis.onSwitchedToMainThread) || _globalThis_onSwitchedToMainThread.call(_globalThis);
    }
    clearGlobal() {
        var _this_originals, _this_originals1;
        null == (_this_originals = this.originals) || _this_originals.forEach((v, k)=>{
            global[k] = v;
        });
        null == (_this_originals1 = this.originals) || _this_originals1.clear();
    }
    reset() {
        var _globalThis_onResetLynxTestingEnv, _globalThis;
        this.injectGlobals();
        this.switchToMainThread();
        this.switchToBackgroundThread();
        null == (_globalThis_onResetLynxTestingEnv = (_globalThis = globalThis).onResetLynxTestingEnv) || _globalThis_onResetLynxTestingEnv.call(_globalThis);
    }
    constructor(jsdom){
        dist_define_property(this, "originals", new Map());
        dist_define_property(this, "backgroundThread", void 0);
        dist_define_property(this, "mainThread", void 0);
        dist_define_property(this, "jsdom", void 0);
        this.jsdom = jsdom ?? global.jsdom;
        if (!this.jsdom) throw new Error("LynxTestingEnv requires a JSDOM instance. Pass one to the constructor, or ensure your test runner sets global.jsdom (e.g., via a setup file).");
        this.backgroundThread = createGlobalThis();
        this.mainThread = createGlobalThis();
        const globalPolyfills = {
            console: this.jsdom.window['console'],
            Event: this.jsdom.window.Event,
            window: this.jsdom.window,
            document: this.jsdom.window.document
        };
        Object.assign(this.mainThread.globalThis, globalPolyfills);
        Object.assign(this.backgroundThread.globalThis, globalPolyfills);
        this.injectGlobals();
        this.switchToBackgroundThread();
    }
}
const env = {
    name: 'lynxTestingEnv',
    transformMode: 'web',
    async setup (global1) {
        const fakeGlobal = {};
        await builtinEnvironments.jsdom.setup(fakeGlobal, {});
        const lynxTestingEnv1 = new LynxTestingEnv(fakeGlobal.jsdom);
        global1.lynxTestingEnv = lynxTestingEnv1;
        global1.Node = lynxTestingEnv1.jsdom.window.Node;
        return {
            teardown (global1) {
                delete global1.lynxTestingEnv;
                delete global1.jsdom;
                delete global1.Node;
            }
        };
    }
};
const vitest = env;
const env_vitest = vitest;
export { env_vitest as default };
