let currentCompanyId;
let currentCompanyName;
let activeJitsiMeeting = null;
let currentUser = {};
const ws = new WebSocket('ws://localhost:3000/ws');

document.addEventListener('DOMContentLoaded', () => {
  // Connect to WebSocket
  ws.onopen = () => {
    console.log('WebSocket connection established');
    ws.send(JSON.stringify({ type: "auth", token: "your_session_token" }));
  };
  
  // ws.onmessage = (event) => {
  //   const data = JSON.parse(event.data);
  //   switch(data.type) {
      
  //     case 'direct_message':
  //       showMessageModal(data);
  //       break;
  //     case 'meeting_invite':
  //       showNotification('Meeting Invite', data.message);
  //       showModal('Meeting Invite', `
  //         <p>${data.message}</p>
  //         <button onclick="startJitsiMeeting('${data.roomId}')">Join Meeting</button>
  //       `);
  //       break;
  //     case 'meeting_reminder':
  //       showNotification('Meeting Reminder', data.message);
  //       break;
  //   }
  // };
  
  ws.onmessage = (event) => {
    const data = JSON.parse(event.data);
    console.log('Received WebSocket message:', data); // Debug
  
    if (data.type === 'exhibition_ended') {
      localStorage.removeItem('authToken');
      window.location.href = '/login?message=exhibition_ended';
      return;
    }
    switch (data.type) {
      case 'direct_message':
        displayMessage(data.senderName, data.senderId, data.content);
        showNotification('New Message', `You received a message from Company ${data.senderName}: ${data.content}`);
        break;
      case 'presence_update':
        if (Array.isArray(data.companies)) {
            updateCompanyStatus(data.companies);
        } else {
            console.error('Invalid presence update format:', data);
        }
        break;
      // case 'meeting_invite':
      //   showNotification('Meeting Invite', `You have been invited to a meeting by Company ${data.senderName}`);
      //   showModal('Meeting Invite', `
      //     <p>You have been invited to a meeting by Company ${data.senderName}.</p>
      //     <button onclick="startJitsiMeeting('${data.roomId}')">Join Meeting</button>
      //   `);
      //   break;
      case 'incoming_call':
        webRTCHandler.handleIncomingCall(data);
        break;
      case 'call_request':
        // Show incoming call UI immediately
        showIncomingCallModal(data).then(accepted => {
            if (accepted) {
                webRTCHandler.handleIncomingCall(data);
            }
        });
        break;
      case 'call_response':
        if (data.accepted) {
            showCallModal('active', data.receiverId);
            webRTCHandler.handleAnswer(data);
        } else {
            showNotification('Call Declined', `${data.receiverName || 'The recipient'} declined your call`);
            webRTCHandler.endCall();
        }
        break;
      case 'offer':
        webRTCHandler.handleOffer(data);
        break;
      case 'answer':
        webRTCHandler.handleAnswer(data);
        break;
      case 'ice_candidate':
        webRTCHandler.handleICECandidate(data);
        break;
      case 'meeting_scheduled':
        showNotification('Meeting Scheduled', `Meeting "${data.title}" scheduled for ${new Date(data.scheduledTime).toLocaleString()}`);
        break;
      case 'meeting_started':
        showMeetingStartedModal(data);
        break;
      case 'new_discussion':
        addNewDiscussionToUI(data.discussion);
        break;
      
      case 'new_comment':
        if (isViewingDiscussion(data.comment.discussion_id)) {
          addNewCommentToUI(data.comment);
        }
        break;
      case 'discussion_deleted':
        removeDiscussionFromUI(data.discussionId);
        break;
    }
  };

  // Initial fetch
  fetch('/api/companies')
    .then(response => response.json())
    .then(renderCompanies)
    .catch(console.error);

  fetch('/api/current-user')
    .then(response => response.json())
    .then(user => {
      currentCompanyId = user.companyId;
      currentCompanyName = user.companyName;
      currentUser = user; // Store the full user object
      console.log('Current user:', user);
      console.log('Current company ID:', currentCompanyId);
      console.log('Current company name:', currentCompanyName);
    })
    .catch(error => console.error('Error fetching current user:', error));
  
});
// Simple UUID generator (or import properly)
function uuidv4() {
  return 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
    const r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
    return v.toString(16);
  });
}
// Function to display a message in the chat box
function removeDiscussionFromUI(discussionId) {
  const discussionElement = document.querySelector(`.discussion-card[data-id="${discussionId}"]`);
  if (discussionElement) {
    discussionElement.remove();
  }
  // If viewing the deleted discussion, close its modal
  if (isViewingDiscussion(discussionId)) {
    document.getElementById('action-modal').remove();
  }
}
function displayMessage(senderId, senderName, content) {
  const chatMessages = document.getElementById('chat-messages');
  if (!chatMessages) return;

  const messageElement = document.createElement('div');
  messageElement.classList.add('message');
  messageElement.innerHTML = `
    <strong>${senderName}:</strong> ${content}
  `;
  chatMessages.appendChild(messageElement);

  // Scroll to the bottom of the chat box
  chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Request permission when the page loads
document.addEventListener('DOMContentLoaded', requestNotificationPermission);
function addNewDiscussionToUI(discussion) {
  const discussionsList = document.getElementById('discussions-list');
  if (discussionsList) {
    const discussionHTML = `
      <div class="discussion-card">
        <h4>${discussion.title}</h4>
        <div class="meta">
          <span>By ${discussion.creatorName}</span>
          <span>•</span>
          <span>${new Date(discussion.created_at).toLocaleDateString()}</span>
        </div>
        <p>${discussion.content.substring(0, 150)}...</p>
        <div class="stats">
          <span>${discussion.participantCount} participants</span>
          <button class="btn btn-primary" onclick="joinDiscussion(${discussion.id})">
            <i class="fas fa-comment"></i> Join Discussion
          </button>
        </div>
      </div>
    `;
    discussionsList.insertAdjacentHTML('afterbegin', discussionHTML);
  }
}

function addNewCommentToUI(comment) {
  const commentsContainer = document.getElementById('discussion-comments');
  if (commentsContainer) {
    const commentHTML = `
      <div class="comment">
        <p><strong>${comment.authorName}:</strong> ${comment.content}</p>
        <small>${new Date(comment.created_at).toLocaleString()}</small>
      </div>
    `;
    commentsContainer.insertAdjacentHTML('afterbegin', commentHTML);
  }
}

function isViewingDiscussion(discussionId) {
  // Check if current modal shows this discussion
  const modal = document.getElementById('action-modal');
  return modal && modal.querySelector('.discussion-view') && 
         modal.querySelector('.discussion-view').dataset.discussionId == discussionId;
}
// function renderCompanies(companies) {
//   const list = document.getElementById('company-list');
//   list.innerHTML = companies.map(company => `
//     <li class="company-card" data-company-id="${company.company_id}">
//       <div class="company-header">
//         <img src="${company.logo_url}" alt="${company.company_name}" class="company-logo">
//         <h3>${company.company_name}</h3>
//         <span class="status-dot" style="background: ${company.status === 'available' ? 'var(--online-color)' : 'var(--offline-color)'}" data-status="${company.status === 'available' ? 'Available' : 'Offline'}"></span>
//       </div>
//       <div class="action-buttons">
//         <button class="btn btn-primary" onclick="showBusinessCard(${company.company_id})">
//           <i class="fas fa-address-card"></i> Card
//         </button>
//         <button class="btn btn-primary"
//           onclick="openChat(${company.company_id})">
//           <i class="fas fa-comments"></i> Chat
//         </button>
        
//         <button class="btn btn-primary" onclick="webRTCHandler.startCall(${company.company_id})" 
//           ${company.status === 'offline' ? 'disabled' : ''}>
//           <i class="fas fa-phone"></i> Call
//         </button>
//       </div>
//     </li>
//   `).join('');
// }
function renderCompanies(companies) {
  const list = document.getElementById('company-list');
  list.innerHTML = companies.map(company => `
      <li class="company-card" data-company-id="${company.company_id}">
          <div class="company-header">
              <img src="${company.logo_url}" alt="${company.company_name}" class="company-logo">
              <h3>${company.company_name}</h3>
              <span class="status-dot" 
                    style="background: ${company.status === 'available' ? 'var(--online-color)' : 'var(--offline-color)'}"
                    data-status="${company.status === 'available' ? 'Available' : 'Offline'}"></span>
          </div>
          <div class="action-buttons">
              <button class="btn btn-primary" onclick="showBusinessCard(${company.company_id})">
                  <i class="fas fa-address-card"></i> Card
              </button>
              <button class="btn btn-primary" onclick="openChat(${company.company_id})">
                  <i class="fas fa-comments"></i> Chat
              </button>
              <button class="btn btn-primary" onclick="startPeerToPeerCall(${company.company_id})" 
                  ${company.status === 'offline' ? 'disabled' : ''}>
                  <i class="fas fa-phone"></i> Call
              </button>
          </div>
      </li>
  `).join('');
}
async function showIncomingCallModal(data) {
  return new Promise((resolve) => {
      const modalContent = `
          <div class="incoming-call-modal">
              <div class="caller-info">
                  <img src="${getCompanyLogo(data.callerId)}" class="caller-avatar">
                  <h3>Incoming Call</h3>
                  <p>From: ${data.callerName}</p>
              </div>
              <div class="call-actions">
                  <button class="btn btn-accept" id="accept-call-btn">
                      <i class="fas fa-phone"></i> Accept
                  </button>
                  <button class="btn btn-reject" id="reject-call-btn">
                      <i class="fas fa-phone-slash"></i> Reject
                  </button>
              </div>
          </div>
      `;

      showModal('Incoming Call', modalContent);

      document.getElementById('accept-call-btn').addEventListener('click', () => {
          document.getElementById('action-modal').remove();
          resolve(true);
      });

      document.getElementById('reject-call-btn').addEventListener('click', () => {
          document.getElementById('action-modal').remove();
          resolve(false);
      });
  });
}

// Helper function (you'll need to implement this)
function getCompanyLogo(companyId) {
  // Query your companies data or cache to get logo URL
  return '/images/default-avatar.png'; // Fallback image
}
// Add this new function to handle call initiation
function startPeerToPeerCall(receiverId) {
  webRTCHandler.startCall(receiverId);
}
function updateCompanyStatus(activeIds) {
  const companyList = document.getElementById('company-list');
  if (!companyList) return;

  companyList.querySelectorAll('.company-card').forEach(card => {
    const companyId = parseInt(card.dataset.companyId);
    const statusDot = card.querySelector('.status-dot');

    if (activeIds.includes(companyId)) {
      statusDot.style.backgroundColor = 'var(--online-color)';
      statusDot.setAttribute('data-status', 'Available');
    } else {
      statusDot.style.backgroundColor = 'var(--offline-color)';
      statusDot.setAttribute('data-status', 'Offline');
    }
  });
}
// networking.js (frontend)
async function openChat(receiverId) {
  const senderId = currentCompanyId;
  console.log('Attempting to open chat with:', receiverId);
  // Create the modal first
  showModal('Direct Message', `
    <div class="chat-container">
      <div class="chat-messages" id="chat-messages"></div>
      <input type="text" id="message-input" placeholder="Type your message...">
      <button onclick="sendMessage(${receiverId})">Send</button>
    </div>
  `);
  console.log('Modal should be visible now');
  const modal = document.getElementById('action-modal');
  if (!modal) {
    console.error('Modal not found');
    return;
  }
  await new Promise(resolve => setTimeout(resolve, 50));
  // Now fetch chat history
  const response = await fetch(`/api/chat-history?senderId=${senderId}&receiverId=${receiverId}`);
  const chatHistory = await response.json();

  // Display chat history
  const chatMessages = document.getElementById('chat-messages');
  if (!chatMessages) {
    console.error('Chat messages element not found');
    return;
  }

  chatMessages.innerHTML = ''; // Clear previous messages

  chatMessages.innerHTML = chatHistory.map(msg => `
    <div class="message">
      <strong>Company ${msg.sender_name}:</strong> ${msg.content}
    </div>
  `).join('');

  // Scroll to the bottom of the chat box
  chatMessages.scrollTop = chatMessages.scrollHeight;
}
// Business Card Modal
async function showBusinessCard(companyId) {
  const response = await fetch(`/api/company/${companyId}`);
  const company = await response.json();
  
  const modalBody = `
    <div class="business-card">
      <h3>${company.company_name}</h3>
      <p><i class="fas fa-user"></i> ${company.primary_contact_name}</p>
      <p><i class="fas fa-envelope"></i> ${company.email}</p>
      <p><i class="fas fa-globe"></i> <a href="${company.website_url}" target="_blank">Website</a></p>
      ${company.social_media ? `<p><i class="fas fa-hashtag"></i> ${company.social_media}</p>` : ''}
    </div>
  `;
  
  showModal('Business Card', modalBody);
}

// WebSocket Message Handling
function startChat(receiverId) {
  const modalBody = `
    <div class="chat-container">
      <div class="chat-messages" id="chat-messages"></div>
      <input type="text" id="message-input" placeholder="Type your message...">
      <button onclick="sendMessage(${receiverId})">Send</button>
    </div>
  `;
  showModal('Direct Message', modalBody);
}


// function sendMessage(receiverId) {
//   const message = document.getElementById('message-input').value;
//   if (!message) return;

//   // Display the sent message immediately
//   displayMessage(currentCompanyId, req.session.user.companyName, message);

//   // Clear the input field
//   document.getElementById('message-input').value = '';

//   // Send the message via WebSocket
//   ws.send(JSON.stringify({
//     type: 'direct_message',
//     senderId: currentCompanyId,
//     receiverId,
//     content: message
//   }));
// }
function sendMessage(receiverId) {
  const message = document.getElementById('message-input').value;
  if (!message) return;

  // Use stored company name instead of req.session
  displayMessage(currentCompanyId, currentCompanyName, message); // Add currentCompanyName

  // Clear input
  document.getElementById('message-input').value = '';

  // Send via WebSocket
  ws.send(JSON.stringify({
    type: 'direct_message',
    senderId: currentCompanyId,
    receiverId,
    content: message
  }));
}
function getCompanyName(companyId) {
  const companyCard = document.querySelector(`.company-card[data-company-id="${companyId}"]`);
  if (companyCard) {
      return companyCard.querySelector('.company-header h3').textContent;
  }
  return `Company ${companyId}`; // Fallback
}
// Replace the existing WebRTC code with this complete implementation

class WebRTCHandler {
  constructor() {
      this.peerConnection = null;
      this.localStream = null;
      this.remoteStream = null;
      this.currentCall = null;
      this.mediaConstraints = {
          video: {
              width: { ideal: 1280 },
              height: { ideal: 720 },
              frameRate: { ideal: 30 }
          },
          audio: {
              echoCancellation: true,
              noiseSuppression: true,
              autoGainControl: true
          }
      };
  }

  async initLocalStream() {
      try {
          this.localStream = await navigator.mediaDevices.getUserMedia(this.mediaConstraints);
          return this.localStream;
      } catch (error) {
          console.error('Error accessing media devices:', error);
          throw error;
      }
  }

  async startCall(receiverId) {
      try {
          await this.initLocalStream();
          const callId = uuidv4();
          this.currentCall = { callId, receiverId };

          // Create peer connection
          this.peerConnection = new RTCPeerConnection({
              iceServers: [
                  { urls: 'stun:stun.l.google.com:19302' },
                  // Add your TURN servers here if needed
              ]
          });

          // Add local stream tracks
          this.localStream.getTracks().forEach(track => {
              this.peerConnection.addTrack(track, this.localStream);
          });

          // Handle ICE candidates
          this.peerConnection.onicecandidate = (event) => {
              if (event.candidate) {
                  ws.send(JSON.stringify({
                      type: 'ice_candidate',
                      callId,
                      receiverId,
                      candidate: event.candidate.toJSON()
                  }));
              }
          };

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

          // Create offer
          const offer = await this.peerConnection.createOffer();
          await this.peerConnection.setLocalDescription(offer);

          // Send call request
          ws.send(JSON.stringify({
              type: 'call_request',
              callId,
              callerId: currentCompanyId,
              callerName: currentCompanyName,
              receiverId,
              offer
          }));

          // Show calling UI
          showCallModal('outgoing', receiverId, getCompanyName(receiverId));

      } catch (error) {
          console.error('Call setup failed:', error);
          showNotification('Error', 'Failed to start call');
      }
  }

  async handleIncomingCall(data) {
      try {
          // Show incoming call UI
          const acceptCall = await showIncomingCallModal(data);
          
          if (acceptCall) {
              await this.initLocalStream();
              this.currentCall = { callId: data.callId, callerId: data.callerId };

              // Create peer connection
              this.peerConnection = new RTCPeerConnection({
                  iceServers: [
                      { urls: 'stun:stun.l.google.com:19302' }
                  ]
              });

              // Add local stream tracks
              this.localStream.getTracks().forEach(track => {
                  this.peerConnection.addTrack(track, this.localStream);
              });

              // Handle ICE candidates
              this.peerConnection.onicecandidate = (event) => {
                  if (event.candidate) {
                      ws.send(JSON.stringify({
                          type: 'ice_candidate',
                          callId: data.callId,
                          receiverId: data.callerId,
                          candidate: event.candidate.toJSON()
                      }));
                  }
              };

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

              // Set remote description
              await this.peerConnection.setRemoteDescription(
                  new RTCSessionDescription(data.offer)
              );

              // Create answer
              const answer = await this.peerConnection.createAnswer();
              await this.peerConnection.setLocalDescription(answer);

              // Send call response
              ws.send(JSON.stringify({
                  type: 'call_response',
                  callId: data.callId,
                  callerId: data.callerId,
                  receiverId: currentCompanyId,
                  receiverName: currentCompanyName,
                  answer,
                  accepted: true
              }));

              // Show call UI
              showCallModal('incoming', data.callerId, data.callerName);

          } else {
              // Send call rejection
              ws.send(JSON.stringify({
                  type: 'call_response',
                  callId: data.callId,
                  callerId: data.callerId,
                  receiverId: currentCompanyId,
                  accepted: false
              }));
          }
      } catch (error) {
          console.error('Error handling incoming call:', error);
          showNotification('Error', 'Failed to handle call');
      }
  }
  
  async handleAnswer(data) {
      if (!this.peerConnection || !this.currentCall || this.currentCall.callId !== data.callId) {
          return;
      }

      try {
          await this.peerConnection.setRemoteDescription(
              new RTCSessionDescription(data.answer)
          );
      } catch (error) {
          console.error('Error setting remote description:', error);
      }
  }

  async handleICECandidate(data) {
      if (!this.peerConnection || !this.currentCall || this.currentCall.callId !== data.callId) {
          return;
      }

      try {
          await this.peerConnection.addIceCandidate(
              new RTCIceCandidate(data.candidate)
          );
      } catch (error) {
          console.error('Error adding ICE candidate:', error);
      }
  }

  endCall() {
      if (this.peerConnection) {
          this.peerConnection.close();
          this.peerConnection = null;
      }
      
      if (this.localStream) {
          this.localStream.getTracks().forEach(track => track.stop());
          this.localStream = null;
      }
      
      this.remoteStream = null;
      this.currentCall = null;
      hideCallModal();
  }
}
// Initialize WebRTC handler
const webRTCHandler = new WebRTCHandler();
// Make it globally accessible (only for debugging, remove in production)
window.webRTCHandler = webRTCHandler;

// UI Functions
function showCallModal(type, targetId, targetName) {
  const title = type === 'outgoing' ? 
      `Calling ${targetName}` : 
      `In Call with ${targetName}`;
  
  const content = `
      <div class="call-container">
          <div class="video-container">
              <video id="remote-video" autoplay playsinline></video>
              <video id="local-video" autoplay muted playsinline></video>
              <div class="call-stats" id="call-stats"></div>
          </div>
          <div class="fullscreen-controls-wrapper">
            <div class="call-controls">
                <button class="control-btn mute" onclick="toggleMute()" title="Mute">
                    <i class="fas fa-microphone"></i>
                </button>
                <button class="control-btn video" onclick="toggleVideo()" title="Video Off">
                    <i class="fas fa-video"></i>
                </button>
                <button class="control-btn volume" onclick="toggleVolume()" title="Volume">
                    <i class="fas fa-volume-up"></i>
                </button>
                <button class="control-btn fullscreen" onclick="toggleFullscreen()" title="Fullscreen">
                    <i class="fas fa-expand"></i>
                </button>
                <button class="control-btn stats" onclick="toggleStats()" title="Connection Stats">
                    <i class="fas fa-chart-bar"></i>
                </button>
                <button class="control-btn end-call" onclick="webRTCHandler.endCall()" title="End Call">
                    <i class="fas fa-phone-slash"></i>
                </button>
            </div>
            <div class="volume-control" id="volume-control" style="display:none">
                <input type="range" min="0" max="100" value="100" 
                    oninput="setVolume(this.value)" orient="vertical">
            </div>
            <div class="volume-control-wrapper" id="volume-control" style="display:none">
              <div class="volume-control">
                  <input type="range" 
                        class="volume-slider" 
                        min="0" 
                        max="100" 
                        value="100" 
                        orient="vertical"
                        oninput="setVolume(this.value)">
              </div>
          </div>
      </div>
      </div>
  `;

  showModal(title, content);

  // Display local video
  const localVideo = document.getElementById('local-video');
  if (localVideo && webRTCHandler.localStream) {
      localVideo.srcObject = webRTCHandler.localStream;
  }

  // Start stats monitoring
  callStatsInterval = setInterval(updateCallStats, 1000);
}
// Volume control
let currentVolume = 100;
let volumeTimeout;
function toggleVolume() {
    const volControl = document.getElementById('volume-control');
    if (volControl.style.display === 'block') {
        volControl.style.display = 'none';
    } else {
        volControl.style.display = 'block';
        clearTimeout(volumeTimeout);
        volumeTimeout = setTimeout(() => {
            volControl.style.display = 'none';
        }, 3000);
    }
}

function setVolume(level) {
  currentVolume = level;
  const remoteVideo = document.getElementById('remote-video');
  if (remoteVideo) remoteVideo.volume = level / 100;
  
  // Auto-hide after 2 seconds
  clearTimeout(volumeTimeout);
  volumeTimeout = setTimeout(() => {
      document.getElementById('volume-control').style.display = 'none';
  }, 2000);
}

// Fullscreen
function toggleFullscreen() {
  const container = document.querySelector('.call-container');
  
  if (!document.fullscreenElement) {
      container.requestFullscreen().then(() => {
          // Show controls in fullscreen
          document.querySelector('.call-controls').classList.add('fullscreen-controls');
          // Position volume control differently in fullscreen
          document.getElementById('volume-control').classList.add('fullscreen-volume');
      }).catch(err => {
          console.error('Fullscreen error:', err);
      });
  } else {
      document.exitFullscreen().then(() => {
          // Restore normal controls
          document.querySelector('.call-controls').classList.remove('fullscreen-controls');
          document.getElementById('volume-control').classList.remove('fullscreen-volume');
      });
  }
  // Add to your existing JavaScript
document.addEventListener('fullscreenchange', () => {
  const controls = document.querySelector('.call-controls');
  if (document.fullscreenElement) {
      // Auto-hide controls after 3 seconds
      let hideTimeout;
      const resetHideTimeout = () => {
          clearTimeout(hideTimeout);
          controls.style.opacity = '1';
          hideTimeout = setTimeout(() => {
              controls.style.opacity = '0.5';
          }, 3000);
      };
      
      controls.addEventListener('mousemove', resetHideTimeout);
      resetHideTimeout();
  }
});
}
document.addEventListener('keydown', (e) => {
  if (!document.fullscreenElement) return;
  
  switch(e.key) {
      case ' ':
          toggleMute();
          break;
      case 'f':
          toggleFullscreen();
          break;
      case 'm':
          toggleVideo();
          break;
      case 'ArrowUp':
          setVolume(Math.min(currentVolume + 10, 100));
          break;
      case 'ArrowDown':
          setVolume(Math.max(currentVolume - 10, 0));
          break;
  }
});
// Connection stats
let callStatsInterval;
function toggleStats() {
    const statsDiv = document.getElementById('call-stats');
    statsDiv.style.display = statsDiv.style.display === 'block' ? 'none' : 'block';
}

async function updateCallStats() {
    if (!webRTCHandler.peerConnection) return;
    
    const stats = await webRTCHandler.peerConnection.getStats();
    let statsOutput = '';
    
    stats.forEach(report => {
        if (report.type === 'candidate-pair' && report.nominated) {
            statsOutput += `Connection: ${report.state || 'active'}<br>`;
            statsOutput += `Round-trip: ${report.currentRoundTripTime ? (report.currentRoundTripTime*1000).toFixed(0) : 'N/A'}ms<br>`;
        }
        if (report.type === 'track') {
            statsOutput += `${report.kind} ${report.direction}: ${report.frameWidth || ''}${report.frameWidth ? 'x' : ''}${report.frameHeight || ''}<br>`;
        }
    });
    
    document.getElementById('call-stats').innerHTML = statsOutput;
}

// Add to WebRTCHandler.endCall()
clearInterval(callStatsInterval);

async function showIncomingCallModal(data) {
  return new Promise((resolve) => {
      const content = `
          <div class="incoming-call">
              <div class="caller-info">
                  <h3>Incoming Call</h3>
                  <p>From: ${data.callerName}</p>
              </div>
              <div class="call-actions">
                  <button class="btn btn-accept" onclick="acceptCall()">
                      <i class="fas fa-phone"></i> Accept
                  </button>
                  <button class="btn btn-reject" onclick="rejectCall()">
                      <i class="fas fa-phone-slash"></i> Reject
                  </button>
              </div>
          </div>
      `;

      showModal('Incoming Call', content);

      window.acceptCall = () => {
          document.getElementById('action-modal').remove();
          resolve(true);
      };

      window.rejectCall = () => {
          document.getElementById('action-modal').remove();
          resolve(false);
      };
  });
}

function hideCallModal() {
  const modal = document.getElementById('action-modal');
  if (modal) {
      modal.remove();
  }
}

// Quick Meeting Functions
function startQuickMeeting() {
  showModal('Start Quick Meeting', `
      <div class="quick-meeting-form">
          <div class="form-group">
              <label>Meeting Title</label>
              <input type="text" id="quick-meeting-title" placeholder="Enter meeting title">
          </div>
          <div class="form-group">
              <label>Participants</label>
              <div id="quick-meeting-participants" class="participant-list">
                  <!-- Participants will be added here dynamically -->
              </div>
          </div>
          <button class="btn btn-primary" onclick="createQuickMeeting()">
              <i class="fas fa-bolt"></i> Start Meeting
          </button>
      </div>
  `);

  // Load available participants
  loadQuickMeetingParticipants();
}
function loadComments(discussionId) {
  if (!discussionId) {
      console.error('No discussion ID provided');
      return;
  }
  
  fetch(`/api/comments?discussionId=${discussionId}`)
      .then(response => {
          if (!response.ok) throw new Error('Failed to load comments');
          return response.json();
      })
      .then(comments => {
          const container = document.getElementById('discussion-comments');
          if (container) {
              container.innerHTML = comments.map(comment => `
                  <div class="comment">
                      <p><strong>${comment.authorName || 'Anonymous'}:</strong> ${comment.content}</p>
                      <small>${new Date(comment.created_at).toLocaleString()}</small>
                  </div>
              `).join('');
          }
      })
      .catch(error => {
          console.error('Comment load error:', error);
          showNotification('Error', 'Failed to load comments');
      });
}
async function loadQuickMeetingParticipants() {
  const participantsList = document.getElementById('quick-meeting-participants');
  if (!participantsList) return;

  try {
      const response = await fetch('/api/companies');
      const companies = await response.json();
      
      participantsList.innerHTML = companies.map(company => `
          <div class="participant-item">
              <input type="checkbox" id="participant-${company.company_id}" 
                  value="${company.company_id}">
              <label for="participant-${company.company_id}">
                  <img src="${company.logo_url}" alt="${company.company_name}" class="participant-avatar">
                  ${company.company_name}
                  <span class="status-dot" style="background: ${company.status === 'available' ? 'var(--online-color)' : 'var(--offline-color)'}"></span>
              </label>
          </div>
      `).join('');
  } catch (error) {
      console.error('Error loading participants:', error);
  }
}

function createQuickMeeting() {
  const title = document.getElementById('quick-meeting-title').value;
  const checkboxes = document.querySelectorAll('#quick-meeting-participants input:checked');
  const participantIds = Array.from(checkboxes).map(cb => cb.value);

  if (!title || participantIds.length === 0) {
      showNotification('Error', 'Please provide a title and select at least one participant');
      return;
  }

  // For now, we'll just start a group call
  // In a real implementation, you would create a meeting room
  showNotification('Info', 'Quick meeting feature will be implemented fully in the next version');
  document.getElementById('action-modal').remove();
}

function showGroupCallModal(roomId) {
  const content = `
    <div class="group-call-container">
      <div class="participants-grid" id="participants-grid"></div>
      <div class="call-controls">
        <button class="control-btn end-call" onclick="endGroupCall()">
          <i class="fas fa-phone-slash"></i>
        </button>
        <button class="control-btn mute" onclick="toggleMute()">
          <i class="fas fa-microphone"></i>
        </button>
        <button class="control-btn video" onclick="toggleVideo()">
          <i class="fas fa-video"></i>
        </button>
        <button class="control-btn invite" onclick="showInviteParticipants()">
          <i class="fas fa-user-plus"></i>
        </button>
      </div>
      <div id="invite-participants-modal" class="invite-modal">
        <!-- Participant list would go here -->
      </div>
    </div>
  `;

  showModal('Group Call', content);
  document.getElementById('local-video').srcObject = webRTCHandler.localStream;
}

// Schedule Meeting UI
async function showScheduleMeetingModal() {
  const companies = await fetch('/api/companies').then(res => res.json());
  
  const content = `
    <div class="schedule-meeting-form">
      <div class="form-group">
        <label>Meeting Title</label>
        <input type="text" id="meeting-title" placeholder="Enter meeting title">
      </div>
      <div class="form-group">
        <label>Date & Time</label>
        <input type="datetime-local" id="meeting-time">
      </div>
      <div class="form-group">
        <label>Duration (minutes)</label>
        <input type="number" id="meeting-duration" value="30" min="15" max="240">
      </div>
      <div class="form-group">
        <label>Participants</label>
        <div class="participant-list">
          ${companies.map(company => `
            <div class="participant-checkbox">
              <input type="checkbox" id="participant-${company.company_id}" 
                value="${company.company_id}">
              <label for="participant-${company.company_id}">
                ${company.company_name}
              </label>
            </div>
          `).join('')}
        </div>
      </div>
      <button onclick="scheduleMeeting()">Schedule Meeting</button>
    </div>
  `;

  showModal('Schedule Meeting', content);
}

async function scheduleMeeting() {
  const title = document.getElementById('meeting-title').value;
  const scheduledTime = document.getElementById('meeting-time').value;
  const duration = document.getElementById('meeting-duration').value;
  
  const checkboxes = document.querySelectorAll('.participant-checkbox input:checked');
  const participantIds = Array.from(checkboxes).map(cb => cb.value);

  if (!title || !scheduledTime || participantIds.length === 0) {
    showNotification('Error', 'Please fill all fields and select at least one participant');
    return;
  }

  try {
    const response = await fetch('/api/schedule-meeting', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
        title,
        scheduledTime,
        duration,
        participantIds
      })
    });

    const result = await response.json();
    if (result.success) {
      showNotification('Success', 'Meeting scheduled successfully');
      document.getElementById('action-modal').remove();
    }
  } catch (error) {
    console.error('Error scheduling meeting:', error);
    showNotification('Error', 'Failed to schedule meeting');
  }
}

