/**
 * TreeView.js - design.html tree-node + API tree-view for SharePoint
 * tree-node: design.html style (nested data, used by Sitecore)
 * tree-view + api-tree-node: API fetch on expand (used by SharePoint)
 */

/** Umbraco: DB/API can return duplicate folders/items; keep first occurrence per id for stable UI. */
function dedupeTreeNodesById(nodes) {
    if (!nodes || !nodes.length) return [];
    var seen = {};
    var out = [];
    for (var i = 0; i < nodes.length; i++) {
        var n = nodes[i];
        var id = n.id != null ? n.id : n.Id;
        var key = id != null && id !== '' ? String(id) : '__noid_' + i;
        if (seen[key]) continue;
        seen[key] = true;
        out.push(n);
    }
    return out;
}

// Tree Node - from design.html (nested children, in-memory)
Vue.component('tree-node', {
    name: 'tree-node',
    props: {
        node: { type: Object, required: true },
        depth: { type: Number, default: 0 },
        selectedId: { type: [String, Number], default: null },
        excludedIds: { type: Array, default: () => [] },
        ancestorExcluded: { type: Boolean, default: false }
    },
    computed: {
        iconClass() {
            var m = {
                site: 'bi bi-globe2 site',
                folder: 'bi bi-folder-fill folder',
                page: 'bi bi-file-earmark-richtext page',
                component: 'bi bi-puzzle-fill component',
                media: 'bi bi-image media',
                data: 'bi bi-database data'
            };
            return m[this.node.type] || 'bi bi-file-earmark page';
        },
        isExcluded() {
            if (this.ancestorExcluded) return true;
            if (!this.excludedIds || !this.excludedIds.length) return this.node.excluded;
            return this.excludedIds.indexOf(this.node.id) !== -1 || this.node.excluded;
        }
    },
    methods: {
        onSelect() {
            this.$emit('select', this.node);
        },
        onToggle(e) {
            e.stopPropagation();
            this.$emit('toggle', this.node);
        },
        onChildSelect(node) {
            this.$emit('select', node);
        },
        onChildToggle(node) {
            this.$emit('toggle', node);
        }
    },
    template: `
        <div class="tree-node" v-show="node.visible !== false">
            <div class="tree-row"
                :class="{ selected: selectedId === node.id, excluded: isExcluded }"
                :style="{ paddingLeft: (depth * 16 + 12) + 'px' }"
                @click="onSelect">
                <span class="tree-toggle" :class="{ open: node.expanded }"
                    v-if="node.children && node.children.length"
                    @click.stop="onToggle">
                    <i class="bi bi-chevron-right"></i>
                </span>
                <span v-else style="width: 18px; flex-shrink: 0;"></span>
                <i class="tree-icon" :class="iconClass"></i>
                <span class="tree-label">{{ node.name }}</span>
                <span class="tree-badges">
                    <span v-if="node.notes" class="tree-badge-note" title="Has notes"></span>
                    <span v-if="isExcluded" class="tree-badge-excluded">SKIP</span>
                </span>
            </div>
            <div class="tree-children" v-if="node.expanded && node.children">
                <tree-node v-for="child in node.children" :key="child.id"
                    :node="child" :depth="depth + 1" :selected-id="selectedId"
                    :excluded-ids="excludedIds"
                    :ancestor-excluded="isExcluded"
                    @select="onChildSelect"
                    @toggle="onChildToggle">
                </tree-node>
            </div>
        </div>
    `
});

