$(document).ready(function () {
    if ($('#hotspotImg').length > 0) {
      $('#hotspotImg').hotSpot({
        bindselector: 'both'
      });
    }
  });
  
  // Function to get modal content based on hotspot
  
  // function getModalContent(hotspot) {
  //   // Check if hotspot is a valid jQuery object and has child elements
  //   var contentType = hotspot.data('content-type');
  
  //   if (contentType === 'image') {
  //     return getImageCarouselContent(hotspot.find('img').attr('src'));
  //   } else if (contentType === 'video') {
  //     return getVideoModalContent(hotspot.find('video').attr('src'));
  //       // Handle other content types or provide a default behavior
  //       return '<p>No content available</p>';
  //     }
  //     else if (contentType === 'document'){
  //         var doclist=fetchAndDisplayDocumentContent();
  //         console.log(doclist);
  //      return doclist;
  //     }
  //    else {
  //     // Handle cases where hotspot is not a valid jQuery object or has no child elements
  //     return '<p>No content available</p>';
  //   }
  // }
  
  
  // Function to get video modal content based on hotspot
  function getVideoCarouselContent(videoUrls) {
    var carouselContent = '<div id="videoCarousel" class="carousel slide" data-ride="carousel">';
    carouselContent += '<div class="carousel-inner">';
  
    videoUrls.forEach(function (videoUrl, index) {
      var activeClass = index === 0 ? ' active' : '';
      carouselContent += '<div class="carousel-item' + activeClass + '">';
      carouselContent += '<video class="d-block w-100" controls><source src="' + videoUrl + '" type="video/mp4"></video>';
      carouselContent += '</div>';
    });
  
    carouselContent += '</div>';
    carouselContent += '<a class="carousel-control-prev" href="#videoCarousel" role="button" data-slide="prev">';
    carouselContent += '<span class="carousel-control-prev-icon" aria-hidden="true"></span>';
    carouselContent += '<span class="sr-only">Previous</span>';
    carouselContent += '</a>';
    carouselContent += '<a class="carousel-control-next" href="#videoCarousel" role="button" data-slide="next">';
    carouselContent += '<span class="carousel-control-next-icon" aria-hidden="true"></span>';
    carouselContent += '<span class="sr-only">Next</span>';
    carouselContent += '</a>';
    carouselContent += '</div>';
  
    return carouselContent;
  }
  
  
  function getDocumentListContent(pdfUrls) {
    var documentListContent = '<ul>';

    // Iterate over each PDF URL and extract the file name
    pdfUrls.forEach(function(pdfUrl) {
        var fileName = pdfUrl.substring(pdfUrl.lastIndexOf('/') + 1);
        documentListContent += '<li><a href="' + pdfUrl + '" download>' + fileName + '</a></li>';
    });

    documentListContent += '</ul>';

    return documentListContent;
}
  
  // Function to get images for the carousel
  // function getImagesForCarousel(imageCount, folderPath) {
  //   var images = [];
  
  //   for (var i = 1; i <= imageCount; i++) {
  //     images.push(folderPath + '/image' + i + '.jpg');
  //   }
  
  //   return images;
  // }
  
  // Function to get carousel content for images
  function getImageCarouselContent(imageUrls) {
    var carouselContent = '<div id="hotspotCarousel" class="carousel slide" data-ride="carousel">';
    carouselContent += '<div class="carousel-inner">';
  
    imageUrls.forEach(function (imageUrl, index) {
      var activeClass = index === 0 ? ' active' : '';
      carouselContent += '<div class="carousel-item' + activeClass + '">';
      carouselContent += '<img src="' + imageUrl + '" class="d-block w-100" alt="Image ' + (index + 1) + '">';
      carouselContent += '</div>';
    });
  
    carouselContent += '</div>';
    carouselContent += '<a class="carousel-control-prev" href="#hotspotCarousel" role="button" data-slide="prev">';
    carouselContent += '<span class="carousel-control-prev-icon" aria-hidden="true"></span>';
    carouselContent += '<span class="sr-only">Previous</span>';
    carouselContent += '</a>';
    carouselContent += '<a class="carousel-control-next" href="#hotspotCarousel" role="button" data-slide="next">';
    carouselContent += '<span class="carousel-control-next-icon" aria-hidden="true"></span>';
    carouselContent += '<span class="sr-only">Next</span>';
    carouselContent += '</a>';
    carouselContent += '</div>';
  
    return carouselContent;
  }
  
  // Function to handle clicks on image hotspots
  function fetchMediaUrls(companyId, mediaType, callback) {
    // Make an AJAX request to your server to fetch media URLs based on the company ID and media type
    // Example:
    $.ajax({
        url: '/media',
        method: 'GET',
        data: {
            companyId: companyId,
            mediaType: mediaType
        },
        success: function(response) {
            // Extract media URLs from the response
            const mediaUrls = response.mediaUrls;
            console.log('mediaurls:'+mediaUrls);
            // Pass the media URLs to the callback function
            callback(mediaUrls);
        },
        error: function(xhr, status, error) {
            console.error('Error fetching media URLs:', error);
        }
    });
}

function handleImageHotspotClick(companyId) {
  fetchMediaUrls(companyId, 'image', function(mediaUrls) {
      var modalContent = getImageCarouselContent(mediaUrls);
      console.log('modalcontent of images:'+modalContent);
      openModal(modalContent);
  });
}

