// Create the hover display element
const hoverBox = document.createElement('div');
hoverBox.style.id = "hoverBox"
hoverBox.style.position = 'fixed';
hoverBox.style.padding = '8px 12px';
hoverBox.style.backgroundColor = 'var(--green)';
hoverBox.style.border = '1px solid var(--tan)';
hoverBox.style.color = 'var(--tan)';
hoverBox.style.opacity = '80%';
hoverBox.style.pointerEvents = 'none';
hoverBox.style.zIndex = '9999';
hoverBox.style.fontFamily = 'sans-serif';
hoverBox.style.fontSize = '14px';
hoverBox.style.display = 'none';
document.body.appendChild(hoverBox);
let currentTarget = null;

function capitalizeWords(str) {
  return str
    .split('-')
    .map(word => word.charAt(0).toUpperCase() + word.slice(1))
    .join(' ');
}

function onMouseOver(e) {
  const target = e.target;
  let paintingName; let artistName;
  if(target.id === "back") {
    paintingName = "The Garden Terrace"
    artistName = "Caspar David Friedrich"
  } else if (target.tagName.toLowerCase() === 'img' && target.classList.contains('interactive')) {
    const match = target.src.match(/([^\/]+)\.([a-z]{3,4})(\?.*)?$/i); // extract filename
    if (!match) return;

    const filename = match[1];
    const parts = filename.split('_');
    if (parts.length !== 2) return;

    paintingName = capitalizeWords(parts[0]);
    artistName = capitalizeWords(parts[1]);
  } else {
    return
  }

  hoverBox.innerHTML = `<strong>${paintingName}</strong><br><span style="font-size: 12px;">${artistName}</span>`;
  hoverBox.style.display = 'block';
  currentTarget = target;
  hoverBox.style.left = `${e.clientX + 15}px`;
  hoverBox.style.top = `${e.clientY + 15}px`;
}

function onMouseOut(e) {
  if (e.target === currentTarget) {
    hoverBox.style.display = 'none';
    currentTarget = null;
  }
}

function onMouseMove(e) {
  if (hoverBox.style.display === 'block') {
    hoverBox.style.left = `${e.clientX + 15}px`;
    hoverBox.style.top = `${e.clientY + 15}px`;
  }
}

document.addEventListener('mouseover', onMouseOver);
document.addEventListener('mouseout', onMouseOut);
document.addEventListener('mousemove', onMouseMove);