// Import components and services
import './components/TreeView.js';
import './services/apiService.js';
import './utils/helpers.js';

// Main Content Screen Component
Vue.component('content-screen', {
    data() {
        return {
            selectedNode: null,
            contentTypes: [],
            isLoading: false,
            error: null
        };
    },
    methods: {
        /**
         * Handles node selection
         * @param {Object} node - The selected node
         */
        async handleNodeSelected(node) {
            this.selectedNode = node;
            this.isLoading = true;
            this.error = null;

            try {
                this.contentTypes = await ApiService.fetchContentTypes(node.id);
            } catch (error) {
                this.error = error.message;
                Helpers.showNotification(error.message, 'error');
            } finally {
                this.isLoading = false;
            }
        },

        /**
         * Handles connection changes
         * @param {Object} connection - The new connection
         */
        handleConnectionChange(connection) {
            ApiService.setCurrentConnection(connection);
            this.selectedNode = null;
            this.contentTypes = [];
        }
    },
    template: `
        <div class="content-screen">
            <div class="error-message" v-if="error">
                {{ error }}
            </div>
            
            <div class="loading" v-if="isLoading">
                Loading...
            </div>

            <tree-view 
                @node-selected="handleNodeSelected"
                :connection="ApiService.getCurrentConnection()"
            />

            <div class="content-types" v-if="contentTypes.length">
                <h3>Content Types</h3>
                <ul>
                    <li v-for="type in contentTypes" :key="type.id">
                        {{ type.name }}
                    </li>
                </ul>
            </div>
        </div>
    `
});

