"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

var _interopRequireWildcard = require("@babel/runtime/helpers/interopRequireWildcard");

exports.__esModule = true;
exports.StoresMap = void 0;

var _taggedTemplateLiteralLoose2 = _interopRequireDefault(require("@babel/runtime/helpers/taggedTemplateLiteralLoose"));

var _react = _interopRequireWildcard(require("react"));

var _reactDom = _interopRequireDefault(require("react-dom"));

var _stores = require("../../stores.context");

var _googleMapsReact = require("google-maps-react");

var _styledComponents = _interopRequireWildcard(require("styled-components"));

var _Common = require("../../../Common");

var _lib = require("@sentecacommerce-theme/lib");

var _router = require("next/router");

var _templateObject, _templateObject2, _templateObject3, _templateObject4, _templateObject5, _templateObject6, _templateObject7;

function _createForOfIteratorHelperLoose(o, allowArrayLike) { var it; if (typeof Symbol === "undefined" || o[Symbol.iterator] == null) { if (Array.isArray(o) || (it = _unsupportedIterableToArray(o)) || allowArrayLike && o && typeof o.length === "number") { if (it) o = it; var i = 0; return function () { if (i >= o.length) return { done: true }; return { done: false, value: o[i++] }; }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } it = o[Symbol.iterator](); return it.next.bind(it); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

// >:((
var Marker = _googleMapsReact.Marker;
var InfoWindow = _googleMapsReact.InfoWindow;

var MapComponent = function MapComponent(_ref) {
  var google = _ref.google,
      pinIcon = _ref.pinIcon,
      fullWidth = _ref.fullWidth;
  var router = (0, _router.useRouter)();
  var labels = (0, _lib.useStrings)('stores');

  var _useState = (0, _react.useState)(),
      map = _useState[0],
      setMap = _useState[1];

  var _useState2 = (0, _react.useState)(),
      selectedPin = _useState2[0],
      setSelectedPin = _useState2[1];

  var _useState3 = (0, _react.useState)(),
      storeDistance = _useState3[0],
      setStoreDistance = _useState3[1];

  var _useState4 = (0, _react.useState)(),
      currentPos = _useState4[0],
      setCurrentPos = _useState4[1];

  var _useStoresContext = (0, _stores.useStoresContext)(),
      selectedStoreFromList = _useStoresContext.selectedStore,
      setSelectedStoreFromList = _useStoresContext.setSelectedStore;

  var markerRefs = (0, _react.useRef)([]);

  var _useState5 = (0, _react.useState)(),
      closestLocation = _useState5[0],
      setClosestLocation = _useState5[1];

  var stores = (0, _stores.useStores)();
  var pinsToFitInMap = (0, _stores.useStoresPinsToFitInView)();

  var onReady = function onReady(_, map) {
    setMap(map);
  };
  /**
   * Center the map to the current pins
   */


  (0, _react.useEffect)(function () {
    var bounds = new google.maps.LatLngBounds();
    pinsToFitInMap.forEach(function (pin) {
      bounds.extend(pin);
    });
    if (!map) return;
    map.fitBounds(bounds); // set min zoom

    map.setZoom(Math.min(map.getZoom(), 14)); // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [pinsToFitInMap]);

  var onMarkerClick = function onMarkerClick(store) {
    return function (_, marker) {
      setSelectedStoreFromList(store.name);
      setSelectedPin({
        marker: marker,
        store: store
      });
    };
  };

  var hideInfoWindow = function hideInfoWindow() {
    setSelectedStoreFromList(null);
    setSelectedPin(null);
  }; // Attaches the button to the React DOM after the info window has been opened to preserve
  // the event bindings like (onClick) which are otherwise lost and don't bubble up through the iframe
  // if they're put directly in the InfoWindow


  var onInfoWindowOpen = function onInfoWindowOpen() {
    var button = /*#__PURE__*/_react["default"].createElement(_Common.Button, {
      className: "mt-2",
      fullWidth: true,
      borderRadius: "large",
      small: true,
      onClick: function onClick() {
        return router.push('/stores/' + selectedStore.slug);
      }
    }, labels.viewStoreLabel);

    _reactDom["default"].render(_react["default"].Children.only(button), document.getElementById('viewStoreBtn'));
  };

  var selectedStore = selectedPin == null ? void 0 : selectedPin.store;
  var selectedMarker = selectedPin == null ? void 0 : selectedPin.marker; // memo markers to prevent unnecessary markers initialization

  var markers = (0, _react.useMemo)(function () {
    return stores.map(function (store, i) {
      var pin = {
        lat: +store.latitude,
        lng: +store.longitude
      };
      markerRefs.current = Array(stores.length).fill(null).map(function (_, i) {
        return markerRefs.current[i] || /*#__PURE__*/(0, _react.createRef)();
      });
      return /*#__PURE__*/_react["default"].createElement(Marker, {
        key: "Marker__" + pin.lat + "x" + pin.lng,
        position: pin,
        icon: (pinIcon == null ? void 0 : pinIcon.trim()) || undefined,
        onClick: onMarkerClick(store),
        ref: markerRefs.current[i]
      });
    });
  }, [stores, pinIcon]);

  var findClosestDistance = function findClosestDistance(pos) {
    var _closestMarker, _closestMarker2;

    var closestDistance = Number.MAX_VALUE;
    var closestMarker = null;

    for (var _iterator = _createForOfIteratorHelperLoose(markers), _step; !(_step = _iterator()).done;) {
      var marker = _step.value;
      var posCoords = {
        lat: pos.coords.latitude,
        lng: pos.coords.longitude
      };
      var markerCoords = marker.props.position;
      var distance = (0, _lib.getDistance)(posCoords, markerCoords);

      if (closestDistance > distance) {
        closestDistance = distance;
        closestMarker = marker;
      }
    }

    setClosestLocation({
      lat: (_closestMarker = closestMarker) == null ? void 0 : _closestMarker.props.position.lat,
      lng: (_closestMarker2 = closestMarker) == null ? void 0 : _closestMarker2.props.position.lng
    });
  };

  var setDistanceFromSelectedStore = function setDistanceFromSelectedStore() {
    var pos = {
      lat: currentPos == null ? void 0 : currentPos.coords.latitude,
      lng: currentPos == null ? void 0 : currentPos.coords.longitude
    };
    var storePos = {
      lat: parseFloat(selectedStore == null ? void 0 : selectedStore.latitude),
      lng: parseFloat(selectedStore == null ? void 0 : selectedStore.longitude)
    };
    var distance = (0, _lib.getDistance)(pos, storePos);
    setStoreDistance(distance);
  };

  var onMapAndGeolocationLoad = function onMapAndGeolocationLoad() {
    navigator.geolocation.getCurrentPosition(function (pos) {
      setCurrentPos(pos);
      findClosestDistance(pos);
      setDistanceFromSelectedStore();
      map == null ? void 0 : map.setZoom(13);
    });
  };

  (0, _react.useEffect)(function () {
    map == null ? void 0 : map.setZoom(13);
    setDistanceFromSelectedStore();

    if (selectedStoreFromList !== (selectedPin == null ? void 0 : selectedPin.store.name)) {
      stores.forEach(function (store, i) {
        if (selectedStoreFromList === store.name) {
          var marker = markers[i];
          var storeCoords = {
            lat: +store.latitude,
            lng: +store.longitude
          };
          var markerCoords = marker.props.position;

          if (storeCoords.lat === markerCoords.lat && storeCoords.lng === markerCoords.lng) {
            setSelectedPin({
              marker: markerRefs.current[i].current.marker,
              store: store
            });
          }
        }
      });
    }
  });
  (0, _react.useEffect)(function () {
    onMapAndGeolocationLoad();
  }, []);
  return /*#__PURE__*/_react["default"].createElement(MapContainer, {
    fullWidth: fullWidth
  }, /*#__PURE__*/_react["default"].createElement(_googleMapsReact.Map, {
    google: google,
    initialCenter: closestLocation,
    center: closestLocation,
    onReady: onReady
  }, markers, /*#__PURE__*/_react["default"].createElement(InfoWindow, {
    marker: selectedMarker,
    onClose: hideInfoWindow,
    visible: Boolean(selectedMarker),
    onOpen: onInfoWindowOpen
  }, selectedStore && /*#__PURE__*/_react["default"].createElement(InfoWindowContentWrapper, null, /*#__PURE__*/_react["default"].createElement(InfoWindowTitle, null, selectedStore.name), /*#__PURE__*/_react["default"].createElement(InfoWindowText, null, selectedStore.fullAddress), /*#__PURE__*/_react["default"].createElement(InfoWindowDistance, null, !isNaN(storeDistance) && storeDistance.toFixed(2) + ' km'), /*#__PURE__*/_react["default"].createElement(_Common.Button, {
    fullWidth: true,
    borderRadius: "large",
    small: true,
    className: "mt-3",
    bordered: true,
    target: "_blank",
    link: "https://www.google.com/maps/dir/" + selectedStore.latitude + "," + selectedStore.longitude
  }, labels.getDirectionsLabel), /*#__PURE__*/_react["default"].createElement("div", {
    id: "viewStoreBtn"
  })))));
};

var StoresMap = (0, _googleMapsReact.GoogleApiWrapper)({
  apiKey: ''
})(MapComponent);
exports.StoresMap = StoresMap;

var InfoWindowContentWrapper = _styledComponents["default"].div.attrs({
  className: 'p-3'
})(_templateObject || (_templateObject = (0, _taggedTemplateLiteralLoose2["default"])(["\n  min-width: 14rem;\n  min-height: 10rem;\n  max-width: 25rem;\n\n  position: relative;\n\n  @media (min-width: ", ") {\n    min-height: 4rem;\n  }\n\n  button,\n  a {\n    font-size: 1.2rem !important;\n\n    @media (min-width: ", ") {\n      font-size: 1.6rem !important;\n    }\n  }\n"])), function (_ref2) {
  var _theme$breakpoints;

  var theme = _ref2.theme;
  return (_theme$breakpoints = theme.breakpoints) == null ? void 0 : _theme$breakpoints.md.min;
}, function (_ref3) {
  var _theme$breakpoints2;

  var theme = _ref3.theme;
  return (_theme$breakpoints2 = theme.breakpoints) == null ? void 0 : _theme$breakpoints2.md.min;
});

var InfoWindowTitle = _styledComponents["default"].h2.attrs({
  className: 'mb-2'
})(_templateObject2 || (_templateObject2 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  color: ", ";\n  font-weight: 500;\n  font-size: 1.6rem;\n\n  @media (min-width: ", ") {\n    font-size: 2.2rem;\n  }\n"])), function (_ref4) {
  var _theme$palette;

  var theme = _ref4.theme;
  return (_theme$palette = theme.palette) == null ? void 0 : _theme$palette.primary;
}, function (_ref5) {
  var _theme$breakpoints3;

  var theme = _ref5.theme;
  return (_theme$breakpoints3 = theme.breakpoints) == null ? void 0 : _theme$breakpoints3.md.min;
});

var InfoWindowText = _styledComponents["default"].p.attrs({
  className: 'pb-2'
})(_templateObject3 || (_templateObject3 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  color: ", ";\n  font-size: 1.4rem;\n\n  @media (min-width: ", ") {\n    font-size: 1.6rem;\n  }\n\n  & a {\n    &:hover {\n      text-decoration: underline;\n    }\n  }\n"])), function (_ref6) {
  var _theme$palette2;

  var theme = _ref6.theme;
  return (_theme$palette2 = theme.palette) == null ? void 0 : _theme$palette2.primary;
}, function (_ref7) {
  var _theme$breakpoints4;

  var theme = _ref7.theme;
  return (_theme$breakpoints4 = theme.breakpoints) == null ? void 0 : _theme$breakpoints4.md.min;
});

var InfoWindowDistance = _styledComponents["default"].p.attrs({
  className: 'mt-1 mb-1'
})(_templateObject4 || (_templateObject4 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  color: ", ";\n  font-size: 1.3rem;\n\n  @media (min-width: ", ") {\n    font-size: 1.6rem;\n  }\n"])), function (_ref8) {
  var _theme$palette3;

  var theme = _ref8.theme;
  return (_theme$palette3 = theme.palette) == null ? void 0 : _theme$palette3.hint;
}, function (_ref9) {
  var _theme$breakpoints5;

  var theme = _ref9.theme;
  return (_theme$breakpoints5 = theme.breakpoints) == null ? void 0 : _theme$breakpoints5.md.min;
});

var MapContainer = _styledComponents["default"].div(_templateObject5 || (_templateObject5 = (0, _taggedTemplateLiteralLoose2["default"])(["\n  position: relative;\n  width: 100%;\n  height: 50rem;\n\n  @media (min-width: ", ") {\n    position: relative;\n    width: 100%;\n    max-height: 700px;\n    top: 0;\n    left: 0;\n\n    // the actual map\n    & > div {\n      position: absolute;\n      width: 100%;\n      max-height: 700px;\n      top: 0;\n      left: 0;\n    }\n  }\n\n  ", "\n\n  .gm-style-iw.gm-style-iw-c {\n    border-radius: 0 !important;\n  }\n\n  button.gm-ui-hover-effect {\n    top: 0.2rem !important;\n    right: 1rem !important;\n\n    img {\n      width: 2.2rem !important;\n      height: 2.2rem !important;\n    }\n  }\n"])), function (_ref10) {
  var _theme$breakpoints6;

  var theme = _ref10.theme;
  return (_theme$breakpoints6 = theme.breakpoints) == null ? void 0 : _theme$breakpoints6.md.min;
}, function (props) {
  return props.fullWidth ? (0, _styledComponents.css)(_templateObject6 || (_templateObject6 = (0, _taggedTemplateLiteralLoose2["default"])(["\n          height: calc(100vh - 6rem);\n          position: absolute;\n        "]))) : (0, _styledComponents.css)(_templateObject7 || (_templateObject7 = (0, _taggedTemplateLiteralLoose2["default"])(["\n          padding-bottom: 100%;\n          position: relative;\n        "])));
});
//# sourceMappingURL=index.js.map