// Initialize the main Vue instance for Sitefinity Target page
document.addEventListener('DOMContentLoaded', function () {
    new Vue({
        el: '#sitefinityApp',
        data: {
            selectedConnection: null,
            selectedNode: null,
            showReportModal: false,
            treeItems: [],
            treeLoading: false,
            initLoading: false,
            exportExcelLoading: false,
            sitesCount: 0,
            modulesCount: 0,
            contentTypesCount: 0,
            sites: [],
            activeTab: 'dashboard',
            contentTypes: [],
            contentTypesLoading: false,
            renderings: [],
            itemCountsByLanguage: [],
            refreshAllDataBusy: false
        },
        mounted() {
            var lastConn = localStorage.getItem('lastSitefinityConnection');
            if (lastConn) {
                try {
                    var conn = JSON.parse(lastConn);
                    if (conn && (conn.id || conn.Id)) {
                        this.selectedConnection = conn;
                    }
                } catch (e) {
                    console.error('Failed to restore Sitefinity connection', e);
                }
            }
            this.registerRefreshShortcut();
        },
        beforeDestroy() {
            this.unregisterRefreshShortcut();
        },
        computed: {
            contentTypesForDashboard: function () {
                return Array(this.contentTypesCount || 0).fill({});
            }
        },
        watch: {
            selectedConnection: {
                handler(conn) {
                    var connId = conn && (conn.id || conn.Id);
                    if (connId) {
                        this.ensureInitialized();
                    } else {
                        this.treeItems = [];
                        this.sites = [];
                        this.sitesCount = 0;
                        this.modulesCount = 0;
                        this.contentTypesCount = 0;
                        this.contentTypes = [];
                    }
                }
            },
            selectedNode: { handler: function () { /* no per-node content types; we show all */ } }
        },
        methods: {
            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 connId = this.selectedConnection.id || this.selectedConnection.Id;
                    if (typeof ChameleonCacheRefresh !== 'undefined')
                        await ChameleonCacheRefresh.invalidateSitefinityCaches(connId);
                    await this.ensureInitialized();
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Refreshed from server', 'success');
                } catch (err) {
                    console.error('refreshAllData:', err);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification((err && err.message) ? err.message : 'Could not refresh', 'error');
                } finally {
                    this.refreshAllDataBusy = false;
                }
            },
            ConnectTo(connection) {
                this.selectedConnection = connection;
                try {
                    localStorage.setItem('lastSitefinityConnection', JSON.stringify(connection));
                } catch (e) { /* quota or disabled */ }
            },
            disconnect() {
                this.selectedConnection = null;
                this.selectedNode = null;
                this.treeItems = [];
                this.sites = [];
                this.sitesCount = 0;
                this.contentTypesCount = 0;
                this.contentTypes = [];
                localStorage.removeItem('lastSitefinityConnection');
            },
            handleNodeSelected(node) {
                this.selectedNode = node;
                if (node) this.activeTab = 'details';
            },
            refreshContentTypes() {
                this.fetchAllContentTypes();
            },
            exportToExcel() {
                var self = this;
                if (!this.selectedConnection || this.exportExcelLoading) return;
                this.exportExcelLoading = true;
                var connId = this.selectedConnection.id || this.selectedConnection.Id;
                fetch('/api/SitefinityConnectivity/ExportToExcel', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ connectionId: connId, platformType: 'Sitefinity' })
                })
                .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, '') : 'sitefinity-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;
                });
            },
            async ensureInitialized() {
                var connId = this.selectedConnection && (this.selectedConnection.id || this.selectedConnection.Id);
                if (!connId) return;
                this.initLoading = true;
                this.treeItems = [];
                this.sites = [];
                this.sitesCount = 0;
                this.contentTypes = [];
                try {
                    var res = await fetch("/api/SitefinityConnectivity/EnsureInitialized?connectionId=" + connId);
                    var json = await res.json();
                    if (json && json.success) {
                        this.sitesCount = json.SitesCount || 0;
                        this.modulesCount = json.ModulesCount || 0;
                        this.contentTypesCount = json.ContentTypesCount || 0;
                        this.fetchRootNodes();
                        this.fetchAllContentTypes();
                    } else {
                        if (typeof Helpers !== 'undefined') Helpers.showNotification(json?.message || 'Failed to initialize', 'error');
                    }
                } catch (err) {
                    console.error('Error initializing:', err);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Error initializing connection', 'error');
                } finally {
                    this.initLoading = false;
                }
            },
            async fetchAllContentTypes() {
                var connId = this.selectedConnection && (this.selectedConnection.id || this.selectedConnection.Id);
                if (!connId) return;
                this.contentTypesLoading = true;
                this.contentTypes = [];
                try {
                    var res = await fetch("/api/SitefinityConnectivity/GetAllContentTypes?connectionId=" + connId);
                    var json = await res.json();
                    var raw = json.contentTypes || json.ContentTypes || [];
                    this.contentTypes = raw.map(function (ct) {
                        var fields = (ct.fields || []).map(function (f) {
                            var name = f.title || f.Title || f.name || f.Name || '';
                            var type = f.typeName || f.TypeName || '—';
                            return { name: name, type: type };
                        });
                        return {
                            name: ct.name || ct.fullTypeName || ct.Name || ct.FullTypeName || '—',
                            path: ct.entitySet || ct.fullTypeName || ct.EntitySet || ct.FullTypeName || '',
                            itemCount: 0,
                            fields: fields,
                            custom: true
                        };
                    });
                } catch (err) {
                    console.error('Error fetching content types:', err);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Error loading content types', 'error');
                } finally {
                    this.contentTypesLoading = false;
                }
            },
            async fetchRootNodes() {
                var connId = this.selectedConnection && (this.selectedConnection.id || this.selectedConnection.Id);
                if (!connId) return;
                this.treeLoading = true;
                this.treeItems = [];
                try {
                    var res = await fetch("/api/SitefinityConnectivity/GetNodes?parentId=&connectionId=" + connId);
                    var data = await res.json();
                    if (Array.isArray(data)) {
                        this.treeItems = data;
                        this.sites = data.map(function (n) { return { id: n.id, name: n.name }; });
                        this.sitesCount = data.length;
                    } else {
                        this.treeItems = [];
                        this.sites = [];
                        this.sitesCount = 0;
                    }
                } catch (err) {
                    console.error('Error fetching nodes:', err);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification('Error loading tree', 'error');
                } finally {
                    this.treeLoading = false;
                }
            }
        }
    });
});