// Utility functions
function toggleMute() {
  if (webRTCHandler.localStream) {
      const audioTrack = webRTCHandler.localStream.getAudioTracks()[0];
      if (audioTrack) {
          audioTrack.enabled = !audioTrack.enabled;
          const btn = document.querySelector('.control-btn.mute i');
          btn.classList.toggle('fa-microphone');
          btn.classList.toggle('fa-microphone-slash');
          showNotification(
              audioTrack.enabled ? 'Microphone On' : 'Microphone Off', 
              audioTrack.enabled ? 'You are now unmuted' : 'You are now muted'
          );
      }
  }
}

function toggleVideo() {
  if (webRTCHandler.localStream) {
      const videoTrack = webRTCHandler.localStream.getVideoTracks()[0];
      if (videoTrack) {
          videoTrack.enabled = !videoTrack.enabled;
          const btn = document.querySelector('.control-btn.video i');
          btn.classList.toggle('fa-video');
          btn.classList.toggle('fa-video-slash');
          showNotification(
              videoTrack.enabled ? 'Video On' : 'Video Off', 
              videoTrack.enabled ? 'Your video is now visible' : 'Your video is now hidden'
          );
      }
  }
}

// General Modal Functions
function showModal(title, content) {
  // Remove existing modal
  const existingModal = document.getElementById('action-modal');
  if (existingModal) existingModal.remove();

  // Create new modal
  const modal = document.createElement('div');
  modal.id = 'action-modal';
  modal.className = 'modal';
  modal.innerHTML = `
    <div class="modal-content" id="modal-content">
      <div class="modal-header" id="drag-header">
        <span class="close">&times;</span>
        <h2>${title}</h2>
      </div>
      <div class="modal-body" id="modal-body">
        ${content}
        <div id="jitsi-container"></div> <!-- Add this line -->
      </div>
    </div>
  `;

  // Add drag and close functionality
  const dragHeader = modal.querySelector('#drag-header');
  let offsetX, offsetY, isDragging = false;

  dragHeader.addEventListener('mousedown', (e) => {
    isDragging = true;
    offsetX = e.clientX - modal.offsetLeft;
    offsetY = e.clientY - modal.offsetTop;
    dragHeader.style.cursor = 'grabbing';
  });

  document.addEventListener('mousemove', (e) => {
    if (isDragging) {
      modal.style.left = `${e.clientX - offsetX}px`;
      modal.style.top = `${e.clientY - offsetY}px`;
    }
  });

  document.addEventListener('mouseup', () => {
    isDragging = false;
    dragHeader.style.cursor = 'grab';
  });

  // Close button
  modal.querySelector('.close').onclick = () => modal.remove();
  modal.style.display = 'block';
  document.body.appendChild(modal);
}

