function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), !0).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
function _defineProperty(e, r, t) { return (r = _toPropertyKey(r)) in e ? Object.defineProperty(e, r, { value: t, enumerable: !0, configurable: !0, writable: !0 }) : e[r] = t, e; }
function _toPropertyKey(t) { var i = _toPrimitive(t, "string"); return "symbol" == typeof i ? i : i + ""; }
function _toPrimitive(t, r) { if ("object" != typeof t || !t) return t; var e = t[Symbol.toPrimitive]; if (void 0 !== e) { var i = e.call(t, r || "default"); if ("object" != typeof i) return i; throw new TypeError("@@toPrimitive must return a primitive value."); } return ("string" === r ? String : Number)(t); }
import React, { useEffect, useMemo, useRef, useState } from "react";
import PropTypes from "prop-types";
import Feature from "ol/Feature";
import { useSelector } from "react-redux";
import { makeStyles } from "@mui/styles";
import { Typography } from "@mui/material";
import Link from "../../components/Link";
import useTranslation from "../../utils/useTranslation";
const propTypes = {
  feature: PropTypes.instanceOf(Feature).isRequired
};
const cache = {};
const flexStyle = {
  display: "flex",
  flexDirection: "column",
  gap: 15
};
const useStyles = makeStyles(() => ({
  popup: _objectSpread(_objectSpread({
    padding: 10
  }, flexStyle), {}, {
    "& legend": {
      fontWeight: "bold" // Ensure the title is bold in gitlab
    },
    "& fieldset": _objectSpread(_objectSpread({}, flexStyle), {}, {
      borderWidth: 1,
      // Ensure border is 1px in gitlab
      padding: "20px 10px"
    })
  })
}));

