// Store an array of Backlinks globally and prevent clobbering existing ones.
window.simBackLinks = window.simBackLinks || [];

Drupal.simple_interactive_maps.ajax_load_map = function (elem, config, region) {

  // locate the parent map element (with class .interactive_map__wrapper)
  const map = jQuery(elem).closest('.interactive_map__wrapper');

  // Get the immediate parent of map
  const mapParent = map.parent();

  // get the map id
  const map_id = map.attr('id');

  // Build the URL from Drupal's base path rather than hardcoding a
  // root-absolute one: on a site installed in a subdirectory (or with a
  // language path prefix) '/simple-interactive-maps/ajax' resolves against
  // the domain root and 404s, so the map never loads.
  const targetUrl = Drupal.url('simple-interactive-maps/ajax');

  function buildBackLinks() {
    let backLink = document.querySelector('.interactive_map__back-link');

    if (!backLink && window.simBackLinks.length > 0) {

      backLink = document.createElement('a');
      backLink.classList.add('interactive_map__back-link');
      backLink.classList.add('button');
      backLink.href = '#';
      backLink.innerHTML = 'Back to previous map';
      mapParent.prepend(backLink);

      backLink.addEventListener('click', function (e) {
        e.preventDefault();

        const linkConfig = window.simBackLinks.pop();

        if (window.simBackLinks.length === 0) {
          backLink.remove();
        }


        const ajaxSettings = {
          url: targetUrl,
          submit: linkConfig,
        };
        const ajax = new Drupal.ajax(ajaxSettings);
        ajax.execute().then(() => {
          buildBackLinks();
        });
      });
    }

  }

  elem.addEventListener('click', function (e) {
    e.preventDefault();

    const ajaxSettings = {
      url: targetUrl,
      submit: {
        map_to_load: config['target_map_id'],
        target_element: map_id,
      },
    };

    window.simBackLinks.push({
      map_to_load: map_id,
      target_element: config['target_map_id'],
    });

    const ajax = new Drupal.ajax(ajaxSettings);
    ajax.execute().then(() => {
      buildBackLinks();
    });

  });

  elem.setAttribute('role', 'link');
};

