let localStream = null;
let screenStream = null;
let peerConnections = {};
let currentMeetingId = null;
let socket = null;
let isAudioEnabled = true;
let isVideoEnabled = true;
let participants = {};
let myUserId = null;

const configuration = {
    iceServers: [
        { urls: 'stun:stun.l.google.com:19302' },
        { urls: 'stun:stun1.l.google.com:19302' },
        { urls: 'stun:stun2.l.google.com:19302' }
    ]
};

function isMobileDevice() {
    return /Android|webOS|iPhone|iPad|iPod|BlackBerry|IEMobile|Opera Mini/i.test(navigator.userAgent) || window.innerWidth < 1024;
}

document.addEventListener('DOMContentLoaded', function() {
    if (isMobileDevice()) {
        document.getElementById('mobile-block').classList.remove('hidden');
        document.getElementById('desktop-meeting').classList.add('hidden');
        return;
    }

    const meetingTab = document.querySelector('.meeting-tab');
    if (meetingTab) {
        meetingTab.addEventListener('click', initMeeting);
    }

    const createMeetingBtn = document.getElementById('create-meeting-btn');
    if (createMeetingBtn) {
        createMeetingBtn.addEventListener('click', showCreateMeetingModal);
    }

    const joinMeetingBtn = document.getElementById('join-meeting-btn');
    if (joinMeetingBtn) {
        joinMeetingBtn.addEventListener('click', joinMeeting);
    }

    const meetingCodeInput = document.getElementById('meeting-code-input');
    if (meetingCodeInput) {
        meetingCodeInput.addEventListener('input', function(e) {
            this.value = this.value.toUpperCase().replace(/[^A-Z0-9]/g, '');
        });
        
        meetingCodeInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                joinMeeting();
            }
        });
    }

    document.querySelectorAll('.close-create-meeting').forEach(btn => {
        btn.addEventListener('click', closeCreateMeetingModal);
    });

    const createMeetingForm = document.getElementById('create-meeting-form');
    if (createMeetingForm) {
        createMeetingForm.addEventListener('submit', createMeeting);
    }

    const leaveMeetingBtn = document.getElementById('leave-meeting');
    if (leaveMeetingBtn) {
        leaveMeetingBtn.addEventListener('click', leaveMeeting);
    }

    const endMeetingBtn = document.getElementById('end-meeting-btn');
    if (endMeetingBtn) {
        endMeetingBtn.addEventListener('click', endMeeting);
    }

    const toggleAudioBtn = document.getElementById('toggle-audio');
    if (toggleAudioBtn) {
        toggleAudioBtn.addEventListener('click', toggleAudio);
    }

    const toggleVideoBtn = document.getElementById('toggle-video');
    if (toggleVideoBtn) {
        toggleVideoBtn.addEventListener('click', toggleVideo);
    }

    const shareScreenBtn = document.getElementById('share-screen');
    if (shareScreenBtn) {
        shareScreenBtn.addEventListener('click', toggleScreenShare);
    }

    const sendMessageBtn = document.getElementById('send-message');
    if (sendMessageBtn) {
        sendMessageBtn.addEventListener('click', sendChatMessage);
    }

    const chatInput = document.getElementById('chat-input');
    if (chatInput) {
        chatInput.addEventListener('keypress', function(e) {
            if (e.key === 'Enter') {
                sendChatMessage();
            }
        });
    }

    const copyLinkBtn = document.getElementById('copy-meeting-link');
    if (copyLinkBtn) {
        copyLinkBtn.addEventListener('click', copyMeetingLink);
    }

    const tabChat = document.getElementById('tab-chat');
    const tabParticipants = document.getElementById('tab-participants');
    if (tabChat && tabParticipants) {
        tabChat.addEventListener('click', () => switchTab('chat'));
        tabParticipants.addEventListener('click', () => switchTab('participants'));
    }

    const urlParams = new URLSearchParams(window.location.search);
    const meetingId = urlParams.get('meeting');
    if (meetingId) {
        document.getElementById('meeting-code-input').value = meetingId;
        document.querySelector('.meeting-tab').click();
        setTimeout(() => joinMeeting(), 500);
    }
});