// Tree View Component
Vue.component('tree-view', {
    props: {
        connection: {
            type: Object,
            required: false
        },
    },
    data() {
        return {
            expanded: {},
            nodeData: {},
            rootNodes: [],
        };
    },
    created() {
        // Load initial root level data
        this.loadRootNodes();
    },
    methods: {
        loadRootNodes() {
            // Simulate API call to get root nodes
            this.fetchNodes(null).then(data => {
                this.rootNodes = data;
            });
        },
        toggleNode(node) {
            const nodeId = node.id;

            if (!this.expanded[nodeId]) {
                // Node is being expanded, load its children if not already loaded
                if (!this.nodeData[nodeId]) {
                    this.fetchNodes(nodeId).then(children => {
                        this.$set(this.nodeData, nodeId, children);
                        this.$set(this.expanded, nodeId, true);
                    });
                } else {
                    this.$set(this.expanded, nodeId, true);
                }
            } else {
                // Node is being collapsed
                this.$set(this.expanded, nodeId, false);
            }
        },
        fetchNodes(parentId) {
            var connection = localStorage.getItem("lastConnection");
            if (!connection) {
                alert('Please connect first!');
            }
            else {
                //this.$emit("connect", connection);
                //this.connection = JSON.parse(connection);
            }

            // Make actual API call to your backend
            return new Promise((resolve, reject) => {
                if (!this.connection || !this.connection.id) {
                    resolve(null);
                }
                else {
                    const url = parentId === null
                        ? '/api/ContentTree/GetNodes?connectionId=' + this.connection.id
                        : `/api/ContentTree/GetNodes?parentId=${encodeURIComponent(parentId)}&connectionId=${this.connection.id}`;

                    fetch(url)
                        .then(response => {
                            if (!response.ok) {
                                throw new Error('Network response was not ok');
                            }
                            return response.json();
                        })
                        .then(data => {
                            resolve(data);
                        })
                        .catch(error => {
                            console.error('Error fetching nodes:', error);
                            // Fallback to mock data in case of error

                        });
                }
            });
        },

        // Fallback mock data in case API is not available
        selectNode(node) {
            this.$emit('node-selected', node);
            this.toggleNode(node);
        },
        isExpanded(nodeId) {
            return this.expanded[nodeId] || false;
        },
        getChildNodes(nodeId) {
            return this.nodeData[nodeId] || [];
        }
    },
    template: `
        <div class="tree-view">
            <ul class="tree-root list-unstyled">
                <li v-for="node in rootNodes" :key="node.id" class="tree-node mb-2">
                    <div class="d-flex align-items-center">
                        <span 
                            v-if="node.hasChildren" 
                            @click="toggleNode(node)" 
                            class="toggle-icon mr-2"
                        >
                            <i class="toggle-symbol">{{ isExpanded(node.id) ? '-' : '+' }}</i>
                        </span>
                        <span v-else class="mr-2 placeholder-icon">&nbsp;&nbsp;</span>
                        
                        <span 
                            class="node-text" 
                            @click="selectNode(node)"
                            :class="{ 'font-weight-bold': node.selected }"
                        >
                            {{ node.name }}
                        </span>
                    </div>
                    
                    <div v-if="isExpanded(node.id)" class="tree-children-container">
                        <ul class="list-unstyled tree-children">
                            <li v-for="child in getChildNodes(node.id)" :key="child.id" class="mb-2 tree-child-item">
                                <div class="d-flex align-items-center">
                                    <span 
                                        v-if="child.hasChildren" 
                                        @click="toggleNode(child)" 
                                        class="toggle-icon mr-2"
                                    >
                                        <i class="toggle-symbol">{{ isExpanded(child.id) ? '-' : '+' }}</i>
                                    </span>
                                    <span v-else class="mr-2 placeholder-icon">&nbsp;&nbsp;</span>
                                    
                                    <span 
                                        class="node-text" 
                                        @click="selectNode(child)"
                                        :class="{ 'font-weight-bold': child.selected }"
                                    >
                                        {{ child.name }}
                                    </span>
                                </div>
                                
                                <div v-if="isExpanded(child.id)" class="tree-children-container">
                                    <ul class="list-unstyled tree-children">
                                        <li v-for="subChild in getChildNodes(child.id)" :key="subChild.id" class="mb-2 tree-child-item">
                                            <div class="d-flex align-items-center">
                                                <span 
                                                    v-if="subChild.hasChildren" 
                                                    @click="toggleNode(subChild)" 
                                                    class="toggle-icon mr-2"
                                                >
                                                    <i class="toggle-symbol">{{ isExpanded(subChild.id) ? '-' : '+' }}</i>
                                                </span>
                                                <span v-else class="mr-2 placeholder-icon">&nbsp;&nbsp;</span>
                                                
                                                <span 
                                                    class="node-text" 
                                                    @click="selectNode(subChild)"
                                                    :class="{ 'font-weight-bold': subChild.selected }"
                                                >
                                                    {{ subChild.name }}
                                                </span>
                                            </div>
                                            
                                            <div v-if="isExpanded(subChild.id)" class="tree-children-container">
                                                <ul class="list-unstyled tree-children">
                                                    <li v-for="leaf in getChildNodes(subChild.id)" :key="leaf.id" class="mb-2 tree-child-item">
                                                        <div class="d-flex align-items-center">
                                                            <span 
                                                                v-if="leaf.hasChildren" 
                                                                @click="toggleNode(leaf)" 
                                                                class="toggle-icon mr-2"
                                                            >
                                                                <i class="toggle-symbol">{{ isExpanded(leaf.id) ? '-' : '+' }}</i>
                                                            </span>
                                                            <span v-else class="mr-2 placeholder-icon">&nbsp;&nbsp;</span>
                                                            
                                                            <span 
                                                                class="node-text" 
                                                                @click="selectNode(leaf)"
                                                                :class="{ 'font-weight-bold': leaf.selected }"
                                                            >
                                                                {{ leaf.name }}
                                                            </span>
                                                        </div>
                                                    </li>
                                                </ul>
                                            </div>
                                        </li>
                                    </ul>
                                </div>
                            </li>
                        </ul>
                    </div>
                </li>
            </ul>
        </div>
    `,
    watch: {
        connection: {
            immediate: true,
            deep: true,
            handler(val) {
                console.log('Connection changed:', val);
                // Do something with the connection value
                if (val) {
                    this.loadRootNodes(); // Reload nodes when connection changes
                }
            }
        }
    }
});

