/**
 * OverviewTab Component
 * Displays basic information about the selected node.
 * Uses detail-panel layout with Mark not needed / Include again (ExcludedStore).
 */
Vue.component('overview-tab', {
    props: {
        selectedNode: {
            type: Object,
            default: null
        },
        platformType: {
            type: String,
        },
        connection: {
            type: Object,
            default: null
        }
    },
    data() {
        return {
            fields: [],
            renderings: [],
            finalRenderings: [],
            loading: false,
            loadingRenderings: false,
            error: null,
            renderingsError: null,
            isMediaItem: false,
            overviewSubTab: 'fields',
            expandedFieldKeys: {}
        };
    },
    watch: {
        selectedNode: {
            immediate: true,
            handler(newVal) {
                if (newVal) {
                    this.loadFields();
                    this.expandedFieldKeys = {};
                } else {
                    this.fields = [];
                    this.expandedFieldKeys = {};
                }
            }
        }
    },
    methods: {
        async loadFields() {
            if (!this.selectedNode || !this.connection) {
                return;
            }

            this.loading = true;
            this.error = null;

            try {
                // Use fields from node when available (Sitecore only - SharePoint always needs GetNodeFields for resolved field names)
                if (this.isSitecore && this.selectedNode.fields && this.selectedNode.fields.length > 0) {
                    this.fields = this.selectedNode.fields;
                    this.loadRenderings();
                } else if (this.isSitecore) {
                    // Fetch for Sitecore
                    const platformToUse = this.platformType || this.connection.platformType;
                    const nodeId = this.selectedNode.id || this.selectedNode.Id;
                    const connId = this.connection.id || this.connection.Id;
                    const res = await fetch(`/api/ContentTree/GetNodeFields?id=${encodeURIComponent(nodeId)}&platformType=${platformToUse}&connectionId=${connId}`);
                    const data = await res.json();
                    
                    if (data.success === false) {
                        this.error = data.message;
                    } else {
                        this.fields = data.fields || [];
                        this.isMediaItem = data.isMediaItem;
                        this.loadRenderings();
                    }
                } else {
                    // SharePoint and other platforms - fetch via GetNodeFields
                    const platformToUse = this.platformType || this.connection.platformType;
                    const nodeId = this.selectedNode.id || this.selectedNode.Id;
                    const connId = this.connection.id || this.connection.Id;
                    const res = await fetch(`/api/ContentTree/GetNodeFields?id=${encodeURIComponent(nodeId)}&platformType=${platformToUse}&connectionId=${connId}`);
                    const data = await res.json();
                    
                    if (data.success === false) {
                        this.error = data.message;
                    } else {
                        this.fields = data.fields || [];
                        this.isMediaItem = data.isMediaItem;
                    }
                }
            } catch (error) {
                console.error('Error loading fields:', error);
                this.error = 'Failed to load fields. Please try again.';
            } finally {
                this.loading = false;
            }
        },
        
        async loadRenderings() {
            if (!this.isSitecore || !this.selectedNode || !this.connection) {
                return;
            }
            
            this.loadingRenderings = true;
            this.renderingsError = null;
            
            try {
                const platformToUse = this.platformType || this.connection.platformType;
                const nodeId = this.selectedNode.id || this.selectedNode.Id;
                const connId = this.connection.id || this.connection.Id;
                const res = await fetch(`/api/ContentTree/GetNodeRenderings?id=${encodeURIComponent(nodeId)}&platformType=${platformToUse}&connectionId=${connId}`);
                const data = await res.json();
                
                if (data.success === false) {
                    this.renderingsError = data.message;
                } else {
                    this.renderings = data.renderings || [];
                    this.finalRenderings = data.finalRenderings || [];
                }
            } catch (error) {
                console.error('Error loading renderings:', error);
                this.renderingsError = 'Failed to load renderings. Please try again.';
            } finally {
                this.loadingRenderings = false;
            }
        },
        formatValue(value) {
            if (value === null || value === undefined) {
                return '—';
            }
            
            // Convert to string
            const strValue = String(value);
            
            // Handle boolean values
            if (strValue === 'True' || strValue === 'true' || strValue === '1') {
                return 'Yes';
            }
            if (strValue === 'False' || strValue === 'false' || strValue === '0') {
                return 'No';
            }
            
            // Handle dates
            if (strValue.match(/^\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2}/)) {
                return new Date(strValue).toLocaleString();
            }
            
            // Handle empty values
            if (strValue.trim() === '') {
                return '—';
            }
            
            // Handle Sitecore image field
            if (this.isSitecore && strValue.includes('<image mediaid="{')) {
                const mediaIdMatch = strValue.match(/<image mediaid="{([^}]+)}"[^>]*>/);
                if (mediaIdMatch && mediaIdMatch[1]) {
                    const mediaId = mediaIdMatch[1];
                    const platformToUse = this.platformType || this.connection.platformType;
                    const imageUrl = `/api/ContentTree/GetFile?connectionId=${this.connection.id}&itemId=${mediaId}`;
                    
                    return `<div class="field-code">${this.escapeHtml(strValue)}</div>
                            <div class="mt-2"><img src="${imageUrl}" alt="Field Image Preview" style="max-width:80%" /></div>`;
                }
            }
            
            // Handle HTML content
            if (strValue.startsWith('<') && (strValue.includes('</') || strValue.includes('/>'))) {
                return `<div class="field-code">${this.escapeHtml(strValue)}</div>`;
            }
            
            // Handle JSON content
            if ((strValue.startsWith('{') && strValue.endsWith('}')) || 
                (strValue.startsWith('[') && strValue.endsWith(']'))) {
                try {
                    const parsed = JSON.parse(strValue);
                    return `<div class="field-code">${this.escapeHtml(JSON.stringify(parsed, null, 2))}</div>`;
                } catch (e) {
                    // Not valid JSON, continue
                }
            }
            
            // Handle long text
            if (strValue.length > 100 || strValue.includes('\n')) {
                return `<div class="field-long-text">${this.escapeHtml(strValue)}</div>`;
            }
            
            // For all other values, escape HTML entities
            return this.escapeHtml(strValue);
        },
        
        escapeHtml(text) {
            const map = {
                '&': '&amp;',
                '<': '&lt;',
                '>': '&gt;',
                '"': '&quot;',
                "'": '&#039;'
            };
            
            return text.replace(/[&<>"']/g, m => map[m]);
        },
        toggleExcluded() {
            if (!this.selectedNode || !this.connection || typeof ExcludedStore === 'undefined') return;
            var connId = this.connection.id || this.connection.Id;
            var nodeId = this.selectedNode.id || this.selectedNode.Id;
            ExcludedStore.toggleExcluded(connId, this.platformType || 'Sitecore', nodeId);
            this.$root.$emit('excluded-updated');
        },
        templateLinkUrl(templateId) {
            if (!templateId) return '#';
            var base = (typeof window !== 'undefined' && window.location) ? window.location.pathname : '/Sitecore';
            var sep = base.indexOf('?') >= 0 ? '&' : '?';
            return base + sep + 'id=' + encodeURIComponent(templateId);
        },
        toggleFieldExpand(key) {
            this.$set(this.expandedFieldKeys, key, !this.expandedFieldKeys[key]);
        },
        isFieldExpanded(key) {
            return !!this.expandedFieldKeys[key];
        },
        fieldKey(field) {
            return (field.name || '') + '_' + (field.language || '');
        },
        isCodeLike(value) {
            if (value == null || value === '') return false;
            const s = String(value);
            return (s.startsWith('<') && s.includes('</')) ||
                (s.startsWith('{') && s.endsWith('}')) ||
                (s.startsWith('[') && s.endsWith(']')) ||
                s.length > 100 ||
                s.includes('\n');
        }
    },
    computed: {
        isSitecore() {
            return this.platformType === 'Sitecore' || (this.connection && this.connection.platformType === 'Sitecore');
        },
        isExcluded() {
            if (!this.selectedNode || !this.connection || typeof ExcludedStore === 'undefined') return false;
            var connId = this.connection.id || this.connection.Id;
            var nodeId = this.selectedNode.id || this.selectedNode.Id;
            return ExcludedStore.isExcluded(connId, this.platformType || 'Sitecore', nodeId);
        },
        regularFields() {
            return this.fields
                .filter(f => !(f.name || '').startsWith('__'))
                .sort((a, b) => (a.name || '').localeCompare(b.name || ''));
        },
        systemFields() {
            return this.fields
                .filter(f => (f.name || '').startsWith('__'))
                .sort((a, b) => (a.name || '').localeCompare(b.name || ''));
        }
    },
    template: `
        <div class="overview-tab">
            <div v-if="selectedNode">
                <div class="detail-panel">
                    <div class="detail-header">
                        <div>
                            <div style="font-size: 1.1rem; font-weight: 600;">{{ selectedNode.name }}</div>
                            <div style="font-size: 0.78rem; color: var(--text-muted); margin-top: 0.15rem;" class="mono">{{ selectedNode.fullUrl || selectedNode.path || selectedNode.id }}</div>
                            <span v-if="selectedNode.type || selectedNode.contentType || selectedNode.templateName" class="chip chip-accent mt-1" style="display:inline-block;">{{ selectedNode.type || selectedNode.contentType || selectedNode.templateName || 'Unknown' }}</span>
                        </div>
                        <div style="display: flex; gap: 0.5rem; align-items: center;">
                            <button v-if="!isExcluded" class="btn-danger-subtle" @click="toggleExcluded">
                                <i class="bi bi-x-circle me-1"></i>Mark Not Needed
                            </button>
                            <button v-else class="btn-outline-subtle" @click="toggleExcluded" style="color: var(--success); border-color: rgba(52,211,153,0.3);">
                                <i class="bi bi-check-circle me-1"></i>Include Again
                            </button>
                        </div>
                    </div>
                    <div class="detail-body">
                        <div v-if="loading" class="text-center p-3">
                            <div class="spinner-border text-primary" role="status">
                                <span class="sr-only">Loading...</span>
                            </div>
                        </div>
                        
                        <div v-else-if="error" class="alert alert-danger">
                            {{ error }}
                        </div>
                        <div v-else>
                            <!-- Item ID with Template and Type -->
                            <div class="detail-meta-row mb-4">
                                <div class="detail-field-label">Item ID</div>
                                <div class="detail-field-value mono" style="font-size:0.78rem;">{{ selectedNode.id || selectedNode.Id }}</div>
                                <div class="detail-meta-sub mt-2" style="font-size:0.8rem; color: var(--text-muted);">
                                    <span><strong>Template:</strong> </span>
                                    <a v-if="selectedNode.templateId" :href="templateLinkUrl(selectedNode.templateId)" target="_blank" class="detail-link">{{ selectedNode.template || selectedNode.contentType || selectedNode.templateName || '—' }}</a>
                                    <span v-else>{{ selectedNode.template || selectedNode.contentType || selectedNode.templateName || '—' }}</span>
                                    <span class="mx-2">|</span>
                                    <span><strong>Type:</strong> </span>
                                    <a v-if="selectedNode.templateId" :href="templateLinkUrl(selectedNode.templateId)" target="_blank" class="detail-link">{{ selectedNode.type || '—' }}</a>
                                    <span v-else>{{ selectedNode.type || '—' }}</span>
                                </div>
                            </div>
                            <!-- Media preview -->
                            <div v-if="isMediaItem">
                                <img :src="'/api/ContentTree/GetFile?connectionId=' + connection.id + '&itemId=' + selectedNode.id" style="max-width:80%" />
                            </div>
                            <!-- Sub-tabs: Fields | System Fields | Renderings -->
                            <div v-if="fields.length > 0 || isSitecore" class="mt-4">
                                <div class="overview-sub-tabs mb-3">
                                    <span class="overview-sub-tab" :class="{ active: overviewSubTab === 'fields' }" @click="overviewSubTab = 'fields'">
                                        Fields <span class="tab-count">{{ regularFields.length }}</span>
                                    </span>
                                    <span class="overview-sub-tab" :class="{ active: overviewSubTab === 'system' }" @click="overviewSubTab = 'system'">
                                        System Fields <span class="tab-count">{{ systemFields.length }}</span>
                                    </span>
                                    <span v-if="isSitecore" class="overview-sub-tab" :class="{ active: overviewSubTab === 'renderings' }" @click="overviewSubTab = 'renderings'">
                                        Renderings <span class="tab-count">{{ renderings.length + finalRenderings.length }}</span>
                                    </span>
                                </div>
                                
                                <!-- Fields tab -->
                                <div v-show="overviewSubTab === 'fields'">
                                    <div v-if="regularFields.length > 0" class="table-responsive">
                                        <table class="table table-sm table-hover">
                                            <thead><tr><th style="width: 30%">Name</th><th>Value</th></tr></thead>
                                            <tbody>
                                                <tr v-for="field in regularFields" :key="fieldKey(field)">
                                                    <th>{{ field.name }} {{ field.language }}</th>
                                                    <td>
                                                        <div class="field-value-cell" :class="{ 'expandable': isCodeLike(field.value) }"
                                                             @click="isCodeLike(field.value) && toggleFieldExpand(fieldKey(field))">
                                                            <div class="field-display" :class="{ 'field-code-expanded': isFieldExpanded(fieldKey(field)) }" v-html="formatValue(field.value)"></div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div v-else class="alert alert-info">No regular fields.</div>
                                </div>
                                
                                <!-- System Fields tab -->
                                <div v-show="overviewSubTab === 'system'">
                                    <div v-if="systemFields.length > 0" class="table-responsive">
                                        <table class="table table-sm table-hover">
                                            <thead><tr><th style="width: 30%">Name</th><th>Value</th></tr></thead>
                                            <tbody>
                                                <tr v-for="field in systemFields" :key="fieldKey(field)" class="text-muted">
                                                    <th>{{ field.name }} {{ field.language }}</th>
                                                    <td>
                                                        <div class="field-value-cell" :class="{ 'expandable': isCodeLike(field.value) }"
                                                             @click="isCodeLike(field.value) && toggleFieldExpand(fieldKey(field))">
                                                            <div class="field-display" :class="{ 'field-code-expanded': isFieldExpanded(fieldKey(field)) }" v-html="formatValue(field.value)"></div>
                                                        </div>
                                                    </td>
                                                </tr>
                                            </tbody>
                                        </table>
                                    </div>
                                    <div v-else class="alert alert-info">No system fields.</div>
                                </div>
                                
                                <!-- Renderings tab (Sitecore only) -->
                                <div v-show="overviewSubTab === 'renderings' && isSitecore">
                                <div v-if="loadingRenderings" class="text-center p-3">
                                    <div class="spinner-border spinner-border-sm text-primary" role="status">
                                        <span class="sr-only">Loading renderings...</span>
                                    </div>
                                    <span class="ml-2">Loading renderings...</span>
                                </div>
                                
                                <div v-else-if="renderingsError" class="alert alert-danger">
                                    {{ renderingsError }}
                                </div>
                                
                                <div v-else>
                                    <!-- Renderings (shared presentation) -->
                                    <div v-if="renderings.length > 0" class="mb-4">
                                        <h6>Renderings <span class="text-muted" style="font-weight:normal;font-size:0.85em">(shared)</span></h6>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Placeholder</th>
                                                        <th>Datasource</th>
                                                        <th>Type</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <template v-for="rendering in renderings">
                                                        <tr :key="rendering.id">
                                                            <td>{{ rendering.name }}</td>
                                                            <td>{{ rendering.placeholder || '—' }}</td>
                                                            <td>{{ rendering.dataSourceName || '—' }}</td>
                                                            <td>{{ rendering.renderingDetails?.type || '—' }}</td>
                                                        </tr>
                                                        <tr :key="rendering.id + '-details'" class="rendering-details-row">
                                                            <td colspan="4" class="text-muted" style="font-size:0.85em; padding-top:0; padding-left:1rem; border-top:none; word-break:break-all;">
                                                                <span v-if="rendering.renderingDetails && rendering.renderingDetails.type === 'Controller'">
                                                                    {{ rendering.renderingDetails.controller }}/{{ rendering.renderingDetails.action }}
                                                                </span>
                                                                <span v-else-if="rendering.renderingDetails && rendering.renderingDetails.type === 'View'">
                                                                    {{ rendering.renderingDetails.view }}
                                                                </span>
                                                                <span v-else>—</span>
                                                            </td>
                                                        </tr>
                                                    </template>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    
                                    <!-- Final Renderings (version-specific delta) -->
                                    <div v-if="finalRenderings.length > 0" class="mb-4">
                                        <h6>Final Renderings <span class="text-muted" style="font-weight:normal;font-size:0.85em">(version-specific)</span></h6>
                                        <div class="table-responsive">
                                            <table class="table table-sm table-hover">
                                                <thead>
                                                    <tr>
                                                        <th>Name</th>
                                                        <th>Placeholder</th>
                                                        <th>Datasource</th>
                                                        <th>Type</th>
                                                    </tr>
                                                </thead>
                                                <tbody>
                                                    <template v-for="rendering in finalRenderings">
                                                        <tr :key="rendering.id">
                                                            <td>{{ rendering.name }}</td>
                                                            <td>{{ rendering.placeholder || '—' }}</td>
                                                            <td>{{ rendering.dataSourceName || '—' }}</td>
                                                            <td>{{ rendering.renderingDetails?.type || '—' }}</td>
                                                        </tr>
                                                        <tr :key="rendering.id + '-details'" class="rendering-details-row">
                                                            <td colspan="4" class="text-muted" style="font-size:0.85em; padding-top:0; padding-left:1rem; border-top:none; word-break:break-all;">
                                                                <span v-if="rendering.renderingDetails && rendering.renderingDetails.type === 'Controller'">
                                                                    {{ rendering.renderingDetails.controller }}/{{ rendering.renderingDetails.action }}
                                                                </span>
                                                                <span v-else-if="rendering.renderingDetails && rendering.renderingDetails.type === 'View'">
                                                                    {{ rendering.renderingDetails.view }}
                                                                </span>
                                                                <span v-else>—</span>
                                                            </td>
                                                        </tr>
                                                    </template>
                                                </tbody>
                                            </table>
                                        </div>
                                    </div>
                                    
                                    <div v-if="renderings.length === 0 && finalRenderings.length === 0" class="alert alert-info">
                                        No renderings found for this item.
                                    </div>
                                </div>
                                </div>
                            </div>
                            <div v-else class="alert alert-info mt-3">
                                No fields available for this item.
                            </div>
                        </div>
                    </div>
                </div>
            </div>
            <div v-else style="text-align: center; padding: 4rem 2rem; color: var(--text-muted);">
                <i class="bi bi-cursor" style="font-size: 2rem; display: block; margin-bottom: 0.75rem;"></i>
                Select a node from the tree to view details
            </div>
        </div>
    `
}); 