function initMeeting() {
    if (isMobileDevice()) {
        document.getElementById('mobile-block').classList.remove('hidden');
        return;
    }
    loadActiveMeetings();
    loadMeetingHistory();
}

function showCreateMeetingModal() {
    document.getElementById('create-meeting-modal').classList.remove('hidden');
}

function closeCreateMeetingModal() {
    document.getElementById('create-meeting-modal').classList.add('hidden');
    document.getElementById('create-meeting-form').reset();
}

async function createMeeting(e) {
    e.preventDefault();
    
    const title = document.getElementById('meeting-title').value;
    const description = document.getElementById('meeting-description').value;

    try {
        const response = await fetch('meeting_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'create',
                title: title,
                description: description
            })
        });

        const data = await response.json();
        
        if (data.success) {
            closeCreateMeetingModal();
            document.getElementById('meeting-code-input').value = data.meetingCode;
            await joinMeeting();
        } else {
            alert(data.message || 'Error creating meeting');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error creating meeting');
    }
}

async function joinMeeting() {
    const code = document.getElementById('meeting-code-input').value.trim();
    
    if (!code) {
        alert('Please enter a meeting code');
        return;
    }

    try {
        const response = await fetch('meeting_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'join',
                meetingCode: code
            })
        });

        const data = await response.json();
        
        if (data.success) {
            currentMeetingId = data.meetingId;
            myUserId = getUserId();
            
            const mediaReady = await setupMediaDevices();
            if (!mediaReady) return;
            
            showMeetingRoom(data.meetingTitle, code);
            connectToSignalingServer(data.meetingId);
        } else {
            alert(data.message || 'Meeting not found');
        }
    } catch (error) {
        console.error('Error:', error);
        alert('Error joining meeting');
    }
}

async function setupMediaDevices() {
    try {
        localStream = await navigator.mediaDevices.getUserMedia({
            video: {
                width: { ideal: 1280 },
                height: { ideal: 720 }
            },
            audio: {
                echoCancellation: true,
                noiseSuppression: true
            }
        });
        return true;
    } catch (error) {
        console.error('Media access error:', error);
        alert('Unable to access camera/microphone. Please check permissions.');
        return false;
    }
}

function connectToSignalingServer(meetingId) {
    const wsUrl = `wss://imators.systems:45678`;
    socket = new WebSocket(wsUrl);

    socket.onopen = () => {
        console.log('Connected to signaling server');
        socket.send(JSON.stringify({
            type: 'join',
            meetingId: meetingId,
            userId: myUserId,
            userName: getUserName(),
            userProfilePic: getUserProfilePic()
        }));
    };

    socket.onmessage = async (event) => {
        const message = JSON.parse(event.data);
        await handleSignalingMessage(message);
    };

    socket.onerror = (error) => {
        console.error('WebSocket error:', error);
        alert('Connection error. Please check if signaling server is running.');
    };

    socket.onclose = () => {
        console.log('Disconnected from signaling server');
    };
}

async function handleSignalingMessage(message) {
    console.log('Received message:', message.type);
    
    switch (message.type) {
        case 'user-joined':
            await handleUserJoined(message);
            break;
        case 'user-left':
            handleUserLeft(message);
            break;
        case 'offer':
            await handleOffer(message);
            break;
        case 'answer':
            await handleAnswer(message);
            break;
        case 'ice-candidate':
            await handleIceCandidate(message);
            break;
        case 'chat':
            displayChatMessage(message);
            break;
        case 'video-toggle':
            updateRemoteVideoState(message);
            break;
        case 'meeting-ended':
            handleMeetingEnded();
            break;
    }
}

async function handleUserJoined(message) {
    const { userId, userName, userProfilePic } = message;
    
    if (userId === myUserId) return;
    
    console.log(`User joined: ${userName} (${userId})`);
    
    participants[userId] = {
        name: userName,
        profilePic: userProfilePic,
        videoEnabled: true
    };
    
    updateParticipantsList();
    
    const pc = createPeerConnection(userId);
    
    localStream.getTracks().forEach(track => {
        pc.addTrack(track, localStream);
    });

    const offer = await pc.createOffer();
    await pc.setLocalDescription(offer);

    socket.send(JSON.stringify({
        type: 'offer',
        offer: offer,
        targetId: userId,
        fromId: myUserId
    }));
}

