import { useEffect, useState } from '@wordpress/element';

const CONTAINER_SELECTOR = '.dokan-selling-disabled-notice';
const DEFAULT_SELECTOR = '.dokan-selling-disabled-notice__default';

/**
 * Get the dashboard-wide notice slot printed by PHP.
 *
 * @return The slot element, or null when PHP printed no notice on this page.
 */
export const getGlobalNoticeContainer = (): HTMLElement | null =>
    document.querySelector< HTMLElement >( CONTAINER_SELECTOR );

/**
 * Show or hide the default message inside the notice slot.
 *
 * @param visible Whether the default message should be visible.
 */
export const setDefaultNoticeVisible = ( visible: boolean ): void => {
    const defaultMessage =
        getGlobalNoticeContainer()?.querySelector< HTMLElement >(
            DEFAULT_SELECTOR
        );

    if ( defaultMessage ) {
        defaultMessage.style.display = visible ? '' : 'none';
    }
};

/**
 * Take over the dashboard-wide verification notice with page-specific wording.
 *
 * PHP prints that notice above the page heading — a spot no React slot can
 * reach, because the app mounts further down the page. Pages with their own
 * wording portal into it and hide the default message, so every verification
 * notice lands in the same place.
 *
 * @param active Whether the calling page has its own message to show.
 *
 * @return The element to portal into, or null when there is nothing to take over.
 */
const useGlobalNoticeMount = ( active: boolean ): HTMLElement | null => {
    const [ container, setContainer ] = useState< HTMLElement | null >( null );

    useEffect( () => {
        if ( ! active ) {
            setContainer( null );
            return;
        }

        const element = getGlobalNoticeContainer();

        if ( ! element ) {
            return;
        }

        setDefaultNoticeVisible( false );
        setContainer( element );

        return () => {
            setDefaultNoticeVisible( true );
            setContainer( null );
        };
    }, [ active ] );

    return container;
};

export default useGlobalNoticeMount;
