const socket = io(); // Connect to Socket.IO server

let localStream;
let remoteStream;
let peerConnection;

// Get room ID from URL
const urlParams = new URLSearchParams(window.location.search);
const roomId = urlParams.get("roomId");

if (roomId) {
    socket.emit("join-room", roomId);
} else {
    Swal.fire({
        icon: "error",
        title: "Room ID Missing",
        text: "Room ID is required to join the call.",
    }).then(() => {
        window.location.href = "/";
    });
}

// Get user media (camera and microphone)
navigator.mediaDevices
    .getUserMedia({ video: true, audio: true })
    .then((stream) => {
        localStream = stream;
        document.getElementById("local-video").srcObject = localStream;

        // Create peer connection
        createPeerConnection();

        // Create and send an offer to the other peer
        peerConnection
            .createOffer()
            .then((offer) => peerConnection.setLocalDescription(offer))
            .then(() => {
                socket.emit("signal", { roomId, signal: peerConnection.localDescription });
            });
    })
    .catch((error) => {
        console.error("Error accessing media devices:", error);
        Swal.fire({
            icon: "error",
            title: "Media Error",
            text: "Failed to access camera or microphone. Please check your permissions.",
        });
    });

// Handle signaling data from the server
socket.on("signal", (data) => {
    if (data.signal.type === "offer") {
        peerConnection
            .setRemoteDescription(new RTCSessionDescription(data.signal))
            .then(() => peerConnection.createAnswer())
            .then((answer) => peerConnection.setLocalDescription(answer))
            .then(() => {
                socket.emit("signal", { roomId, signal: peerConnection.localDescription });
            });
    } else if (data.signal.type === "answer") {
        peerConnection.setRemoteDescription(new RTCSessionDescription(data.signal));
    } else if (data.signal.type === "candidate") {
        peerConnection.addIceCandidate(new RTCIceCandidate(data.signal));
    }
});

// Create a peer connection
function createPeerConnection() {
    peerConnection = new RTCPeerConnection();

    // Add local stream tracks to the peer connection
    localStream.getTracks().forEach((track) => peerConnection.addTrack(track, localStream));

    // Handle remote stream
    peerConnection.ontrack = (event) => {
        remoteStream = event.streams[0];
        document.getElementById("remote-video").srcObject = remoteStream;
    };

    // Handle ICE candidates
    peerConnection.onicecandidate = (event) => {
        if (event.candidate) {
            socket.emit("signal", { roomId, signal: event.candidate });
        }
    };
}

// End call
document.getElementById("end-call-btn").addEventListener("click", () => {
    if (peerConnection) {
        peerConnection.close();
    }
    if (localStream) {
        localStream.getTracks().forEach((track) => track.stop());
    }
    Swal.fire({
        icon: "success",
        title: "Call Ended",
        text: "The video call has been ended.",
    }).then(() => {
        window.location.reload();
    });
});

// Fullscreen functionality
document.getElementById("fullscreen-local-btn").addEventListener("click", () => {
    document.getElementById("local-video").requestFullscreen();
});

document.getElementById("fullscreen-remote-btn").addEventListener("click", () => {
    document.getElementById("remote-video").requestFullscreen();
});