<?php

use Fisharebest\Webtrees\I18N;
use Fisharebest\Webtrees\View;

/**
 * @var array<mixed> $data
 * @var object       $leaflet_config
 */
?>

<div class="row my-4 gchart wt-pedigree-map-wrapper">
    <div id="wt-map" class="col-sm-9 wt-ajax-load wt-map wt-pedigree-map-map" dir="ltr"></div>
    <ul class="col-sm-3 wt-pedigree-map-sidebar wt-page-options-value list-unstyled px-md-1"></ul>
</div>

<?php View::push('javascript') ?>
<script>
  'use strict';

  (function () {
    const config = <?= json_encode($leaflet_config, JSON_THROW_ON_ERROR) ?>;
    const sidebar = document.querySelector('.wt-pedigree-map-sidebar');

    const scrollOptions = {
      behavior: "smooth",
      block: "start",
      inline: "start"
    };

    let map = null;

    // Map components
    let markers = L.markerClusterGroup({
      showCoverageOnHover: false,
    });

    /**
     * Passed to resetControl to
     * perform necessary reset actions on map
     */
     let resetCallback = function () {
      map.flyToBounds(markers.getBounds(), {padding: [50, 30], maxZoom: 15 });
      sidebar.firstElementChild.scrollIntoView(scrollOptions);
    }

    /**
     *
     * @private
     */
    let _drawMap = function () {
      map = webtrees.buildLeafletJsMap('wt-map', config, resetCallback);
    };

    /**
     *
     * @private
     */
    let _buildMapData = function () {
      let geoJson_data = <?= json_encode($data, JSON_THROW_ON_ERROR) ?>;

      if (geoJson_data.features.length === 0) {
        map.fitWorld();
        sidebar.innerHTML = '<div class="bg-info text-white text-center">' + <?= json_encode(I18N::translate('Nothing to show'), JSON_THROW_ON_ERROR) ?> + '</div>';
      } else {
        sidebar.innerHTML = '';
        let geoJsonLayer = L.geoJson(geoJson_data, {
          pointToLayer: function (feature, latlng) {
            return new L.Marker(latlng, {
              icon: L.BeautifyIcon.icon({
                icon: 'bullseye fas',
                borderColor: 'transparent',
                backgroundColor: feature.properties.iconcolor,
                iconShape: 'marker',
                textColor: 'white',
              }),
              title: feature.properties.tooltip,
              alt: feature.properties.tooltip,
              id: feature.id,
            })
              .on('popupopen', function (e) {
                let item = document.querySelector('.gchart[data-wt-feature-id="' + e.target.feature.id + '"]');
                item.classList.add('messagebox');
                item.scrollIntoView(scrollOptions);
              })
              .on('popupclose', function () {
                sidebar.childNodes.forEach(e => e.classList.remove('messagebox'));
                sidebar.firstElementChild.scrollIntoView(scrollOptions);
              });
          },
          onEachFeature: function (feature, layer) {
            if (feature.properties.polyline) {
              let pline = L.polyline(feature.properties.polyline.points, feature.properties.polyline.options);
              markers.addLayer(pline);
            }
            layer.bindPopup(feature.properties.summary);
            sidebar.innerHTML += `<li class="gchart px-md-2" data-wt-feature-id=${feature.id}>${feature.properties.summary}</li>`;
          },
        });
        markers.addLayer(geoJsonLayer);
        map.addLayer(markers);
        map.fitBounds(markers.getBounds(), { padding: [50, 30], maxZoom: 15 });
      }
    };

    window.onload = function() {
    // Activate marker popup when sidebar entry clicked
      sidebar.querySelectorAll('.gchart').forEach((element) => {
        var eventId = parseInt(element.dataset.wtFeatureId);

        element.addEventListener('click', () => {
          // first close any existing
          map.closePopup();
          //find the marker corresponding to the clicked event
          let mkrLayer = markers.getLayers().filter(function (v) {
            return v.feature !== undefined && v.feature.id === eventId;
          });

          let mkr = mkrLayer.pop();

          markers.zoomToShowLayer(mkr, function (e) {
            mkr.openPopup();
          });

          return false;
        });

        // stop click on a person also opening the popup
        element.querySelectorAll('a').forEach((el) => {
          el.addEventListener('click', (e) => {
            e.stopPropagation();
          });
        });
      });
    }

    _drawMap();
    _buildMapData();
  })();
</script>
<?php View::endpush() ?>
