
export default () => {
  const google = window.google;
  const $ = jQuery;

  function render_map($el) {
    // var
    const $markers = $el.find('.marker');
    const styles = []; // insert code from https://snazzymaps.com/
    // vars
    const center = new google.maps.LatLng(0, 0);
    const type = google.maps.MapTypeId.ROADMAP;
    const args = {
      zoom: 14,
      scrollwheel: false,
      center: center,
      mapTypeId: type,
      styles: styles,
    }
    const map = new google.maps.Map($el[0], args);
    map.markers = [];
    $markers.each(function () {
      add_marker($(this), map);
    })
    center_map($('.marker'), map);
    // center map on resize
    $(window).resize(function () {
      center_map($('.marker'), map);
    })
    onMarkerHover(map);
  }

  function add_marker($marker, map) {
    const latlng = new google.maps.LatLng($marker.attr('data-lat'), $marker.attr('data-lng'));

    const $icon = {
      url: $marker.attr('data-icon'),
      //state your size parameters in terms of pixels
      size: new google.maps.Size(50, 50),
      scaledSize: new google.maps.Size(50, 50),
      origin: new google.maps.Point(0, 0),
    }

    const marker = new google.maps.Marker({
      position: latlng,
      map: map,
      icon: $icon,
    })

    map.markers.push(marker);
    if ($marker.html()) {
      // create info window
      const infowindow = new google.maps.InfoWindow({
        content: $marker.html(),
      })
      // infowindow.open( map, marker );
      // show info window when marker is clicked
      google.maps.event.addListener(marker, 'click', function () {
        infowindow.open(map, marker);
      })
    }

  }

  function onMarkerHover(map) {
    $('[data-index]').on('mouseenter', function () {
      const index = Number($(this).data('index')) - 1;
      map.markers.map(function (marker, i) {
        if (index === i) {
          marker.setOptions({
            animation: google.maps.Animation.BOUNCE,
          })
        }
      })
    })
    $('[data-index]').on('mouseleave', function () {
      const index = Number($(this).data('index')) - 1;
      map.markers.map(function (marker, i) {
        if (index === i) {
          marker.setOptions({
            animation: null,
          })
        }
      })
    })
  }

  function center_map($marker, map) {
    // vars
    const bounds = new google.maps.LatLngBounds()
    // loop through all markers and create bounds
    $.each(map.markers, function (i, marker) {
      const latlng = new google.maps.LatLng(marker.position.lat(), marker.position.lng());
      bounds.extend(latlng)
    });
    if (map.markers.length == 1) {
      // set center of map
      map.setCenter(bounds.getCenter());
      map.setZoom(14);
    } else {
      map.fitBounds(bounds)
    }
  }
}