(function() {
    // Extend the WebinarManager class
    const originalWebinarManager = WebinarManager;

    class ExtendedWebinarManager extends originalWebinarManager {
        constructor() {
            super();

            // Bind methods defined in webinar2.js
            this.handleWebinarStarted = this.handleWebinarStarted.bind(this);
            this.handleNewProducer = this.handleNewProducer.bind(this);
            this.handleProducerClosed = this.handleProducerClosed.bind(this);
            this.handleChatMessage = this.handleChatMessage.bind(this);
            this.handleMuteRequest = this.handleMuteRequest.bind(this);
            this.handlePresentationStarted = this.handlePresentationStarted.bind(this);
            this.handlePresentationEnded = this.handlePresentationEnded.bind(this);
            this.handleParticipantJoined = this.handleParticipantJoined.bind(this);
            this.handleParticipantLeft = this.handleParticipantLeft.bind(this);
            this.handleWebinarStatus = this.handleWebinarStatus.bind(this);
        }

        // ===== Page Initialization Methods =====
        async initializePage() {
            try {
                if (!this.companyId) {
                    await this.getCurrentUser();
                }
                this.initializeEventListeners();
                if (window.location.pathname.includes('webinar.html')) {
                    this.loadWebinars('live');
                    this.loadWebinars('upcoming');
                    this.loadWebinars('recordings');
                }
                this.startPeriodicSessionChecks();
                this.startSessionMonitor();
                this.setupActivityListeners();
            } catch (error) {
                console.error('Page initialization error:', error);
                this.handleAuthFailure();
            }
        }

        initializeEventListeners() {
            // Webinar creation form
            const webinarForm = document.getElementById('webinarForm');
            if (webinarForm) {
                webinarForm.addEventListener('submit', this.handleCreateWebinar.bind(this));
            }

            // Webinar room controls
            const toggleAudio = document.getElementById('toggleAudio');
            if (toggleAudio) {
                toggleAudio.addEventListener('click', this.toggleAudio.bind(this));
                document.getElementById('toggleVideo').addEventListener('click', this.toggleVideo.bind(this));
                document.getElementById('screenShare').addEventListener('click', this.toggleScreenShare.bind(this));
                document.getElementById('leaveBtn').addEventListener('click', this.leaveWebinar.bind(this));
                document.getElementById('sendMessage').addEventListener('click', this.sendChatMessage.bind(this));
                // Add Enter key support for chat
                document.getElementById('chatInput')?.addEventListener('keypress', (e) => {
                    if (e.key === 'Enter') this.sendChatMessage();
                });
            }

            // Participant controls
            if (document.getElementById('muteParticipantBtn')) {
                document.getElementById('muteParticipantBtn').addEventListener('click', () => {
                    const participantId = selectedParticipantId;
                    this.muteParticipant(participantId);
                });
            }

            // Presentation controls
            if (document.getElementById('startPresentationBtn')) {
                document.getElementById('startPresentationBtn').addEventListener('click', () => {
                    const type = 'slides';
                    const url = prompt('Enter presentation URL:');
                    if (url) this.startPresentation(type, url);
                });
            }

            if (document.getElementById('endPresentationBtn')) {
                document.getElementById('endPresentationBtn').addEventListener('click', this.endPresentation.bind(this));
            }

            // Tab navigation
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.addEventListener('click', (e) => {
                    if (!window.webinarManager) {
                        console.error('WebinarManager not ready yet');
                        return;
                    }

                    const tab = e.target.dataset.tab;
                    this.currentTab = tab;

                    document.querySelectorAll('.tab-btn').forEach(b => b.classList.remove('active'));
                    document.querySelectorAll('.tab-content').forEach(c => c.classList.remove('active'));

                    e.target.classList.add('active');
                    document.getElementById(tab).classList.add('active');
                    this.switchTab(this.currentTab);
                    this.loadWebinars(tab);
                });
            });

            // Search and filter
            const searchBox = document.querySelector('.searchBox');
            if (searchBox) {
                searchBox.addEventListener('input', (e) => {
                    this.filterWebinars(e.target.value);
                });
            }

            const filterDropdown = document.querySelector('.filter-btn');
            const filterMenu = document.querySelector('.filter-menu');
            if (filterDropdown) {
                filterDropdown.addEventListener('click', () => {
                    filterMenu?.classList.toggle('show');
                });
            }

            document.addEventListener('click', (e) => {
                if (!e.target.closest('.filter-dropdown')) {
                    filterMenu?.classList.remove('show');
                }
            });

            document.querySelectorAll('.filter-item').forEach(item => {
                item.addEventListener('click', () => {
                    const filterType = item.dataset.filter;
                    this.filterWebinars(filterType);
                    filterMenu?.classList.remove('show');
                    this.applyFilter(filterType);
                });
            });
        }

        switchTab(tabName) {
            try {
                document.querySelectorAll('.tab-btn').forEach(btn => {
                    btn.classList.toggle('active', btn.dataset.tab === tabName);
                });

                document.querySelectorAll('.tab-content').forEach(content => {
                    content.classList.toggle('active', content.id === tabName);
                });

                this.currentTab = tabName;
            } catch (error) {
                console.error('Error switching tab:', error);
                this.showNotification('Failed to switch tab', 'error');
            }
        }

        // ===== Webinar Management Methods =====
        async loadWebinars(type) {
            try {
                this.showLoader(type);

                const endpointMap = {
                    'live': '/api/webinars/live',
                    'upcoming': '/api/webinars/upcoming',
                    'recordings': '/api/webinars/recordings'
                };

                const response = await fetch(endpointMap[type], {
                    headers: {
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `HTTP Error ${response.status}`);
                }

                const webinars = await response.json();
                const filteredWebinars = this.filterWebinarsByTab(webinars, type);
                this.renderWebinars(filteredWebinars, type);
            } catch (error) {
                console.error(`Error loading ${type} webinars:`, error);
                this.showError(error.message, type);
            }
        }

        filterWebinarsByTab(webinars, tab) {
            const now = new Date();
            return webinars.filter(webinar => {
                const scheduledTime = new Date(webinar.scheduled_time);
                const endTime = new Date(scheduledTime.getTime() + webinar.duration * 60 * 1000);

                switch (tab) {
                    case 'live':
                        return now >= scheduledTime && now <= endTime;
                    case 'upcoming':
                        return scheduledTime > now;
                    case 'recordings':
                        return endTime < now;
                    default:
                        return true;
                }
            });
        }

        renderWebinars(webinars, type) {
            const grid = document.querySelector(`#${type} .webinar-grid`);
            if (!grid) return;

            grid.innerHTML = webinars.length === 0
                ? this.emptyStateHTML(type)
                : '';

            webinars.forEach(webinar => {
                const card = this.createWebinarCard(webinar, type);
                grid.appendChild(card);
            });
        }

        createWebinarCard(webinar, type) {
            const card = document.createElement('div');
            card.className = `webinar-card ${type}`;

            const isOrganizer = webinar.organizer_id === this.companyId;
            const isRegistered = webinar.is_registered;

            let dateInfo = '';
            if (type === 'upcoming' && webinar.scheduled_time) {
                const scheduledTime = new Date(webinar.scheduled_time);
                const istTime = new Date(scheduledTime.getTime() + 5.5 * 60 * 60 * 1000); // Convert UTC to IST
                dateInfo = `
                    <span><i class="fas fa-calendar-alt"></i> ${istTime.toLocaleDateString()}</span>
                    <span><i class="fas fa-clock"></i> ${istTime.toLocaleTimeString([], {hour: '2-digit', minute:'2-digit'})}</span>
                `;
            }

            let countInfo = '';
            if (type === 'live') {
                countInfo = `<span><i class="fas fa-users"></i> ${webinar.participants || 0} attending</span>`;
            } else if (type === 'recordings') {
                countInfo = `<span><i class="fas fa-eye"></i> ${webinar.views || 0} views</span>`;
            } else if (type === 'upcoming') {
                countInfo = `<span><i class="fas fa-user-plus"></i> ${webinar.registrations || 0} registered</span>`;
            }

            card.innerHTML = `
                <div class="webinar-thumbnail">
                    <img src="${webinar.thumbnail_url || this.getDefaultThumbnail(type)}" alt="${webinar.title}">
                    ${type === 'recordings' ? '<div class="play-btn"><i class="fas fa-play"></i></div>' : ''}
                </div>
                <div class="webinar-info">
                    <h3>${webinar.title}</h3>
                    <div class="webinar-meta">
                        <span><i class="fas fa-user"></i> ${webinar.organizer_name}</span>
                        ${dateInfo}
                        ${countInfo}
                    </div>
                    <p class="webinar-desc">${webinar.description || 'No description available'}</p>
                    <div class="webinar-actions">
                        ${this.getActionButtons(webinar, type)}
                    </div>
                </div>
            `;

            const primaryBtn = card.querySelector('.btn-primary');
            if (primaryBtn) {
                primaryBtn.addEventListener('click', async () => {
                    if (type === 'live') {
                        if (isRegistered) {
                            window.location.href = `/webinar-room.html?webinarId=${webinar.webinar_id}`;
                        } else {
                            await this.registerForWebinar(webinar.webinar_id);
                        }
                    } else if (type === 'recordings') {
                        this.watchRecording(webinar.webinar_id);
                    } else if (type === 'upcoming' && isOrganizer) {
                        if (confirm('Start this webinar now?')) {
                            await this.startWebinar(webinar.webinar_id);
                        }
                    } else if (isRegistered) {
                        window.location.href = `/webinar-room.html?webinarId=${webinar.webinar_id}`;
                    } else {
                        this.registerForWebinar(webinar.webinar_id);
                    }
                });
            }

            return card;
        }

        async startWebinar(webinarId) {
            try {
                if (!this.companyId) {
                    await this.getCurrentUser();
                    if (!this.companyId) throw new Error('Not logged in');
                }

                const response = await fetch(`/api/webinars/${webinarId}/start`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Failed to start webinar');
                }

                const result = await response.json();
                this.showNotification('Webinar started successfully!');
                this.routerRtpCapabilities = result.routerRtpCapabilities;
                window.location.href = `/webinar-room.html?webinarId=${webinarId}&presenter=true`;
            } catch (error) {
                console.error('Error starting webinar:', error);
                this.showNotification(error.message, 'error');
                this.loadWebinars(this.currentTab);
            }
        }

        async registerForWebinar(webinarId) {
            try {
                if (!this.companyId) {
                    await this.getCurrentUser();
                    if (!this.companyId) throw new Error('Not logged in');
                }

                const response = await fetch(`/api/webinars/${webinarId}/register`, {
                    method: 'POST',
                    headers: {
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Registration failed');
                }

                await response.json();
                this.showNotification('Successfully registered for this webinar!');
                this.loadWebinars('upcoming');
            } catch (error) {
                console.error('Registration error:', error);
                this.showNotification(error.message, 'error');
            }
        }

        watchRecording(webinarId) {
            window.open(`/webinar-recording.html?id=${webinarId}`, '_blank');
        }

        async handleCreateWebinar(e) {
            e.preventDefault();

            const webinarData = {
                title: document.getElementById('title').value,
                description: document.getElementById('description').value,
                scheduledTime: document.getElementById('datetime').value,
                duration: document.getElementById('duration').value,
                isPublic: document.getElementById('isPublic').checked,
                maxParticipants: 100
            };

            // Convert IST to UTC
            const scheduledTimeIST = new Date(webinarData.scheduledTime);
            const scheduledTimeUTC = new Date(scheduledTimeIST.getTime() - 5.5 * 60 * 60 * 1000);
            webinarData.scheduledTime = scheduledTimeUTC.toISOString();

            try {
                const response = await fetch('/api/webinars', {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    body: JSON.stringify(webinarData),
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Failed to create webinar');
                }

                const result = await response.json();
                this.showNotification('Webinar created successfully!');
                window.location.href = `/webinar-room.html?webinarId=${result.webinarId}`;
            } catch (error) {
                console.error('Error creating webinar:', error);
                this.showNotification('Error creating webinar: ' + error.message, 'error');
            }
        }

        filterWebinars(searchTerm) {
            const cards = document.querySelectorAll(`#${this.currentTab} .webinar-card`);
            const term = searchTerm.toLowerCase();

            cards.forEach(card => {
                const title = card.querySelector('h3')?.textContent.toLowerCase();
                const desc = card.querySelector('.webinar-desc')?.textContent.toLowerCase();
                const isVisible = title?.includes(term) || desc?.includes(term);
                card.style.display = isVisible ? 'block' : 'none';
            });
        }

        applyFilter(filter) {
            console.log('Applying filter:', filter);
            this.loadWebinars(this.currentTab);
        }

        // ===== Webinar Room Methods =====
        async setupWebinarRoom() {
            const urlParams = new URLSearchParams(window.location.search);
            this.webinarId = urlParams.get('webinarId');
            this.isPresenter = urlParams.has('presenter');
            this.role = this.isPresenter ? 'presenter' : 'attendee';

            try {
                if (!this.socketInitialized) {
                    await this.initializeSocket();
                }

                this.socket.emit('join_webinar', this.webinarId);

                const response = await fetch(`/api/webinars/${this.webinarId}/join`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    body: JSON.stringify({ isPresenter: this.isPresenter }),
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || `Join failed (HTTP ${response.status})`);
                }

                const data = await response.json();
                await this.initializeMediasoup(data.routerRtpCapabilities);
                await this.fetchParticipants();
            } catch (error) {
                console.error('Webinar setup error:', error);
                this.showNotification(`Join failed: ${error.message}`, 'error');
                if (error.message.includes('not active')) {
                    setTimeout(() => this.setupWebinarRoom(), 5000);
                }
            }
        }

        async fetchParticipants() {
            try {
                const response = await fetch(`/api/webinars/${this.webinarId}/participants`, {
                    headers: {
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    credentials: 'include'
                });
                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Failed to fetch participants');
                }

                const participants = await response.json();
                this.participants = new Map(participants.map(p => [p.id, p]));
                this.updateParticipantsList();
            } catch (error) {
                console.error('Error fetching participants:', error);
            }
        }

        updateParticipantsList() {
            const listElement = document.getElementById('participantsList');
            const countElement = document.getElementById('participantCount');

            if (!listElement || !countElement) return;

            listElement.innerHTML = '';
            countElement.textContent = this.participants.size;

            this.participants.forEach(participant => {
                const li = document.createElement('li');
                li.innerHTML = `
                    <span class="participant-name">${participant.name || participant.companyName || 'Anonymous'}</span>
                    ${participant.isPresenter ? '<span class="badge presenter">Presenter</span>' : ''}
                `;
                listElement.appendChild(li);
            });
        }

        // ===== Media Handling Methods =====
        async loadMediasoupClient() {
            if (!window.mediasoupClient) {
                const url = '/mediasoup-client.js';
                try {
                    await new Promise((resolve, reject) => {
                        if (document.querySelector(`script[src="${url}"]`)) {
                            if (window.mediasoupClient) {
                                this.mediasoupClient = window.mediasoupClient;
                                resolve();
                                return;
                            }
                        }
                        const script = document.createElement('script');
                        script.src = url;
                        script.async = true;
                        script.onload = () => {
                            if (window.mediasoupClient) {
                                this.mediasoupClient = window.mediasoupClient;
                                resolve();
                            } else {
                                reject(new Error('mediasoupClient not defined after loading'));
                            }
                        };
                        script.onerror = () => reject(new Error(`Failed to load mediasoup-client from ${url}`));
                        document.head.appendChild(script);
                    });
                    console.log(`Successfully loaded mediasoup-client from ${url}`);
                } catch (error) {
                    console.error(error.message);
                    throw new Error('Failed to load mediasoup-client');
                }
            } else {
                this.mediasoupClient = window.mediasoupClient;
                console.log('mediasoup-client already loaded');
            }
        }

        async initializeMediasoup(routerRtpCapabilities) {
            try {
                if (!this.mediasoupClient) {
                    await this.loadMediasoupClient();
                }

                this.device = new this.mediasoupClient.Device();
                await this.device.load({ routerRtpCapabilities });

                await this.createTransports();

                if (this.isPresenter) {
                    await this.produceInitialMedia();
                }

                await this.setupConsumerTransports();
            } catch (error) {
                console.error('Mediasoup initialization error:', error);
                this.showNotification('Failed to initialize media', 'error');
                throw error;
            }
        }

        async createTransports() {
            try {
                // Create send transport
                const sendResponse = await fetch(`/api/webinars/${this.webinarId}/create-transport`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    body: JSON.stringify({ isProducer: true }),
                    credentials: 'include'
                });

                if (!sendResponse.ok) {
                    const errorData = await sendResponse.json();
                    throw new Error(errorData.error || 'Failed to create send transport');
                }

                const sendTransportData = await sendResponse.json();
                this.sendTransport = this.device.createSendTransport(sendTransportData);

                // Create receive transport
                const recvResponse = await fetch(`/api/webinars/${this.webinarId}/create-transport`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    body: JSON.stringify({ isProducer: false }),
                    credentials: 'include'
                });

                if (!recvResponse.ok) {
                    const errorData = await recvResponse.json();
                    throw new Error(errorData.error || 'Failed to create receive transport');
                }

                const recvTransportData = await recvResponse.json();
                this.recvTransport = this.device.createRecvTransport(recvTransportData);

                this.setupTransportListeners();
            } catch (error) {
                console.error('Transport creation error:', error);
                this.showNotification('Failed to create media connections', 'error');
                throw error;
            }
        }

        setupTransportListeners() {
            // Send transport events
            this.sendTransport.on('connect', async ({ dtlsParameters }, callback, errback) => {
                try {
                    const response = await fetch(`/api/webinars/${this.webinarId}/connect-transport`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${this.authToken}`
                        },
                        body: JSON.stringify({
                            transportId: this.sendTransport.id,
                            dtlsParameters,
                            isProducer: true
                        }),
                        credentials: 'include'
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || 'Failed to connect send transport');
                    }

                    callback();
                } catch (error) {
                    console.error('Send transport connect error:', error);
                    errback(error);
                }
            });

            this.sendTransport.on('produce', async ({ kind, rtpParameters }, callback, errback) => {
                try {
                    const response = await fetch(`/api/webinars/${this.webinarId}/produce`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${this.authToken}`
                        },
                        body: JSON.stringify({
                            transportId: this.sendTransport.id,
                            kind,
                            rtpParameters
                        }),
                        credentials: 'include'
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || 'Failed to produce');
                    }

                    const { id } = await response.json();
                    callback({ id });
                } catch (error) {
                    console.error('Produce error:', error);
                    errback(error);
                }
            });

            // Receive transport events
            this.recvTransport.on('connect', async ({ dtlsParameters }, callback, errback) => {
                try {
                    const response = await fetch(`/api/webinars/${this.webinarId}/connect-transport`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json',
                            'Authorization': `Bearer ${this.authToken}`
                        },
                        body: JSON.stringify({
                            transportId: this.recvTransport.id,
                            dtlsParameters,
                            isProducer: false
                        }),
                        credentials: 'include'
                    });

                    if (!response.ok) {
                        const errorData = await response.json();
                        throw new Error(errorData.error || 'Failed to connect receive transport');
                    }

                    callback();
                } catch (error) {
                    console.error('Receive transport connect error:', error);
                    errback(error);
                }
            });
        }

        async produceInitialMedia() {
            try {
                const stream = await navigator.mediaDevices.getUserMedia({
                    video: true,
                    audio: true
                });

                this.videoStream = stream;

                const videoTrack = stream.getVideoTracks()[0];
                const audioTrack = stream.getAudioTracks()[0];

                if (videoTrack) {
                    this.videoProducer = await this.sendTransport.produce({
                        track: videoTrack,
                        codecOptions: { videoGoogleStartBitrate: 1000 }
                    });
                    this.producers.set(this.videoProducer.id, this.videoProducer);
                }

                if (audioTrack) {
                    this.audioProducer = await this.sendTransport.produce({
                        track: audioTrack,
                        codecOptions: { opusStereo: true, opusDtx: true }
                    });
                    this.producers.set(this.audioProducer.id, this.audioProducer);
                }

                this.addLocalVideo(stream);
            } catch (error) {
                console.error('Error producing initial media:', error);
                this.showNotification('Failed to start media stream', 'error');
                throw error;
            }
        }

        async setupConsumerTransports() {
            try {
                const response = await fetch(`/api/webinars/${this.webinarId}/producers`, {
                    headers: {
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    credentials: 'include'
                });

                if (!response.ok) {
                    let errorMessage = `Failed to fetch producers (HTTP ${response.status})`;
                    try {
                        const errorData = await response.json();
                        errorMessage = errorData.error || errorMessage;
                    } catch (jsonError) {
                        const text = await response.text();
                        errorMessage = text || errorMessage;
                    }
                    throw new Error(errorMessage);
                }

                const producers = await response.json();

                for (const producer of producers) {
                    await this.consumeProducer(producer);
                }
            } catch (error) {
                console.error('Error setting up consumer transports:', error);
                throw error;
            }
        }

        async consumeProducer(producer) {
            try {
                const response = await fetch(`/api/webinars/${this.webinarId}/consume`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json',
                        'Authorization': `Bearer ${this.authToken}`
                    },
                    body: JSON.stringify({
                        producerId: producer.id,
                        rtpCapabilities: this.device.rtpCapabilities
                    }),
                    credentials: 'include'
                });

                if (!response.ok) {
                    const errorData = await response.json();
                    throw new Error(errorData.error || 'Failed to consume producer');
                }

                const data = await response.json();
                const consumer = await this.recvTransport.consume({
                    id: data.id,
                    producerId: data.producerId,
                    kind: data.kind,
                    rtpParameters: data.rtpParameters
                });

                this.consumers.set(consumer.id, consumer);

                const stream = new MediaStream();
                stream.addTrack(consumer.track);
                this.addRemoteVideo(stream, data.producerId);
            } catch (error) {
                console.error('Error consuming producer:', error);
            }
        }

        addLocalVideo(stream) {
            const videoContainer = document.getElementById('videoContainer');
            if (!videoContainer) return;

            const videoElement = document.createElement('video');
            videoElement.id = `local-video-${this.companyId}`;
            videoElement.srcObject = stream;
            videoElement.autoplay = true;
            videoElement.muted = true;
            videoElement.className = 'video-stream local-video';
            videoContainer.appendChild(videoElement);
        }

        addRemoteVideo(stream, producerId) {
            const videoContainer = document.getElementById('videoContainer');
            if (!videoContainer) return;

            const videoElement = document.createElement('video');
            videoElement.id = `remote-video-${producerId}`;
            videoElement.srcObject = stream;
            videoElement.autoplay = true;
            videoElement.className = 'video-stream remote-video';
            videoContainer.appendChild(videoElement);
        }

        async toggleAudio() {
            try {
                if (!this.audioProducer) {
                    const stream = await navigator.mediaDevices.getUserMedia({ audio: true });
                    const track = stream.getAudioTracks()[0];
                    this.audioProducer = await this.sendTransport.produce({
                        track,
                        codecOptions: { opusStereo: true, opusDtx: true }
                    });
                    this.producers.set(this.audioProducer.id, this.audioProducer);
                }
                this.audioProducer.track.enabled = !this.audioProducer.track.enabled;
                this.showNotification(`Microphone ${this.audioProducer.track.enabled ? 'unmuted' : 'muted'}`);
                this.updateUIForMuteState(!this.audioProducer.track.enabled);
            } catch (error) {
                this.showNotification('Failed to toggle audio: ' + error.message, 'error');
            }
        }

        async toggleVideo() {
            try {
                if (!this.sendTransport) {
                    await this.initializeMediasoup(this.routerRtpCapabilities);
                }

                if (!this.videoProducer) {
                    const stream = await navigator.mediaDevices.getUserMedia({ video: true });
                    const videoTrack = stream.getVideoTracks()[0];

                    this.videoProducer = await this.sendTransport.produce({
                        track: videoTrack,
                        codecOptions: { videoGoogleStartBitrate: 1000 }
                    });
                    this.producers.set(this.videoProducer.id, this.videoProducer);

                    this.videoStream = stream;
                    this.addLocalVideo(stream);
                }

                const newState = !this.videoProducer.track.enabled;
                this.videoProducer.track.enabled = newState;
                this.updateVideoButtonState(newState);
                this.showNotification(`Camera ${newState ? 'enabled' : 'disabled'}`);
            } catch (error) {
                console.error('Error toggling video:', error);
                this.showNotification(`Failed to toggle video: ${error.message}`, 'error');

                if (this.videoProducer && !this.videoProducer.track.enabled) {
                    this.videoProducer.close();
                    this.producers.delete(this.videoProducer.id);
                    this.videoProducer = null;
                    if (this.videoStream) {
                        this.videoStream.getTracks().forEach(track => track.stop());
                        this.videoStream = null;
                    }
                }
            }
        }

        async toggleScreenShare() {
            try {
                if (this.screenProducer) {
                    this.screenProducer.close();
                    this.producers.delete(this.screenProducer.id);
                    this.screenProducer = null;
                    this.showNotification('Screen sharing stopped');
                    document.getElementById('screenShare').textContent = '🖥️';
                } else {
                    const stream = await navigator.mediaDevices.getDisplayMedia({
                        video: true,
                        audio: false
                    });
                    const track = stream.getVideoTracks()[0];
                    this.screenProducer = await this.sendTransport.produce({
                        track,
                        codecOptions: { videoGoogleStartBitrate: 2000 }
                    });
                    this.producers.set(this.screenProducer.id, this.screenProducer);
                    this.showNotification('Screen sharing started');
                    document.getElementById('screenShare').textContent = '🖥️ Stop';

                    track.onended = () => {
                        this.toggleScreenShare();
                    };
                }
            } catch (error) {
                this.showNotification('Screen share failed: ' + error.message, 'error');
            }
        }

        leaveWebinar() {
            try {
                this.producers.forEach(producer => {
                    producer.close();
                });
                this.consumers.forEach(consumer => {
                    consumer.close();
                });

                if (this.sendTransport) this.sendTransport.close();
                if (this.recvTransport) this.recvTransport.close();

                if (this.videoStream) {
                    this.videoStream.getTracks().forEach(track => track.stop());
                    this.videoStream = null;
                }

                this.socket.emit('leave_webinar', this.webinarId);
                window.location.href = '/webinar.html';
            } catch (error) {
                console.error('Error leaving webinar:', error);
                this.showNotification('Error leaving webinar', 'error');
                window.location.href = '/webinar.html';
            }
        }

        // ===== Chat Methods =====
        sendChatMessage() {
            const messageInput = document.getElementById('chatInput');
            const message = messageInput?.value.trim();

            if (message) {
                this.socket.emit('webinar_chat_message', {
                    webinarId: this.webinarId,
                    message,
                    companyName: this.companyName || 'Anonymous',
                    timestamp: Date.now()
                });
                messageInput.value = '';
            }
        }

        handleChatMessage(data) {
            console.log('New chat message:', data);
            const chatMessages = document.getElementById('chatMessages');
            if (!data || !data.companyName || !data.message) {
                console.warn('Invalid chat message format:', data);
                return;
            }
            if (chatMessages) {
                const messageElement = document.createElement('div');
                messageElement.className = 'message';
                const istTime = new Date(data.timestamp + 5.5 * 60 * 60 * 1000); // Convert UTC to IST
                messageElement.innerHTML = `
                    <strong>${data.companyName}:</strong>
                    <span>${data.message}</span>
                    <small>${istTime.toLocaleTimeString([], {hour: '2-digit', minute: '2-digit'})}</small>
                `;
                chatMessages.appendChild(messageElement);
                chatMessages.scrollTop = chatMessages.scrollHeight;
            }
        }

        // ===== Presentation Methods =====
        startPresentation(type, url) {
            this.currentPresentation = { type, url };
            this.socket.emit('presentation_started', {
                webinarId: this.webinarId,
                type,
                url
            });
        }

        endPresentation() {
            this.currentPresentation = null;
            this.socket.emit('presentation_ended', { webinarId: this.webinarId });
        }

        // ===== Participant Control Methods =====
        muteParticipant(participantId) {
            this.socket.emit('mute_request', { webinarId: this.webinarId, participantId });
        }

        // ===== Socket Event Handlers =====
        handleWebinarStarted(data) {
            if (data.webinarId === this.webinarId) {
                this.showNotification('Webinar has started!');
                this.setupWebinarRoom();
            }
        }

        handleNewProducer(data) {
            if (data.webinarId === this.webinarId) {
                this.consumeProducer(data.producer);
            }
        }

        handleProducerClosed(data) {
            const { producerId } = data;
            const consumer = Array.from(this.consumers.values()).find(c => c.producerId === producerId);
            if (consumer) {
                consumer.close();
                this.consumers.delete(consumer.id);
                const videoElement = document.getElementById(`remote-video-${producerId}`);
                if (videoElement) videoElement.remove();
            }
        }

        handleMuteRequest(data) {
            if (data.participantId === this.companyId && this.audioProducer) {
                this.audioProducer.track.enabled = false;
                this.showNotification('You have been muted by the presenter');
                this.updateUIForMuteState(true);
            }
        }

        handlePresentationStarted(data) {
            this.currentPresentation = { type: data.type, url: data.url };
            const presentationArea = document.getElementById('presentationArea');
            if (presentationArea) {
                presentationArea.innerHTML = `<iframe src="${data.url}" frameborder="0"></iframe>`;
            }
        }

        handlePresentationEnded() {
            this.currentPresentation = null;
            const presentationArea = document.getElementById('presentationArea');
            if (presentationArea) presentationArea.innerHTML = '';
        }

        handleParticipantJoined(data) {
            if (!this.participants.has(data.id)) {
                this.participants.set(data.id, data);
                this.updateParticipantsList();
            }
        }

        handleParticipantLeft(data) {
            this.participants.delete(data.id);
            this.updateParticipantsList();
        }

        handleWebinarStatus(data) {
            if (data.webinarId === this.webinarId) {
                if (data.status === 'ended') {
                    this.showNotification('Webinar has ended');
                    setTimeout(() => this.leaveWebinar(), 3000);
                }
            }
        }

        // ===== UI Helper Methods for Media Controls =====
        updateUIForMuteState(isMuted) {
            const toggleAudioBtn = document.getElementById('toggleAudio');
            if (toggleAudioBtn) {
                toggleAudioBtn.textContent = isMuted ? '🔇 Unmute' : '🔊 Mute';
            }
        }

        updateVideoButtonState(isEnabled) {
            const toggleVideoBtn = document.getElementById('toggleVideo');
            if (toggleVideoBtn) {
                toggleVideoBtn.textContent = isEnabled ? '📷 Disable' : '📷 Enable';
            }
        }
    }

    // Override the global WebinarManager with the extended version
    window.WebinarManager = ExtendedWebinarManager;

    // Global function for initializing webinar room (used in HTML)
    window.initializeWebinarManager = function() {
        window.webinarManager = new WebinarManager();
        webinarManager.setupWebinarRoom();
    };
})();