import React__default, { createContext, useContext, useReducer, useMemo, useRef } from 'react';
import { createPortal } from 'react-dom';
import { getComponentRoot } from '../../../utils/index.js';
import { MessageProviderToast } from './components/MessageProviderToast.js';
import { INITIAL_MESSAGE_CONTEXT_VALUE, TOAST_TYPE_COMPACT, TOAST_TYPE_DEFAULT, AUTO_HIDE_DURATION_DEFAULT, MESSAGE_POSITION_DEFAULT } from './constants.js';
import { messagesReducer, initialMessagesState } from './reducer.js';
import { ToastWrapper } from './styles.js';
import { createMessageMethods } from './utils/createMessageMethods.js';

const MessageContext = createContext(INITIAL_MESSAGE_CONTEXT_VALUE);
const useMessageContext = () => useContext(MessageContext);
const defaultProviderOption = {
    action: 'acknowledge',
    autoHideDuration: AUTO_HIDE_DURATION_DEFAULT,
    position: MESSAGE_POSITION_DEFAULT,
    toastType: TOAST_TYPE_COMPACT,
    zIndex: 6000,
};
function MessageProvider({ children, messageRoot, options, }) {
    const [state, dispatch] = useReducer(messagesReducer, initialMessagesState);
    const providerOptions = Object.assign(Object.assign({}, defaultProviderOption), options);
    const methods = useMemo(() => (Object.assign({ compact: createMessageMethods(dispatch, Object.assign(Object.assign({}, providerOptions), { toastType: TOAST_TYPE_COMPACT })), default: createMessageMethods(dispatch, Object.assign(Object.assign({}, providerOptions), { toastType: TOAST_TYPE_DEFAULT })) }, createMessageMethods(dispatch, providerOptions))), []);
    // set message provider root
    const mainElement = useRef(getComponentRoot(messageRoot));
    return (React__default.createElement(MessageContext.Provider, { value: methods },
        children,
        createPortal(React__default.createElement(ToastWrapper, { position: providerOptions.position, zIndex: providerOptions.zIndex }, state.messages.map((message) => (React__default.createElement(MessageProviderToast, Object.assign({}, message, { key: message.id, position: providerOptions.position }))))), mainElement.current)));
}

export { MessageProvider, useMessageContext };