function handleUserLeft(message) {
    const { userId } = message;
    
    console.log(`User left: ${userId}`);
    
    if (peerConnections[userId]) {
        peerConnections[userId].close();
        delete peerConnections[userId];
    }

    delete participants[userId];

    const videoContainer = document.getElementById(`video-container-${userId}`);
    if (videoContainer) {
        videoContainer.remove();
    }

    updateParticipantsList();
    updateVideosGrid();
}

async function handleOffer(message) {
    const { offer, fromId, userName, userProfilePic } = message;
    
    console.log(`Received offer from: ${fromId}`);
    
    participants[fromId] = {
        name: userName,
        profilePic: userProfilePic,
        videoEnabled: true
    };
    
    const pc = createPeerConnection(fromId);
    
    await pc.setRemoteDescription(new RTCSessionDescription(offer));

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

    const answer = await pc.createAnswer();
    await pc.setLocalDescription(answer);

    socket.send(JSON.stringify({
        type: 'answer',
        answer: answer,
        targetId: fromId,
        fromId: myUserId
    }));
}

async function handleAnswer(message) {
    const { answer, fromId } = message;
    
    console.log(`Received answer from: ${fromId}`);
    
    const pc = peerConnections[fromId];
    if (pc) {
        await pc.setRemoteDescription(new RTCSessionDescription(answer));
    }
}

async function handleIceCandidate(message) {
    const { candidate, fromId } = message;
    
    const pc = peerConnections[fromId];
    if (pc && candidate) {
        await pc.addIceCandidate(new RTCIceCandidate(candidate));
    }
}

function createPeerConnection(userId) {
    const pc = new RTCPeerConnection(configuration);

    pc.onicecandidate = (event) => {
        if (event.candidate) {
            socket.send(JSON.stringify({
                type: 'ice-candidate',
                candidate: event.candidate,
                targetId: userId,
                fromId: myUserId
            }));
        }
    };

    pc.ontrack = (event) => {
        console.log(`Received track from: ${userId}`);
        addRemoteVideo(userId, event.streams[0]);
    };

    pc.oniceconnectionstatechange = () => {
        console.log(`ICE connection state for ${userId}: ${pc.iceConnectionState}`);
    };

    peerConnections[userId] = pc;
    return pc;
}

function addRemoteVideo(userId, stream) {
    let videoContainer = document.getElementById(`video-container-${userId}`);
    
    if (!videoContainer) {
        videoContainer = document.createElement('div');
        videoContainer.id = `video-container-${userId}`;
        videoContainer.className = 'relative bg-gray-900 rounded-lg overflow-hidden aspect-video';
        
        const profilePicContainer = document.createElement('div');
        profilePicContainer.id = `profile-pic-${userId}`;
        profilePicContainer.className = 'absolute inset-0 flex items-center justify-center bg-gray-800 hidden';
        
        const participant = participants[userId];
        if (participant && participant.profilePic) {
            profilePicContainer.innerHTML = `
                <img src="${participant.profilePic}" alt="${participant.name}" 
                     class="w-24 h-24 rounded-full object-cover border-4 border-gray-700">
            `;
        } else {
            profilePicContainer.innerHTML = `
                <div class="w-24 h-24 rounded-full bg-gray-700 flex items-center justify-center border-4 border-gray-600">
                    <i class="fas fa-user text-gray-400 text-4xl"></i>
                </div>
            `;
        }
        
        const video = document.createElement('video');
        video.id = `video-${userId}`;
        video.autoplay = true;
        video.playsInline = true;
        video.className = 'w-full h-full object-cover';
        video.srcObject = stream;
        
        const label = document.createElement('div');
        label.className = 'absolute bottom-2 left-2 bg-black/70 text-white px-3 py-1 rounded text-sm';
        label.textContent = participants[userId]?.name || 'Unknown';
        
        videoContainer.appendChild(profilePicContainer);
        videoContainer.appendChild(video);
        videoContainer.appendChild(label);
        
        document.getElementById('videos-grid').appendChild(videoContainer);
        updateVideosGrid();
    } else {
        const video = document.getElementById(`video-${userId}`);
        if (video) {
            video.srcObject = stream;
        }
    }
}