// Tabbed Pane Component
Vue.component('tabbed-pane', {
    props: {
        tabs: {
            type: Array,
            required: true
        },
        activeTab: {
            type: String,
            required: true
        },
        selectedNode: {
            type: Object,
            default: null
        },
        connection: {
            type: Object,
            default: null
        }
    },
    computed: {
        platformType() {
            return this.connection && this.connection.platformType ? this.connection.platformType : 'SharePoint';
        }
    },
    methods: {
        changeTab(tabId) {
            this.$emit('tab-changed', tabId);
        }
    },
    template: `
        <div class="tabbed-pane">
            <ul class="nav nav-tabs">
                <li class="nav-item" v-for="tab in tabs" :key="tab.id">
                    <a 
                        class="nav-link" 
                        :class="{ active: tab.id === activeTab }"
                        href="#" 
                        @click.prevent="changeTab(tab.id)"
                    >
                        {{ tab.name }}
                    </a>
                </li>
            </ul>
            
            <div class="tab-content mt-3">
                <div class="tab-pane fade show active">
                    <component 
                        :is="activeTab + '-tab'" 
                        :selected-node="selectedNode"
                        :connection="connection"
                        :platform-type="platformType"
                    ></component>
                </div>
            </div>
        </div>
    `
});

// Overview Tab Component
Vue.component('overview-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        }
    },
    template: `
        <div class="overview-tab">
            <div v-if="selectedNode">
                <div class="card">
                    <div class="card-body">
                        <h5 class="card-title">{{ selectedNode.name }}</h5>
                        <div class="mt-4">
                            <table class="table table-sm">
                                <tbody>
                                    <tr v-for="field in selectedNode.fields" :key="field.name">
                                        <th style="width: 30%">{{ field.name }}</th>
                                        <td>{{ field.value }}</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else class="alert alert-info">
                Please select a node from the tree to view details.
            </div>
        </div>
    `
});

// Content Type Tab Component
Vue.component('content-type-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            contentTypes: []
        };
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {
                if (newVal && newVal.id) {
                    this.fetchContentTypes(newVal.id);
                } else {
                    this.contentTypes = [];
                }
            }
        }
    },
    methods: {
        fetchContentTypes(nodeId) {

        }
    },
    template: `
        <div class="content-type-tab">
            <h4>Content Types</h4>
            <div v-if="selectedNode">
                <div v-if="contentTypes.length" class="mt-3">
                    <table class="table table-striped">
                        <thead>
                            <tr>
                                <th>Name</th>
                                <th>Fields</th>
                                <th>Actions</th>
                            </tr>
                        </thead>
                        <tbody>
                            <tr v-for="type in contentTypes" :key="type.id">
                                <td>{{ type.name }}</td>
                                <td>{{ type.fields.join(',') }}</td>
                                <td>
                                    <button class="btn btn-sm btn-outline-primary mr-2">Edit</button>
                                    <button class="btn btn-sm btn-outline-danger">Delete</button>
                                </td>
                            </tr>
                        </tbody>
                    </table>
                </div>
                <div v-else-if="selectedNode" class="alert alert-info">
                    No content types found for the selected item.
                </div>
            </div>
            <div v-else class="alert alert-info">
                Please select a node from the tree to view content types.
            </div>
        </div>
    `
});

// Import Tab:

