<kiss-container class="kiss-margin-small">

    <ul class="kiss-breadcrumbs">
        <li><a href="<?=$this->route('/pages')?>"><?=t('Site tree')?></a></li>
    </ul>

    <vue-view>

        <template>

            <div class="kiss-size-4 kiss-margin-large-bottom">
                <strong v-if="!page._id"><?=t('Create page')?></strong>
                <strong v-if="page._id"><?=t('Edit page')?></strong>
            </div>

            <kiss-row gap="large">

                <div class="kiss-flex-1">

                    <div>

                        <kiss-card class="kiss-overlay-input kiss-flex kiss-flex-middle kiss-width-1-3@m kiss-margin-large">
                            <div class="kiss-margin-small-end">
                                <icon class="kiss-size-1" :class="{'kiss-color-muted': !group, 'kiss-color-primary': group}">{{ !group ? 'dialpad' : 'workspaces' }}</icon>
                            </div>
                            <div>
                                <span class="kiss-text-caption kiss-color-muted">{{ t('Group') }}</span>
                                <div class="kiss-text-capitalize" :class="{'kiss-color-muted': !group, 'kiss-text-bold': group}">{{ group || t('All') }}</div>
                            </div>
                            <select v-model="group">
                                <option :value="null">{{ t('All') }}</option>
                                <option :value="'content'">{{ t('Content') }}</option>
                                <hr>
                                <option :value="'meta'">{{ t('Meta') }}</option>
                            </select>
                        </kiss-card>

                        <app-fieldcontainer class="kiss-margin" v-if="!group">

                            <label><?=t('Title')?></label>

                            <div class="kiss-margin-small" v-for="locale in visibleLocales">
                                <span class="kiss-badge kiss-badge-outline kiss-color-primary kiss-margin-small-bottom" v-if="locales.length > 1">{{ locale.i18n }}</span>

                                <div class="kiss-size-xsmall kiss-color-muted kiss-margin-small" v-if="locale.i18n!='default'"><?=t('Title')?></div>
                                <field-text v-model="page['title'+(locale.i18n!='default' ? '_'+locale.i18n:'')]"></field-text>

                                <div class="kiss-size-xsmall kiss-color-muted kiss-margin-small"><?=t('Slug')?></div>
                                <input type="text" class="kiss-input kiss-input-small" v-model="page['slug'+(locale.i18n!='default' ? '_'+locale.i18n:'')]">
                                <div class="kiss-margin-xsmall kiss-size-xsmall kiss-color-muted" v-if="page['_r'+(locale.i18n!='default' ? '_'+locale.i18n:'')]">
                                    {{ page['_r'+(locale.i18n!='default' ? '_'+locale.i18n:'')] }}
                                </div>
                            </div>

                        </app-fieldcontainer>

                        <app-fieldcontainer class="kiss-margin-large" v-if="!group">

                            <label class="kiss-flex kiss-flex-middle">
                                <div><?=t('SEO')?></div>
                                <a class="kiss-margin-small-start kiss-link-muted kiss-size-4">
                                    <icon class="kiss-display-block" @click="showSEO = !showSEO">{{ showSEO ? 'remove_circle_outline': 'add_circle' }}</icon>
                                </a>
                            </label>
                            <div class="kiss-margin-small animated fadeIn" v-if="showSEO">
                                <div class="kiss-margin-small" v-for="locale in visibleLocales">

                                    <span class="kiss-badge kiss-badge-outline kiss-color-primary" v-if="locales.length > 1">{{ locale.i18n }}</span>

                                    <field-seo class="kiss-margin" v-model="page['seo'+(locale.i18n!='default' ? '_'+locale.i18n:'')]"></field-seo>
                                </div>
                            </div>
                        </app-fieldcontainer>

                        <div class="kiss-margin-large" v-if="fields && (!group || group == 'content')">

                            <div class="kiss-flex kiss-flex-middle kiss-margin" v-if="!group || (globalFields && globalFields.length)">
                                <div class="kiss-size-xsmall kiss-text-bold kiss-text-upper kiss-color-muted kiss-margin-small-end"><?=t('Page content')?></div>
                                <hr class="kiss-flex-1 kiss-margin-remove">
                            </div>

                            <kiss-tabs v-if="globalFields && globalFields.length">
                                <tab class="kiss-margin" caption="<?=t('Content')?>">
                                    <fields-renderer class="kiss-margin" v-model="page.data" :fields="fields" :locales="locales"></fields-renderer>
                                </tab>
                                <tab class="kiss-margin" caption="<?=t('Other')?>">
                                    <fields-renderer class="kiss-margin" v-model="page.data" :fields="globalFields" :locales="locales"></fields-renderer>
                                </tab>
                            </kiss-tabs>

                            <fields-renderer class="kiss-margin" v-model="page.data" :fields="fields" :locales="locales" v-if="!globalFields || !globalFields.length"></fields-renderer>

                        </div>

                        <app-fieldcontainer class="kiss-margin-large" v-if="group == 'meta'">

                            <label><?=t('Meta')?></label>

                            <div class="kiss-margin-small" v-for="locale in visibleLocales">
                                <field-object v-model="page._meta"></field-object>
                            </div>

                        </app-fieldcontainer>

                    </div>

                </div>
                <div class="kiss-width-1-4@m">

                    <kiss-card class="kiss-padding kiss-flex kiss-flex-middle kiss-margin kiss-color-muted" theme="bordered">
                        <div class="kiss-margin-small-end">
                            <kiss-svg class="kiss-margin-auto" src="<?=$this->base($pageType['icon'] ?? 'pages:icon.svg')?>" width="35" height="35" style="color:<?=($this->escape($model['color'] ?? 'inherit'))?>"><canvas width="35" height="35"></canvas></kiss-svg>
                        </div>
                        <div>
                            <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold">{{ t('Type') }}</div>
                            <div class="kiss-size-small">{{ pageType.label || pageType.name }}</div>
                        </div>

                    </kiss-card>

                    <div class="kiss-margin" v-if="page._id">

                        <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold">{{ t('Page') }}</div>

                        <kiss-card class="kiss-margin-small kiss-bgcolor-contrast kiss-padding-small">

                            <div class="kiss-margin-xsmall">
                                <div class="kiss-flex kiss-flex-middle">
                                    <div class="kiss-size-4 kiss-margin-small-end kiss-flex" title="ID"><icon>adjust</icon></div>
                                    <div class="kiss-text-truncate kiss-text-bold kiss-text-monospace kiss-size-small kiss-flex-1">{{ page._id }}</div>
                                    <a :title="t('Copy')" @click="copyID()"><icon>content_copy</icon></a>
                                </div>
                            </div>

                            <div class="kiss-margin-xsmall">
                                <div class="kiss-flex kiss-flex-middle">
                                    <div class="kiss-size-4 kiss-margin-small-end kiss-flex kiss-color-muted" :title="t('Created at')"><icon>more_time</icon></div>
                                    <div class="kiss-text-truncate kiss-size-small kiss-text-monospace kiss-color-muted kiss-flex-1"><app-datetime :datetime="page._created" /></div>
                                    <user-info :user-id="page._cby"></user-info>
                                </div>
                            </div>

                            <div class="kiss-margin-xsmall" v-if="page._created != page._modified">
                                <div class="kiss-flex kiss-flex-middle">
                                    <div class="kiss-size-4 kiss-margin-small-end kiss-flex kiss-color-muted" :title="t('Modified at')"><icon>history</icon></div>
                                    <div class="kiss-text-truncate kiss-size-small kiss-text-monospace kiss-color-muted kiss-flex-1"><app-datetime :datetime="page._modified" /></div>
                                    <user-info :user-id="page._mby"></user-info>
                                </div>
                            </div>

                        </kiss-card>
                    </div>

                    <div class="kiss-margin">

                        <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold">{{ t('State') }}</div>

                        <div class="kiss-margin-small">
                            <button type="button" class="kiss-button kiss-flex kiss-flex-middle kiss-width-expand kiss-align-left" :class="{'kiss-bgcolor-danger': !page._state, 'kiss-bgcolor-success': page._state == 1}" kiss-popout="#page-menu-state">
                                <span class="kiss-flex-1" v-if="page._state == 1">{{ t('Published') }}</span>
                                <span class="kiss-flex-1" v-if="!page._state">{{ t('Unpublished') }}</span>
                                <span class="kiss-flex-1" v-if="page._state == -1">{{ t('Archive') }}</span>
                                <icon>expand_more</icon>
                            </button>
                        </div>

                    </div>

                    <div class="kiss-margin">

                        <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold">{{ t('Translation') }}</div>

                        <kiss-card class="kiss-padding-small kiss-margin-small kiss-text-muted kiss-size-small kiss-color-muted kiss-flex kiss-flex-middle" theme="bordered" v-if="locales.length == 1">
                            <span class="kiss-flex-1 kiss-margin-small-end">{{ t('No locales.') }}</span>
                            <a class="kiss-size-xsmall kiss-text-bolder" href="<?=$this->route('/system/locales')?>">{{ t('Manage') }}</a>
                        </kiss-card>

                        <div class="kiss-margin-small" v-if="locales.length > 1">

                            <kiss-card class="kiss-padding-small kiss-margin-xsmall kiss-text-bolder kiss-flex kiss-flex-middle" :class="{'kiss-color-muted': !loc.visible}" :theme="!loc.visible ? 'bordered':'bordered contrast'" v-for="loc in locales">
                                <div class="kiss-position-relative kiss-flex kiss-flex-middle kiss-flex-1">
                                    <icon class="kiss-margin-small-end" :class="{'kiss-color-primary': loc.visible}">{{ loc.visible ? 'visibility' : 'visibility_off' }}</icon>
                                    <span class="kiss-size-small kiss-flex-1">{{ loc.name }}</span>
                                    <span class="kiss-color-muted kiss-size-xsmall" v-if="loc.i18n == 'default'">{{ t('Default') }}</span>
                                    <a class="kiss-cover" @click="loc.visible = !loc.visible"></a>
                                </div>
                                <a class="kiss-margin-xsmall-start" v-if="loc.isPublic && loc.i18n != 'default'" @click="toggleLocale(loc.i18n)" :aria-label="page._locales[loc.i18n] === false ? t('Locale disabled') : t('Locale enabled')" kiss-tooltip="left">
                                    <icon :class="page._locales[loc.i18n] === false ? 'kiss-color-danger':'kiss-color-success'">circle</icon>
                                </a>
                                <icon class="kiss-color-danger kiss-margin-xsmall-start" v-if="!loc.isPublic" :aria-label="t('Locale disabled')" kiss-tooltip="left">cloud_off</icon>
                            </kiss-card>
                        </div>

                    </div>

                    <div class="kiss-margin kiss-visible@m" v-if="settings.preview && settings.preview.length">

                        <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold kiss-margin-small-bottom">{{ t('Page preview') }}</div>

                        <a class="kiss-button kiss-width-1-1" kiss-popout="#page-preview-links" v-if="settings.preview.length > 1">{{ t('Open preview') }}</a>
                        <a class="kiss-button kiss-width-1-1" @click="showPreviewUri(settings.preview[0].uri)" v-if="settings.preview.length == 1">{{ t('Open preview') }}</a>
                    </div>

                    <kiss-card class="kiss-margin kiss-padding kiss-visible@m" theme="contrast bordered" hover="shadow" v-if="settings.revisions && page._id">

                        <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold kiss-margin-small-bottom">{{ t('Revisions') }}</div>
                        <revisions-widget :oid="page._id" :current="page"></revisions-widget>

                    </kiss-card>

                    <?php $this->trigger('pages.page.aside', [$page, $pageType]) ?>

                </div>

            </kiss-row>

            <kiss-popout id="page-menu-state">
                <kiss-content>
                    <kiss-navlist class="kiss-margin-small">

                        <strong class="kiss-text-bold kiss-text-caption"><?=t('State')?></strong>

                        <ul class="app-list-items kiss-margin-small-top">
                            <li>
                                <a class="kiss-flex kiss-flex-middle" :class="{'kiss-color-muted': page._state != 1, 'kiss-text-bold': page._state == 1}" @click="page._state=1">
                                    <icon class="kiss-margin-small-end">{{ page._state != 1 ? 'radio_button_unchecked' : 'radio_button_checked'}}</icon>
                                    <?=t('Published')?>
                                </a>
                            </li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" :class="{'kiss-color-muted': page._state != 0, 'kiss-text-bold': page._state == 0}" @click="page._state=0">
                                    <icon class="kiss-margin-small-end">{{ page._state != 0 ? 'radio_button_unchecked' : 'radio_button_checked'}}</icon>
                                    <?=t('Unpublished')?>
                                </a>
                            </li>
                            <li v-if="page._id">
                                <a class="kiss-flex kiss-flex-middle" :class="{'kiss-color-muted': page._state != -1, 'kiss-text-bold': page._state == -1}" @click="page._state=-1">
                                    <icon class="kiss-margin-small-end">{{ page._state != -1 ? 'radio_button_unchecked' : 'radio_button_checked'}}</icon>
                                    <?=t('Archive')?>
                                </a>
                            </li>
                        </ul>
                    </kiss-navlist>
                </kiss-content>
            </kiss-popout>

            <kiss-popout id="page-preview-links" v-if="settings.preview && settings.preview.length">
                <kiss-content>
                    <kiss-navlist class="kiss-margin">
                        <ul>
                            <li class="kiss-nav-header"><?=t('Open preview')?></li>
                            <li v-for="preview in settings.preview">
                                <a class="kiss-flex kiss-flex-middle" @click="showPreviewUri(preview.uri)">
                                    <icon class="kiss-margin-small-end">travel_explore</icon>
                                    {{ preview.name }}
                                </a>
                            </li>
                        </ul>
                    </kiss-navlist>
                </kiss-content>
            </kiss-popout>


            <app-actionbar>

                <kiss-container>
                    <div class="kiss-flex kiss-flex-middle">
                        <div class="kiss-button-group" v-if="page._id">
                            <a class="kiss-button" @click="createPage()">
                                <?=t('Create new page')?>
                            </a>
                        </div>
                        <div class="kiss-flex-1"></div>
                        <div class="kiss-button-group">
                            <a class="kiss-button" href="<?=$this->route("/pages")?>">
                                <span v-if="!page._id"><?=t('Cancel')?></span>
                                <span v-if="page._id"><?=t('Close')?></span>
                            </a>
                            <a class="kiss-button kiss-button-primary" @click="save()">
                                <span v-if="!page._id"><?=t('Create page')?></span>
                                <span v-if="page._id"><?=t('Update page')?></span>
                            </a>
                        </div>
                    </div>
                </kiss-container>

            </app-actionbar>


        </template>

        <script type="module">

            export default {

                data() {
                    return {
                        page: <?=json_encode($page)?>,
                        pageType: <?=json_encode($pageType)?>,
                        locales: <?=json_encode($locales)?>,
                        settings: <?=json_encode($settings)?>,
                        group: null,
                        showSEO: false,
                        fields: <?=json_encode($fields)?>,
                        globalFields: <?=json_encode($globalFields)?>,
                        savedItemState: null
                    }
                },

                mounted() {

                    setTimeout(() => {

                        this.savedItemState = JSON.stringify(this.page);

                        window.onbeforeunload = e => {

                            if (this.isModified) {
                                e.preventDefault();
                                e.returnValue = this.t('You have unsaved data! Are you sure you want to leave?');
                            }
                        };

                    }, 1500);
                },

                computed: {
                    visibleLocales() {
                        return this.locales.filter(l => l.visible);
                    },
                    isModified() {
                        return JSON.stringify(this.page) != this.savedItemState;
                    },
                },

                methods: {

                    copyID() {
                        App.utils.copyText(this.page._id, () =>  App.ui.notify('ID copied!'));
                    },

                    save() {

                        if (!this.page.title.trim()) {
                            App.ui.notify('Default page title is missing!', 'error');
                            return;
                        }

                        let validate = {root: this.$el.parentNode};

                        App.trigger('fields-renderer-validate', validate);

                        if (validate.errors) {
                            return;
                        }

                        let isUpdate = this.page._id;

                        this.$request('/pages/save', {page: this.page}).then(page => {

                            Object.assign(this.page, page);

                            if (isUpdate) {
                                App.ui.notify('Page updated!');
                            } else {
                                App.ui.notify('Page created!');
                                this.isUpdate = true;
                            }

                            this.$nextTick(() => this.savedItemState = JSON.stringify(this.page));

                        }).catch(res => {
                            this.saving = false;
                            App.ui.notify(res.error || 'Saving failed!', 'error');
                        });
                    },

                    showPreviewUri(uri) {

                        VueView.ui.offcanvas('system:assets/dialogs/content-preview.js', {
                            uri,
                            fields: this.fields,
                            item: this.page.data,
                            locales: this.locales.length ? this.locales : [],
                            context: {
                                page: this.page
                            },
                            resolver: KISS.utils.debounce((data, update) => {

                                data.context.page.data = data.data;

                                this.$request(`/pages/resolve`, {page: data.context.page, locale: data.locale}).then(page => {
                                    update(Object.assign(data, {data: page.data}));
                                }).catch(error => {

                                });

                            }, 350)
                        }, {
                            update: (item) => {
                                this.page.data = Object.assign(this.page.data, item);
                            }
                        }, {size: 'screen'})
                    },

                    createPage(pid = null) {
                        VueView.ui.offcanvas('pages:assets/dialogs/choose-pagetype.js', {pid});
                    },

                    toggleLocale(locale) {

                        if (this.page._locales[locale] === false) {
                            delete this.page._locales[locale];
                        } else {
                            this.page._locales[locale] = false;
                        }
                    }
                }
            }

        </script>
    </vue-view>
</kiss-container>