function updateRemoteVideoState(message) {
    const { userId, videoEnabled } = message;
    
    const videoElement = document.getElementById(`video-${userId}`);
    const profilePicElement = document.getElementById(`profile-pic-${userId}`);
    
    if (participants[userId]) {
        participants[userId].videoEnabled = videoEnabled;
    }
    
    if (videoElement && profilePicElement) {
        if (videoEnabled) {
            videoElement.classList.remove('hidden');
            profilePicElement.classList.add('hidden');
        } else {
            videoElement.classList.add('hidden');
            profilePicElement.classList.remove('hidden');
        }
    }
}

function showMeetingRoom(title, code) {
    document.getElementById('meeting-lobby').classList.add('hidden');
    document.getElementById('meeting-room').classList.remove('hidden');
    document.getElementById('meeting-room-title').textContent = title;
    document.getElementById('meeting-room-code').textContent = `Code: ${code}`;

    const videosGrid = document.getElementById('videos-grid');
    videosGrid.innerHTML = '';

    const localVideoContainer = document.createElement('div');
    localVideoContainer.id = 'local-video-container';
    localVideoContainer.className = 'relative bg-gray-900 rounded-lg overflow-hidden aspect-video';
    
    const localProfilePic = document.createElement('div');
    localProfilePic.id = 'local-profile-pic';
    localProfilePic.className = 'absolute inset-0 flex items-center justify-center bg-gray-800 hidden';
    
    const userProfilePic = getUserProfilePic();
    if (userProfilePic) {
        localProfilePic.innerHTML = `
            <img src="${userProfilePic}" alt="You" 
                 class="w-24 h-24 rounded-full object-cover border-4 border-gray-700">
        `;
    } else {
        localProfilePic.innerHTML = `
            <div class="w-24 h-24 rounded-full bg-gray-700 flex items-center justify-center border-4 border-gray-600">
                <i class="fas fa-user text-gray-400 text-4xl"></i>
            </div>
        `;
    }
    
    const localVideo = document.createElement('video');
    localVideo.id = 'local-video';
    localVideo.autoplay = true;
    localVideo.muted = true;
    localVideo.playsInline = true;
    localVideo.className = 'w-full h-fullobject-cover';
    localVideo.srcObject = localStream;
    
    const localLabel = document.createElement('div');
    localLabel.className = 'absolute bottom-2 left-2 bg-black/70 text-white px-3 py-1 rounded text-sm';
    localLabel.textContent = 'You';
    
    localVideoContainer.appendChild(localProfilePic);
    localVideoContainer.appendChild(localVideo);
    localVideoContainer.appendChild(localLabel);
    videosGrid.appendChild(localVideoContainer);
    
    updateVideosGrid();
}

function updateVideosGrid() {
    const grid = document.getElementById('videos-grid');
    if (!grid) return;
    
    const videoCount = grid.children.length;
    
    if (videoCount === 1) {
        grid.className = 'grid grid-cols-1 gap-3 min-h-[400px]';
    } else if (videoCount === 2) {
        grid.className = 'grid grid-cols-2 gap-3 min-h-[400px]';
    } else if (videoCount <= 4) {
        grid.className = 'grid grid-cols-2 gap-3 min-h-[400px]';
    } else if (videoCount <= 6) {
        grid.className = 'grid grid-cols-3 gap-3 min-h-[400px]';
    } else {
        grid.className = 'grid grid-cols-4 gap-2 min-h-[400px]';
    }
}

function toggleAudio() {
    if (localStream) {
        isAudioEnabled = !isAudioEnabled;
        localStream.getAudioTracks().forEach(track => {
            track.enabled = isAudioEnabled;
        });
        
        const btn = document.getElementById('toggle-audio');
        btn.innerHTML = `<i class="fas fa-microphone${isAudioEnabled ? '' : '-slash'}"></i>`;
        btn.classList.toggle('bg-red-600', !isAudioEnabled);
        btn.classList.toggle('hover:bg-red-700', !isAudioEnabled);
        btn.classList.toggle('bg-gray-600', isAudioEnabled);
        btn.classList.toggle('hover:bg-gray-700', isAudioEnabled);
    }
}

