(function () {
    function post(action, payload) {
        var message = JSON.stringify({
            action: action,
            payload: payload || {},
        });

        if (
            window.flutter_inappwebview &&
            window.flutter_inappwebview.callHandler
        ) {
            return window.flutter_inappwebview.callHandler(
                'HyAppBridge',
                action,
                payload || {}
            );
        }
        if (
            window.HyAppBridgeChannel &&
            window.HyAppBridgeChannel.postMessage
        ) {
            window.HyAppBridgeChannel.postMessage(message);
            return Promise.resolve();
        }
        if (window.FlutterBridge && window.FlutterBridge.postMessage) {
            window.FlutterBridge.postMessage(message);
            return Promise.resolve();
        }
        if (
            window.webkit &&
            window.webkit.messageHandlers &&
            window.webkit.messageHandlers.HyAppBridge
        ) {
            window.webkit.messageHandlers.HyAppBridge.postMessage({
                action: action,
                payload: payload || {},
            });
            return Promise.resolve();
        }

        window.dispatchEvent(
            new CustomEvent('hyapp:bridge-message', {
                detail: { action: action, payload: payload || {} },
            })
        );
        return Promise.resolve();
    }

    window.HyAppBridge = {
        post: post,
        back: function () {
            return post('back');
        },
        openUser: function (userId) {
            return post('openUser', { user_id: String(userId || '') });
        },
        openRoom: function (roomId) {
            return post('openRoom', { room_id: String(roomId || '') });
        },
        openRankNote: function (boardType) {
            return post('openRankNote', {
                board_type: String(boardType || ''),
            });
        },
        openTaskAction: function (payload) {
            return post('taskAction', payload || {});
        },
        ready: function (payload) {
            return post('ready', payload || {});
        },
    };
})();
