// WordPress assessment UI — connect, content tree, imports
(function() {
    if (typeof Vue === 'undefined') return;
    var el = document.getElementById('wordpressApp');
    if (!el) return;
    new Vue({
        el: el,
        data: function() {
            return {
                selectedNode: null,
                selectedConnection: null,
                treeItems: [],
                searchFilter: '',
                excludedIds: [],
                showReportModal: false,
                activeTab: 'details',
                repositoryAlert: null,
                awaitingConnectToast: false,
                refreshAllDataBusy: false,
                importMappingNodeIds: []
            };
        },
        mounted: function() {
            var lastConnection = localStorage.getItem('lastWordPressConnection');
            if (lastConnection) {
                try {
                    this.selectedConnection = JSON.parse(lastConnection);
                    this.refreshExcluded();
                    this.fetchRootItems(this.selectedConnection);
                    this.fetchImportMappingNodeIds();
                } catch (e) {
                    console.error('Failed to parse last WordPress connection', e);
                }
            }
            this.$root.$on('excluded-updated', this.refreshExcluded);
            this.registerRefreshShortcut();
        },
        beforeDestroy: function() {
            this.unregisterRefreshShortcut();
            this.$root.$off('excluded-updated', this.refreshExcluded);
        },
        watch: {
            activeTab: function(tab) {
                if (tab === 'imports') this.fetchImportMappingNodeIds();
            }
        },
        methods: {
            handleNodeSelected: function(node) {
                this.selectedNode = node;
                this.activeTab = 'details';
            },
            disconnect: function() {
                this.selectedConnection = null;
                this.selectedNode = null;
                this.treeItems = [];
                this.repositoryAlert = null;
                this.awaitingConnectToast = false;
                this.importMappingNodeIds = [];
                localStorage.removeItem('lastWordPressConnection');
            },
            refreshExcluded: function() {
                if (!this.selectedConnection || typeof ExcludedStore === 'undefined') return;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                this.excludedIds = [...ExcludedStore.getExcludedIds(connId, 'WordPress')];
            },
            registerRefreshShortcut: function() {
                var self = this;
                this._chameleonRefreshKey = function(e) {
                    if (!self.selectedConnection || self.refreshAllDataBusy) return;
                    var t = e.target;
                    if (t && (t.tagName === 'INPUT' || t.tagName === 'TEXTAREA' || t.isContentEditable)) return;
                    if (e.altKey && e.shiftKey && !e.ctrlKey && !e.metaKey && (e.key === 'r' || e.key === 'R')) {
                        e.preventDefault();
                        self.refreshAllData();
                    }
                };
                window.addEventListener('keydown', this._chameleonRefreshKey);
            },
            unregisterRefreshShortcut: function() {
                if (this._chameleonRefreshKey) {
                    window.removeEventListener('keydown', this._chameleonRefreshKey);
                    this._chameleonRefreshKey = null;
                }
            },
            refreshAllData: async function() {
                if (!this.selectedConnection || this.refreshAllDataBusy) return;
                this.refreshAllDataBusy = true;
                try {
                    var connId = this.selectedConnection.id || this.selectedConnection.Id;
                    if (typeof ChameleonCacheRefresh !== 'undefined')
                        await ChameleonCacheRefresh.invalidateSourceCaches(connId, 'WordPress');
                    this.repositoryAlert = null;
                    this.awaitingConnectToast = false;
                    this.refreshExcluded();
                    this.fetchRootItems(this.selectedConnection);
                    this.fetchImportMappingNodeIds();
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Refreshed from server', 'success');
                } catch (e) {
                    console.error('refreshAllData:', e);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification((e && e.message) ? e.message : 'Could not refresh', 'error');
                } finally {
                    this.refreshAllDataBusy = false;
                }
            },
            ConnectTo: function(connection) {
                Vue.set(this, 'selectedConnection', connection);
                localStorage.setItem('lastWordPressConnection', JSON.stringify(connection));
                this.repositoryAlert = null;
                this.awaitingConnectToast = true;
                this.refreshExcluded();
                this.fetchRootItems(connection);
                this.fetchImportMappingNodeIds();
            },
            fetchImportMappingNodeIds: function() {
                var self = this;
                if (!this.selectedConnection) {
                    this.importMappingNodeIds = [];
                    return;
                }
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                fetch('/api/SitefinityConnectivity/GetMappings?connectionId=' + encodeURIComponent(connId))
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        var list = (data && data.result) || [];
                        var set = {};
                        for (var i = 0; i < list.length; i++) {
                            var nid = list[i].nodeId;
                            if (nid != null && nid !== '') set[String(nid)] = true;
                        }
                        self.importMappingNodeIds = Object.keys(set);
                    })
                    .catch(function() {
                        self.importMappingNodeIds = [];
                    });
            },
            fetchRootItems: function(connection) {
                if (!connection) return;
                this.treeItems = [];
                var self = this;
                var connId = connection.id || connection.Id;
                var url = '/api/ContentTree/GetRootItems?platformType=WordPress&connectionId=' + encodeURIComponent(connId);
                function parseErr(body) {
                    if (!body || typeof body !== 'object') return { brief: 'Unexpected response', details: '' };
                    var m = body.message || body.Message || body.error || '';
                    var d = body.details || body.Details || '';
                    return { brief: m || 'Request failed', details: d };
                }
                var emptyWarning = {
                    kind: 'warning',
                    title: 'Empty or unrecognized datasource',
                    brief: 'Connection succeeded, but no content was found. Check the database name, table prefix (wp_), and that posts exist.',
                    details: ''
                };
                fetch(url)
                    .then(function(r) {
                        return r.text().then(function(t) {
                            var body = null;
                            try { body = t ? JSON.parse(t) : null; } catch (e) { body = null; }
                            return { ok: r.ok, status: r.status, body: body, rawText: t || '' };
                        });
                    })
                    .then(function(res) {
                        self.repositoryAlert = null;
                        if (!res.ok) {
                            var p = parseErr(res.body);
                            self.repositoryAlert = {
                                kind: 'error',
                                title: 'Connection failed',
                                brief: p.brief || ('HTTP ' + res.status),
                                details: p.details || res.rawText || ''
                            };
                            self.treeItems = [];
                            self.awaitingConnectToast = false;
                            return;
                        }
                        var data = res.body;
                        if (data && typeof data === 'object' && !Array.isArray(data) && (data.success === false || data.Success === false)) {
                            var p2 = parseErr(data);
                            self.repositoryAlert = {
                                kind: 'error',
                                title: 'Connection failed',
                                brief: p2.brief,
                                details: p2.details || ''
                            };
                            self.treeItems = [];
                            self.awaitingConnectToast = false;
                            return;
                        }
                        var raw = [];
                        if (Array.isArray(data)) raw = data;
                        else if (data && typeof data === 'object' && Array.isArray(data.items)) raw = data.items;
                        self.treeItems = raw;
                        if (raw.length === 0) self.repositoryAlert = emptyWarning;
                        else if (self.awaitingConnectToast && typeof Helpers !== 'undefined')
                            Helpers.showNotification('Connected successfully', 'success');
                        self.awaitingConnectToast = false;
                    })
                    .catch(function(err) {
                        console.error('Error fetching WordPress root items:', err);
                        self.repositoryAlert = {
                            kind: 'error',
                            title: 'Connection failed',
                            brief: err.message || 'Network error',
                            details: err.stack || String(err)
                        };
                        self.treeItems = [];
                        self.awaitingConnectToast = false;
                    });
            }
        },
        computed: {
            totalItems: function() {
                return (this.treeItems && this.treeItems.length) || 0;
            },
            excludedCount: function() {
                return this.excludedIds ? this.excludedIds.length : 0;
            }
        }
    });
})();
