"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const tslib_1 = require("tslib");
const jsx_runtime_1 = require("react/jsx-runtime");
const React = tslib_1.__importStar(require("react"));
const uikit_1 = require("@gravity-ui/uikit");
const debounce_1 = tslib_1.__importDefault(require("lodash/debounce.js"));
const localeContext_1 = require("../../gravity-blocks/context/localeContext/index.js");
const mapsContext_1 = require("../../gravity-blocks/context/mapsContext/mapsContext.js");
const mobileContext_1 = require("../../gravity-blocks/context/mobileContext/index.js");
const utils_1 = require("../../utils/index.js");
const helpers_1 = require("./helpers.js");
const b = (0, utils_1.block)('map');
function getScriptSrc(params) {
    const { apiKey, scriptSrc, address, lang, zoom } = params;
    return `${scriptSrc}?key=${apiKey}&language=${lang}${zoom ? '&zoom=' + zoom : ''}&q=${encodeURI(address)}`;
}
const GoogleMap = (props) => {
    const { address, zoom, className, forceAspectRatio = true } = props;
    const { apiKey, scriptSrc } = React.useContext(mapsContext_1.MapsContext);
    const { lang = uikit_1.Lang.Ru } = React.useContext(localeContext_1.LocaleContext);
    const isMobile = React.useContext(mobileContext_1.MobileContext);
    const [height, setHeight] = React.useState(undefined);
    const ref = React.useRef(null);
    const src = React.useMemo(() => getScriptSrc({ apiKey, scriptSrc, address, lang, zoom }), [apiKey, scriptSrc, address, lang, zoom]);
    React.useEffect(() => {
        if (!forceAspectRatio) {
            return;
        }
        const updateSize = (0, debounce_1.default)(() => {
            if (ref.current) {
                setHeight(Math.round((0, helpers_1.getMapHeight)(ref.current.offsetWidth, isMobile)));
            }
        }, 100);
        updateSize();
        window.addEventListener('resize', updateSize, { passive: true });
        // eslint-disable-next-line consistent-return
        return () => {
            window.removeEventListener('resize', updateSize);
        };
    }, [forceAspectRatio, isMobile]);
    // Generate Schema.org JSON-LD for Google Map
    const mapMicrodataScript = React.useMemo(() => {
        if (!address) {
            return null;
        }
        const json = JSON.stringify({
            '@context': 'https://schema.org',
            '@type': 'Place',
            address,
        });
        return (0, jsx_runtime_1.jsx)("script", { type: "application/ld+json", dangerouslySetInnerHTML: { __html: json } });
    }, [address]);
    if (!apiKey || !address) {
        return null;
    }
    return ((0, jsx_runtime_1.jsx)("iframe", { className: b(null, className), ref: ref, style: {
            height,
        }, title: "Google Map", loading: "lazy", allowFullScreen: true, referrerPolicy: "no-referrer-when-downgrade", src: src, children: mapMicrodataScript }));
};
exports.default = GoogleMap;
//# sourceMappingURL=GoogleMap.js.map
