import { __assign, __read } from "tslib";
import React, { createContext, useState, useContext, useEffect, useRef } from "react";
import { createPortal } from "react-dom";
import { getContainerBanner } from "./helpers";
import Banner from "./Banner";
var BannerContext = createContext({
    bannerShow: function () { return function () {
        /* */
    }; }
});
BannerContext.displayName = "BannerContext";
export var BannerService = function (_a) {
    var children = _a.children, idContainer = _a.idContainer;
    var _b = __read(useState(new Map()), 2), banners = _b[0], setBanners = _b[1];
    var bannersRef = useRef(Array.from(banners.values()).map(function (_a) {
        var container = _a.container;
        return container;
    }));
    useEffect(function () {
        bannersRef.current = Array.from(banners.values()).map(function (_a) {
            var container = _a.container;
            return container;
        });
    }, [banners]);
    useEffect(function () { return function () {
        bannersRef.current.forEach(function (container) {
            container.remove();
        });
    }; }, []);
    var bannerShow = function (props) {
        var key = "banner-" + Math.random();
        var container = getContainerBanner(props.type, idContainer);
        setBanners(new Map(banners.set(key, { params: props, container: container })));
        return function () { return bannerClose(key); };
    };
    var bannerClose = function (key) {
        var _a;
        (_a = banners.get(key)) === null || _a === void 0 ? void 0 : _a.container.remove();
        banners.delete(key);
    };
    return (React.createElement(BannerContext.Provider, { value: { bannerShow: bannerShow } },
        children,
        Array.from(banners.keys()).map(function (key) {
            var banner = banners.get(key);
            if (banner) {
                var handlePrimaryClick = function () {
                    var _a, _b;
                    (_b = (_a = banner.params).onPrimaryClick) === null || _b === void 0 ? void 0 : _b.call(_a);
                    bannerClose(key);
                };
                return createPortal(React.createElement(Banner, __assign({}, banner.params, { onPrimaryClick: handlePrimaryClick })), banner.container);
            }
            return null;
        })));
};
export var useBannerService = function () {
    var bannerShow = useContext(BannerContext).bannerShow;
    return [bannerShow];
};
