(function($){
    let currentRoom = 'Lobby';
    let pollingInterval = null;
    let localStream = null;
    let currentMuted = false;

    // WebRTC / signaling
    let socket = null;
    let peerConnections = {}; // remoteSessionId -> RTCPeerConnection
    let remoteVideo = null;

    function init() {
        if (!SVC_SETTINGS.license_active) {
            return;
        }

        $('#svc-display-name').val(SVC_SETTINGS.user_name);
        $('#svc-text-color').val(SVC_SETTINGS.default_color);
        $('#svc-country-code').val(SVC_SETTINGS.country_code);

        remoteVideo = document.getElementById('svc-remote-video');

        bindEvents();
        startCamera();
        autoDetectCountry();
        connectSignaling();
        pollState();
        pollingInterval = setInterval(pollState, 4000);
    }

    function bindEvents() {
        $('#svc-save-profile').on('click', saveProfile);
        $('#svc-send-message').on('click', sendMessage);
        $('#svc-create-room-btn').on('click', createRoom);

        $('#svc-toggle-mic').on('click', toggleMic);
        $('#svc-fullscreen').on('click', toggleFullscreen);
        $('#svc-switch-camera').on('click', switchCameraPlaceholder);
    }

    function startCamera() {
        if (!navigator.mediaDevices || !navigator.mediaDevices.getUserMedia) {
            console.warn('getUserMedia not supported');
            return;
        }

        navigator.mediaDevices.getUserMedia({ video: true, audio: true })
            .then(function(stream){
                localStream = stream;
                const mainVideo = document.getElementById('svc-main-video');
                mainVideo.srcObject = stream;
            })
            .catch(function(err){
                console.error('Error accessing media devices', err);
            });
    }

    function autoDetectCountry() {
        var current = ($('#svc-country-code').val() || '').toUpperCase();
        if (current && current !== 'XX') {
            return;
        }

        try {
            fetch('https://ipapi.co/json/')
                .then(function(r){ return r.json(); })
                .then(function(data){
                    if (!data || !data.country_code) return;
                    var cc = String(data.country_code).toUpperCase();
                    $('#svc-country-code').val(cc);
                    SVC_SETTINGS.country_code = cc;
                    saveProfile();
                })
                .catch(function(){});
        } catch (e) {}
    }

    function saveProfile() {
        var name = $('#svc-display-name').val() || 'User';
        var color = $('#svc-text-color').val() || SVC_SETTINGS.default_color;
        var country = ($('#svc-country-code').val() || 'XX').toUpperCase();

        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_update_profile',
            nonce: SVC_SETTINGS.nonce,
            session_id: SVC_SETTINGS.session_id,
            name: name,
            color: color,
            country: country,
            muted: currentMuted
        });
    }

    function pollState() {
        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_get_state',
            nonce: SVC_SETTINGS.nonce,
            session_id: SVC_SETTINGS.session_id
        }, function(resp){
            if (!resp || !resp.success) return;
            var state = resp.data.state;
            renderRooms(state.rooms);
            renderUsers(state.users || {});
            if (state.messages[currentRoom]) {
                renderMessages(state.messages[currentRoom]);
            }
        });
    }

    function renderRooms(rooms) {
        var container = $('#svc-room-buttons');
        container.empty();
        Object.keys(rooms).forEach(function(roomName){
            var btn = $('<button type="button"></button>')
                .text(roomName)
                .toggleClass('svc-active', roomName === currentRoom)
                .on('click', function(){
                    switchRoom(roomName);
                });
            container.append(btn);
        });
        $('#svc-current-room-name').text(currentRoom);
    }

    function renderUsers(users) {
        var list = $('#svc-users-list');
        list.empty();
        Object.keys(users).forEach(function(sessionId){
            var u = users[sessionId];
            var li = $('<li></li>')
                .attr('data-session', sessionId)
                .toggleClass('svc-active', sessionId === SVC_SETTINGS.session_id)
                .on('click', function(){
                    highlightUser(sessionId);
                    startCall(sessionId);
                });

            var flag = $('<span class="svc-flag"></span>');
            if (u.country && u.country !== 'XX') {
                var cc = String(u.country).toLowerCase();
                flag.css('background-image', 'url(https://flagcdn.com/w20/' + cc + '.png)');
            }

            var name = $('<span></span>').text(u.name || 'User');
            li.append(flag).append(name);

            if (SVC_SETTINGS.is_admin && sessionId !== SVC_SETTINGS.session_id) {
                var blockBtn = $('<button type="button" style="margin-left:auto;font-size:11px;">Block</button>');
                blockBtn.on('click', function(e){
                    e.stopPropagation();
                    blockUser(sessionId);
                });
                li.append(blockBtn);
            }

            list.append(li);
        });
    }

    function highlightUser(sessionId) {
        $('#svc-users-list li').removeClass('svc-active');
        $('#svc-users-list li[data-session="'+sessionId+'"]').addClass('svc-active');
    }

    function renderMessages(messages) {
        var chat = $('#svc-chat-messages');
        chat.empty();
        messages.forEach(function(msg){
            var row = $('<div class="svc-chat-message"></div>');
            var head = $('<div class="svc-chat-message-header"></div>');
            var flag = $('<span class="svc-flag"></span>');

            if (msg.country && msg.country !== 'XX') {
                var cc = String(msg.country).toLowerCase();
                flag.css('background-image', 'url(https://flagcdn.com/w20/' + cc + '.png)');
            }

            head.append(flag);
            head.append($('<span></span>').text(msg.user_name || 'User'));

            var text = $('<div class="svc-chat-message-text"></div>')
                .text(msg.text)
                .css('color', msg.color || SVC_SETTINGS.default_color);

            row.append(head).append(text);
            chat.append(row);
        });
        chat.scrollTop(chat[0].scrollHeight);
    }

    function sendMessage() {
        var txt = $('#svc-chat-text').val().trim();
        if (!txt) return;

        var color = $('#svc-text-color').val() || SVC_SETTINGS.default_color;
        $('#svc-chat-text').val('');

        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_post_message',
            nonce: SVC_SETTINGS.nonce,
            session_id: SVC_SETTINGS.session_id,
            room: currentRoom,
            text: txt,
            color: color
        }, function(resp){
            if (!resp || !resp.success) {
                alert(resp && resp.data && resp.data.message ? resp.data.message : 'Error sending message');
                return;
            }
            renderMessages(resp.data.messages);
        });
    }

    function createRoom() {
        var name = $('#svc-new-room-name').val().trim();
        if (!name) return;

        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_create_room',
            nonce: SVC_SETTINGS.nonce,
            room_name: name,
            creator: SVC_SETTINGS.user_name
        }, function(resp){
            if (!resp || !resp.success) return;
            $('#svc-new-room-name').val('');
            currentRoom = name;
            renderRooms(resp.data.rooms);
            switchRoom(name);
        });
    }

    function switchRoom(roomName) {
        currentRoom = roomName;
        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_switch_room',
            nonce: SVC_SETTINGS.nonce,
            room: roomName
        }, function(resp){
            if (!resp || !resp.success) return;
            currentRoom = resp.data.room;
            $('#svc-current-room-name').text(currentRoom);
            renderMessages(resp.data.messages);
            pollState();

            // also (re)join room on signaling server
            if (socket) {
                socket.emit('join-room', {
                    room: currentRoom,
                    sessionId: SVC_SETTINGS.session_id,
                    name: SVC_SETTINGS.user_name
                });
            }
        });
    }

    function blockUser(sessionId) {
        if (!confirm('Block this user?')) return;

        $.post(SVC_SETTINGS.ajax_url, {
            action: 'svc_block_user',
            nonce: SVC_SETTINGS.nonce,
            session_id: sessionId
        }, function(resp){
            if (!resp || !resp.success) {
                alert('Could not block user');
                return;
            }
            alert('User blocked.');
        });
    }

    function toggleMic() {
        if (!localStream) return;
        var audioTracks = localStream.getAudioTracks();
        if (!audioTracks.length) return;

        currentMuted = !currentMuted;
        audioTracks.forEach(function(t){ t.enabled = !currentMuted; });
        $('#svc-toggle-mic .svc-icon').text(currentMuted ? '🔇' : '🎙️');

        saveProfile();
    }

    function toggleFullscreen() {
        var videoWrapper = document.querySelector('.svc-video-box-main');
        if (!document.fullscreenElement) {
            if (videoWrapper.requestFullscreen) {
                videoWrapper.requestFullscreen();
            }
        } else {
            if (document.exitFullscreen) {
                document.exitFullscreen();
            }
        }
    }

    function switchCameraPlaceholder() {
        alert('Camera switching is not implemented in this prototype.');
    }

    /* ===== Signaling & WebRTC ===== */

    function connectSignaling() {
        if (typeof io === 'undefined' || !SVC_SETTINGS.signaling_url) {
            console.warn('Signaling not configured');
            return;
        }

        socket = io(SVC_SETTINGS.signaling_url, {
            transports: ['websocket']
        });

        socket.on('connect', function(){
            socket.emit('join-room', {
                room: currentRoom,
                sessionId: SVC_SETTINGS.session_id,
                name: SVC_SETTINGS.user_name
            });
        });

        // we are callee
        socket.on('offer', async function(data){
            const fromId = data.callerSessionId;
            const pc = await getPeerConnection(fromId, false);

            await pc.setRemoteDescription(new RTCSessionDescription(data.sdp));
            const answer = await pc.createAnswer();
            await pc.setLocalDescription(answer);

            socket.emit('answer', {
                targetSessionId: fromId,
                sdp: answer
            });
        });

        // we are caller, receive answer
        socket.on('answer', async function(data){
            const fromId = data.fromSessionId;
            const pc = peerConnections[fromId];
            if (!pc) return;
            await pc.setRemoteDescription(new RTCSessionDescription(data.sdp));
        });

        socket.on('ice-candidate', function(data){
            const pc = peerConnections[data.fromSessionId];
            if (!pc) return;
            pc.addIceCandidate(new RTCIceCandidate(data.candidate));
        });

        socket.on('user-left', function(data){
            const pc = peerConnections[data.sessionId];
            if (pc) {
                pc.close();
                delete peerConnections[data.sessionId];
            }
        });
    }

    async function getPeerConnection(remoteSessionId, isCaller) {
        if (peerConnections[remoteSessionId]) {
            return peerConnections[remoteSessionId];
        }

        const pc = new RTCPeerConnection({
            iceServers: [
                { urls: 'stun:stun.l.google.com:19302' }
            ]
        });

        peerConnections[remoteSessionId] = pc;

        if (localStream) {
            localStream.getTracks().forEach(track => pc.addTrack(track, localStream));
        }

        pc.ontrack = function(event) {
            if (event.streams && event.streams[0]) {
                if (remoteVideo) {
                    remoteVideo.srcObject = event.streams[0];
                }
            }
        };

        pc.onicecandidate = function(event) {
            if (event.candidate && socket) {
                socket.emit('ice-candidate', {
                    targetSessionId: remoteSessionId,
                    candidate: event.candidate
                });
            }
        };

        if (isCaller) {
            const offer = await pc.createOffer();
            await pc.setLocalDescription(offer);

            if (socket) {
                socket.emit('offer', {
                    targetSessionId: remoteSessionId,
                    callerSessionId: SVC_SETTINGS.session_id,
                    sdp: offer
                });
            }
        }

        return pc;
    }

    async function startCall(targetSessionId) {
        if (!socket) {
            alert('Signaling server not connected');
            return;
        }
        if (targetSessionId === SVC_SETTINGS.session_id) {
            return;
        }
        await getPeerConnection(targetSessionId, true);
    }

    $(document).ready(init);

})(jQuery);