// document.querySelector('.close').onclick = () => {
//   document.getElementById('action-modal').style.display = 'none';
// };
// networkingjs.js
let isMeetingButtonDisabled = false;
// networkingjs.js
async function startMeeting(receiverId) {
  try {
    // 1. Create MeetHour meeting via your backend
    const response = await fetch('/api/create-1on1-meeting', { method: 'POST' });
    const { joinUrl } = await response.json();

    // 2. Send meeting URL to the receiver via WebSocket
    ws.send(JSON.stringify({
      type: 'meeting_invite',
      receiverId: receiverId,
      joinUrl: joinUrl,
      senderName: currentCompanyName // From your existing code
    }));

    // 3. Show MeetHour in a modal (no extra registration)
    showModal('1:1 Meeting', `
      <iframe 
        src="${joinUrl}" 
        width="100%" 
        height="500px" 
        allow="camera; microphone"
      ></iframe>
    `);
  } catch (error) {
    console.error('Meeting error:', error);
    showNotification('Error', 'Failed to start meeting');
  }
}
async function showMeetingHistory() {
  const response = await fetch('/api/meeting-history');
  const meetings = await response.json();

  const modalBody = `
    <h3>Meeting History</h3>
    <ul class="meeting-list">
      ${meetings.map(meeting => `
        <li>
          <strong>${meeting.title}</strong>
          <p>${new Date(meeting.meeting_time).toLocaleString()}</p>
          <button onclick="startJitsiMeeting('${meeting.room_id}')">Rejoin Meeting</button>
        </li>
      `).join('')}
    </ul>
  `;

  showModal('Meeting History', modalBody);
}
function requestNotificationPermission() {
  if (Notification.permission !== 'granted') {
    Notification.requestPermission().then(permission => {
      if (permission === 'granted') {
        console.log('Notification permission granted');
      }
    });
  }
}

