/* Essentials YOOtheme Pro 2.2.16 build 0813.1608; ZOOlanders https://www.zoolanders.com; Copyright (C) Joolanders, SL; http://www.gnu.org/licenses/gpl.html GNU/GPL */

import Vue from 'vue';
import { $, on, removeClass } from 'uikit-util';
import { showPanel } from '@codemirror/view';
import { Facet, StateEffect } from '@codemirror/state';
import TopPanel from './TopPanel.vue';

const addPanelItems = StateEffect.define();
const setPanelStatus = StateEffect.define();

const panelItem = Facet.define({
    combine: (v) => v.flat(),
});

export { setPanelStatus, addPanelItems, panelItem };

function createTopPanel(vm) {
    const wrap = $('<div/>');

    return showPanel.of((view) => {
        const panel = new Vue({
            parent: vm,
            el: wrap.appendChild($('<span/>')),
            extends: TopPanel,
            propsData: {
                items: view.state.facet(panelItem),
            },
        });

        panel.$on('run', (item) => {
            item.run(view);
        });

        return {
            top: true,
            dom: wrap,
        };
    });
}

function createBottomPanel(vm) {
    const wrap = $('<div/>');
    const statusWrap = $('<span class="uk-text-meta uk-margin-small-left"/>');
    const initialContent = 'Start by placing the cursor in the editor';

    statusWrap.innerHTML = initialContent;

    // reset if click outside the editor
    on('body', 'click', (e) => {
        if (!vm.$el.contains(e.target)) {
            statusWrap.innerHTML = initialContent;
        }
    });

    return showPanel.of(() => ({
        dom: wrap.appendChild(statusWrap),
        update(update) {
            const status = update?.transactions?.[0]?.effects
                ?.filter((effect) => effect.is(setPanelStatus))
                ?.map((effect) => effect.value);

            if (status?.length) {
                statusWrap.innerHTML = status[0];
                return;
            }

            if (update.view.hasFocus) {
                removeClass(statusWrap, 'uk-invisible');
                statusWrap.innerHTML = 'Press <span class="uk-text-bold">/</span> to add a Source';
            }
        },
    }));
}

export default function (vm) {
    return [
        panelItem.of([
            {
                name: 'bold',
                icon: 'bold',
                tooltip: 'Bold',
            },
            {
                name: 'italic',
                icon: 'italic',
                tooltip: 'Italic',
            },
        ]),
        createTopPanel(vm),
        // createBottomPanel(vm),
    ];
}
