const RelaySocket = {
    async joinRtcChannel() {
        await window.HybridWebView.InvokeDotNet("JoinRtcChannel");
    },

    async leaveRtcChannel() {
        await window.HybridWebView.InvokeDotNet("LeaveRtcChannel");
    },

    async getRtcParticipants() {
        const raw = await window.HybridWebView.InvokeDotNet("GetRtcParticipants");

        if (!raw) return [];

        return typeof raw === "string"
            ? JSON.parse(raw)
            : raw;
    },

    async sendRtcSignal(signal) {
        if (!signal.channelId) signal.channelId = currentChannelId;
        if (!signal.from) signal.from = currentUsername;

        await window.HybridWebView.InvokeDotNet("SendRtcSignal", [
            JSON.stringify(signal)
        ]);
    },

    receiveRtcSignal(rawJson) {
        LogMessage("RelaySocket.receiveRtcSignal hit");

        if (window.RelayRtc?.handleRtcSignal) {
            LogMessage("Forwarding RTC signal to RelayRtc.handleRtcSignal");
            return window.RelayRtc.handleRtcSignal(rawJson);
        }

        if (typeof window.handleRtcSignal === "function") {
            LogMessage("Forwarding RTC signal to window.handleRtcSignal");
            return window.handleRtcSignal(rawJson);
        }

        LogMessage("No RTC signal handler registered.");
    }
};

window.RelaySocket = RelaySocket;