import { jsx as _jsx } from "react/jsx-runtime";
import * as React from 'react';
import { Lang } from '@gravity-ui/uikit';
import debounce from "lodash/debounce.js";
import { LocaleContext } from "../../gravity-blocks/context/localeContext/index.js";
import { MapsContext } from "../../gravity-blocks/context/mapsContext/mapsContext.js";
import { MobileContext } from "../../gravity-blocks/context/mobileContext/index.js";
import { block } from "../../utils/index.js";
import { getMapHeight } from "./helpers.js";
const b = 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);
    const { lang = Lang.Ru } = React.useContext(LocaleContext);
    const isMobile = React.useContext(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 = debounce(() => {
            if (ref.current) {
                setHeight(Math.round(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 _jsx("script", { type: "application/ld+json", dangerouslySetInnerHTML: { __html: json } });
    }, [address]);
    if (!apiKey || !address) {
        return null;
    }
    return (_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 }));
};
export default GoogleMap;
//# sourceMappingURL=GoogleMap.js.map
