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

let localStream;
let remoteStream;
let peerConnection;
let mediaRecorder;
let recordedChunks = [];

// Generate room ID and share URL
document.getElementById("create-room").addEventListener("click", async () => {
    try {
        const roomId = Math.random().toString(36).substring(7);
        const roomUrl = `${window.location.origin}/user.html?roomId=${roomId}`;
        document.getElementById("room-url").textContent = `Room URL: ${roomUrl}`;
        socket.emit("join-room", roomId);

        // Get user media (camera and microphone)
        localStream = await navigator.mediaDevices.getUserMedia({ video: true, audio: true });

        // Show local video and hide placeholder
        const localVideo = document.getElementById("local-video");
        localVideo.srcObject = localStream;
        localVideo.style.display = "block";
        document.getElementById("local-video-placeholder").style.display = "none";
        document.getElementById("fullscreen-local-btn").style.display = "block";

        // Enable media controls
        document.getElementById("mute-audio-btn").disabled = false;
        document.getElementById("mute-video-btn").disabled = false;
        document.getElementById("end-call-btn").disabled = false;
        document.getElementById("start-recording").disabled = false;

        // Create peer connection
        createPeerConnection();

        // Create and send an offer to the other peer
        const offer = await peerConnection.createOffer();
        await peerConnection.setLocalDescription(offer);
        socket.emit("signal", { roomId, signal: peerConnection.localDescription });

        Swal.fire({
            icon: "success",
            title: "Room Created",
            text: `Share this URL with the user: ${roomUrl}`,
        });
    } catch (error) {
        console.error("Error creating room:", error);
        Swal.fire({
            icon: "error",
            title: "Error",
            text: "Failed to create room. Please check your camera and microphone permissions.",
        });
    }
});

// Handle signaling data from the server
socket.on("signal", async (data) => {
    if (data.signal.type === "offer") {
        await peerConnection.setRemoteDescription(new RTCSessionDescription(data.signal));
        const answer = await peerConnection.createAnswer();
        await peerConnection.setLocalDescription(answer);
        socket.emit("signal", { roomId, signal: peerConnection.localDescription });
    } else if (data.signal.type === "answer") {
        await peerConnection.setRemoteDescription(new RTCSessionDescription(data.signal));
    } else if (data.signal.type === "candidate") {
        await 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];
        const remoteVideo = document.getElementById("remote-video");
        remoteVideo.srcObject = remoteStream;
        remoteVideo.style.display = "block";
        document.getElementById("remote-video-placeholder").style.display = "none";
        document.getElementById("fullscreen-remote-btn").style.display = "block";
    };

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

// Media controls
document.getElementById("mute-audio-btn").addEventListener("click", () => {
    const audioTracks = localStream.getAudioTracks();
    if (audioTracks.length > 0) {
        audioTracks[0].enabled = !audioTracks[0].enabled;
        const icon = document.querySelector("#mute-audio-btn i");
        icon.classList.toggle("fa-microphone");
        icon.classList.toggle("fa-microphone-slash");
    }
});

document.getElementById("mute-video-btn").addEventListener("click", () => {
    const videoTracks = localStream.getVideoTracks();
    if (videoTracks.length > 0) {
        videoTracks[0].enabled = !videoTracks[0].enabled;
        const icon = document.querySelector("#mute-video-btn i");
        icon.classList.toggle("fa-video");
        icon.classList.toggle("fa-video-slash");
    }
});

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();
    });
});

// Recording functionality
document.getElementById("start-recording").addEventListener("click", () => {
    recordedChunks = [];
    mediaRecorder = new MediaRecorder(remoteStream);
    mediaRecorder.ondataavailable = (event) => {
        if (event.data.size > 0) {
            recordedChunks.push(event.data);
        }
    };
    mediaRecorder.start();
    document.getElementById("stop-recording").disabled = false;
    document.getElementById("start-recording").disabled = true;
    Swal.fire({
        icon: "info",
        title: "Recording Started",
        text: "The video call is now being recorded.",
    });
});

document.getElementById("stop-recording").addEventListener("click", () => {
    mediaRecorder.stop();
    document.getElementById("stop-recording").disabled = true;
    document.getElementById("download-recording").disabled = false;
    Swal.fire({
        icon: "info",
        title: "Recording Stopped",
        text: "The video call recording has been stopped.",
    });
});

document.getElementById("download-recording").addEventListener("click", () => {
    const blob = new Blob(recordedChunks, { type: "video/webm" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = "recording.webm";
    a.click();
    URL.revokeObjectURL(url);
    Swal.fire({
        icon: "success",
        title: "Recording Downloaded",
        text: "The video call recording has been downloaded.",
    });
});

// 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();
});