Vue.component('import-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        },
        connection: {
            type: Object,
            default: null
        },
        platformType: {
            type: String,
            default: 'SharePoint'  // Provide a default value to ensure it's never undefined
        }
    },
    data() {
        return {
            contentTypes: [],
            inSetup: false,
            targetServers: [],
            targetServer: null,
            targetSite: null,
            targetModules: null,
            targetModule: null,
            targetSource: null,
            targetFields: null,
            AllModules: null,
            targetTypes: null,
            targetType: null,
            moduleDetails: null,
            currentStep: 0,
            steps: ["Server Info", "Mappings"],
            mappings: null,
            MappingName: "",
            MappingDescription: "",
            existingMappings: null,
            //connection: null
        };
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {
                this.LoadMappings()
            }
        },
        targetSite: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.GetSiteModules(newVal);
                }
            }
        },
        targetModule: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.GetModuleDetails();
                }
            }
        },
        targetType: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.GetTypeDetails();
                }
            }
        }
    },
    methods: {
        fetchContentTypes(nodeId) {

        },
        SetupImport() {
            this.inSetup = true;
            this.GetSitefinityConnections();
        },
        async GetSitefinityConnections() {
            var connections = await fetch("/api/SitefinityConnectivity/GetAvailableConnectionStrings");
            var json = await connections.json();

            for (var i = 0; i < json.length; i++) {
                var serverToProcess = json[i];
                try {
                    if (serverToProcess.rawSiteResponse) {
                        jsonResult = JSON.parse(serverToProcess.rawSiteResponse);
                        if (jsonResult) {
                            serverToProcess.parsedResponse = jsonResult;
                        }
                    }
                }
                catch (err) {

                }
            }

            this.targetServers = json;
        },
        async GetSiteModules(siteId) {
            var modules = await fetch("/api/SitefinityConnectivity/GetSiteModules?siteId=" + siteId + "&connectionId=" + this.targetServer.id);
            var modulesJson = await modules.json();
            this.targetModules = JSON.parse(modulesJson.result);
        },
        async GetModuleDetails() {
            var moduleInfo = await fetch("/api/SitefinityConnectivity/GetSiteModuleDetails?connectionId=" + this.targetServer.id + "&type=" + this.targetModule.Name);
            var json = await moduleInfo.json();
            if (json && json.result && json.result.contentTypes) {
                this.targetTypes = json.result.contentTypes;
            }
            if (json && json.result && json.result.moduleDetails) {
                this.AllModules = json.result.moduleDetails;
            }
        },
        async GetTypeDetails() {
            var module = this.AllModules.items.filter(i => i.contentTypeName == this.targetModule.Name);
            if (module && module.length > 0) {
                module.moduleId = module[0].moduleId;

                var moduleInfo = await fetch("/api/SitefinityConnectivity/GetTypeDetails?connectionId=" + this.targetServer.id + "&moduleId=" + module[0].moduleId + "&typeId=" + this.targetType.contentTypeId);
                var moduleDetails = await moduleInfo.json();
                this.moduleDetails = moduleDetails;
            }
        },
        async AddMapping() {
            if (this.mappings == null)
                this.mappings = [];

            this.mappings.push({
                "Id": new Date().getTime(),
                "Source": "",
                "Target": "",
            })
        },
        async SaveMappings() {
            debugger;
            var mappingsToSave = this.mappings.map(function (m) {
                return {
                    Source: m.Source.name,
                    Target: m.Target.name,
                    TargetTypeName: m.Target.typeName,
                    TargetFullDetails: m.Target,
                    SourceFullDetails: m.Source
                }
            });

            var mappingJSON = {
                Name: this.MappingName,
                Description: this.MappingDescription,
                ConnectionId: this.connection.id,
                SiteId: this.targetSite,
                MappingsJSON: JSON.stringify(mappingsToSave),
                ModuleId: this.targetModule.moduleId,
                OData: (this.targetType && (this.targetType.entitySet || this.targetType.EntitySet))
                    ? String(this.targetType.entitySet || this.targetType.EntitySet).trim()
                    : (this.targetModule && this.targetModule.Name ? this.targetModule.Name : ""),
                TypeId: this.targetType.contentTypeId,
                NodeId: this.selectedNode.id,
                TargetServerConnectionId: this.targetServer.id,
                ProviderName: this.targetSource,
                PlatformType: this.platformType || (this.connection ? this.connection.platformType : "SharePoint")
            };

            var modules = this.AllModules.items.filter(i => i.contentTypeName == this.targetModule.Name);
            debugger;
            mappingJSON.ModuleId = modules[0].moduleId;


            await fetch("/api/SitefinityConnectivity/SaveMapping", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(mappingJSON)
            })

            this.LoadMappings();
        },
        async LoadMappings() {
            // Ensure platformType has a value, default to 'SharePoint' if undefined
            const platform = this.platformType || (this.connection ? this.connection.platformType : "SharePoint");
            
            // Use the appropriate localStorage key based on platform type
            const storageKey = platform === 'Sitecore' ? 'lastSitecoreConnection' : 'lastConnection';
            var connection = localStorage.getItem(storageKey);

            if (!connection) {
                alert(`Please connect to ${platform} first!`);
            }
            else {
                this.connection = JSON.parse(connection);
            }

            if (this.connection && this.connection.id && this.selectedNode && this.selectedNode.id) {
                var mappings = await fetch("/api/SitefinityConnectivity/GetMappings?connectionId=" + this.connection.id + "&nodeId=" + this.selectedNode.id);
                var json = await mappings.json();
                this.existingMappings = json.result;
            } else {
                console.warn("Unable to load mappings: missing connection ID or selected node ID");
            }
        },

        async RunImport(mapping) {

            var date = new Date();

            var importPayload = {
                connectionId: this.connection.id,
                sourceItemId: this.selectedNode.id,
                mappingId: mapping.id,
                name: mapping.name + " (" + date.getFullYear() + " " + date.getMonth() + " " + date.getDay() + " " + date.getMilliseconds() + ")",
            };

            try {
                var running = await fetch("/api/Import/StartImport", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(importPayload)
                });

                if (running.status == 400) {
                    var errMsg = await running.text();

                    alert("Error starting import: " + errMsg);
                }
            }
            catch (err) {
                alert(err);
            }

        },
        async DeleteMapping(mapping) {
            if (confirm("Are you sure you want to delete this mapping?")) {
                await fetch("/api/SitefinityConnectivity/DeleteMapping?mappingId=" + mapping.id);
                this.LoadMappings();
            }
        },
        async ClearMemory(mapping) {
            if (confirm("This operation is intended if you have imported items and then deleted them.\nAre you sure you want to proceed?")) {
                var res = await fetch("/api/Import/ClearMemoryMappings?mappingId=" + mapping.id);
                var jsonRes = await res.json();
                if (jsonRes && jsonRes.NumberOfItemsRemoved && jsonRes.Succeess) {
                    alert("Successfully removed " + jsonRes.NumberOfItemsRemoved + " items from the memory.");
                    this.LoadMappings();
                }
            }
        },
        PopulateItemFieldMapping(mapping) {
            
        }
    },
    template: `
        <div class="import">
            <div>
                <div>
                    <a href="javascript:void(0);" @click="SetupImport">Setup Import</a>
                    <generic-popup :visible="inSetup" :domId="'importWizard'" :title="'Import Wizard'">
                        <template v-slot:content>
                            <input required placeholder="Enter your mapping name here..." type="text" style="border:0px; font-weight:bold; width:100%;" v-model="MappingName" /><br/>
                            <textarea required placeholder="Enter your mapping description..." style="width:100%; height:2em; border:0px;" v-model="MappingDescription"></textarea>

                            <table v-if="currentStep == 0" class="table table-striped table-hover table-bordered mb-3">
                                 <tbody>
                                <tr>
                                    <td>
                                        Target Server
                                    </td>
                                    <td>
                                         <select v-model="targetServer">
                                            <option value="">Select</option>
                                            <option v-for="server in targetServers" :value="server">{{server.name}}</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr v-if="targetServer && targetServer.parsedResponse">
                                    <td>
                                        Site:
                                    </td>
                                    <td>
                                        <select v-model="targetSite">
                                            <option value="">Select</option>
                                            <option v-for="site in targetServer.parsedResponse.Items" :value="site.Id">{{site.Name}}</option>
                                        </select>
                                    </td>
                                </tr>
                                <tr v-if="targetModules">
                                    <td>
                                        Module:
                                    </td>
                                    <td>
                                        <select v-model="targetModule">
                                        <option value="">Select</option>
                                        <option v-for="module in targetModules.DataSources" :value="module">{{module.Title}}</option>
                                    </select>
                                    </td>
                                </tr>
                                <tr v-if="targetTypes">
                                    <td>
                                        Content type:
                                    </td>
                                    <td>
                                        <textarea v-if="false">{{JSON.stringify(targetTypes, null, 3)}}</textarea>
                                        <select v-model="targetType">
                                            <option value="">Select</option>
                                            <option v-for="targetType in targetTypes.items" :value="targetType">{{targetType.contentTypeItemName}}</option>
                                        </select>
                                        <textarea v-if="false" style="width:500px;">{{JSON.stringify(targetModule, null, 3)}}</textarea>
                                    </td>
                                </tr>
                                <tr v-if="targetModule">
                                    <td>
                                        Source:
                                    </td>
                                    <td>
                                        <select v-model="targetSource">
                                            <option value="">Select</option>
                                            <option v-for="module in targetModule.Links" :value="module.ProviderName">{{module.ProviderTitle}}</option>
                                        </select>
                                        <textarea v-if="false" style="width:500px;">{{JSON.stringify(targetModule, null, 3)}}</textarea>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                            <table v-if="currentStep == 1" class="table table-striped table-hover table-bordered mb-3">
                                <thead>
                                    <th>
                                        Source field:
                                    </th>
                                    <th>
                                        Target field:
                                    </th>
                                    <th>
                                        Options:
                                    </th>
                                </thead>
                                <tbody>
                                <tr v-for="mapping in mappings">
                                    <td>
                                        <textarea v-if="false">{{JSON.stringify(selectedNode.fields, null, 3)}}</textarea>
                                        <select v-model="mapping.Source">
                                            <option v-for="(field) in selectedNode.fields" :value="field">{{field.name}}</option>
                                        </select>
                                    </td>
                                    <td>
                                <textarea v-if="false">{{JSON.stringify(moduleDetails.result.typeInfo.fields, null, 3)}}</textarea>
                                            <select v-model="mapping.Target" @change="PopulateItemFieldMapping(mapping)">
                                                <option v-for="(field) in moduleDetails.result.typeInfo.fields" :value="field">{{field.title}}</option>
                                            </select>
                                    </td>
                                    <td>
                                        <a href="javascript:void(0);" class="text-danger">Delete</a>
                                    </td>
                                </tr>
                                </tbody>
                            </table>
                            <button v-if="currentStep == 1" class="btn btn-primary" @click="AddMapping()">Add</button>
                        </template>
                        <template v-slot:footer>
                            <button class="btn btn-primary" @click="currentStep = currentStep - 1" v-if="currentStep > 0" style="float:left;"><< {{steps[currentStep - 1]}}</button>
                            <button  style="float:right;" @click="currentStep = currentStep + 1" v-if="currentStep < steps.length - 1" type="button" class="btn btn-primary" data-dismiss="modal">{{steps[currentStep + 1]}} >></button>
                            <button  v-if="currentStep == 1" type="button" class="btn btn-primary" data-dismiss="modal" @click="SaveMappings()">Save Mappings</button>
                        </template>
                    </generic-popup>
                </div>
            </div>
            <div v-if="existingMappings && existingMappings.length > 0" class="mt-4">
                <table class="table table-striped table-hover table-bordered mb-3">
                    <thead>
                        <tr>
                            <td>Name:</td>
                            <td>Description:</td>
                            <td>Actions: </td>
                        </tr>
                    </thead>
                    <tbody>
                        <tr v-for="mapping in existingMappings">
                            <td>{{mapping.name}}</td>
                            <td>{{mapping.description}}</td>
                            <td>
                                <a href="javascript:void(0);" @click="RunImport(mapping)">Run Import</a>
                                <a class="text-danger" href="javascript:void(0);" @click="DeleteMapping(mapping)">Delete</a>
                                <a class="text-danger" href="javascript:void(0);" @click="ClearMemory(mapping)">Clear memory</a>
                            </td>
                        </tr>
                    </tbody>
                </table>
            </div>
        </div>
    `
});

