// Sitefinity source assessment UI — connect, content tree, imports
(function() {
    if (typeof Vue === 'undefined') return;
    var el = document.getElementById('sitefinitySourceApp');
    if (!el) return;
    new Vue({
        el: el,
        data: function() {
            return {
                selectedNode: null,
                selectedConnection: null,
                treeItems: [],
                searchFilter: '',
                excludedIds: [],
                includedIds: [],
                showReportModal: false,
                activeTab: 'details',
                repositoryAlert: null,
                awaitingConnectToast: false,
                refreshAllDataBusy: false,
                importMappingNodeIds: []
            };
        },
        mounted: function() {
            var lastConnection = localStorage.getItem('lastSitefinitySourceConnection');
            if (lastConnection) {
                try {
                    var stored = JSON.parse(lastConnection);
                    this.ensureSourceLinkAndConnect(stored);
                } catch (e) {
                    console.error('Failed to parse last Sitefinity source 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('lastSitefinitySourceConnection');
            },
            refreshExcluded: function() {
                if (!this.selectedConnection || typeof ImportMarksStore === 'undefined') return;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                this.excludedIds = [...ImportMarksStore.getExcludedIds(connId, 'SitefinitySource')];
                this.includedIds = [...ImportMarksStore.getIncludedIds(connId, 'SitefinitySource')];
            },
            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, 'SitefinitySource');
                    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: async function(sfConnection) {
                var self = this;
                var sfId = sfConnection && (sfConnection.id != null ? sfConnection.id : sfConnection.Id);
                if (!sfId) {
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Invalid Sitefinity connection', 'error');
                    return;
                }
                try {
                    var res = await fetch('/api/ContentTree/EnsureSitefinitySourceLink', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ sitefinityConnectionId: sfId })
                    });
                    var link = await res.json();
                    if (!res.ok || !link || link.success === false) {
                        throw new Error((link && link.message) ? link.message : 'Could not link Sitefinity source connection');
                    }
                    var linked = {
                        id: link.id,
                        name: link.name || sfConnection.name || sfConnection.Name || 'Sitefinity',
                        sitefinityConnectionId: sfId,
                        platformType: 'SitefinitySource'
                    };
                    Vue.set(this, 'selectedConnection', linked);
                    localStorage.setItem('lastSitefinitySourceConnection', JSON.stringify(linked));
                    this.repositoryAlert = null;
                    this.awaitingConnectToast = true;
                    this.refreshExcluded();
                    this.fetchRootItems(linked);
                    this.fetchImportMappingNodeIds();
                } catch (e) {
                    console.error('ConnectTo Sitefinity source:', e);
                    this.repositoryAlert = {
                        kind: 'error',
                        title: 'Connection failed',
                        brief: (e && e.message) ? e.message : 'Could not connect',
                        details: ''
                    };
                    if (typeof Helpers !== 'undefined') Helpers.showNotification(this.repositoryAlert.brief, 'error');
                }
            },
            ensureSourceLinkAndConnect: async function(stored) {
                var sfId = stored.sitefinityConnectionId || stored.id || stored.Id;
                if (!sfId) return;
                await this.ConnectTo({ id: sfId, name: stored.name || stored.Name });
            },
            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=SitefinitySource&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 sites were found. Check the URL and access key.',
                    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 Sitefinity source 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;
            }
        }
    });
})();