// Show browser notification
function showNotification(title, message) {
  if (Notification.permission === 'granted') {
    new Notification(title, { body: message });
  } else if (Notification.permission !== 'denied') {
    Notification.requestPermission().then(permission => {
      if (permission === 'granted') {
        new Notification(title, { body: message });
      }
    });
  }
}
// Forum/Discussion Functions
let discussions = []; // This would normally come from your backend
let currentPage = 1;
let totalPages = 1;

function loadDiscussions() {
  const limit = 10;
  fetch(`/api/discussions?page=${currentPage}&limit=${limit}`)
      .then(response => {
          if (!response.ok) {
              return response.json().then(err => {
                  throw new Error(err.error || 'Failed to load discussions');
              });
          }
          return response.json();
      })
      .then(data => {
          discussions = data.discussions;
          renderDiscussions(data);
      })
      .catch(error => {
          console.error('Discussion load error:', error);
          showNotification('Error', error.message);
      });
}
function renderPaginationControls() {
  const pagination = document.getElementById('pagination-controls');
  if (!pagination) return;

  pagination.innerHTML = `
      <div class="pagination">
          <button ${currentPage === 1 ? 'disabled' : ''} onclick="changePage(${currentPage - 1})">
              <i class="fas fa-chevron-left"></i>
          </button>
          <span>Page ${currentPage} of ${totalPages}</span>
          <button ${currentPage >= totalPages ? 'disabled' : ''} onclick="changePage(${currentPage + 1})">
              <i class="fas fa-chevron-right"></i>
          </button>
      </div>
  `;
}
function changePage(newPage) {
  if (newPage < 1 || newPage > totalPages) return;
  currentPage = newPage;
  loadDiscussions();
}
async function deleteDiscussion(discussionId) {
  const reason = prompt('Please enter reason for deletion (optional):');
  
  try {
    const response = await fetch(`/api/discussions/${discussionId}`, {
      method: 'DELETE',
      headers: {
        'Content-Type': 'application/json'
      },
      body: JSON.stringify({ reason })
    });

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

    showNotification('Success', 'Discussion deleted and archived');
    // The WebSocket message will handle UI update
  } catch (error) {
    console.error('Delete error:', error);
    showNotification('Error', error.message);
    
    // Check if it's a 404 and refresh discussions
    if (error.message.includes('not found')) {
      loadDiscussions();
    }
  }
}
function renderDiscussions(data) {
  try {
    const list = document.getElementById('discussions-list');
    if (!data?.discussions?.length) {
      list.innerHTML = `<div class="no-discussions">No discussions found</div>`;
      return;
    }

    list.innerHTML = data.discussions.map(discussion => {
      const isCreator = discussion.creator_id == currentUser.companyId;
      const canDelete = currentUser.isAdmin || isCreator;
      const formattedDate = formatDate(new Date(discussion.created_at).toLocaleString());
      return `
        <div class="discussion-card" data-id="${discussion.id}">
          <h4>${discussion.title}</h4>
          <div class="meta">
            <span>By ${discussion.creatorName}</span>
            <span>•</span>
            <span>${formattedDate}</span>
          </div>
          <p>${discussion.content.substring(0, 150)}...</p>
          <div class="stats">
            <span>${discussion.participantCount} participants</span>
            <button class="btn btn-primary" onclick="joinDiscussion(${discussion.id})">
              <i class="fas fa-comment"></i> Join Discussion
            </button>
            ${canDelete ? `
              <button class="btn btn-danger" onclick="deleteDiscussion(${discussion.id})">
                <i class="fas fa-trash"></i> Delete
              </button>
            ` : ''}
          </div>
        </div>
      `;
    }).join('');
  } catch (error) {
    console.error('Render error:', error);
    showNotification('Error', 'Failed to display discussions');
  }
}

