/**
 * Creates a link preview of a specific div from the target URL when a link is hovered.
 * @param {string} linkSelector - CSS selector for the links to preview.
 * @param {string} divSelector - CSS selector for the div to extract from the target page.
 */

function setupLinkPreview(linkSelector, divSelector) {
  const preview = document.createElement('div');
  preview.style.position = 'absolute';
  preview.style.border = '1px solid #ccc';
  preview.style.width = '400px';
  preview.style.height = '300px';
  preview.style.overflow = 'auto';
  preview.style.zIndex = '9999';
  preview.style.display = 'none';
  preview.style.backgroundColor = '#fff';
  preview.style.boxShadow = '0 0 10px rgba(0,0,0,0.2)';
  preview.style.padding = '10px';
  document.body.appendChild(preview);
  const links = document.querySelectorAll(linkSelector);
  links.forEach(link => {
    link.addEventListener('mouseover', async (e) => {
      try {
        const response = await fetch(link.href);
        const html = await response.text();
        const parser = new DOMParser();
        const doc = parser.parseFromString(html, 'text/html');
        const targetDiv = doc.querySelector(divSelector);
        if (targetDiv) {
          preview.innerHTML = targetDiv.innerHTML;
          preview.style.display = 'block';
          preview.style.left = `${e.pageX + 10}px`;
          preview.style.top = `${e.pageY + 10}px`;
        } else {
          preview.innerHTML = '<p>Target div not found.</p>';
          preview.style.display = 'block';
        }
      } catch (error) {
        preview.innerHTML = '<p>Failed to load preview.</p>';
        preview.style.display = 'block';
      }
    });

    link.addEventListener('mouseout', () => {
      preview.style.display = 'none';
      preview.innerHTML = '';
    });
  });
}

// Example usage:
// Call this function after the DOM is loaded.
// setupLinkPreview('a.external-link', '#target-div');
