/**
 * Copyright © Resurs Bank AB. All rights reserved.
 * See LICENSE for license details.
 */

// Configure static instance to be used on product pages.
let RB_PP_WIDGET_INSTANCE = null;

document.addEventListener('DOMContentLoaded', function () {
  if (typeof Resursbank_PartPayment !== 'function') {
    return;
  }

  const overrides = {
    getObservableElements: function () {
      let result = [this.getQtyElement()];

      let qtyBtns = document.querySelectorAll('.product-add-to-cart button.btn');

      // If there are no quantity buttons, append them to the observable elements.
      if (qtyBtns.length > 0) {
        qtyBtns.forEach(function (btn) {
          result.push(btn);
        });
      }

      return result;
    },

    getQtyElement: function () {
      return document.querySelector('#quantity_wanted');
    },

    getAmountElement: function () {
      // When the current price is missing, we'll look for further elements.
      // Occurs between different language and locations.
      return (
        document.querySelector('.current-price .current-price-value') ||
        document.querySelector('.cart-total .value') ||
        document.querySelector('[itemprop="price"]') ||
        null
      );
    }
  }

  RB_PP_WIDGET_INSTANCE = Resursbank_PartPayment.createInstance(
    document.getElementById('rb-pp-widget-container'),
    overrides
  );

  // Pick up all .rb-pp-widget-container elements, and move them to up to the
  // parent element.
  const containers = document.querySelectorAll('.rb-pp-widget-container');
  containers.forEach(function (container) {
    // Insert container after parent.
    container.parentElement.insertAdjacentElement('afterend', container);

    // Display the container again.
    container.style.display = 'block';
  });

  // Reload widget instance when the DOM of .product-add-to-cart changes.
  const productAddToCart = document.querySelector('.product-add-to-cart');
  if (productAddToCart) {
    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        if (mutation.type === 'childList') {
          RB_PP_WIDGET_INSTANCE.reloadElementObservers();
        }
      });
    });

    observer.observe(productAddToCart, {
      childList: true,
      subtree: true
    });
  }
});

// Configure flexible widget instance to be used in quick view element.
// Wait for the quick view element to be injected into the DOM.
document.body.addEventListener('DOMNodeInserted', function (event) {
  if (event.target.classList && event.target.classList.contains('quickview')) {
    // Find the flexible widget container inside the footer.
    const rbPPWidgetContainer = document.querySelector('#rb-pp-flexible-widget-container');

    if (!rbPPWidgetContainer) {
      return;
    }

    // Clone container.
    const clonedContainer = rbPPWidgetContainer.cloneNode(true);

    // Find the .product-add-to-cart element inside the quick view.
    const quickviewProductAddToCart = event.target.querySelector('.product-add-to-cart');

    if (!quickviewProductAddToCart) {
      return;
    }

    // Insert the cloned container after the .product-add-to-cart element.
    quickviewProductAddToCart.insertAdjacentElement('afterend', clonedContainer);

    // Create an instance of Resursbank_PartPayment for the cloned container.
    let INSTANCE = Resursbank_PartPayment.createInstance(clonedContainer, {
      getObservableElements: function () {
        let result = [this.getQtyElement()];

        let qtyBtns = quickviewProductAddToCart.querySelectorAll('.product-add-to-cart button.btn');

        // If there are no quantity buttons, append them to the observable elements.
        if (qtyBtns.length > 0) {
          qtyBtns.forEach(function (btn) {
            result.push(btn);
          });
        }

        return result;
      },
      getQtyElement: function () {
        return quickviewProductAddToCart.querySelector('#quantity_wanted');
      },
      getAmountElement: function () {
        return event.target.querySelector('.current-price .current-price-value');
      },
    });

    // Reload price info, because otherwise the default remains.
    INSTANCE.updateStartingCost().then(() => {
      // Display the container again.
      clonedContainer.style.display = 'block';
    });

    // Reload widget instance when the DOM of .product-add-to-cart changes,
    // since changing qty value reloads parts of the DOM in the quick view.
    const observer = new MutationObserver(function (mutations) {
      mutations.forEach(function (mutation) {
        if (mutation.type === 'childList') {
          INSTANCE.reloadElementObservers();
        }
      });
    });

    observer.observe(quickviewProductAddToCart, {
      childList: true,
      subtree: true
    });
  }
});