// API Tree Node - for SharePoint (fetches children on expand)
Vue.component('api-tree-node', {
    name: 'api-tree-node',
    props: {
        node: { type: Object, required: true },
        expanded: { type: Object, required: true },
        nodeData: { type: Object, required: true },
        platformType: { type: String },
        connection: { type: Object, required: true },
        selectedNode: { type: Object, default: null },
        excludedIds: { type: Array, default: () => [] },
        ancestorExcluded: { type: Boolean, default: false },
        depth: { type: Number, default: 0 },
        nodesEndpoint: { type: String, default: '' },
        /** Node ids (source tree) that have at least one saved import mapping */
        importNodeIds: { type: Array, default: () => [] }
    },
    methods: {
        async toggleNode(node, e) {
            if (e) e.stopPropagation();
            if (!this.expanded[node.id]) {
                try {
                    var children = await this.fetchNodes(node.id);
                    this.$set(this.nodeData, node.id, children);
                    this.$set(this.expanded, node.id, true);
                } catch (error) {
                    console.error('Error expanding node:', error);
                    if (typeof Helpers !== 'undefined') Helpers.showNotification(error.message, 'error');
                }
            } else {
                this.$set(this.expanded, node.id, false);
            }
        },
        async fetchNodes(parentId) {
            if (!this.connection) throw new Error('Please connect first!');
            var connId = this.connection.id || this.connection.Id;
            var url;
            if (this.nodesEndpoint) {
                url = this.nodesEndpoint + '?parentId=' + encodeURIComponent(parentId || '') + '&connectionId=' + encodeURIComponent(connId);
            } else {
                url = '/api/ContentTree/GetNodes?parentId=' + encodeURIComponent(parentId || '') + '&connectionId=' + encodeURIComponent(connId) + '&platform=' + encodeURIComponent(this.platformType || '');
            }
            var response = await fetch(url);
            if (!response.ok) throw new Error('Failed to fetch nodes');
            var list = await response.json();
            if (!Array.isArray(list)) list = [];
            if (this.platformType === 'Umbraco') {
                list = dedupeTreeNodesById(list);
            }
            return list;
        },
        selectNode(node) {
            this.$emit('node-selected', node);
        }
    },
    computed: {
        isSelected: function() {
            return this.selectedNode && this.selectedNode.id === this.node.id;
        },
        isExcluded: function() {
            if (this.ancestorExcluded) return true;
            if (!this.excludedIds) return false;
            var nodeId = this.node.id || this.node.Id;
            if (this.excludedIds instanceof Set) return this.excludedIds.has(nodeId);
            return Array.isArray(this.excludedIds) && this.excludedIds.indexOf(nodeId) !== -1;
        },
        iconClass: function() {
            // Sitefinity target tree: Site, Module, Provider
            if (this.nodesEndpoint) {
                var t = (this.node.type || this.node.contentType || '').toLowerCase();
                if (t === 'site') return 'bi bi-globe2 tree-icon site';
                if (t === 'module') return 'bi bi-puzzle tree-icon component';
                if (t === 'provider') return 'bi bi-database tree-icon data';
                return 'bi bi-folder-fill tree-icon folder';
            }
            // Sitecore: Inconsistent content node - bug icon, red
            var ghostId = 'aaaaaaaa-aaaa-aaaa-aaaa-aaaaaaaaaaaa';
            if ((this.node.id || this.node.Id) === ghostId) return 'bi bi-bug tree-icon tree-icon-ghost';
            // Sitecore: use isSite, hasRenderings, hasChildren from API
            if (this.platformType === 'Sitecore') {
                if (this.node.isSite) return 'bi bi-globe2 tree-icon site';
                if (this.node.hasRenderings) return 'bi bi-file-earmark-richtext tree-icon page';
                if (this.node.hasChildren) return 'bi bi-folder-fill tree-icon folder';
                return 'bi bi-file-earmark tree-icon item';
            }
            // SharePoint / other: fallback to name/type heuristics
            var t = (this.node.type || this.node.name || '').toLowerCase();
            if (t.indexOf('media') !== -1 || t.indexOf('image') !== -1) return 'bi bi-image tree-icon media';
            if (t.indexOf('template') !== -1 || t.indexOf('folder') !== -1) return 'bi bi-folder-fill tree-icon folder';
            if (this.node.hasChildren) return 'bi bi-folder-fill tree-icon folder';
            return 'bi bi-file-earmark tree-icon page';
        },
        hasImportMapping: function() {
            var ids = this.importNodeIds;
            if (!ids || !ids.length) return false;
            var nid = String(this.node.id != null ? this.node.id : (this.node.Id != null ? this.node.Id : ''));
            for (var i = 0; i < ids.length; i++) {
                if (String(ids[i]) === nid) return true;
            }
            return false;
        }
    },
    template: [
        '<li class="tree-node">',
        '  <div class="tree-row"',
        '    :class="{ selected: isSelected, excluded: isExcluded }"',
        '    :style="{ paddingLeft: (depth * 16 + 12) + \'px\' }"',
        '    @click="selectNode(node)">',
        '    <span class="tree-toggle" :class="{ open: expanded[node.id] }"',
        '      v-if="node.hasChildren"',
        '      @click.stop="toggleNode(node, $event)">',
        '      <i class="bi bi-chevron-right"></i>',
        '    </span>',
        '    <span v-else class="tree-toggle-placeholder"></span>',
        '    <i class="tree-icon" :class="iconClass"></i>',
        '    <span class="tree-label">{{ node.name }}</span>',
        '    <span class="tree-badges">',
        '      <span v-if="hasImportMapping" class="tree-badge-import" title="Has saved import mapping">IMPORT</span>',
        '      <span v-if="isExcluded" class="tree-badge-excluded">SKIP</span>',
        '    </span>',
        '  </div>',
        '  <div v-if="expanded[node.id] && node.hasChildren" class="tree-children">',
        '    <ul class="list-unstyled">',
        '      <api-tree-node',
        '        v-for="child in nodeData[node.id]"',
        '        :key="child.id"',
        '        :node="child"',
        '        :expanded="expanded"',
        '        :nodeData="nodeData"',
        '        :platformType="platformType"',
        '        :connection="connection"',
        '        :selectedNode="selectedNode"',
        '        :excludedIds="excludedIds"',
        '        :ancestorExcluded="isExcluded"',
        '        :depth="depth + 1"',
        '        :nodesEndpoint="nodesEndpoint"',
        '        :import-node-ids="importNodeIds"',
        '        @node-selected="$emit(\'node-selected\', $event)"',
        '      ></api-tree-node>',
        '    </ul>',
        '  </div>',
        '</li>'
    ].join('')
});