// Add this helper function
// function formatDiscussionDate(timestamp) {
//   const date = new Date(timestamp);
//   return date.toLocaleDateString('en-US', {
//     year: 'numeric',
//     month: 'short',
//     day: 'numeric',
//     hour: '2-digit',
//     minute: '2-digit'
//   });
// }
function formatDate(dateStr) {
  const date = new Date(dateStr);
  
  const day = String(date.getDate()).padStart(2, '0');   // Adds leading zero if day is less than 10
  const month = String(date.getMonth() + 1).padStart(2, '0'); // Months are 0-indexed, so add 1
  const year = date.getFullYear();
  const hours = String(date.getHours()).padStart(2, '0');
  const minutes = String(date.getMinutes()).padStart(2, '0');
  
  return `${day}/${month}/${year} ${hours}:${minutes}`;
}
function showNewDiscussionModal() {
    showModal('Start New Discussion', `
        <div class="discussion-form">
            <div class="form-group">
                <label for="discussion-title">Title</label>
                <input type="text" id="discussion-title" placeholder="Discussion topic">
            </div>
            <div class="form-group">
                <label for="discussion-content">Content</label>
                <textarea id="discussion-content" placeholder="What do you want to discuss?"></textarea>
            </div>
            <button class="btn btn-primary" onclick="createDiscussion()">
                <i class="fas fa-paper-plane"></i> Post Discussion
            </button>
        </div>
    `);
}
function createDiscussion() {
  const title = document.getElementById('discussion-title').value;
  const content = document.getElementById('discussion-content').value;
  
  if (!title || !content) {
    showNotification('Error', 'Please fill in both title and content');
    return;
  }

  fetch('/api/discussions', {
    method: 'POST',
    headers: { 'Content-Type': 'application/json' },
    body: JSON.stringify({
      title,
      content,
      creatorId: currentCompanyId
    })
  })
  .then(response => {
    if (!response.ok) {
      return response.json().then(err => { 
        throw new Error(err.details || err.error || 'Failed to create discussion');
      });
    }
    return response.json();
  })
  .then(newDiscussion => {
    // Close the modal
    document.getElementById('action-modal').remove();
    // Show success notification
    showNotification('Success', 'Discussion created successfully!');
    // Reload discussions to show the new one
    loadDiscussions();
  })
  .catch(error => {
    console.error('Error creating discussion:', error);
    showNotification('Error', error.message);
  });
}