function toggleVideo() {
    if (localStream) {
        isVideoEnabled = !isVideoEnabled;
        localStream.getVideoTracks().forEach(track => {
            track.enabled = isVideoEnabled;
        });
        
        const btn = document.getElementById('toggle-video');
        btn.innerHTML = `<i class="fas fa-video${isVideoEnabled ? '' : '-slash'}"></i>`;
        btn.classList.toggle('bg-red-600', !isVideoEnabled);
        btn.classList.toggle('hover:bg-red-700', !isVideoEnabled);
        btn.classList.toggle('bg-gray-600', isVideoEnabled);
        btn.classList.toggle('hover:bg-gray-700', isVideoEnabled);
        
        const localVideo = document.getElementById('local-video');
        const localProfilePic = document.getElementById('local-profile-pic');
        
        if (localVideo && localProfilePic) {
            if (isVideoEnabled) {
                localVideo.classList.remove('hidden');
                localProfilePic.classList.add('hidden');
            } else {
                localVideo.classList.add('hidden');
                localProfilePic.classList.remove('hidden');
            }
        }
        
        if (socket && socket.readyState === WebSocket.OPEN) {
            socket.send(JSON.stringify({
                type: 'video-toggle',
                userId: myUserId,
                videoEnabled: isVideoEnabled
            }));
        }
    }
}

async function toggleScreenShare() {
    const btn = document.getElementById('share-screen');
    
    if (!screenStream) {
        try {
            screenStream = await navigator.mediaDevices.getDisplayMedia({
                video: {
                    cursor: "always"
                },
                audio: false
            });
            
            const screenTrack = screenStream.getVideoTracks()[0];
            
            Object.values(peerConnections).forEach(pc => {
                const sender = pc.getSenders().find(s => s.track?.kind === 'video');
                if (sender) {
                    sender.replaceTrack(screenTrack);
                }
            });

            const localVideo = document.getElementById('local-video');
            if (localVideo) {
                localVideo.srcObject = screenStream;
            }

            screenTrack.onended = () => {
                stopScreenShare();
            };
            
            btn.classList.add('bg-blue-600');
            btn.classList.remove('bg-gray-600');
            
        } catch (error) {
            console.error('Screen share error:', error);
        }
    } else {
        stopScreenShare();
    }
}

function stopScreenShare() {
    if (screenStream) {
        screenStream.getTracks().forEach(track => track.stop());
        screenStream = null;
        
        const videoTrack = localStream.getVideoTracks()[0];
        Object.values(peerConnections).forEach(pc => {
            const sender = pc.getSenders().find(s => s.track?.kind === 'video');
            if (sender) {
                sender.replaceTrack(videoTrack);
            }
        });
        
        const localVideo = document.getElementById('local-video');
        if (localVideo) {
            localVideo.srcObject = localStream;
        }
        
        const btn = document.getElementById('share-screen');
        btn.classList.remove('bg-blue-600');
        btn.classList.add('bg-gray-600');
    }
}

function sendChatMessage() {
    const input = document.getElementById('chat-input');
    const message = input.value.trim();
    
    if (message && socket && socket.readyState === WebSocket.OPEN) {
        socket.send(JSON.stringify({
            type: 'chat',
            message: message,
            userName: getUserName(),
            timestamp: new Date().toISOString()
        }));
        
        input.value = '';
    }
}

function displayChatMessage(data) {
    const messagesContainer = document.getElementById('chat-messages');
    
    const time = new Date(data.timestamp).toLocaleTimeString('en-US', {
        hour: '2-digit',
        minute: '2-digit'
    });
    
    const messageDiv = document.createElement('div');
    messageDiv.className = 'bg-white dark:bg-gray-700 rounded-lg p-2';
    messageDiv.innerHTML = `
        <div class="flex justify-between items-start mb-1">
            <span class="font-medium text-sm">${escapeHtml(data.userName)}</span>
            <span class="text-xs text-gray-500">${time}</span>
        </div>
        <p class="text-sm break-words">${escapeHtml(data.message)}</p>
    `;
    
    messagesContainer.appendChild(messageDiv);
    messagesContainer.scrollTop = messagesContainer.scrollHeight;
}

