{% block style %}
    {% do csp_handler.addSource('img-src', 'data:') %}

    <style{{ attrs().set('data-cto-toolbar').setIfExists('nonce', csp_handler.getNonce('style-src')) }}>
        :host {
            .cto-toolbar {
                font-family: -apple-system, system-ui, "Segoe UI", Roboto, Oxygen-Sans, Ubuntu, Cantarell, "Helvetica Neue", sans-serif;
                font-weight: 400;
                font-size: 14px;
                line-height: 1;
                color: #444;
            }

            @media (min-resolution: 2dppx) {
                .cto-toolbar {
                    font-weight: 300;
                    color: #222;
                }
            }

            .cto-toolbar__open {
                width: 36px;
                height: 36px;
                position: fixed;
                right: 0;
                top: 0;
                background: #222;
                border-radius: 0 0 0 4px;
                display: flex;
                align-items: center;
                justify-content: center;
                z-index: 99999;
                cursor: pointer;
            }

            .cto-toolbar--visible .cto-toolbar__open {
                display: none;
            }

            .cto-toolbar__open a {
                opacity: .7;
            }

            .cto-toolbar__inside {
                display: grid;
                grid-template: auto / 1fr auto;
                width: 100%;
                background: #f2f2f2;
                position: fixed;
                left: 0;
                top: 0;
                z-index: 99999;
                border-bottom: 1px solid #ccc;
            }

            .cto-toolbar--hidden .cto-toolbar__inside {
                display: none;
            }

            .cto-toolbar__close {
                border: none;
                border-left: 1px solid #ccc;
                padding: 3px 8px;
                background: none;
                display: flex;
                align-items: center;
                cursor: pointer;
            }

            .cto-toolbar__close:hover {
                color: #666;
                background: rgba(0, 0, 0, 0.03);
            }

            .cto-toolbar__close .color-scheme--dark {
                display: none;
            }

            .cto-toolbar__clear {
                height: 40px;
                display: none;
            }

            .cto-toolbar--visible .cto-toolbar__clear {
                display: block;
            }

            .cto-toolbar input, .cto-toolbar select, .cto-toolbar button {
                font: inherit;
                color: inherit;
                line-height: 18px;
            }

            .cto-toolbar.ajax-loading .formbody {
                pointer-events: none;
                opacity: .5;
            }

            .cto-toolbar .formbody {
                display: flex;
                align-items: baseline;
                justify-content: flex-end;
                padding: 5px 0;
                margin: 0 .5em 0 0;
                background: none;
            }

            .cto-toolbar .formbody > div {
                display: flex;
                align-items: baseline;
                margin-left: 1em;
            }

            @media only screen and (max-width: 676px) {
                .cto-toolbar .formbody {
                    display: block;
                    text-align: right;
                }

                .cto-toolbar .formbody > div {
                    justify-content: flex-end;
                    padding: 3px 0;
                }
            }

            .cto-toolbar label {
                width: auto;
                margin: 0 3px 0 0;
            }

            .cto-toolbar input[type="text"] {
                margin: 0;
                width: auto;
                box-sizing: border-box;
                padding: 4px 6px 5px;
                border: 1px solid #aaa;
                border-radius: 2px;
                background-color: #fff;
                -moz-appearance: none;
                -webkit-appearance: none;
            }

            .cto-toolbar .tl_select {
                margin: 0;
                width: auto;
                box-sizing: border-box;
                border: 1px solid #aaa;
                padding: 4px 22px 5px 6px;
                border-radius: 2px;
                background: #fff url({{ asset('system/themes/flexible/icons/down.svg') }}) right -16px center no-repeat;
                background-origin: content-box;
                cursor: pointer;
                text-transform: none;
                -moz-appearance: none;
                -webkit-appearance: none;
            }

            .cto-toolbar .tl_submit {
                margin: 0 0 0 6px;
                padding: 4px 10px 5px;
                border: 1px solid #aaa;
                border-radius: 2px;
                box-sizing: border-box;
                cursor: pointer;
                background: #eee;
                transition: background .2s ease;
                font-family: inherit;
                font-size: inherit;
                color: inherit;
                line-height: 18px;
                text-decoration: none;
            }

            @media only screen and (max-width: 676px) {
                .cto-toolbar .tl_submit {
                    margin-top: 3px;
                    margin-bottom: 1px;
                }
            }

            .cto-toolbar .tl_submit:hover {
                color: inherit;
                background-color: #f6f6f6;
            }

            .cto-toolbar .tl_submit:active {
                color: #aaa;
            }

            .cto-toolbar .badge-title {
                align-self: center;
                margin: 0 auto 0 9px;
                border-radius: 8px;
                padding: 2px 5px;
                background: #0f1c26;
                color: #fff;
                font-size: .75rem;
                font-weight: 600;
            }

            @media (min-resolution: 2dppx) {
                .cto-toolbar .badge-title {
                    font-weight: 500;
                }
            }

            @media only screen and (max-width: 676px) {
                .cto-toolbar .badge-title {
                    float: left;
                    margin: 3px auto 0 8px;
                }
            }
        }
    </style>
{% endblock %}