function handleVideoHotspotClick(companyId) {
  fetchMediaUrls(companyId, 'video', function(videoUrls) {
      var modalContent = getVideoCarouselContent(videoUrls);
      openModal(modalContent);
  });
} 
// Function to handle clicks on video hotspots
function handleDocumentHotspotClick(companyId) {
  fetchMediaUrls(companyId, 'pdf', function(pdfUrls) {
      var modalContent = getDocumentListContent(pdfUrls);
      openModal(modalContent);
  });
}
function handleBusinessCardClick(companyId) {
  fetchCompanyDetails(companyId, function(company) {
      const businessCardHTML = `
          <div class="business-card">
              <div class="card-header">
                  <img src="${company.logo_url}" class="company-logo" alt="Company Logo">
                  <h3>${company.company_name}</h3>
                  <p class="tagline">${company.tagline || 'Innovating the Future'}</p>
              </div>
              <div class="card-body">
                  <div class="contact-info">
                      <p><i class="fas fa-user-tie"></i> ${company.primary_contact_name}</p>
                      <p><i class="fas fa-envelope"></i> ${company.email}</p>
                      <p><i class="fas fa-phone"></i> ${company.phone}</p>
                      <p><i class="fas fa-map-marker-alt"></i> ${company.address}</p>
                  </div>
                  <div class="social-links">
                      ${company.social_media ? company.social_media.split(',').map(link => `
                          <a href="${link.trim()}" target="_blank" class="social-icon">
                              <i class="${getSocialIcon(link)}"></i>
                          </a>
                      `).join('') : ''}
                  </div>
              </div>
          </div>
      `;
      
      // Use existing modal structure
      $('.modal-title').text('Business Card');
      $('.modal-body').html(businessCardHTML);
      $('#myModal').modal('show');
  });
}

function fetchCompanyDetails(companyId, callback) {
  const query = 'SELECT company_name, primary_contact_name, email, phone, address, social_media, logo_url FROM companies WHERE company_id = ?';
  connection.query(query, [companyId], (error, results) => {
      if (error || results.length === 0) {
          console.error('Error fetching company details:', error);
          return;
      }
      callback(results[0]);
  });
}

function getSocialIcon(link) {
  if (link.includes('linkedin')) return 'fab fa-linkedin';
  if (link.includes('twitter')) return 'fab fa-twitter';
  if (link.includes('facebook')) return 'fab fa-facebook';
  if (link.includes('instagram')) return 'fab fa-instagram';
  return 'fas fa-globe';
}
  // Function to open modal
  function openModal(modalContent) {
    //var modalContent = getModalContent(hotspot);
    const modal = $('#myModal');
    modal.find('.modal-content').addClass('modal-enter');
    // Ensure that modalContent is a DOM element
    var modalBody = $('#myModal .modal-body');
    modalBody.empty(); // Clear existing content
  
    // Append the modal content (converted to a jQuery object) to the modal body
    $(modalContent).appendTo(modalBody);
  
    // Show the modal
    $('#myModal').modal('show');
  
    // Initialize the carousel if needed (adjust as per your structure)
    if ($(modalContent).find('.carousel').length > 0) {
      $(modalContent).find('.carousel').carousel();
    }
    modal.on('hidden.bs.modal', () => {
      modal.find('.modal-content').removeClass('modal-enter');
  });
  }
  
  // Function to populate the document list dynamically
      // Modified populateDocumentList function
  function populateDocumentList(folder, files) {
    var documentListContent = '';
  
    // Loop through the list of files and add them to the document list
    files.forEach(function (file) {
      // Create a link for each document that triggers the download on click
      documentListContent += '<li><a href="'+folder+'/'+ file + '" download>' + file + '</a></li>';
    });
  
    return documentListContent;
  }
  
  // Modified fetchAndDisplayDocumentContent function
  function fetchAndDisplayDocumentContent() {
    // Simulate fetching data from the server (replace this with actual server-side logic)
    var documentFolder = 'docs';
    var documentFiles = [];
    for (var i = 1; i <= 3; i++) {
      documentFiles.push('document' + i + '.pdf');
    }
  
    // Populate the document modal with dynamic content
    var documentListContent = populateDocumentList(documentFolder, documentFiles);
  
    // Now documentListContent contains the HTML string for the document list
    // You can use this string as needed, for example, to update the modal content
    // or append it to a container
    console.log(documentListContent);
    return documentListContent
  }
  // Initialize WebSocket
const ws = new WebSocket('ws://localhost:3000');

// Chat UI functions
function initChat() {
  // Load history
  fetch('/chat/history')
    .then(res => res.json())
    .then(messages => {
      messages.reverse().forEach(msg => {
        appendMessage(msg.user_name, msg.content);
      });
    });

  // Send message
  document.getElementById('send-btn').addEventListener('click', () => {
    const message = document.getElementById('message-input').value;
    if(message) {
      ws.send(JSON.stringify({
        userId: currentUser.id,
        userName: currentUser.name,
        content: message
      }));
    }
  });

  // Receive messages
  ws.onmessage = (event) => {
    const msg = JSON.parse(event.data);
    // Handle exhibition_ended
  if (msg.type === 'exhibition_ended') {
    localStorage.removeItem('authToken');
    window.location.href = '/login?message=exhibition_ended';
    return;
  }
    appendMessage(msg.user, msg.content);
  };
}

function appendMessage(user, content) {
  const chatBox = document.getElementById('chat-box');
  chatBox.innerHTML += `
    <div class="chat-message">
      <strong>${user}:</strong> ${sanitize(content)}
    </div>`;
  chatBox.scrollTop = chatBox.scrollHeight;
}

function sanitize(text) {
  return text.replace(/</g, '&lt;').replace(/>/g, '&gt;');
}
  