// Initialize the main Vue instance for Sitefinity Target page
document.addEventListener('DOMContentLoaded', function () {
    new Vue({
        el: '#sitefinityApp',
        data: {
            selectedConnection: null,
            selectedNode: null,
            showReportModal: false,
            repositoryAlert: null,
            treeItems: [],
            treeLoading: false,
            initLoading: false,
            initProgressMessage: "",
            _initOpsUnsub: null,
            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();
            this.unwatchInitProgress();
        },
        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: {
            parseErrorPayload(body) {
                if (!body || typeof body !== 'object')
                    return { brief: 'Unexpected response', details: '' };
                var msg = body.message || body.Message || body.error || '';
                var details = body.details || body.Details || '';
                return { brief: msg || 'Request failed', details: details || '' };
            },
            setRemoteConnectionErrorAlert(brief, details) {
                this.repositoryAlert = {
                    kind: 'error',
                    title: 'Connection failed',
                    brief: 'The connection to the remote server failed: ' + (brief || 'Request failed'),
                    details: details || ''
                };
            },
            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;
                });
            },
            watchInitProgress(connectionId) {
                this.unwatchInitProgress();
                if (typeof LongRunningOps === "undefined" || !connectionId) return;
                var self = this;
                var opId = LongRunningOps.ids.sitefinityInit(connectionId);
                this._initOpsUnsub = LongRunningOps.watch(opId, function (op) {
                    self.initProgressMessage = LongRunningOps.operationMessage(op);
                });
            },
            unwatchInitProgress() {
                if (this._initOpsUnsub) {
                    this._initOpsUnsub();
                    this._initOpsUnsub = null;
                }
                this.initProgressMessage = "";
            },
            async ensureInitialized() {
                var connId = this.selectedConnection && (this.selectedConnection.id || this.selectedConnection.Id);
                if (!connId) return;
                this.initLoading = true;
                this.watchInitProgress(connId);
                this.repositoryAlert = null;
                this.treeItems = [];
                this.sites = [];
                this.sitesCount = 0;
                this.contentTypes = [];
                try {
                    var res = await fetch("/api/SitefinityConnectivity/EnsureInitialized?connectionId=" + connId);
                    var text = await res.text();
                    var json = null;
                    try { json = text ? JSON.parse(text) : null; } catch (e) { json = null; }

                    if (!res.ok) {
                        if (!json && text) {
                            this.setRemoteConnectionErrorAlert('HTTP ' + res.status, text.length > 8000 ? text.slice(0, 8000) + '\n...' : text);
                        } else {
                            var p = this.parseErrorPayload(json);
                            this.setRemoteConnectionErrorAlert(p.brief, p.details);
                        }
                        return;
                    }

                    if (json && json.success) {
                        this.sitesCount = json.SitesCount || 0;
                        this.modulesCount = json.ModulesCount || 0;
                        this.contentTypesCount = json.ContentTypesCount || 0;
                        this.fetchRootNodes();
                        this.fetchAllContentTypes();
                    } else {
                        var parsed = this.parseErrorPayload(json);
                        this.setRemoteConnectionErrorAlert(parsed.brief || 'Failed to initialize', parsed.details);
                    }
                } catch (err) {
                    console.error('Error initializing:', err);
                    this.setRemoteConnectionErrorAlert(err && err.message ? err.message : 'Network error', err && err.stack ? err.stack : String(err));
                } finally {
                    this.initLoading = false;
                    this.unwatchInitProgress();
                }
            },
            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;
                }
            }
        }
    });
});
