/*
 * This file is part of the Sylius package.
 *
 * (c) Paweł Jędrzejewski
 *
 * For the full copyright and license information, please view the LICENSE
 * file that was distributed with this source code.
 */

/* eslint-env browser */

const getActiveVariant = () => {
  const items = document.querySelectorAll(`
    input[name="sylius_add_to_cart[cartItem][variant]"]:checked,
    select[name*="sylius_add_to_cart[cartItem][variant]"] option:checked
  `);

  return [...items].map((el) => el.value).join(' ');
};

const getActiveImageSrc = (variant, defaultImageLink, defaultImageSrc) => {
  let imageLink = defaultImageLink;
  let imageSrc = defaultImageSrc;
  const item = document.querySelector(`
      .sylius-image-variants [data-variant-code="${variant}"],
      .sylius-image-variants [data-variant-options="${variant} "]
  `);

  if (item) {
    const parent = item.closest('[data-js-product-thumbnail]');
    const imageEl = parent.querySelector('img');
    imageLink = parent.querySelector('a').getAttribute('href');
    imageSrc = imageEl.dataset.lazy || imageEl.getAttribute('src');
  }

  return { imageLink, imageSrc };
};

const setImage = (mainImageLink, mainImage, defaultImageLink, defaultImageSrc) => {
  const img = getActiveImageSrc(getActiveVariant(), defaultImageLink, defaultImageSrc);

  mainImageLink.setAttribute('href', img.imageLink);
  mainImage.setAttribute('src', img.imageSrc);
};

const SyliusVariantImages = () => {
  const mainImageLink = document.querySelector('[data-js-product-image]');
  if (!mainImageLink) {
    return;
  }

  const mainImage = mainImageLink.querySelector('img');
  const defaultImageLink = mainImageLink.getAttribute('href');
  const defaultImageSrc = mainImage.dataset.lazy || mainImage.getAttribute('src');

  document.querySelectorAll('[name*="sylius_add_to_cart[cartItem][variant]"]').forEach((item) => {
    item.addEventListener('change', () => setImage(mainImageLink, mainImage, defaultImageLink, defaultImageSrc));
  });

  setImage(mainImageLink, mainImage, defaultImageLink, defaultImageSrc);
};

export default SyliusVariantImages;