function switchTab(tab) {
    const chatPanel = document.getElementById('chat-panel');
    const participantsPanel = document.getElementById('participants-panel');
    const tabChat = document.getElementById('tab-chat');
    const tabParticipants = document.getElementById('tab-participants');
    
    if (tab === 'chat') {
        chatPanel.classList.remove('hidden');
        participantsPanel.classList.add('hidden');
        tabChat.classList.add('border-black', 'dark:border-white');
        tabChat.classList.remove('border-transparent', 'text-gray-500');
        tabParticipants.classList.remove('border-black', 'dark:border-white');
        tabParticipants.classList.add('border-transparent', 'text-gray-500');
    } else {
        chatPanel.classList.add('hidden');
        participantsPanel.classList.remove('hidden');
        tabParticipants.classList.add('border-black', 'dark:border-white');
        tabParticipants.classList.remove('border-transparent', 'text-gray-500');
        tabChat.classList.remove('border-black', 'dark:border-white');
        tabChat.classList.add('border-transparent', 'text-gray-500');
        
        updateParticipantsList();
    }
}

function updateParticipantsList() {
    const list = document.getElementById('participants-list');
    list.innerHTML = '';
    
    const allParticipants = [
        { 
            id: myUserId, 
            name: getUserName(), 
            profilePic: getUserProfilePic(), 
            isMe: true 
        },
        ...Object.entries(participants).map(([id, p]) => ({ 
            id, 
            ...p, 
            isMe: false 
        }))
    ];
    
    document.getElementById('participants-count').textContent = allParticipants.length;
    
    allParticipants.forEach(participant => {
        const div = document.createElement('div');
        div.className = 'flex items-center justify-between p-2 bg-white dark:bg-gray-700 rounded-lg';
        
        const profileHTML = participant.profilePic 
            ? `<img src="${participant.profilePic}" alt="${participant.name}" class="w-8 h-8 rounded-full object-cover">`
            : `<div class="w-8 h-8 rounded-full bg-gray-300 dark:bg-gray-600 flex items-center justify-center">
                 <i class="fas fa-user text-gray-600 dark:text-gray-300 text-sm"></i>
               </div>`;
        
        div.innerHTML = `
            <div class="flex items-center space-x-2">
                ${profileHTML}
                <span class="text-sm">${escapeHtml(participant.name)}${participant.isMe ? ' (You)' : ''}</span>
            </div>
        `;
        
        list.appendChild(div);
    });
}

