export function getCurrentProductOptionsPricing() {
  let selector = '';

  document.querySelectorAll('#sylius-product-adding-to-cart select[data-option]').forEach((element) => {
    const select = element;
    const option = select[select.selectedIndex].value;
    selector += `[data-${select.getAttribute('data-option')}="${option}"]`;
  });

  document.querySelectorAll('#sylius-product-adding-to-cart [data-option] input[type="radio"]:checked').forEach((element) => {
    const { option } = element.closest('[data-option]').dataset;
    selector += `[data-${option}="${element.value}"]`;
  });

  if (selector === '') {
    return selector;
  }

  return document.querySelector('#sylius-variants-pricing').querySelector(selector);
}

export function getCurrentProductOptionsTracked() {
  let selector = '';

  const syliusVariantsTracked = document.querySelector('#sylius-variants-tracked');
  if (syliusVariantsTracked === null) {
    return selector;
  }

  document.querySelectorAll('#sylius-product-adding-to-cart select[data-option]').forEach((element) => {
    const select = element;
    const option = select[select.selectedIndex].value;
    selector += `[data-${select.getAttribute('data-option')}="${option}"]`;
  });

  document.querySelectorAll('#sylius-product-adding-to-cart[data-option] input[type="radio"]:checked').forEach((element) => {
    const { option } = element.closest('[data-option]').dataset;
    selector += `[data-${option}="${element.value}"]`;
  });

  if (selector === '') {
    return selector;
  }

  return syliusVariantsTracked.querySelector(selector);
}

export function displayProductOptionsStock() {
  const price = getCurrentProductOptionsPricing();
  const isTracked = getCurrentProductOptionsTracked();

  if (price === '' || isTracked === '') {
    return;
  }

  const addToCartForm = document.querySelector('form#sylius-product-adding-to-cart');
  const outOfStockBlock = document.querySelector('#product-option-out-of-stock');
  const isInStockBlock = document.querySelector('#product-option-stock-tracked');
  const priceContainer = document.querySelector('.product-show-price');

  if (price) {
    priceContainer.innerHTML = price.innerHTML;
    addToCartForm.querySelector('button.btn-add-cart').style.display = 'inline-flex';
    outOfStockBlock.classList.add('d-none');

    if (isTracked.getAttribute('data-is-tracked')) {
      isInStockBlock.classList.remove('d-none');
    } else {
      isInStockBlock.classList.add('d-none');
    }
  } else {
    priceContainer.innerHTML = document.querySelector('#sylius-variants-pricing').getAttribute('data-unavailable-text');
    addToCartForm.querySelector('button.btn-add-cart').style.display = 'none';
    outOfStockBlock.classList.remove('d-none');
    isInStockBlock.classList.add('d-none');
  }
}
