
// 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) {
            // Make actual API call to your backend
            return new Promise((resolve, reject) => {
                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);
        },
        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
        }
    },
    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"
                    ></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>
    `
});

Vue.component('statistics-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        }
    },
    data() {
        return {

        };
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {

            }
        }
    },
    methods: {
        fetchContentTypes(nodeId) {

        }
    },
    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>
    `
});

Vue.component('popup-component', {
    props: {
        visible: false,
        connections: {
            type: Array,
            default: () => []
        }
    },
    data() {
        return {
            Id: 0,
            Name: "",
            Url: "",
            AccessKey: ""
        };
    },
    mounted() { 
    },
    computed: {
        editingSavedConnection() {
            return this.Id != null && Number(this.Id) > 0;
        },
    },
    methods: {
        normalizeSitefinityUrl(url) {
            var raw = (url || '').trim();
            if (!raw) return '';
            if (!/^https?:\/\//i.test(raw)) raw = 'https://' + raw;
            return raw.replace(/\/+$/, '') + '/';
        },
        beginAdd() {
            this.Id = 0;
            this.Name = '';
            this.Url = '';
            this.AccessKey = '';
        },
        loadForEdit(connection) {
            if (!connection) return;
            this.Id = connection.id != null ? connection.id : 0;
            this.Name = connection.name || '';
            var rawUrl = connection.url || '';
            this.Url = String(rawUrl).replace(/\/+$/, '');
            this.AccessKey = connection.accessKey || connection.AccessKey || '';
        },
        cancelEdit() {
            this.beginAdd();
        },
        CloseModal() {
            this.$emit("CloseModal");
        },
        ConnectTo(connection) {
            this.$emit("ConnectTo", connection);
        },
        async SaveConnectionString() {
            var url = this.normalizeSitefinityUrl(this.Url);
            var csData = {
                Name: (this.Name || '').trim(),
                Id: this.Id || 0,
                AccessKey: (this.AccessKey || '').trim(),
                Url: url
            };
            if (!csData.Name || !csData.Url || !csData.AccessKey) return;

            try {
                await fetch("/api/SitefinityConnectivity/UpdateConnectionString", {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify(csData)
                });
                this.beginAdd();
                this.$emit('connection-saved');
                if (typeof Helpers !== 'undefined') Helpers.showNotification('Connection saved successfully', 'success');
            } catch (e) {
                console.error(e);
                if (typeof Helpers !== 'undefined') Helpers.showNotification('Error saving connection', 'error');
            }
        }
    },
    template: `
                <div class="modal fade" id="manage-connections" tabindex="-1" role="dialog" aria-hidden="true">
                  <div class="modal-dialog modal-lg">
                    <div class="modal-content">
                      <div class="modal-header">
                        <h5>{{ editingSavedConnection ? 'Edit Sitefinity connection' : 'Add Sitefinity connection' }}</h5>
                      </div>
                      <div class="modal-body">
                        <slot>
                            <div class="form-group mb-3">
                                <label for="sfFriendlyName">Friendly Name</label>
                                <input v-model="Name" type="text" class="form-control" id="sfFriendlyName" required>
                              </div>
                            <div class="form-group mb-3">
                                <label for="sfUrl">Url</label>
                                <input v-model="Url" type="text" class="form-control" id="sfUrl" required>
                              </div>
                          <div class="form-group mb-3">
                            <label for="accessKey">Access Key:</label>
                            <input type="password" v-model="AccessKey" class="form-control" id="accessKey" required autocomplete="off">
                            <a href="https://webstack.azurewebsites.net/pages/pdf-view?oid=105" target="_blank">How to get one?</a>
                          </div>
                          <button v-if="editingSavedConnection" type="button" class="btn btn-outline-secondary btn-sm" @click="cancelEdit">Cancel edit</button>
                        </slot>
                      </div>
                      <div class="modal-footer">
                        <slot name="footer">
                            <button type="button" class="btn btn-primary" data-dismiss="modal" @click="SaveConnectionString">{{ editingSavedConnection ? 'Update' : 'Save' }}</button>
                            <button type="button" class="btn btn-secondary" data-dismiss="modal" @click="CloseModal">Close</button>
                        </slot>
                      </div>
                    </div>
                  </div>
                </div>
    `,
    watch: {
        visible: {
            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: '#targetServers',
        data: {
            popupVisible: false,
            targetServers: []
        },
        methods: {
            ConnectToSitefinity() {
                this.popupVisible = true;
                this.$nextTick(function () {
                    var p = this.$refs.sitefinityConnPopup;
                    if (p && p.beginAdd) p.beginAdd();
                }.bind(this));
            },
            EditConnection(server) {
                this.popupVisible = true;
                this.$nextTick(function () {
                    var p = this.$refs.sitefinityConnPopup;
                    if (p && p.loadForEdit) p.loadForEdit(server);
                }.bind(this));
            },
            OnSitefinityConnectionSaved() {
                this.GetSitefinityConnections();
                this.popupVisible = false;
            },
            CloseModal() {
                this.popupVisible = false;
            },
            async DeleteConnection(connection) {
                var con = {
                    Id: connection.id,
                    Name: connection.name,
                    Url: connection.url,
                    AccessKey: connection.accessKey
                }

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

                this.GetSitefinityConnections();
            },
            GetDetails(server) {
                if (server && server.rawSiteResponse) {
                    try {
                        jsonResult = JSON.parse(server.rawSiteResponse);
                        if (jsonResult) {
                            server.parsedResponse = jsonResult;
                        }
                    }
                    catch (err) {

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

// Add some basic styling
document.addEventListener('DOMContentLoaded', function () {
    const style = document.createElement('style');
    style.textContent = `
        .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);
});