{% block script %}
    <script{{ attrs().setIfExists('nonce', csp_handler.getNonce('script-src')) }}>
        (function () {
            const toolbarWrapper = document.createElement('cto-toolbar');
            document.querySelector('body').prepend(toolbarWrapper);
            toolbarWrapper.attachShadow({mode: 'open'});

            toolbarWrapper.shadowRoot.appendChild(document.querySelector('style[data-cto-toolbar]'));

            const toolbar = document.createElement('div');
            toolbar.classList.add('cto-toolbar');
            toolbarWrapper.shadowRoot.appendChild(toolbar);

            function request(method, uri, body, callback, addClass = true) {
                body = body || null;
                const request = new XMLHttpRequest();
                request.open(method, uri, true);
                request.setRequestHeader('X-Requested-With', 'XMLHttpRequest');

                if (body instanceof URLSearchParams) {
                    request.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded;charset=UTF-8');
                }

                if (addClass) {
                    toolbar.classList.add('ajax-loading');
                }

                request.onload = function () {
                    toolbar.classList.remove('ajax-loading');
                    callback.apply(this);
                };

                request.send(body)
            }

            // Initialize toolbar
            if ('hidden' === localStorage.getItem('contao/previewBar/displayState')) {
                toolbar.classList.add('cto-toolbar--hidden');
            } else {
                toolbar.classList.add('cto-toolbar--visible');
            }

            // Fetch toolbar
            request('GET', '{{ action }}', null, function () {
                if (200 === this.status) {
                    toolbar.innerHTML = this.responseText;

                    toolbar.querySelectorAll('.cto-toolbar__share-url').forEach((link) => {
                        link.addEventListener('click', (e) => {
                            e.preventDefault();
                            window.open(link.href+'&url='+location.href);
                            return false;
                        });
                    })

                    const event = new Event('cto-toolbar-loaded');
                    toolbar.dispatchEvent(event);
                } else {
                    toolbar.innerHTML = '<p>Error while loading the preview bar.</p>';
                }
            });

            // Js for the authenticator
            toolbar.addEventListener("cto-toolbar-loaded", function () {
                const form = toolbar.querySelector('input[name="FORM_SUBMIT"][value="tl_switch"]').form;

                if (!form) {
                    return;
                }

                const userField = form.querySelector('input[name="user"]');

                form.addEventListener('submit', function (e) {
                    e.preventDefault();
                    const formData = new FormData(form);

                    request('POST', form.action, formData, function () {
                        if (422 !== this.status) {
                            location.reload();
                        } else if (userField) {
                            userField.setCustomValidity(this.responseText || 'An unknown error occurred.');
                            userField.reportValidity();
                        }
                    });
                });

                if (userField) {
                    // Reset custom validity message
                    form.querySelector('[type="submit"]').addEventListener('click', function () {
                        userField.setCustomValidity('');
                    });

                    if (document.createElement('datalist') && window.HTMLDataListElement) {
                        let timer;

                        userField.addEventListener('input', function () {
                            userField.setCustomValidity('');

                            if (userField.value.length < 2) {
                                return;
                            }

                            if (timer) {
                                clearTimeout(timer);
                            }

                            timer = setTimeout(function () {
                                const body = {
                                    FORM_SUBMIT: 'datalist_members',
                                    REQUEST_TOKEN: form.querySelector('input[name="REQUEST_TOKEN"]').value,
                                    value: userField.value
                                };

                                const userList = form.querySelector('datalist[id="userlist"]');

                                request('POST', form.action, new URLSearchParams(body), function () {
                                    userList.innerHTML = '';
                                    JSON.parse(this.response).forEach(item => {
                                        const option = document.createElement('option');
                                        option.value = item;
                                        userList.appendChild(option);
                                    });
                                }, false);
                            }, 300);
                        });
                    }
                }

                // Collapse toolbar
                Array.from([toolbar.querySelector('.cto-toolbar__close'), toolbar.querySelector('.cto-toolbar__open')]).forEach(toggle => {
                    toggle.addEventListener('click', function (event) {
                        event.preventDefault();

                        const toolbar = event.currentTarget.closest('.cto-toolbar');
                        if (toolbar.classList.contains('cto-toolbar--hidden')) {
                            localStorage.setItem('contao/previewBar/displayState', 'visible');
                            toolbar.classList.replace('cto-toolbar--hidden', 'cto-toolbar--visible');
                        } else {
                            localStorage.setItem('contao/previewBar/displayState', 'hidden');
                            toolbar.classList.replace('cto-toolbar--visible', 'cto-toolbar--hidden');
                        }

                    });
                });
            });

            // Copy published link to clipboard
            toolbar.addEventListener('cto-toolbar-loaded', function() {
                const copyButton = toolbar.querySelector('#copyPublishedPath');

                if (!copyButton) {
                    return;
                }

                copyButton.addEventListener('click', function(event) {
                    const href = window.location.href.replace('{{ preview_script|escape('js') }}', '');

                    function clipboardFallback() {
                        const input = document.createElement('input');
                        input.value = href;
                        document.body.appendChild(input);
                        input.select();
                        input.setSelectionRange(0, 99999);
                        document.execCommand('copy');
                        document.body.removeChild(input);
                    }

                    event.preventDefault();

                    if (navigator.clipboard && navigator.clipboard.writeText) {
                        navigator.clipboard.writeText(href).catch(clipboardFallback);
                    } else {
                        clipboardFallback();
                    }
                });
            });
        })();
    </script>
{% endblock %}
