{% extends "djangocms_frontend/admin/base.html" %}

{% block object-tools %}
    {{ block.super }}

    <script src="https://cdnjs.cloudflare.com/ajax/libs/ace/1.4.14/ace.js" integrity="sha512-6ts6Fu561/yzWvD6uwQp3XVYwiWNpWnZ0hdeQrETqtnQiGjTfOS06W76aUDnq51hl1SxXtJaqy7IsZ3oP/uZEg==" crossorigin="anonymous" referrerpolicy="no-referrer"></script>
    <script>
        django.jQuery(function () {
            // ace editor cannot be attached directly to a textarea
            var textarea = django.jQuery('textarea').css('display', 'none');
            var settings = textarea.data();
            var div = django.jQuery('<div>', {
                position: 'absolute',
                width: '100%',
                style: 'font-size: 14px',
                height: textarea.height(),
                'class': textarea.attr('class'),
            }).insertBefore(textarea);

            // init editor with settings
            var editor = ace.edit(div[0]);
            if (window.matchMedia && window.matchMedia('(prefers-color-scheme: dark)').matches) {
                // dark mode
                editor.setTheme('ace/theme/tomorrow_night');
            }  else {
                editor.setTheme('ace/theme/github');
            }
            editor.getSession().setValue(textarea.val());
            editor.getSession().setMode('ace/mode/python');
            editor.setOptions({
                fontSize: '14px',
                cursorStyle: 'smooth'
            });
            editor.renderer.setScrollMargin(5, 5);

            // send data back to textarea when submitting
            textarea.closest('form').submit(function () {
                textarea.val(editor.getSession().getValue());
            });

            // immediate update while typing inside CKEditor
            editor.getSession().on('change', function () {
                textarea.val(editor.getSession().getValue());
            });
        });
    </script>
{% endblock %}
