// JS <-> native RPC bridge (paired with the WKScriptMessageHandler in main.swift).
(function () {
    let _id = 0;
    const _pending = {};
    window.hasNative = !!(window.webkit && window.webkit.messageHandlers && window.webkit.messageHandlers.bridge);

    window.nativeCall = function (cmd, args) {
        return new Promise((resolve, reject) => {
            if (!window.hasNative) { reject(new Error('Native bridge unavailable')); return; }
            const id = ++_id;
            _pending[id] = { resolve, reject };
            try {
                window.webkit.messageHandlers.bridge.postMessage({ id, cmd, args: args || {} });
            } catch (e) {
                delete _pending[id];
                reject(new Error('Bridge post failed: ' + e.message));
            }
        });
    };

    // Called from Swift: window.__bridgeResolveRaw({id, ok, payload})
    window.__bridgeResolveRaw = function (env) {
        const p = _pending[env.id];
        if (!p) return;
        delete _pending[env.id];
        if (env.ok) p.resolve(env.payload);
        else p.reject(new Error(String(env.payload)));
    };

    // Called from Swift when files/folders are dropped on the window.
    window.__onDrop = function (payload) {
        if (typeof window.onNativeDrop === 'function') window.onNativeDrop(payload);
    };
})();
