// Initialize the main Vue instance for Umbraco (run immediately - scripts load at end of body)
(function() {
    if (typeof Vue === 'undefined') return;
    var el = document.getElementById('umbracoApp');
    if (!el) return;
    new Vue({
        el: el,
        data: function() {
            return {
                selectedNode: null,
                selectedConnection: null,
                treeItems: [],
                searchFilter: '',
                excludedIds: [],
                includedIds: [],
                exportExcelLoading: false,
                showReportModal: false,
                activeTab: 'dashboard',
                dashboardLoading: false,
                sites: [],
                contentTypes: [],
                renderings: [],
                languages: [],
                itemCountsByLanguage: [],
                notesCount: 0,
                pageCount: 0,
                mediaCount: 0,
                dataCount: 0,
                /** Distinct source tree node ids that have saved import mappings (for tree badge). */
                importMappingNodeIds: [],
                repositoryAlert: null,
                awaitingConnectToast: false,
                refreshAllDataBusy: false
            };
        },
        mounted() {
            const lastConnection = localStorage.getItem("lastUmbracoConnection");
            if (lastConnection) {
                try {
                    this.selectedConnection = JSON.parse(lastConnection);
                    this.refreshExcluded();
                    this.fetchRootItems(this.selectedConnection);
                    this.fetchImportMappingNodeIds();
                } catch (e) {
                    console.error("Failed to parse last connection", e);
                }
            }
            this.$root.$on('excluded-updated', this.refreshExcluded);
            this.registerRefreshShortcut();
        },
        beforeDestroy() {
            this.unregisterRefreshShortcut();
            this.$root.$off('excluded-updated', this.refreshExcluded);
        },
        methods: {
            handleNodeSelected(node) {
                this.selectedNode = node;
                this.activeTab = 'details';
            },
            disconnect() {
                this.selectedConnection = null;
                this.selectedNode = null;
                this.treeItems = [];
                this.sites = [];
                this.contentTypes = [];
                this.renderings = [];
                this.languages = [];
                this.pageCount = 0;
                this.mediaCount = 0;
                this.dataCount = 0;
                this.repositoryAlert = null;
                this.awaitingConnectToast = false;
                this.importMappingNodeIds = [];
                localStorage.removeItem("lastUmbracoConnection");
            },
            refreshExcluded() {
                if (!this.selectedConnection || typeof ImportMarksStore === 'undefined') return;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                this.excludedIds = [...ImportMarksStore.getExcludedIds(connId, 'Umbraco')];
                this.includedIds = [...ImportMarksStore.getIncludedIds(connId, 'Umbraco')];
                this.fetchInstanceOverview(this.selectedConnection);
            },
            registerRefreshShortcut() {
                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() {
                if (this._chameleonRefreshKey) {
                    window.removeEventListener('keydown', this._chameleonRefreshKey);
                    this._chameleonRefreshKey = null;
                }
            },
            async refreshAllData() {
                if (!this.selectedConnection || this.refreshAllDataBusy) return;
                this.refreshAllDataBusy = true;
                this.dashboardLoading = true;
                try {
                    var connId = this.selectedConnection.id || this.selectedConnection.Id;
                    if (typeof ChameleonCacheRefresh !== 'undefined')
                        await ChameleonCacheRefresh.invalidateSourceCaches(connId, 'Umbraco');
                    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);
                    this.dashboardLoading = false;
                    if (typeof Helpers !== 'undefined') Helpers.showNotification((e && e.message) ? e.message : 'Could not refresh', 'error');
                } finally {
                    this.refreshAllDataBusy = false;
                }
            },
            ConnectTo(connection) {
                Vue.set(this, 'selectedConnection', connection);
                localStorage.setItem("lastUmbracoConnection", 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 = [];
                    });
            },
            fetchInstanceOverview(connection) {
                if (!connection) return;
                var connId = connection.id || connection.Id;
                var self = this;
                this.dashboardLoading = true;
                var url = '/api/ContentTree/GetInstanceOverview?platformType=Umbraco&connectionId=' + encodeURIComponent(connId);
                var excluded = this.excludedIds ? (this.excludedIds instanceof Set ? [...this.excludedIds] : this.excludedIds) : [];
                if (excluded.length > 0) {
                    url += '&excludedIds=' + encodeURIComponent(excluded.slice(0, 500).join(','));
                }
                fetch(url)
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        self.dashboardLoading = false;
                        if (data && data.success !== false) {
                            self.sites = data.sites || [];
                            self.contentTypes = data.contentTypes || [];
                            self.renderings = data.renderings || [];
                            self.languages = data.languages || [];
                            self.itemCountsByLanguage = data.itemCountsByLanguage || [];
                            self.pageCount = data.pageCount || 0;
                            self.mediaCount = data.mediaCount || 0;
                            self.dataCount = data.dataCount || 0;
                        } else {
                            self.sites = [];
                            self.contentTypes = [];
                            self.renderings = [];
                            self.languages = [];
                            self.itemCountsByLanguage = [];
                            self.pageCount = 0;
                            self.mediaCount = 0;
                            self.dataCount = 0;
                        }
                    })
                    .catch(function(err) {
                        console.error('Error fetching instance overview:', err);
                        self.dashboardLoading = false;
                        self.sites = [];
                        self.contentTypes = [];
                        self.renderings = [];
                        self.languages = [];
                        self.itemCountsByLanguage = [];
                        self.pageCount = 0;
                        self.mediaCount = 0;
                        self.dataCount = 0;
                    });
            },
            exportToExcel: function() {
                var self = this;
                if (!this.selectedConnection || this.exportExcelLoading) return;
                this.exportExcelLoading = true;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                var excludedIds = this.excludedIds ? (this.excludedIds instanceof Set ? [...this.excludedIds] : this.excludedIds) : [];
                fetch('/api/ContentTree/ExportToExcel', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        connectionId: connId,
                        platformType: 'Umbraco',
                        excludedIds: excludedIds
                    })
                })
                .then(function(r) {
                    if (!r.ok) return r.json().then(function(j) { throw new Error(j.message || 'Export failed'); });
                    var disp = r.headers.get('Content-Disposition');
                    var match = disp && disp.match(/filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/);
                    var filename = (match && match[1]) ? match[1].replace(/['"]/g, '') : 'umbraco-migration-assessment.xlsx';
                    return r.blob().then(function(blob) { return { blob: blob, filename: filename }; });
                })
                .then(function(result) {
                    var url = URL.createObjectURL(result.blob);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = result.filename;
                    a.click();
                    URL.revokeObjectURL(url);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Exported to Excel', 'success');
                })
                .catch(function(err) {
                    console.error('Export error:', err);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification(err.message || 'Export failed', 'error');
                })
                .finally(function() {
                    self.exportExcelLoading = false;
                });
            },
            fetchRootItems: function(connection) {
                if (!connection) return;

                this.treeItems = [];
                var self = this;
                var connId = connection.id || connection.Id;
                var url = '/api/ContentTree/GetRootItems?platformType=Umbraco&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 the target datasource appears empty, uses a different schema, or needs additional setup.',
                    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);
                            if (!res.body && res.rawText) {
                                self.repositoryAlert = {
                                    kind: 'error',
                                    title: 'Connection failed',
                                    brief: 'The connection to the remote server failed: HTTP ' + res.status,
                                    details: res.rawText.length > 8000 ? res.rawText.slice(0, 8000) + '\n…' : res.rawText
                                };
                            } else {
                                self.repositoryAlert = {
                                    kind: 'error',
                                    title: 'Connection failed',
                                    brief: 'The connection to the remote server failed: ' + p.brief,
                                    details: p.details || ''
                                };
                            }
                            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: 'The connection to the remote server failed: ' + 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;
                        var seen = {};
                        var list = [];
                        for (var i = 0; i < raw.length; i++) {
                            var n = raw[i];
                            var id = n.id != null ? n.id : n.Id;
                            var key = id != null && id !== '' ? String(id) : '__noid_' + i;
                            if (seen[key]) continue;
                            seen[key] = true;
                            list.push(n);
                        }
                        self.treeItems = list;
                        if (list.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 root items:', err);
                        self.repositoryAlert = {
                            kind: 'error',
                            title: 'Connection failed',
                            brief: 'The connection to the remote server failed: ' + (err.message || 'Network error'),
                            details: err.stack || String(err)
                        };
                        self.treeItems = [];
                        self.awaitingConnectToast = false;
                    });
            },
        },
        watch: {
            activeTab: function(tab) {
                if (tab === 'imports') this.fetchImportMappingNodeIds();
            }
        },
        computed: {
            totalItems() {
                return (this.treeItems && this.treeItems.length) || 0;
            },
            excludedCount() {
                return this.excludedIds ? this.excludedIds.length : 0;
            }
        }
    });
})();
