import { onPageLoadComplete } from '@nimius/event-utility';

const getCookie = (name) => {
    const v = document.cookie.match('(^|;) ?' + name + '=([^;]*)(;|$)');
    return v ? v[2] : null;
};

const setCookie = (name, value) => {
    document.cookie = name + "=" + value + ";path=/;expires=";
};

const initNotification = (notification) => {
    const header = document.querySelector('[data-site-header]');
    const mainContent = document.querySelector('[data-main-content]');
    const closeButton = document.querySelector('[data-notification-close]');
    let cookie = getCookie('notification_dismissed');
    let notificationHeight = 0;

    const setNotificationSpacing = (height) => {
        header.style.top = height + "px";
        mainContent.style.marginTop = height + "px";
    };

    if (cookie == null) {
        notification.setAttribute('data-state', 'active');
        notificationHeight = notification.offsetHeight;
        // set margin-top to site header and main content
        setNotificationSpacing(notificationHeight);

        closeButton.addEventListener('click', (e) => {
            e.preventDefault();

            notification.setAttribute('data-state', 'inactive');
            setCookie('notification_dismissed', 'true');
            // remove margin-top from site header and main content
            setNotificationSpacing(0);
            cookie = getCookie('notification_dismissed');
        });

        window.addEventListener('resize', () => {
            if (cookie == null) {
                notificationHeight = notification.offsetHeight;
                setNotificationSpacing(notificationHeight);
            }
        });
    }

};

onPageLoadComplete(() => {
    const notification = document.querySelector('[data-notification]');

    if (notification) {
        initNotification(notification);
    }
});