Vue.component('statistics-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            currentNodeStats: null
        };
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.UpdateNodeStats(newVal);
                }
                else {
                    currentNodeStats = null;
                }
            }
        }
    },
    methods: {
        fetchContentTypes(nodeId) {

        },
        async UpdateNodeStats(node) {
            var res = await fetch("/api/ContentTree/GetNodeStats?platformType=SharePoint&id=" + node.id);
        }
    },
    template: `
        <div class="statistics-tab">
            <h4>Statistics</h4>
            <div v-if="selectedNode">
                Name: {{selectedNode.name}}
            </div>
            <div v-else class="alert alert-info">
                Please select a node from the tree to view content types.
            </div>
            <div v-if="currentNodeStats">
                
            </div>
        </div>
    `
});

Vue.component('connection-dialog', {
    data() {
        return {
            connectionStrings: [],
            popupVisible: false,
        };
    },
    mounted() {
        this.GetConnections();
    },
    template: `
            <div>
                <span class="mb-3 mt-3" style="cursor:pointer;" @click="popupVisible = !popupVisible">Manage Connections</span>
                <br/>
                <popup-component @CloseModal="CloseModal" @ConnectTo="ConnectTo" :visible="popupVisible" :connections="connectionStrings">
                    
                </popup-component>
            </div>
    `,
    methods: {
        async GetConnections() {
            var res = await fetch("/api/ContentTree/GetAvailableConnectionStrings?platform=SharePoint&connectionId=" + (this.selectedConnection ? this.selectedConnection.Id : -1));
            var json = await res.json();
            this.connectionStrings = json;
        },
        CloseModal() {
            this.popupVisible = !this.popupVisible;
        },
        ConnectTo(connection) {
            this.$emit("connect", connection);
        }
    },
});

