<script>
import { ref } from 'vue';
import { createPopper } from '@popperjs/core';
// popper
export const popper = ref(null);
export const showPopper = (content, element) => {
  removePopperIfOpen();
  // If the element is not set, we want to use the mouse position instead
  const mousePosition = {
    x: window.event.clientX,
    y: window.event.clientY
  };
  const reference = element
    ? element
    : {
      getBoundingClientRect: () => ({
        top: mousePosition.y,
        left: mousePosition.x,
        bottom: mousePosition.y,
        right: mousePosition.x,
        width: 0,
        height: 0,
      }),
    };
  const popperElement = document.createElement('div');
  popperElement.classList.add('popper');
  popperElement.innerHTML = content;
  document.body.appendChild(popperElement);
  popper.value = createPopper(reference, popperElement, {
    placement: 'bottom',
    modifiers: [
      {
        name: 'offset',
        options: {
          offset: [0, 8],
        },
      },
    ],
  });
};

export const removePopperIfOpen = () => {
  // Remove any poppers that are open
  if (popper.value) {
    popper.value.destroy();
    popper.value = null;
    const popperElement = document.querySelector('.popper');
    if (popperElement) {
      popperElement.remove();
    }
  }
};

export const popperBox = (title, content, data_key = null) => {
  // If the data key is not set, we want to use a random key
  if (!data_key) {
    data_key = Math.random().toString(36).substring(7);
  }
  return `<div class="popper-box" data-key="${data_key}">
<article class="message">
  <div class="message-body">
    <strong>${title}</strong><br>
    ${content}
  </div>
</article>
</div>`;
};

export const popperBoxProductAddonHtml = (id, name, price, description, classes = '') => {

  let html = `<div class="popper-box ${classes}" data-key="product-addon-${id}-popper">`;
  html += `<p class="title is-6">${name}&nbsp; / &nbsp;${price} Kr.</p>`;
  html += `<p class="subtitle is-6 mb-1 has-text-link">No. ${id}</p>`;
  // If the description is set (and isn't empty), show it
  if (description && description !== '' && description !== ' ') {
    html += `<p class="subtitle is-6">${description}</p>`;
  }
  // Otherwise, show a placeholder
  else {
    html += `<p class="subtitle is-6">No description available</p>`;
  }
  html += `</div>`;
  return html;
};

export const showPopperWithContent = (title, content) => {
  showPopper(popperBox(title, content));
};

</script>