// TODO: The NOVA data is still quite incomplete. For now check the API accessibility note for this hardcoded string. This needs to be improved when the data is updated
const hardcodedStringForNote = "Bei dieser Verbindung benötigen Sie Ein- und Ausstiegshilfen. Bitte melden Sie sich bis spätestens 1 Stunde vor Abfahrt unter swisspass.ch/handicap oder beim Contact Center Handicap.Contact Center Handicaptäglich 5.00–24.00 Uhr, Telefon 0800 007 102 (kostenlos in der Schweiz), aus dem Ausland +41 800 007 102.";
const useStopPlaceData = (uic, cartaroUrl) => {
  const [loading, setLoading] = useState();
  const [data, setData] = useState();
  useEffect(() => {
    const abortController = new AbortController();
    setData();
    if (uic && cache[uic]) {
      setData(cache[uic]);
    } else if (uic) {
      const fetchData = () => {
        setLoading(true);
        fetch("".concat(cartaroUrl, "journey_poi/stop_place?id=").concat(uic)).then(response => response.json()).then(newData => {
          cache[uic] = newData;
          setData(newData);
        }).catch(() => {
          // eslint-disable-next-line no-console
          console.warn("StopPlacePopup. No data for stations: ".concat(uic));
        }).finally(() => {
          setLoading(false);
        });
      };
      fetchData();
    }
    return () => {
      abortController.abort();
    };
  }, [cartaroUrl, uic]);
  return {
    data,
    loading
  };
};
const formatStateData = data => {
  if (data === "YES") return "Ja";
  if (data === "NO") return "Nein";
  if (data === "UNKNOWN") return "Unbekannt";
  if (data === "PARTIALLY") return "Teilweise";
  return data;
};
const getNoteTranslation = (note, language) => {
  return typeof note === "object" ? (note === null || note === void 0 ? void 0 : note[language]) || (note === null || note === void 0 ? void 0 : note.de) : note;
};
const getAccessibility = (value, language, t) => {
  if (!value) return null;
  const note = getNoteTranslation(value === null || value === void 0 ? void 0 : value.note, language);
  const hasTranslatedString = note === null || note === void 0 ? void 0 : note.includes(hardcodedStringForNote);
  const notTranslatedInfo = hasTranslatedString ? note === null || note === void 0 ? void 0 : note.split(hardcodedStringForNote)[1] : note;
  return {
    component: /*#__PURE__*/React.createElement("fieldset", {
      key: "accessibility",
      "data-testid": "stopplace-accessibility"
    }, /*#__PURE__*/React.createElement("legend", null, t("accessibility")), /*#__PURE__*/React.createElement(Typography, null, t(formatStateData(value === null || value === void 0 ? void 0 : value.state))), hasTranslatedString && /*#__PURE__*/React.createElement(Typography, null, /*#__PURE__*/React.createElement("span", {
      // eslint-disable-next-line react/no-danger
      dangerouslySetInnerHTML: {
        __html: t(hardcodedStringForNote).replace("swisspass.ch/handicap", '<a href="https://www.swisspass.ch/handicap" rel="noopener noreferrer"  target="_blank">swisspass.ch/handicap</a>')
      }
    }), "s"), notTranslatedInfo && /*#__PURE__*/React.createElement(Typography, null, notTranslatedInfo)),
    text: "".concat(t("accessibility"), ", ").concat(t(formatStateData(value === null || value === void 0 ? void 0 : value.state))).concat(hasTranslatedString ? ", ".concat(t(hardcodedStringForNote)) : "").concat(notTranslatedInfo ? ", ".concat(notTranslatedInfo) : "")
  };
};
const getAlternativeTransport = (value, language, t) => {
  const note = getNoteTranslation(value === null || value === void 0 ? void 0 : value.note, language);
  if (!value || /NO|UNKNOWN|NOT_APPLICABLE|PARTIALLY/.test(value === null || value === void 0 ? void 0 : value.state) && !note) return null;
  const hasShuttleService = !note && /YES/.test(value === null || value === void 0 ? void 0 : value.state);
  return {
    component: /*#__PURE__*/React.createElement("fieldset", {
      key: "alternativeTransport",
      "data-testid": "stopplace-alternative-transport"
    }, /*#__PURE__*/React.createElement("legend", null, t("alternativeTransport")), hasShuttleService && /*#__PURE__*/React.createElement(Typography, {
      "data-testid": "stopplace-alternative-transport-state"
    }, t("Shuttle-Fahrdienst")), note && /*#__PURE__*/React.createElement(Typography, {
      "data-testid": "stopplace-alternative-transport-note"
    }, note)),
    text: "".concat(t("alternativeTransport"), ", ").concat(hasShuttleService ? ", ".concat(t("Shuttle-Fahrdienst")) : "").concat(note ? ", ".concat(note) : "")
  };
};
const getPassengerInformation = (value, t) => {
  if (!value) return null;
  const entries = Object.entries(value).filter(_ref => {
    let [k, val] = _ref;
    return val !== "NO" && val !== "UNKNOWN" && k !== "note";
  });
  return entries.length ? {
    component: /*#__PURE__*/React.createElement("fieldset", {
      key: "passengerInformation",
      "data-testid": "stopplace-passengerinfo"
    }, /*#__PURE__*/React.createElement("legend", null, t("passengerInformation")), entries.map(_ref2 => {
      let [k] = _ref2;
      return /*#__PURE__*/React.createElement("div", {
        key: k,
        "data-testid": "stopplace-passengerinfo-".concat(k)
      }, t(k));
    })),
    text: "".concat(t("passengerInformation"), ", ").concat(entries.map(_ref3 => {
      let [k] = _ref3;
      return t(k);
    }).join(", "))
  } : null;
};
const getNote = (value, language, t) => {
  const text = getNoteTranslation(value, language);
  if (!text) return null;
  return {
    component: /*#__PURE__*/React.createElement("fieldset", {
      key: "note",
      "data-testid": "stopplace-note"
    }, /*#__PURE__*/React.createElement("legend", null, t("Hinweise zur Haltestelle")), text),
    text: "".concat(t("Hinweise zur Haltestelle"), ", ").concat(text)
  };
};
const getUrl = (value, t) => {
  if (!value) return null;
  const url = /^http(s)?:\/\//.test(value) ? value : "https://".concat(value);
  let niceVal = value;
  try {
    niceVal = /^http(s)?:\/\//.test(url) ? new URL(url).hostname : value;
  } catch (e) {
    // eslint-disable-next-line no-console
    console.log("StopPlacePopup. Not a parseable url: ", value);
    niceVal = value;
  }
  return {
    component: /*#__PURE__*/React.createElement("fieldset", {
      key: "url",
      "data-testid": "stopplace-url"
    }, /*#__PURE__*/React.createElement("legend", null, t("Weitere Informationen")), /*#__PURE__*/React.createElement(Link, {
      href: url
    }, niceVal)),
    text: "".concat(t("Weitere Informationen"), ", ").concat(url)
  };
};
function StopPlacePopup(_ref4) {
  let {
    feature
  } = _ref4;
  const classes = useStyles();
  const {
    t,
    i18n
  } = useTranslation();
  const announcerRef = useRef(null);
  const cartaroUrl = useSelector(state => state.app.cartaroUrl);
  const uic = useMemo(() => {
    return feature === null || feature === void 0 ? void 0 : feature.get("uic");
  }, [feature]);
  const {
    data,
    loading
  } = useStopPlaceData(uic, cartaroUrl);
  const popupContent = useMemo(() => {
    const infos = (data === null || data === void 0 ? void 0 : data.prmInformation) || {};
    const accessibility = getAccessibility(infos.accessibility, i18n.language, t);
    const alternativeTransport = getAlternativeTransport(infos.alternativeTransport, i18n.language, t);
    const passengerInformation = getPassengerInformation(infos.passengerInformation, t);
    const note = getNote(infos.note, i18n.language, t);
    const url = getUrl(infos.url, t);
    const components = [note === null || note === void 0 ? void 0 : note.component, accessibility === null || accessibility === void 0 ? void 0 : accessibility.component, alternativeTransport === null || alternativeTransport === void 0 ? void 0 : alternativeTransport.component, passengerInformation === null || passengerInformation === void 0 ? void 0 : passengerInformation.component, url === null || url === void 0 ? void 0 : url.component].filter(Boolean);
    return {
      component: components.length ? /*#__PURE__*/React.createElement("div", {
        className: classes.popup,
        "data-testid": "stopplace-popup"
      }, components) : /*#__PURE__*/React.createElement("div", {
        className: classes.popup,
        "data-testid": "stopplace-popup"
      }, /*#__PURE__*/React.createElement(Typography, null, t("Keine Daten für diese Station"))),
      text: [note === null || note === void 0 ? void 0 : note.text, accessibility === null || accessibility === void 0 ? void 0 : accessibility.text, alternativeTransport === null || alternativeTransport === void 0 ? void 0 : alternativeTransport.text, passengerInformation === null || passengerInformation === void 0 ? void 0 : passengerInformation.text, url === null || url === void 0 ? void 0 : url.text].filter(Boolean).join(". ")
    };
  }, [classes.popup, data === null || data === void 0 ? void 0 : data.prmInformation, i18n.language, t]);
  useEffect(() => {
    if (popupContent.text && announcerRef.current) {
      announcerRef.current.textContent = popupContent.text;
    }
  }, [popupContent.text]);
  if (loading || !popupContent) {
    return /*#__PURE__*/React.createElement("div", null, t("Laden..."));
  }
  return /*#__PURE__*/React.createElement("div", null, /*#__PURE__*/React.createElement("div", {
    "data-testid": "stopplace-announcer",
    ref: announcerRef,
    "aria-live": "assertive",
    "aria-atomic": "true",
    className: "sr-only",
    style: {
      position: "absolute",
      left: "-9999px",
      height: "1px",
      width: "1px",
      overflow: "hidden"
    }
  }), popupContent === null || popupContent === void 0 ? void 0 : popupContent.component);
}
StopPlacePopup.propTypes = propTypes;
const memoized = /*#__PURE__*/React.memo(StopPlacePopup);
memoized.renderTitle = feat => feat.get("name");
export default memoized;
//# sourceMappingURL=StopPlacePopup.js.map