Vue.component('generic-popup', {
    props: {
        visible: false,
        domId: '',
        title: '',
    },
    template:
        `
                <div class="modal fade" :id="domId" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
                  <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">{{title}}</h5>
                      </div>
                      <div class="modal-body">
                        <slot name="content">

                        </slot>
                      </div>
                      <div class="modal-footer">
                        <slot name="footer">
                            
                        </slot>
                      </div>
                    </div>
                  </div>
                </div>
    `,
    watch: {
        visible: {
            immediate: true,
            handler(newVal) {
                try {
                    if (newVal == true)
                        $("#" + this.domId).modal('show');
                    else
                        $("#" + this.domId).modal('hide');

                }
                catch (err) {

                }
            }
        }
    }
});

Vue.component('popup-component', {
    props: {
        visible: false,
        connections: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            Id: 0,
            Name: "",
            ConnectionString: "",
            DefaultMediaHost: "",
            Platform: "SharePoint"
        };
    },
    mounted() {

    },
    methods: {
        CloseModal() {
            this.$emit("CloseModal");
        },
        ConnectTo(connection) {
            this.$emit("ConnectTo", connection);
        },
        loadConnectionForEdit(cs) {
            this.Id = cs && cs.id != null ? cs.id : 0;
            this.Name = (cs && cs.name) || '';
            this.ConnectionString = (cs && cs.connectionString) || '';
            this.DefaultMediaHost = (cs && (cs.defaultMediaHost != null ? cs.defaultMediaHost : cs.DefaultMediaHost)) || '';
            this.Platform = (cs && (cs.platform != null ? cs.platform : cs.Platform)) || 'SharePoint';
        },
        clearConnectionForm() {
            this.Id = 0;
            this.Name = '';
            this.ConnectionString = '';
            this.DefaultMediaHost = '';
            this.Platform = 'SharePoint';
        },
        async SaveConnectionString() {
            var csData = {
                Name: this.Name,
                Id: this.Id,
                ConnectionString: this.ConnectionString,
                PlatformType: this.Platform,
                DefaultMediaHost: this.DefaultMediaHost && String(this.DefaultMediaHost).trim() ? String(this.DefaultMediaHost).trim() : null
            };

            await fetch("/api/ContentTree/UpdateConnectionString", {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(csData)
            });
            this.clearConnectionForm();
        },
        async DeleteConnection(connection) {
            if (confirm("Are you sure you want to delete this SharePoint connection?")) {
                await fetch("/api/ContentTree/DeleteConnectionString?id=" + connection.id, {
                    method: 'GET',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                })
            }
        }
    },
    template: `
                <div class="modal fade" id="manage-connections" tabindex="-1" role="dialog" aria-hidden="true" data-backdrop="static" data-keyboard="false">
                  <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5 class="modal-title">{{ Id > 0 ? 'Edit connection' : 'Add New connection' }}</h5>
                      </div>
                      <div class="modal-body">
                        <slot>
                        <h4>Select Connection ({{connections.length}}):</h4>
                        <table class="table table-striped table-hover table-bordered mb-3">
                            <thead class="table-dark">
                                <tr>
                                    <th scope="col">Id</th>
                                    <th scope="col">Name</th>
                                    <th scope="col">Platform</th>
                                    <th scope="col">Actions</th>
                                </tr>
                            </thead>
                            <tbody>
                                <tr v-for="(cs, csIdx) in connections">
                                    <td>{{cs.id}}</td>
                                    <td>{{cs.name}}</td>
                                    <td>{{cs.platform}}</td>
                                    <td>
                                        <span style="cursor:pointer" @click="ConnectTo(cs)">Connect</span> |
                                        <span style="cursor:pointer" @click="loadConnectionForEdit(cs)">Edit</span> |
                                        <span class="text-danger" style="cursor:pointer" @click="DeleteConnection(cs)">Delete</span>
                                    </td>
                                </tr>

                                </tbody>
                          </table>
                          <h4 class="mt-5 mb-2">{{ Id > 0 ? 'Edit selected connection:' : 'Or Create a new one:' }}</h4>
                            <div class="form-group">
                                <label for="name">Name</label>
                                <input v-model="Name" type="text" class="form-control" id="name" required>
                              </div>
                          <div class="form-group">
                            <label for="connectionString">Connection String:</label>
                            <input type="password" v-model="ConnectionString" class="form-control" id="connectionString" required autocomplete="off">
                          </div>
                          <div class="form-group">
                            <label for="defaultMediaHostPopup">Media base URL (optional, Umbraco)</label>
                            <input v-model="DefaultMediaHost" type="text" class="form-control" id="defaultMediaHostPopup" placeholder="https://..." autocomplete="off">
                          </div>
                          <button v-if="Id > 0" type="button" class="btn btn-outline-secondary btn-sm mb-2" @click="clearConnectionForm">Cancel edit</button>
                        </slot>
                      </div>
                      <div class="modal-footer">
                        <slot name="footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal" @click="SaveConnectionString">Save</button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="CloseModal">Close</button>
                        </slot>
                      </div>
                    </div>
                  </div>
                </div>
    `,
    watch: {
        visible: {
            immediate: true,
            handler(newVal) {
                try {
                    if (newVal == true)
                        $("#manage-connections").modal('show');
                    else
                        $("#manage-connections").modal('hide');

                }
                catch (err) {

                }
            }
        }
    }
});


