import 'slick-carousel';

import SyliusRating from './sylius-rating';
import SyliusAddressBook from './sylius-address-book';
import SyliusProvinceField from './sylius-province-field';
import SyliusLoadableForms from './sylius-loadable-forms';
import SyliusToggle from './sylius-toggle';
import SyliusApiToggle from './sylius-api-toggle';
import SyliusApiLogin from './sylius-api-login';
import SyliusVariantImages from './sylius-variant-images';
import SyliusVariantsPrices from './sylius-variants-prices';
import SyliusAddToCart from './sylius-add-to-cart';
import SyliusCartSummary from './sylius-cart-summary';

document.addEventListener('DOMContentLoaded', () => {
  const {
    syliusProvinceEnabled = true,
    syliusProvinceBeforeAjaxCallback,
    syliusProvinceAfterAjaxCallback,
  } = window.DEDI_THEME;

  const labelEl = document.querySelector('*[data-lightbox-label]');
  // eslint-disable-next-line no-undef
  lightbox.option({ albumLabel: labelEl ? labelEl.dataset.lightboxLabel : undefined });

  $('[data-carousel]').slick({
    infinite: true,
    slidesToShow: 2,
    slidesToScroll: 1,
    prevArrow: $('.carousel-left'),
    nextArrow: $('.carousel-right'),
    appendArrows: false,
  });

  // Star rating
  document.querySelectorAll('[data-rating]').forEach((elem) => {
    // eslint-disable-next-line no-new
    new SyliusRating(elem, {
      onRate(value) {
        document.querySelector(`#sylius_product_review_rating_${value - 1}`).checked = true;
      },
    });
  });

  // Province field
  if (syliusProvinceEnabled) {
    SyliusProvinceField(syliusProvinceBeforeAjaxCallback, syliusProvinceAfterAjaxCallback);
  }

  // Address book
  const syliusBillingAddress = document.querySelector('#sylius-shipping-address');
  if (syliusBillingAddress && syliusBillingAddress.querySelector('.dropdown')) {
    SyliusAddressBook(syliusBillingAddress);
  }

  const syliusShippingAddress = document.querySelector('#sylius-billing-address');
  if (syliusShippingAddress && syliusShippingAddress.querySelector('.dropdown')) {
    SyliusAddressBook(syliusShippingAddress);
  }

  // Toggle and login from checkout
  if (document.querySelector('#sylius-api-login')) {
    SyliusApiToggle(document.querySelector('input[type=email]'));
    SyliusApiLogin(document.querySelector('#sylius-api-login'));
  }

  // Toggle billing address on the checkout page
  document.querySelectorAll('[data-toggles]').forEach((elem) => new SyliusToggle(elem));

  // Loadable forms
  SyliusLoadableForms();

  // Variantes prices and images
  SyliusVariantsPrices();
  SyliusVariantImages();

  const addToCart = document.querySelector('#sylius-product-adding-to-cart');
  if (addToCart) {
    // Add to cart
    SyliusAddToCart(addToCart);
  }

  SyliusCartSummary();
});
