const { registerPlugin } = wp.plugins;
const { useState, useEffect } = wp.element;

const CustomNotices = () => {
    const [noticesData, setNoticesData] = useState([]);

    useEffect(() => {
        // Get the cart data from the store
        const unsubscribe = wp.data.subscribe(() => {
            const cartStore = wp.data.select('wc/store/cart');
            if (cartStore) {
                const cartData = cartStore.getCartData();
                const customData = cartData?.extensions?.['coupons-plus'];
                
                if (customData?.notices && Array.isArray(customData.notices)) {
                    setNoticesData(customData.notices);
                } else {
                    setNoticesData([]);
                }
            }
        });

        return unsubscribe;
    }, []);

    useEffect(() => {
        // Find the notice container
        const findAndInjectNotices = () => {
            // Look for the WooCommerce blocks notice container
            const noticeContainer = document.querySelector('.wc-block-components-notice-banner-container') || 
                                   document.querySelector('.wc-block-components-main');
            
            if (!noticeContainer) {
                return;
            }

            // Remove all existing coupons-plus notices
            const existingNotices = document.querySelectorAll('[id^="coupons-plus-custom-notice-"]');
            existingNotices.forEach(notice => notice.remove());

            // If no notices to show, return
            if (!noticesData || noticesData.length === 0) {
                return;
            }

            // Define notice class based on type
            const noticeTypes = {
                info: 'is-info',
                success: 'is-success',
                warning: 'is-warning',
                error: 'is-error',
            };

            // Create and inject each notice
            noticesData.forEach((noticeData, index) => {
                const noticeType = noticeTypes[noticeData.type] || noticeTypes.info;

                // Create the notice element
                const noticeDiv = document.createElement('div');
                noticeDiv.id = `coupons-plus-custom-notice-${index}`;
                noticeDiv.className = `wc-block-components-notice-banner ${noticeType}`;
                noticeDiv.style.marginBottom = '1rem';
                noticeDiv.setAttribute('role', 'alert');

                const contentDiv = document.createElement('div');
                contentDiv.className = 'wc-block-components-notice-banner__content';
                contentDiv.style.display = 'flex';
                contentDiv.style.alignItems = 'center';
                contentDiv.style.justifyContent = 'space-between';
                contentDiv.style.gap = '1rem';
                contentDiv.style.width = '100%';

                const messageSpan = document.createElement('span');
                messageSpan.textContent = noticeData.message;

                contentDiv.appendChild(messageSpan);

                // Add button if provided
                if (noticeData.button && noticeData.button.text && noticeData.button.url) {
                    const buttonLink = document.createElement('a');
                    buttonLink.href = noticeData.button.url;
                    buttonLink.className = 'wc-block-components-button wp-element-button';
                    buttonLink.textContent = noticeData.button.text;
                    buttonLink.style.whiteSpace = 'nowrap';
                    buttonLink.style.padding = '0.5rem 1rem';
                    buttonLink.style.textDecoration = 'none';
                    buttonLink.style.marginLeft = 'auto';
                    
                    contentDiv.appendChild(buttonLink);
                }

                noticeDiv.appendChild(contentDiv);

                // Insert at the beginning of the container
                noticeContainer.insertBefore(noticeDiv, noticeContainer.firstChild);
            });
        };

        // Try immediately
        findAndInjectNotices();

        // Also try after a short delay in case the DOM isn't ready
        const timeout = setTimeout(findAndInjectNotices, 100);

        return () => clearTimeout(timeout);
    }, [noticesData]);

    return null;
};

const render = () => {
    return wp.element.createElement(CustomNotices, null);
};

registerPlugin('coupons-plus-notice', {
    render,
    scope: 'woocommerce-checkout',
});