// Tree View - for SharePoint (API fetch, uses api-tree-node)
Vue.component('tree-view', {
    props: {
        items: { type: Array, default: function() { return []; } },
        connection: { type: Object, required: true },
        selectedNode: { type: Object, default: null },
        platformType: { type: String, default: 'Sitecore' },
        excludedIds: { type: Array, default: function() { return []; } },
        searchFilter: { type: String, default: '' },
        initialNodeData: { type: Object, default: function() { return {}; } },
        initialExpanded: { type: Object, default: function() { return {}; } },
        nodesEndpoint: { type: String, default: '' },
        importNodeIds: { type: Array, default: function() { return []; } }
    },
    data: function() {
        return {
            expanded: {},
            nodeData: {}
        };
    },
    computed: {
        excludedSet: function() {
            var ids = this.excludedIds;
            if (!ids) return [];
            if (ids instanceof Set) return [...ids];
            return Array.isArray(ids) ? ids : [];
        },
        rootNodes: function() {
            var items = this.items || [];
            if (this.platformType === 'Umbraco') {
                items = dedupeTreeNodesById(items);
            }
            var q = (this.searchFilter || '').trim().toLowerCase();
            if (!q) return items;
            return items.filter(function(n) { return (n.name || '').toLowerCase().indexOf(q) !== -1; });
        }
    },
    mounted: function() {
        if (this.initialExpanded && Object.keys(this.initialExpanded).length) {
            this.expanded = Object.assign({}, this.initialExpanded);
        }
        if (this.initialNodeData && Object.keys(this.initialNodeData).length) {
            this.nodeData = Object.assign({}, this.initialNodeData);
        }
    },
    watch: {
        items: function(val) {
            if (val && val.length) {
                this.expanded = Object.assign({}, this.initialExpanded);
                this.nodeData = Object.assign({}, this.initialNodeData);
            } else {
                this.expanded = {};
                this.nodeData = {};
            }
        },
        initialNodeData: function(val) {
            if (val && Object.keys(val).length) {
                this.nodeData = Object.assign({}, val);
            }
        },
        initialExpanded: function(val) {
            if (val && Object.keys(val).length) {
                this.expanded = Object.assign({}, val);
            }
        }
    },
    methods: {
        onNodeSelected: function(node) {
            this.$emit('node-selected', node);
        }
    },
    template: [
        '<div class="tree-view">',
        '  <ul class="tree-root list-unstyled">',
        '    <api-tree-node',
        '      v-for="node in rootNodes"',
        '      :key="node.id"',
        '      :node="node"',
        '      :expanded="expanded"',
        '      :nodeData="nodeData"',
        '      :platformType="platformType"',
        '      :connection="connection"',
        '      :selectedNode="selectedNode"',
        '      :excludedIds="excludedSet"',
        '      :ancestorExcluded="false"',
        '      :depth="0"',
        '      :nodesEndpoint="nodesEndpoint"',
        '      :import-node-ids="importNodeIds"',
        '      @node-selected="onNodeSelected"',
        '    ></api-tree-node>',
        '  </ul>',
        '</div>'
    ].join('')
});
