(function ($, Drupal, drupalSettings) {
  Drupal.behaviors.simple_interactive_maps = {
    attach: function (context, settings) {

      const maps = once('map-load', '.interactive_map__wrapper');

      maps.forEach(async function (map_wrapper) {
        const mapId = map_wrapper.getAttribute('data-map-id');
        const map = map_wrapper.querySelector('.map-placeholder');
        const mapSettings = settings.simple_interactive_maps[mapId];

        for (let region in mapSettings) {
          applyInteractions(map, region, mapSettings[region]);
        }

      });
    },
  };

  function applyInteractions(map, region, config) {
    const regionElement = map.querySelectorAll(`g[data-region-id="${region}"]`);

    if (!regionElement) {
      return;
    }

    regionElement.forEach(function (element) {
      applyRegionStyles(element, config);
      applyTooltip(config, element);

      if (config.action.name !== 'none') {
        Drupal.simple_interactive_maps[config.action.name](element, config.action.configuration, config);
      }
    });
  }
  function applyRegionStyles(element, config) {

    const pathElems = element.querySelectorAll('path');

    pathElems.forEach(function (pathElem) {
      pathElem.style.transition = 'fill 0.5s ease';

      element.addEventListener('mouseover', function (event) {
        pathElem.style.fill = config.style.hover_color;
      });


      element.addEventListener('mouseout', function (event) {
        pathElem.style.fill = config.style.fill_color;
      });
    });

    const textElems = element.querySelectorAll('text');

    textElems.forEach(function (textElem) {
      textElem.style.pointerEvents = 'none';

      element.addEventListener('mouseover', function (event) {
        textElem.style.fontWeight = 'bold';
      });

      element.addEventListener('mouseout', function (event) {
        textElem.style.fontWeight = 'normal';
      });
    });
  }

  function applyTooltip(config, element) {
    if (config.tooltip != '') {
      new Opentip(element, config.tooltip);
    }
  }

})(jQuery, Drupal, drupalSettings);

var mapData;

Opentip.styles.simple_interactive_maps = {
  extends: 'standard',
  stem: true,
  fixed: true,
  tipJoint: 'bottom',
  showOn: 'mouseover',
  hideOn: 'mouseout',
  removeElementsOnHide: true,
  containInViewport: true,
};
Opentip.defaultStyle = 'simple_interactive_maps';

Drupal.simple_interactive_maps = Drupal.simple_interactive_maps || {};
