import {createRoot} from '@wordpress/element';
import {CampaignBlockApp} from '@givewp/src/Campaigns/Blocks/Campaign/app';

/**
 * @since 4.7.0
 */
export default class CampaignWidget extends elementorModules.frontend.handlers.Base {
    render() {
        const containers = document.querySelectorAll(`[data-id="${this.getID()}"] [data-givewp-campaign-block]`);

        containers?.forEach((container) => {
            const root = createRoot(container);

            const attributes = JSON.parse(container.dataset?.attributes);

            root.render(<CampaignBlockApp attributes={attributes} />);
        });
    }

    onInit() {
        this.render();
    }
}

/**
 * Register JS Handler for the Test Widget
 *
 * When Elementor frontend was initiated, and the widget is ready, register the widet
 * JS handler.
 */
window.addEventListener('elementor/frontend/init', () => {
    const addHandler = ($element) => {
        elementorFrontend.elementsHandler.addHandler(CampaignWidget, {$element});
    };

    elementorFrontend.hooks.addAction('frontend/element_ready/givewp_campaign.default', addHandler);
});