// Initialize the main Vue instance
document.addEventListener('DOMContentLoaded', function () {
    new Vue({
        el: '#sharepointApp',
        data: {

            // Tab configuration
            tabs: [
                { id: 'overview', name: 'Overview' },
                { id: 'content-type', name: 'Content Type' },
                { id: 'statistics', name: 'Statistics' },
                { id: 'import', name: 'Import Details' },
                // You can add the other tabs you mentioned here
            ],
            activeTab: 'overview',
            selectedNode: null,
            selectedConnection: null,
            treeItems: [],
        },
        methods: {
            handleNodeSelected(node) {
                // Simply set the selected node
                this.selectedNode = node;
            },
            handleTabChanged(tabId) {
                this.activeTab = tabId;
            },
            mounted() {
            },
            ConnectTo(connection) {
                Vue.set(this, 'selectedConnection', connection);
                
                // Use the correct localStorage key based on platform
                const storageKey = connection.platformType === 'Sitecore' ? 'lastSitecoreConnection' : 'lastConnection';
                localStorage.setItem(storageKey, JSON.stringify(connection));
            }
        }
    });
});

// Add some basic styling
document.addEventListener('DOMContentLoaded', function () {
    const style = document.createElement('style');
    style.textContent = `

        select {
            width:300px;
        }
        
        .tree-view {
            border-right: 1px solid #dee2e6;
            padding-right: 15px;
            height: 100%;
            min-height: 500px;
        }
        
        .toggle-icon, .node-text {
            cursor: pointer;
        }
        
        .toggle-icon {
            width: 20px;
            height: 20px;
            display: inline-flex;
            align-items: center;
            justify-content: center;
            border: 1px solid #ccc;
            border-radius: 3px;
            margin-right: 5px;
        }
        
        .toggle-symbol {
            font-style: normal;
            font-weight: bold;
            font-size: 14px;
        }
        
        .placeholder-icon {
            width: 20px;
            margin-right: 5px;
            display: inline-block;
        }
        
        .node-text:hover {
            text-decoration: underline;
        }
        
        .font-weight-bold {
            font-weight: bold;
            color: #007bff;
        }
        
        /* Tree hierarchy styling */
        .tree-children-container {
            padding-left: 10px;
        }
        
        .tree-children {
            padding-left: 25px;
            margin-left: 8px;
            margin-top: 8px;
            border-left: 1px dashed #ccc;
        }
        
        .tree-child-item {
            position: relative;
            padding: 3px 0;
        }
        
        .tree-child-item::before {
            content: '';
            position: absolute;
            top: 12px;
            left: -25px;
            width: 20px;
            height: 1px;
            background-color: #ccc;
        }
    `;
    document.head.appendChild(style);
});