function joinDiscussion(discussionId) {
    // In a real app, this would open a discussion view
    const id = parseInt(discussionId);
    const discussion = discussions.find(d => d.id === id);
    if (!discussion) {
      showNotification('Error', 'Discussion not found');
      return;
    }
    showModal(`Discussion: ${discussion.title}`, `
        <div class="discussion-view">
            <div class="discussion-header">
                <h3>${discussion.title}</h3>
                <p>Started by ${discussion.creatorName} on ${new Date(discussion.created_at).toLocaleString()}</p>
            </div>
            <div class="discussion-content">
                <p>${discussion.content}</p>
            </div>
            <div class="discussion-comments" id="discussion-comments">
                <!-- Comments would load here -->
            </div>
            <div class="comment-form">
                <textarea id="new-comment" placeholder="Add your comment..."></textarea>
                <button class="btn btn-primary" onclick="postComment('${id}')">
                    <i class="fas fa-reply"></i> Post Comment
                </button>
            </div>
        </div>
    `);
    
    // Load comments would go here
    loadComments(id);
}
function postComment(discussionId) {
  const content = document.getElementById('new-comment').value;
  
  if (!content) {
      showNotification('Error', 'Please enter a comment');
      return;
  }

  fetch('/api/comments', {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify({
          discussionId,
          content,
          companyId: currentCompanyId
      })
  })
  .then(response => response.json())
  .then(newComment => {
      const commentsContainer = document.getElementById('discussion-comments');
      const commentHTML = `
          <div class="comment">
              <p><strong>${newComment.authorName}:</strong> ${newComment.content}</p>
              <small>${new Date(newComment.created_at).toLocaleString()}</small>
          </div>
      `;
      commentsContainer.insertAdjacentHTML('afterbegin', commentHTML);
      document.getElementById('new-comment').value = '';
  })
  .catch(error => {
      console.error('Comment post error:', error);
      showNotification('Error', 'Failed to post comment');
  });
}
// Initialize on page load
document.addEventListener('DOMContentLoaded', () => {
    // Add this with your other initialization
    loadDiscussions();
});
// Help & Support functionality
document.addEventListener('DOMContentLoaded', () => {
  const helpButton = document.getElementById('helpButton');
  const helpModal = document.getElementById('helpModal');
  const closeHelp = document.querySelector('.close-help');
  const faqModal = document.getElementById('faqModal');
  const supportModal = document.getElementById('supportModal');
  
  
  // Navigation buttons
  const faqBtn = document.getElementById('faqBtn');
  const supportBtn = document.getElementById('supportBtn');
  const backToHelp = document.getElementById('backToHelp');
  const backToHelpFromSupport = document.getElementById('backToHelpFromSupport');
  const closeButtons = document.querySelectorAll('.close-help');

  // Function to close all modals
  function closeAllModals() {
    document.querySelectorAll('.help-modal').forEach(modal => {
      modal.classList.remove('active');
      modal.style.display = 'none';
    });
    document.body.style.overflow = '';
  }
  // Open main help modal
  helpButton.addEventListener('click', () => {
    helpModal.classList.add('active');
    document.body.style.overflow = 'hidden';
    helpModal.style.display = 'block';
  });
  
  // Navigation to FAQ modal
  faqBtn.addEventListener('click', () => {
    helpModal.classList.remove('active');
    faqModal.classList.add('active');
    faqModal.style.display = 'block';
  });
  
  // Navigation to Support modal
  supportBtn.addEventListener('click', () => {
    helpModal.classList.remove('active');
    supportModal.classList.add('active');
    supportModal.style.display = 'block';
  });
  
  // Back buttons
  backToHelp.addEventListener('click', () => {
    faqModal.classList.remove('active');
    helpModal.classList.add('active');
  });
  
  backToHelpFromSupport.addEventListener('click', () => {
    supportModal.classList.remove('active');
    helpModal.classList.add('active');
  });
  
  // Close when clicking outside
  document.querySelectorAll('.help-modal').forEach(modal => {
    modal.addEventListener('click', (e) => {
      if (e.target === modal) {
        closeAllModals();
      }
    });
  });
 // Close buttons
  document.querySelectorAll('.close-help').forEach(button => {
    button.addEventListener('click', closeAllModals);
  });
    
  // Support form submission
  const supportForm = document.getElementById('supportForm');
  if (supportForm) {
    // Update form submission handler
      // Replace the existing form submission code with this:
      document.getElementById('supportForm')?.addEventListener('submit', async (e) => {
        e.preventDefault();
        
        const formData = {
          name: document.getElementById('supportName')?.value,
          email: document.getElementById('supportEmail')?.value,
          phone: document.getElementById('supportPhone')?.value,
          message: document.getElementById('supportMessage')?.value
        };
        // Add this validation before form submission
        if (formData.phone && !/^[\d\s\+\-\(\)]{10,20}$/.test(formData.phone)) {
          showNotification('Error', 'Please enter a valid phone number');
          return;
        }
        try {
          const response = await fetch('/api/support', {
            method: 'POST',
            headers: {
              'Content-Type': 'application/json'
            },
            body: JSON.stringify(formData)
          });
          
          if (response.ok) {
            showNotification('Success', 'Your message has been sent!');
            alert('We received your message and will get back to you shortly.');
            document.getElementById('supportForm')?.reset();
            supportModal.classList.remove('active');
            document.body.style.overflow = '';
          } else {
            throw new Error('Failed to send message');
          }
        } catch (error) {
          showNotification('Error', error.message);
        }
      });
  }
  
  // Close modal when clicking outside content
  helpModal.addEventListener('click', (e) => {
    if (e.target === helpModal) {
      helpModal.classList.remove('active');
      document.body.style.overflow = '';
    }
  });
});
function makeDraggable(modal) {
  const content = modal.querySelector('.help-content');
  let pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  let isDragging = false;
  
  const dragMouseDown = (e) => {
    // Only start drag if clicking on header (h3) or empty space in content
    if (e.target.tagName === 'H3' || e.target === content) {
      e.preventDefault();
      isDragging = true;
      pos3 = e.clientX;
      pos4 = e.clientY;
      document.addEventListener('mousemove', elementDrag);
      document.addEventListener('mouseup', closeDragElement);
    }
  };
  
  const elementDrag = (e) => {
    if (!isDragging) return;
    e.preventDefault();
    
    // Calculate new position
    pos1 = pos3 - e.clientX;
    pos2 = pos4 - e.clientY;
    pos3 = e.clientX;
    pos4 = e.clientY;
    
    // Set new position
    const newTop = content.offsetTop - pos2;
    const newLeft = content.offsetLeft - pos1;
    
    // Keep modal within viewport
    const maxTop = window.innerHeight - content.offsetHeight;
    const maxLeft = window.innerWidth - content.offsetWidth;
    
    content.style.top = `${Math.max(0, Math.min(newTop, maxTop))}px`;
    content.style.left = `${Math.max(0, Math.min(newLeft, maxLeft))}px`;
  };
  
  const closeDragElement = () => {
    isDragging = false;
    document.removeEventListener('mousemove', elementDrag);
    document.removeEventListener('mouseup', closeDragElement);
  };
  
  // Initialize position to center
  content.style.position = 'absolute';
  content.style.top = '50%';
  content.style.left = '50%';
  content.style.transform = 'translate(-50%, -50%)';
  
  content.addEventListener('mousedown', dragMouseDown);
}

// Initialize draggable modals when they're shown
document.querySelectorAll('.help-modal').forEach(modal => {
  modal.addEventListener('click', (e) => {
    if (e.target === modal) {
      modal.style.display = 'none';
    }
  });
  
  // Make draggable when shown
  const observer = new MutationObserver((mutations) => {
    mutations.forEach((mutation) => {
      if (mutation.attributeName === 'style') {
        const display = window.getComputedStyle(modal).getPropertyValue('display');
        if (display === 'flex') {
          makeDraggable(modal);
        }
      }
    });
  });
  
  observer.observe(modal, { attributes: true });
});