/* eslint-disable */
import { fireEvent } from '@nimius/event-utility';
import { extractPrefixedAttributesFromElement } from '@nimius/dom-utility';
import 'cookieconsent';

export const initCookieConsent = () => {
    const cookieConsentNode = document.querySelector('[data-cookie-consent]');
    if (window.cookieconsent && cookieConsentNode) {
        const settings = extractPrefixedAttributesFromElement(cookieConsentNode, 'data-cookie-consent-');
        if (settings && settings.message) {
            window.cookieconsent.initialise({
                type: settings.type,
                palette: {
                    popup: {
                        background: settings.colorPopupBackground || '#626159',
                        text: settings.colorPopupText || '#ffffff',
                    },
                    button: {
                        background: settings.colorButtonBackground || '#ffffff',
                        text: settings.colorButtonText || '#6f6759',
                    },
                },
                content: {
                    message: settings.message,
                    dismiss: settings.labelDismiss || 'Got it',
                    deny: settings.labelDeny || 'Deny',
                    allow: settings.labelAllow || 'Allow',
                    link: `${settings.linkPolicy || ''}${settings.linkImprint || ''}`,
                },
                elements: {
                    messagelink: '<span id="cookieconsent:desc" class="cc-message">{{message}}{{link}}</span>',
                    dismiss: `<a aria-label="${settings.ariaDismiss}" role=button tabindex="0" class="cc-btn cc-dismiss">{{dismiss}}</a>`,
                    allow: `<a aria-label="${settings.ariaAllow}" role=button tabindex="0"  class="cc-btn cc-allow">{{allow}}</a>`,
                },
                // eslint-disable-next-line object-shorthand,func-names
                onInitialise: function (status) {
                    fireEvent(document, 'cookie-consent-status-change', { status });
                },
                // eslint-disable-next-line object-shorthand,func-names
                onStatusChange: function (status) {
                    fireEvent(document, 'cookie-consent-status-change', { status });
                },
            }, popup => {
                window.consentObject = popup;
            }, err => {
                // eslint-disabel-next-line no-console
                console.error(err);
            });
        }
    }

    for (const revokeButton of document.querySelectorAll('[data-cookie-consent-revoke]')) {
        revokeButton.addEventListener('click', event => {
            event.preventDefault();
            if (window.consentObject) {
                window.consentObject.revokeChoice(true);
                fireEvent(document, 'cookie-consent-status-change', { status: 'disallow' });
            }
        });
    }
};
