// Initialize the main Vue instance for SharePoint (run immediately - scripts load at end of body)
(function() {
    if (typeof Vue === 'undefined') return;
    var el = document.getElementById('sharepointApp');
    if (!el) return;
    new Vue({
        el: el,
        data: function() {
            return {
                selectedNode: null,
                selectedConnection: null,
                treeItems: [],
                searchFilter: '',
                excludedIds: [],
                includedIds: [],
                showReportModal: false,
                activeTab: 'dashboard',
                dashboardLoading: false,
                sites: [],
                contentTypes: [],
                renderings: [],
                itemCountsByLanguage: [],
                notesCount: 0,
                pageCount: 0,
                mediaCount: 0,
                dataCount: 0,
                importMappingNodeIds: [],
                repositoryAlert: null,
                awaitingConnectToast: false,
                refreshAllDataBusy: false
            };
        },
        mounted() {
            const lastConnection = localStorage.getItem("lastSharePointConnection");
            if (lastConnection) {
                try {
                    this.selectedConnection = JSON.parse(lastConnection);
                    this.refreshExcluded();
                    this.fetchRootItems(this.selectedConnection);
                    this.fetchInstanceOverview(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.repositoryAlert = null;
                this.awaitingConnectToast = false;
                this.importMappingNodeIds = [];
                localStorage.removeItem("lastSharePointConnection");
            },
            refreshExcluded() {
                if (!this.selectedConnection || typeof ImportMarksStore === 'undefined') return;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                this.excludedIds = [...ImportMarksStore.getExcludedIds(connId, 'SharePoint')];
                this.includedIds = [...ImportMarksStore.getIncludedIds(connId, 'SharePoint')];
            },
            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;
                try {
                    var conn = this.selectedConnection;
                    var connId = conn.id || conn.Id;
                    if (typeof ChameleonCacheRefresh !== 'undefined')
                        await ChameleonCacheRefresh.invalidateSourceCaches(connId, 'SharePoint');
                    this.refreshExcluded();
                    this.repositoryAlert = null;
                    this.awaitingConnectToast = false;
                    this.fetchRootItems(this.selectedConnection);
                    this.fetchInstanceOverview(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(connection) {
                Vue.set(this, 'selectedConnection', connection);
                localStorage.setItem("lastSharePointConnection", JSON.stringify(connection));
                this.repositoryAlert = null;
                this.awaitingConnectToast = true;
                this.refreshExcluded();
                this.fetchRootItems(connection);
                this.fetchInstanceOverview(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;
                fetch('/api/ContentTree/GetInstanceOverview?platformType=SharePoint&connectionId=' + encodeURIComponent(connId))
                    .then(function(r) { return r.json(); })
                    .then(function(data) {
                        if (data && data.success !== false) {
                            self.sites = data.sites || [];
                            self.contentTypes = data.contentTypes || [];
                        }
                    })
                    .catch(function(err) {
                        console.error('Error fetching instance overview:', err);
                        self.sites = [];
                    });
            },
            fetchRootItems(connection) {
                if (!connection) return;

                this.treeItems = [];
                var self = this;
                var connId = connection.id != null ? connection.id : connection.Id;
                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(`/api/ContentTree/GetRootItems?platformType=SharePoint&connectionId=${encodeURIComponent(connId)}`)
                    .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;
                        }
                        if (Array.isArray(data)) {
                            self.treeItems = data;
                        } else if (data && typeof data === 'object') {
                            console.warn('API returned an object instead of an array for tree items. Converting to array.');
                            if (Array.isArray(data.items))
                                self.treeItems = data.items;
                            else
                                self.treeItems = Object.keys(data).map(function(key) {
                                    return Object.assign({ id: key, name: data[key].name || key }, data[key]);
                                }) || [];
                        } else {
                            console.error('Invalid data format returned from API:', data);
                            self.treeItems = [];
                        }
                        var list = self.treeItems || [];
                        if (list.length === 0)
                            self.repositoryAlert = emptyWarning;
                        else if (self.awaitingConnectToast && typeof Helpers !== 'undefined')
                            Helpers.showNotification('Connected successfully', 'success');
                        self.awaitingConnectToast = false;
                    })
                    .catch(function(error) {
                        console.error('Error fetching root items:', error);
                        self.repositoryAlert = {
                            kind: 'error',
                            title: 'Connection failed',
                            brief: 'The connection to the remote server failed: ' + (error.message || 'Network error'),
                            details: error.stack || String(error)
                        };
                        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;
            }
        }
    });
})(); 