class Resursbank_GetAddress_Implementation {
  'use strict';

  /**
   * JS to move widget to the top of the first <form> element parent of itself.
   */
  position_widget() {
    /** @var {HTMLElement} widget */
    var widget = document.getElementById("rb-ga-widget");

    /** @var {HTMLElement} shippingAddressForm */
    var shippingAddressForm = document.querySelector("#checkout-addresses-step .content");

    // Move the widget to the top of the shipping address step.
    if (widget && shippingAddressForm) {
      shippingAddressForm.insertBefore(widget, shippingAddressForm.firstChild);
    }
  }

  /**
   * Initialize the Resursbank_GetAddress widget.
   */
  init() {
    // Check if Resursbank_GetAddress is available.
    if (typeof Resursbank_GetAddress !== "function") {
      return;
    }

    let widget = new Resursbank_GetAddress({
      updateAddress: (data) => {

        Resursbank_GetAddress_Implementation.clear_address();
        const customerType = widget.getCustomerType();

        const map = {
          firstname: 'firstName',
          lastname: 'lastName',
          address1: 'addressRow1',
          address2: 'addressRow2',
          postcode: 'postalCode',
          city: 'postalArea',
          id_country: 'countryCode'
        };

        // Map fullName to a company for LEGAL customers, never for NATURAL.
        if (customerType === 'LEGAL') {
          map.company = 'fullName';
        }

        for (const [key, value] of Object.entries(map)) {
          if (!data.hasOwnProperty(value)) {
            throw new Error(
              `Missing required field "${value}" in data object.`
            );
          }

          const element = document.querySelector(`#checkout-addresses-step [name=${key}]`);

          if (element) {
            element.value = data[value];
          }

          // Trigger chang event on "field-id_country", to reload form elements.
          if (key === "id_country") {
            const event = new Event("change", {
              bubbles: true,
              cancelable: true,
            });

            element.dispatchEvent(event);
          }
        }
      },
    });

    widget.setupEventListeners();
  }

  /**
   * Clear the address fields.
   */
  static clear_address() {
    const fields = [
      'firstname',
      'lastname',
      'address1',
      'address2',
      'postcode',
      'city',
      'id_country',
      'company'
    ];

    // Clear values.
    fields.forEach((field) => {
      const element = document.querySelector(`#checkout-addresses-step [name=${field}]`);

      if (element) {
        element.value = "";
      }
    });
  }
}

// Hide additional information sections by default. Because otherwise, our USP
// data will flash in and out of view since the additional info blocks are
// displayed by default then hidden by some PrestaShop JS after the page has
// finished loading.
document.querySelectorAll('.js-additional-information').forEach((el) => {
  el.style.display = 'none';
});

document.addEventListener("DOMContentLoaded", function () {
  /** @var {HTMLElement} widget */
  var widget = document.getElementById("rb-ga-widget");

  if (!widget) {
    return;
  }

  // Our address widget is hidden by default to ensure it does not show up when
  // the existing address selector is displayed.
  if (!document.querySelector(".add-address")) {
    const containerEl = document.getElementById("rb-ga-widget-container");

    if (containerEl) {
      containerEl.style.display = "block";
      let get_address = new Resursbank_GetAddress_Implementation();
      get_address.position_widget();
      get_address.init();
    }
  }
});

