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

    <ul class="kiss-breadcrumbs">
        <li><a href="<?= $this->route('/lokalize/projects') ?>"><?= t('Lokalize') ?></a></li>
    </ul>

    <div class="kiss-flex kiss-flex-middle kiss-margin-bottom" gap="small">

        <div>
            <kiss-svg class="kiss-margin-auto" src="<?= $this->base(isset($project['icon']) && $project['icon'] ? $project['icon'] : 'lokalize:icon.svg') ?>" width="30" height="30" style="color:<?= ($this->escape($project['color'] ?? 'inherit')) ?>"><canvas width="30" height="30"></canvas></kiss-svg>
        </div>
        <div class="kiss-size-4 kiss-text-bold"><?= $this->escape($project['label'] ? $project['label'] : $project['name']) ?></div>
        <a class="kiss-size-large kiss-margin-small-end" href kiss-popout="#lokalize-project-menu-actions"><icon>more_horiz</icon></a>
    </div>

    <vue-view>
        <template>

            <div class="animated fadeIn kiss-height-30vh kiss-flex kiss-flex-middle kiss-flex-center kiss-align-center kiss-color-muted kiss-margin-large-top" v-if="!project.keys.length">
                <div>
                    <kiss-svg src="<?= $this->base('lokalize:icon.svg') ?>" width="40" height="40"></kiss-svg>
                    <p class="kiss-size-large kiss-margin-top"><?= t('No keys defined') ?></p>
                </div>
            </div>

            <kiss-row gap="large" v-if="project.keys.length">
                <div class="kiss-flex-1">

                    <div class="kiss-margin-large">
                        <input type="text" class="kiss-input" :placeholder="t('Filter keys...')" v-model="filter">
                    </div>

                    <app-scrollcontainer mode="boundary-include" boundary="#lokalize-actionbar">
                        <div class="animated fadeIn kiss-overflow-y-auto">
                            <app-fieldcontainer v-for="key in visibleKeys">
                                <kiss-card theme="contrast">
                                    <kiss-row class="kiss-margin-small-top kiss-margin-small-bottom" match="true">
                                        <div class="kiss-width-1-3@l">
                                            <div class="kiss-bgcolor-contrast kiss-padding-small">
                                                <div class="kiss-flex kiss-flex-middle kiss-text-bold">
                                                    <div class="kiss-flex-1 kiss-size-small kiss-text-truncate kiss-margin-small-end" :title="key.name">
                                                        {{ key.name }}
                                                    </div>
                                                    <a class="kiss-margin-xsmall-start" @click="toggleKeyActions(key)">
                                                        <icon>more_horiz</icon>
                                                    </a>
                                                </div>
                                                <div class="kiss-size-xsmall kiss-color-muted">{{ key.info }}</div>
                                            </div>
                                        </div>
                                        <div class="kiss-flex-1 kiss-padding-small">

                                            <ul class="app-list-items">
                                                <li v-for="loc in locales">

                                                    <div class="kiss-flex kiss-margin-small" :class="{'kiss-flex-middle': editItem.path != `${key.name}.${loc.name}`}">
                                                        <div class="kiss-width-1-4 kiss-width-1-5@xl kiss-size-xsmall kiss-text-upper kiss-text-truncate kiss-margin-xsmall-top" :class="editItem.path == `${key.name}.${loc.name}` ? 'kiss-color-primary kiss-text-bold':'kiss-color-muted'">
                                                            <icon class="kiss-margin-xsmall-end">language</icon> {{ loc.name || loc.i18n}}
                                                        </div>
                                                        <div class="kiss-flex-1">
                                                            <div class="kiss-flex">
                                                                <div class="kiss-margin-small-end" v-if="key.plural" style="min-width:50px"><span class="kiss-badge kiss-width-1-1 kiss-disabled"><?= t('One') ?></span></div>
                                                                <div class="kiss-flex-1">
                                                                    <div class="kiss-position-relative" v-if="editItem.path != `${key.name}.${loc.name}`">
                                                                        <div v-if="!project.values[loc.i18n][key.name].value"><span class="kiss-badge kiss-badge-outline kiss-color-danger">{{ t('Empty') }}</span></div>
                                                                        <div v-if="project.values[loc.i18n][key.name].value && !project.values[loc.i18n][key.name].value.trim()"><span class="kiss-badge kiss-badge-outline kiss-color-muted">{{ t('Non visible') }}</span></div>
                                                                        <div class="kiss-size-small">{{ project.values[loc.i18n][key.name].value }}</div>
                                                                        <a class="kiss-cover" @click="setEditItem(key, loc)"></a>
                                                                    </div>
                                                                    <div v-if="editItem.path == `${key.name}.${loc.name}`">
                                                                        <textarea class="kiss-input kiss-textarea key-value-text" v-model="editItem.value"></textarea>
                                                                        <div class="kiss-button-group kiss-margin-small-top">
                                                                            <button type="button" class="kiss-button kiss-button-small" @click="editItem = {}">{{ t('Cancel') }}</button>
                                                                            <button type="button" class="kiss-button kiss-button-primary kiss-button-small" @click="updateItem()">{{ t('Save') }}</button>
                                                                        </div>
                                                                        <div class="kiss-padding-small kiss-bgcolor-contrast kiss-margin-small-top kiss-size-small animated fadeIn" v-if="editItem.translation">
                                                                            <div class="kiss-text-bold kiss-size-xsmall">{{ t('Suggestion') }}</div>
                                                                            <div class="kiss-margin-small">{{ editItem.translation }}</div>
                                                                            <a class="kiss-size-xsmall" @click="editItem.value = editItem.translation">{{ t('Choose suggestion') }}</a>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                            <div class="kiss-flex kiss-margin-small-top" v-if="key.plural">
                                                                <div class="kiss-margin-small-end" style="min-width:50px"><span class="kiss-badge kiss-width-1-1 kiss-disabled"><?= t('Other') ?></span></div>
                                                                <div class="kiss-flex-1">
                                                                    <div class="kiss-position-relative" v-if="editItem.path != `${key.name}.${loc.name}.plural`">
                                                                        <div v-if="!project.values[loc.i18n][key.name].plural"><span class="kiss-badge kiss-badge-outline kiss-color-danger">{{ t('Empty') }}</span></div>
                                                                        <div class="kiss-size-small">{{ project.values[loc.i18n][key.name].plural }}</div>
                                                                        <a class="kiss-cover" @click="setEditItem(key, loc, true)"></a>
                                                                    </div>
                                                                    <div v-if="editItem.path == `${key.name}.${loc.name}.plural`">
                                                                        <textarea class="kiss-input kiss-textarea key-value-text" v-model="editItem.value"></textarea>
                                                                        <div class="kiss-button-group kiss-margin-small-top">
                                                                            <button type="button" class="kiss-button kiss-button-small" @click="editItem = {}">{{ t('Cancel') }}</button>
                                                                            <button type="button" class="kiss-button kiss-button-primary kiss-button-small" @click="updateItem()">{{ t('Save') }}</button>
                                                                        </div>
                                                                        <div class="kiss-padding-small kiss-bgcolor-contrast kiss-margin-small-top kiss-size-small animated fadeIn" v-if="editItem.translation">
                                                                            <div class="kiss-text-bold kiss-size-xsmall">{{ t('Suggestion') }}</div>
                                                                            <div class="kiss-margin-small">{{ editItem.translation }}</div>
                                                                            <a class="kiss-size-xsmall" @click="editItem.value = editItem.translation">{{ t('Choose suggestion') }}</a>
                                                                        </div>
                                                                    </div>
                                                                </div>
                                                            </div>
                                                        </div>
                                                    </div>
                                                </li>
                                            </ul>

                                        </div>
                                    </kiss-row>
                                </kiss-card>
                            </app-fieldcontainer>
                        </div>
                    </app-scrollcontainer>

                </div>
                <div class="kiss-width-1-4@m kiss-width-1-5@xl">
                    <app-scrollcontainer mode="boundary" boundary="#lokalize-actionbar">

                        <div class="kiss-margin">

                            <div class="kiss-text-caption kiss-size-xsmall kiss-text-bold">{{ t('Project') }}</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 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">{{ (new Date(project._created * 1000).toLocaleString()) }}</div>
                                        <user-info :user-id="project._cby"></user-info>
                                    </div>
                                </div>

                                <div class="kiss-margin-xsmall" v-if="project._created != project._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">{{ (new Date(project._modified * 1000).toLocaleString()) }}</div>
                                        <user-info :user-id="project._mby"></user-info>
                                    </div>
                                </div>

                            </kiss-card>
                        </div>

                        <div class="kiss-margin">

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

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

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

                                <kiss-card class="kiss-position-relative kiss-padding-small kiss-margin-small kiss-text-bolder kiss-flex kiss-flex-middle" :class="{'kiss-color-muted': loc.visible === false}" :theme="loc.visible === false ? 'bordered':'bordered contrast'" v-for="(loc, idx) in project.locales">
                                    <icon class="kiss-margin-small-end" :class="{'kiss-color-primary': loc.visible !== false}">{{ loc.visible !== false ? 'visibility' : 'visibility_off' }}</icon>
                                    <span class="kiss-size-small kiss-flex-1">{{ loc.name || loc.i18n }}</span>
                                    <a class="kiss-cover" @click="loc.visible = (loc.visible === false ? true : false)"></a>
                                </kiss-card>
                            </div>

                        </div>

                        <div class="kiss-margin" v-if="project.status._overall">

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

                            <div class="kiss-size-3 kiss-margin-xsmall-top kiss-margin-small-bottom" :class="{'kiss-color-success': project.status._overall == 100 }">{{ project.status._overall }}%</div>

                            <div class="kiss-flex kiss-child-width-1-2 kiss-size-xsmall kiss-color-muted kiss-margin-xsmall" v-for="(loc, idx) in project.locales">
                                <div>
                                    <icon>language</icon> {{ loc.name || loc.i18n }}
                                </div>
                                <div class="kiss-align-right">{{ project.status[loc.i18n] }}%</div>
                            </div>
                        </div>
                    </app-scrollcontainer>
                </div>
            </kiss-row>

            <app-actionbar id="lokalize-actionbar" space="false">

                <kiss-container>
                    <div class="kiss-flex kiss-flex-middle">

                        <div class="kiss-flex kiss-flex-middle kiss-margin-large-end" :class="{'kiss-color-muted': filter}">
                            <div>
                                <div class="kiss-size-xsmall kiss-text-caption"><?= t('Keys') ?></div>
                                <div class="kiss-size-bold">{{ project.keys.length }}</div>
                            </div>
                        </div>

                        <div class="kiss-flex kiss-flex-middle kiss-margin-large-end" v-if="filter">
                            <div>
                                <div class="kiss-size-xsmall kiss-text-caption"><?= t('Filtered keys') ?></div>
                                <div class="kiss-size-bold">{{ filteredKeys.length }}</div>
                            </div>
                        </div>

                        <div class="kiss-margin-end">
                            <a class="kiss-button" @click="addKey()"><?= t('Add key') ?></a>
                        </div>

                        <div class="kiss-flex kiss-flex-middle kiss-margin-end" v-if="pages > 1">
                            <app-pagination>
                                <a v-if="(page - 1) >= 1" @click="page -= 1">{{ t('Previous') }}</a>
                                <div class="kiss-margin-small-start kiss-overlay-input">
                                    <strong>{{ page }} &mdash; {{pages}}</strong>
                                    <select v-model="page">
                                        <option v-for="p in pages" :value="p">{{ p }}</option>
                                    </select>
                                </div>
                                <a class="kiss-margin-small-start" v-if="(page + 1) <= pages" @click="page += 1">{{ t('Next') }}</a>
                            </app-pagination>
                        </div>

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

                        <div>
                            <div class="kiss-button-group">
                                <a class="kiss-button" href="<?= $this->route('/lokalize/projects') ?>"><?= t('Close') ?></a>
                                <a class="kiss-button kiss-button-primary" @click="save()"><?= t('Save project') ?></a>
                            </div>
                        </div>
                    </div>
                </kiss-container>

            </app-actionbar>

            <kiss-popout :open="actionKey && 'true'" @popoutclose="toggleKeyActions(null)">
                <kiss-content>
                    <kiss-navlist v-if="actionKey">
                        <ul>
                            <li class="kiss-nav-header">{{ t('Key actions') }}</li>
                            <li class="kiss-color-muted kiss-margin-small-bottom"><span>{{ actionKey.name }}</span></li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" @click="editKey(actionKey)">
                                    <icon class="kiss-margin-small-end">create</icon>
                                    <?= t('Edit') ?>
                                </a>
                            </li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" @click="duplicateKey(actionKey)">
                                    <icon class="kiss-margin-small-end">control_point_duplicate</icon>
                                    <?= t('Duplicate') ?>
                                </a>
                            </li>
                            <li class="kiss-nav-divider"></li>
                            <li>
                                <a class="kiss-color-danger kiss-flex kiss-flex-middle" @click="removeKey(actionKey)">
                                    <icon class="kiss-margin-small-end">delete</icon>
                                    <?= t('Delete') ?>
                                </a>
                            </li>
                        </ul>
                    </kiss-navlist>
                </kiss-content>
            </kiss-popout>

            <kiss-popout id="lokalize-project-menu-actions">
                <kiss-content>
                    <kiss-navlist class="kiss-margin">
                        <ul>
                            <li class="kiss-nav-header"><?=t('Project')?></li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle" :href="$routeUrl(`/lokalize/projects/edit/${project.name}`)">
                                    <icon class="kiss-margin-small-end">create</icon>
                                    <?=t('Edit')?>
                                </a>
                            </li>
                            <li class="kiss-nav-header" v-if="canTranslate"><?=t('Actions')?></li>
                            <li v-if="canTranslate">
                                <a class="kiss-flex kiss-flex-middle" @click.prevent="openAutoTranslate()">
                                    <icon class="kiss-margin-small-end">translate</icon>
                                    <?=t('Auto Translate')?>
                                </a>
                            </li>
                            <li class="kiss-nav-header"><?=t('Keys')?></li>
                            <li :class="{'kiss-disabled': !project.keys.length}">
                                <a class="kiss-flex kiss-flex-middle" @click.prevent="exportKeys()">
                                    <icon class="kiss-margin-small-end">download</icon>
                                    <?=t('Export')?>
                                </a>
                            </li>
                            <li>
                                <a class="kiss-flex kiss-flex-middle kiss-overlay-input">
                                    <icon class="kiss-margin-small-end">upload</icon>
                                    <?=t('Import')?>
                                    <input class="kiss-cursor-pointer" type="file" accept=”.csv” @change="handleImportFile" v-if="!importing">
                                </a>
                            </li>
                        </ul>
                    </kiss-navlist>
                </kiss-content>
            </kiss-popout>
        </template>

        <script type="module">

            import {parseCSV} from 'module-lokalize/assets/js/csv.js?nc=<?=APP_VERSION?>';

            export default {
                data() {

                    return {
                        project: <?= json_encode($project) ?>,
                        canTranslate: <?= json_encode($canTranslate) ?>,
                        saving: false,
                        importing: false,
                        filter: '',
                        actionKey: null,
                        editItem: {},

                        pages: 1,
                        page: 1,
                        limit: 100,

                        isModified: false,

                    }
                },

                computed: {

                    locales() {
                        return this.project.locales.filter(l => l.visible !== false);
                    },

                    visibleKeys() {

                        return this.filteredKeys.slice((this.page - 1) * this.limit, this.page * this.limit);
                    },

                    filteredKeys() {

                        let filtered = [];

                        if (!this.filter) {
                            filtered = this.project.keys.sort((a, b) => (a.name > b.name) ? 1 : -1);
                        } else {

                            let filter = this.filter.toLowerCase();

                            filtered = this.project.keys.filter(key => {

                                if (key.name.toLowerCase().indexOf(filter) != -1) {
                                    return true;
                                }

                                for (let locale of this.project.locales) {

                                    if (this.project.values[locale.i18n][key.name].value && this.project.values[locale.i18n][key.name].value.toLowerCase().indexOf(filter) != -1) {
                                        return true;
                                    }
                                    if (this.project.values[locale.i18n][key.name].plural && this.project.values[locale.i18n][key.name].plural.toLowerCase().indexOf(filter) != -1) {
                                        return true;
                                    }
                                }

                                return false;

                            }).sort((a, b) => (a.name > b.name) ? 1 : -1);
                        }

                        this.page = 1;
                        this.pages = Math.ceil(filtered.length / this.limit);

                        return filtered;
                    }
                },

                created() {

                    window.onbeforeunload = e => {

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

                watch: {

                    filter() {
                        console.log('filter changed');
                        this.resetKeysScoller();
                    },
                    page() {
                        this.resetKeysScoller();
                    },

                    project: {
                        handler() {
                            //this.isModified = true;
                        },
                        deep: true
                    }
                },

                methods: {

                    addKey() {

                        let key = {
                            name: '',
                            info: '',
                            tags: [],
                        };

                        VueView.ui.modal('lokalize:assets/dialog/key.js', {
                            lkey: key,
                            keys: this.project.keys
                        }, {
                            save: (key) => {
                                this.project.keys.push(key);

                                this.project.locales.forEach(locale => {
                                    this.project.values[locale.i18n][key.name] = {
                                        value: null
                                    };

                                    if (key.plural) {
                                        this.project.values[locale.i18n][key.name].plural = null;
                                    }
                                });

                                this.filter = key.name;
                            }
                        });
                    },

                    editKey(key) {

                        VueView.ui.modal('lokalize:assets/dialog/key.js', {
                            lkey: key,
                            keys: this.project.keys,
                            skey: key
                        }, {
                            save: (eKey) => {

                                // did keyname change?
                                if (key.name != eKey.name) {

                                    this.project.locales.forEach(locale => {
                                        this.project.values[locale.i18n][eKey.name] = this.project.values[locale.i18n][key.name];
                                        delete this.project.values[locale.i18n][key.name]
                                    });
                                }

                                Object.assign(key, eKey);
                            }
                        });
                    },

                    removeKey(key) {

                        // this.project.keys.splice(this.project.keys.indexOf(key), 1);
                        this.project.keys = this.project.keys.filter(k => k.name !== key.name);

                        this.project.locales.forEach(locale => {
                            if (this.project.values[locale.i18n] && this.project.values[locale.i18n][key.name]) {
                                delete this.project.values[locale.i18n][key.name];
                            }
                        });
                    },

                    duplicateKey(key) {

                        let dKey = JSON.parse(JSON.stringify(key));

                        dKey.name = `${dKey.name}.copy`;

                        VueView.ui.modal('lokalize:assets/dialog/key.js', {
                            lkey: dKey,
                            keys: this.project.keys
                        }, {
                            save: (newKey) => {

                                this.project.keys.push(newKey);

                                this.project.locales.forEach(locale => {
                                    this.project.values[locale.i18n][newKey.name] = JSON.parse(JSON.stringify(this.project.values[locale.i18n][key.name] || { value: null }));
                                });
                            }
                        });
                    },

                    setEditItem(key, locale, plural = false) {

                        let vkey = plural ? 'plural' : 'value';
                        let path = plural ? `${key.name}.${locale.name}.plural` : `${key.name}.${locale.name}`;

                        this.editItem = {
                            key,
                            locale,
                            plural,
                            path,
                            value: this.project.values[locale.i18n][key.name][vkey],
                            translation: null
                        };

                        let translationText = false;

                        this.project.locales.forEach(l => {
                            if (translationText || l === locale) return;
                            if (this.project.values[l.i18n][key.name][vkey]) {
                                translationText = this.project.values[l.i18n][key.name][vkey];
                            }
                        });

                        if (translationText && this.canTranslate) {
                            // request for translation
                            this.$request('/lokalize/utils/translate', {
                                text: translationText,
                                to: locale.i18n
                            }).then(rsp => {

                                if (rsp.error) {
                                    console.log(rsp.error);
                                    return;
                                }

                                if (rsp.translation && !rsp.translation.error) {
                                    this.editItem.translation = rsp.translation
                                }
                            });
                        }

                        setTimeout(() => document.querySelector('.key-value-text').focus(), 150);

                    },

                    openAutoTranslate() {

                        let options = this.project.locales.map(l => {
                            return {value: l.i18n, label: l.name || l.i18n};
                        });

                        VueView.ui.modal('lokalize:assets/dialog/translate.js', {
                            locales: options
                        }, {
                            translate: (data) => {
                                console.log('Auto Translate Triggered', data);
                                this.batchTranslate(data.locale);
                            }
                        });
                    },

                    batchTranslate(targetLocale) {

                        let sourceLocale = this.project.locales[0].i18n; // Assume first is source
                        if (sourceLocale == targetLocale && this.project.locales.length > 1) {
                            sourceLocale = this.project.locales[1].i18n;
                        }

                        let items = [];

                        this.project.keys.forEach(key => {

                            let target = this.project.values[targetLocale][key.name];
                            let source = this.project.values[sourceLocale][key.name];

                            // Check singular value
                            if (!target.value || !target.value.trim()) {
                                if (source.value && source.value.trim()) {
                                    items.push({
                                        text: source.value,
                                        context: key.name,
                                        key: key.name,
                                        field: 'value'
                                    });
                                }
                            }

                            // Check plural value
                            if (key.plural) {
                                if (!target.plural || !target.plural.trim()) {
                                    if (source.plural && source.plural.trim()) {
                                        items.push({
                                            text: source.plural,
                                            context: key.name + ' (plural)',
                                            key: key.name,
                                            field: 'plural'
                                        });
                                    }
                                }
                            }
                        });

                        if (!items.length) {
                            App.ui.notify(this.t('No missing keys found'));
                            return;
                        }

                        App.ui.notify(this.t('Translating keys...') + ` (${items.length})`);
                        this.saving = true;

                        this.$request('/lokalize/utils/translateBatch', {
                            items: items,
                            to: targetLocale
                        }).then(rsp => {

                            this.saving = false;

                            if (rsp.translations) {

                                items.forEach((item, idx) => {
                                    if (rsp.translations[idx]) {
                                         this.project.values[targetLocale][item.key][item.field] = rsp.translations[idx];
                                    }
                                });

                                App.ui.notify(this.t('Translation complete!'));
                                // Trigger check
                                this.project = Object.assign({}, this.project);
                            }

                        }).catch(e => {
                            this.saving = false;
                            App.ui.notify(e.message || 'Error', 'error');
                        });
                    },

                    updateItem() {

                        if (this.editItem.plural) {
                            this.project.values[this.editItem.locale.i18n][this.editItem.key.name].plural = this.editItem.value;
                        } else {
                            this.project.values[this.editItem.locale.i18n][this.editItem.key.name].value = this.editItem.value;
                        }

                        this.editItem = {};
                    },

                    save() {

                        this.$request(`/lokalize/projects/update/${this.project.name}`, {
                            keys: this.project.keys,
                            values: this.project.values
                        }).then(project => {

                            this.project = Object.assign(this.project, project);
                            this.saving = false;

                            App.ui.notify('Project updated!');

                            this.$nextTick(() => this.isModified = false);

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

                    },

                    toggleKeyActions(key) {

                        if (!key) {
                            setTimeout(() => this.actionKey = null, 300);
                            return;
                        }

                        this.actionKey = key;
                    },

                    resetKeysScoller() {
                        (this.$el.parentNode.querySelector('app-scrollcontainer') || {
                            scrollTo() {}
                        }).scrollTo(0, 0);
                        window.scrollTo(0, 0);
                    },

                    exportKeys() {

                        // Convert JSON to array of rows
                        const rows = [];

                        // Add header
                        rows.push(['key', 'locale', 'value', 'plural']);

                        // Process data and create rows
                        Object.entries(this.project.values).forEach(([locale, translations]) => {

                            Object.entries(translations).forEach(([key, content]) => {
                                rows.push([
                                    key,
                                    locale,
                                    content.value || '',
                                    content.plural || ''
                                ]);
                            });
                        });

                        // Sort rows by key (skip header row)
                        const header = rows[0];
                        const sortedData = rows.slice(1).sort((a, b) => a[0].localeCompare(b[0]));
                        const sortedRows = [header, ...sortedData];

                        // Convert to CSV string
                        const csvContent = sortedRows.map(row =>
                            row.map(cell => `"${String(cell).replace(/"/g, '""')}"`).join(',')
                        ).join('\n');

                        // Create Blob and download link
                        const blob = new Blob([csvContent], {type: 'text/csv;charset=utf-8;'});
                        const link = document.createElement('a');
                        const url = window.URL.createObjectURL(blob);
                        link.setAttribute('href', url);
                        link.setAttribute('download', `${this.project.name}.lokalize.csv`);

                        // Append link, trigger download, and cleanup
                        document.body.appendChild(link);
                        link.click();
                        document.body.removeChild(link);
                        window.URL.revokeObjectURL(url);
                    },

                    importKeys(csvContent) {

                        const locales = this.project.locales.map(l => l.i18n);
                        const keys = this.project.keys.map(k => k.name);

                        // Parse CSV content
                        const rows = parseCSV(csvContent);

                        // Remove header row
                        const [headerRow, ...dataRows] = rows;

                        // Define expected headers and create mapping
                        const expectedHeaders = ['locale', 'key', 'value', 'plural'];
                        const headerMapping = {};

                        // Validate headers and create mapping
                        try {
                            expectedHeaders.forEach(expectedHeader => {
                                const index = headerRow.findIndex(h => h.toLowerCase() === expectedHeader.toLowerCase());
                                if (index === -1) {
                                    throw new Error(`Required column '${expectedHeader}' not found in CSV header`);
                                }
                                headerMapping[expectedHeader] = index;
                            });
                        } catch (e) {
                            App.ui.notify(e.message, 'error');
                            return false;
                        }

                        // Process each row
                        dataRows.forEach(row => {

                            const locale = row[headerMapping.locale];
                            const key = row[headerMapping.key];
                            const value = row[headerMapping.value];
                            const plural = row[headerMapping.plural];

                            if (!locales.includes(locale)) {
                                return;
                            }

                            let _keys = {};

                            if (!this.project.values[locale]) {
                                this.project.values[locale] = {};
                            }

                            if (!keys.includes(key)) {

                                let _key = {
                                    name: key,
                                    info: '',
                                    tags: [],
                                };

                                _keys[key] = _key;

                                this.project.keys.push(_key);

                                locales.forEach(locale => {

                                    this.project.values[locale][key] = {
                                        value: null
                                    };

                                    if (plural) this.project.values[locale][key].plural = null;
                                });

                                keys.push(key);
                            }

                            if (value && value.trim()) {
                                this.project.values[locale][key].value = value;
                            }

                            if (plural && plural.trim()) {

                                if (_keys[key]) {
                                    _keys[key] = this.project.keys.find(k => k.name === key)
                                }

                                if (_keys[key]) {
                                    _keys[key].plural = true;
                                }

                                this.project.values[locale][key].plural = plural;
                            }
                        });

                        return true;
                    },

                    handleImportFile(event) {

                        const file = event.target.files[0];

                        if (!file) return;

                        const reader = new FileReader();
                        this.importing = true;

                        reader.onload = (e) => {

                            if (this.importKeys(e.target.result)) {
                                App.ui.notify('Keys imported');
                            }

                            setTimeout(() => this.importing = false, 100);
                        };

                        reader.readAsText(file);
                    }

                }
            }
        </script>

    </vue-view>

</kiss-container>