async function loadActiveMeetings() {
    try {
        const response = await fetch('meeting_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'get_active' })
        });

        const data = await response.json();
        
        if (data.success) {
            const list = document.getElementById('active-meetings-list');
            list.innerHTML = '';
            
            if (data.meetings.length === 0) {
                list.innerHTML = '<div class="text-center text-gray-500 py-4">No active meetings</div>';
                return;
            }
            
            data.meetings.forEach(meeting => {
                const div = document.createElement('div');
                div.className = 'flex items-center justify-between gap-3 p-4 bg-gray-100 dark:bg-gray-800 rounded-lg hover:bg-gray-200 dark:hover:bg-gray-700 transition-colors';
                
                div.innerHTML = `
                    <div>
                        <h4 class="font-medium">${escapeHtml(meeting.title)}</h4>
                        <div class="flex items-center gap-3 mt-1 text-sm text-gray-600 dark:text-gray-400">
                            <span><i class="fas fa-clock mr-1"></i>${meeting.duration}</span>
                            <span><i class="fas fa-users mr-1"></i>${meeting.participants} participant(s)</span>
                            <span class="font-mono text-xs">${meeting.code}</span>
                        </div>
                    </div>
                    <button onclick="quickJoinMeeting('${meeting.code}')" class="px-4 py-2 bg-green-600 hover:bg-green-700 text-white rounded-lg transition-colors text-sm">
                        Join
                    </button>
                `;
                
                list.appendChild(div);
            });
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

async function loadMeetingHistory() {
    try {
        const response = await fetch('meeting_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({ action: 'get_history' })
        });

        const data = await response.json();
        
        if (data.success) {
            const list = document.getElementById('meeting-history');
            if (!list) return;
            
            list.innerHTML = '';
            
            if (data.meetings.length === 0) {
                list.innerHTML = '<div class="text-center text-gray-500 py-4">No history</div>';
                return;
            }
            
            data.meetings.forEach(meeting => {
                const div = document.createElement('div');
                div.className = 'flex items-center justify-between p-3 bg-gray-100 dark:bg-gray-800 rounded-lg';
                
                div.innerHTML = `
                    <div class="flex-1 min-w-0">
                        <h4 class="font-medium text-sm truncate">${escapeHtml(meeting.title)}</h4>
                        <div class="text-xs text-gray-600 dark:text-gray-400 mt-1">
                            ${meeting.date} • ${meeting.duration} • ${meeting.participants} participant(s)
                        </div>
                    </div>
                    <span class="text-xs px-2 py-1 rounded-full whitespace-nowrap ml-2 ${meeting.status === 'completed' ? 'bg-green-100 text-green-800 dark:bg-green-900 dark:text-green-200' : 'bg-gray-200 text-gray-800 dark:bg-gray-700 dark:text-gray-200'}">
                        ${meeting.status === 'completed' ? 'Completed' : 'Active'}
                    </span>
                `;
                
                list.appendChild(div);
            });
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

function quickJoinMeeting(code) {
    document.getElementById('meeting-code-input').value = code;
    joinMeeting();
}

async function endMeeting() {
    if (confirm('Are you sure you want to end this meeting for everyone?')) {
        try {
            const response = await fetch('meeting_api.php', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({
                    action: 'end',
                    meetingId: currentMeetingId
                })
            });

            const data = await response.json();
            
            if (data.success) {
                if (socket && socket.readyState === WebSocket.OPEN) {
                    socket.send(JSON.stringify({ type: 'meeting-ended' }));
                }
                
                leaveMeeting();
            } else {
                alert(data.message || 'Error ending meeting');
            }
        } catch (error) {
            console.error('Error:', error);
            alert('Error ending meeting');
        }
    }
}

async function leaveMeeting() {
    if (localStream) {
        localStream.getTracks().forEach(track => track.stop());
    }
    
    if (screenStream) {
        screenStream.getTracks().forEach(track => track.stop());
    }

    Object.values(peerConnections).forEach(pc => pc.close());
    peerConnections = {};
    participants = {};

    if (socket) {
        socket.send(JSON.stringify({ 
            type: 'leave',
            userId: myUserId
        }));
        socket.close();
    }

    try {
        await fetch('meeting_api.php', {
            method: 'POST',
            headers: { 'Content-Type': 'application/json' },
            body: JSON.stringify({
                action: 'leave',
                meetingId: currentMeetingId
            })
        });
    } catch (error) {
        console.error('Error:', error);
    }

    document.getElementById('meeting-room').classList.add('hidden');
    document.getElementById('meeting-lobby').classList.remove('hidden');
    document.getElementById('meeting-code-input').value = '';
    
    currentMeetingId = null;
    localStream = null;
    screenStream = null;
    isAudioEnabled = true;
    isVideoEnabled = true;
    myUserId = null;
    
    loadActiveMeetings();
}

function handleMeetingEnded() {
    alert('This meeting has been ended by the host');
    leaveMeeting();
}

function copyMeetingLink() {
    const code = document.getElementById('meeting-room-code').textContent.replace('Code: ', '');
    const link = `${window.location.origin}${window.location.pathname}?meeting=${code}`;
    
    navigator.clipboard.writeText(link).then(() => {
        const btn = document.getElementById('copy-meeting-link');
        const originalText = btn.innerHTML;
        btn.innerHTML = '<i class="fas fa-check mr-1"></i>Copied!';
        setTimeout(() => {
            btn.innerHTML = originalText;
        }, 2000);
    });
}

function getUserId() {
    return document.querySelector('[data-user-id]')?.dataset.userId || Math.random().toString(36).substr(2, 9);
}

function getUserName() {
    const username = document.querySelector('.username')?.textContent;
    return username || 'Guest';
}

function getUserProfilePic() {
    const profileImg = document.querySelector('img[alt="Profile"]');
    if (profileImg && profileImg.src && !profileImg.src.includes('default-avatar')) {
        return profileImg.src;
    }
    return '';
}

function escapeHtml(text) {
    const div = document.createElement('div');
    div.textContent = text;
    return div.innerHTML;
}