/**
 * DashboardTab - Matches design.html dashboard
 * Stat cards, Sites table, Renderings table
 */
Vue.component('dashboard-tab', {
    props: {
        selectedNode: { type: Object, default: null },
        connection: { type: Object, default: null },
        platformType: { type: String },
        suppressSampleModal: { type: Boolean, default: false },
        loading: { type: Boolean, default: false },
        loadingSub: { type: String, default: "" },
        totalItems: { type: Number, default: 0 },
        excludedCount: { type: Number, default: 0 },
        detachedCount: { type: Number, default: 0 },
        excludedIds: { type: Array, default: () => [] },
        sites: { type: Array, default: () => [] },
        contentTypes: { type: Array, default: () => [] },
        renderings: { type: Array, default: () => [] },
        itemCountsByLanguage: { type: Array, default: () => [] },
        notesCount: { type: Number, default: 0 },
        pageCount: { type: Number, default: 0 },
        mediaCount: { type: Number, default: 0 },
        dataCount: { type: Number, default: 0 }
    },
    data() {
        return { showTotalItemsSample: false, sampleItems: [], sampleItemsLoading: false };
    },
    methods: {
        async showTotalItemsModal() {
            this.showTotalItemsSample = true;
            this.sampleItems = [];
            this.sampleItemsLoading = true;
            try {
                var connId = (this.connection && (this.connection.id || this.connection.Id)) || -1;
                var url = '/api/ContentTree/GetSampleItems?platformType=' + encodeURIComponent(this.platformType || 'Sitecore') + '&connectionId=' + connId + '&take=10';
                var excluded = this.excludedIds;
                if (excluded && excluded.length > 0) {
                    var idsParam = (excluded instanceof Set ? [...excluded] : excluded).slice(0, 500).join(',');
                    if (idsParam) url += '&excludedIds=' + encodeURIComponent(idsParam);
                }
                var r = await fetch(url);
                var data = await r.json();
                this.sampleItems = (data && data.items) ? data.items : [];
            } catch (e) {
                console.error('Error fetching sample items:', e);
                this.sampleItems = [];
            }
            this.sampleItemsLoading = false;
        },
        closeTotalItemsModal() { this.showTotalItemsSample = false; this.sampleItems = []; }
    },
    template: `
        <div class="dashboard-tab fade-up">
            <div v-if="loading" class="dashboard-loading-overlay">
                <div class="spinner-ring"></div>
                <div class="dashboard-loading-text">Calculating instance ...</div>
                <div v-if="loadingSub" class="dashboard-loading-sub" style="color:var(--accent-bright); font-weight:500;">{{ loadingSub }}</div>
                <div class="dashboard-loading-sub">This usually takes a while</div>
                <div class="dashboard-loading-hint">You can use the tree view in the mean time to include or exclude data or review content.</div>
            </div>
            <template v-if="!loading">
            <div class="row g-3 mb-4 dashboard-stat-row">
                <div class="col-md-3">
                    <div class="stat-card" :class="{ 'stat-card-clickable': !suppressSampleModal }" @click="!suppressSampleModal && showTotalItemsModal()" :title="suppressSampleModal ? '' : 'Click to see first 10 items (with exclusion status)'">
                        <div class="stat-label">Total Items</div>
                        <div class="stat-value">{{ totalItems }}</div>
                        <div class="stat-sub">{{ excludedCount }} excluded</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Content Types</div>
                        <div class="stat-value" style="color: var(--accent-bright);">{{ contentTypes.length }}</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Renderings</div>
                        <div class="stat-value" style="color: var(--orange);">{{ renderings.length }}</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">With Notes</div>
                        <div class="stat-value" style="color: var(--warning);">{{ notesCount }}</div>
                    </div>
                </div>
            </div>
            <div class="row g-3 mb-4 dashboard-stat-row">
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Detached Items</div>
                        <div class="stat-value" style="color: var(--warning);">{{ detachedCount }}</div>
                        <div class="stat-sub">Inconsistent content</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Pages</div>
                        <div class="stat-value">{{ pageCount }}</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Media Items</div>
                        <div class="stat-value" style="color: var(--success);">{{ mediaCount }}</div>
                    </div>
                </div>
                <div class="col-md-3">
                    <div class="stat-card">
                        <div class="stat-label">Data Items</div>
                        <div class="stat-value" style="color: var(--danger);">{{ dataCount }}</div>
                    </div>
                </div>
            </div>

            <!-- Item counts by language (translations) -->
            <div v-if="itemCountsByLanguage && itemCountsByLanguage.length" class="row g-3 mb-4">
                <div class="col-12">
                    <div class="section-card">
                        <div class="section-card-header">
                            <h6><i class="bi bi-translate me-2" style="color:var(--cyan)"></i>Items by Language</h6>
                        </div>
                        <div class="section-card-body">
                            <div class="item-counts-by-lang">
                                <span v-for="lc in itemCountsByLanguage" :key="lc.language" class="lang-chip">
                                    {{ (lc.language || '').toUpperCase() }} – {{ lc.count }} items
                                </span>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Quick tables -->
            <div class="row g-3">
                <div class="col-md-12">
                    <div class="section-card">
                        <div class="section-card-header">
                            <h6><i class="bi bi-puzzle me-2" style="color:var(--orange)"></i>Renderings</h6>
                        </div>
                        <div class="section-card-body">
                            <table class="table-dark-custom">
                                <thead><tr><th>Rendering</th><th>Type</th><th>Usage</th></tr></thead>
                                <tbody>
                                    <tr v-for="r in renderings" :key="r.name">
                                        <td style="color:var(--text-primary); font-weight:500;">{{ r.name }}</td>
                                        <td><span class="chip" :class="r.type === 'View' ? 'chip-accent' : r.type === 'Template' ? 'chip-cyan' : 'chip-warning'">{{ r.type }}</span></td>
                                        <td class="mono">{{ r.usageCount }}</td>
                                    </tr>
                                    <tr v-if="renderings.length === 0">
                                        <td colspan="3" style="text-align: center; color: var(--text-muted);">No renderings</td>
                                    </tr>
                                </tbody>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Total Items sample modal (first 10 with exclusion status for troubleshooting) -->
            <div v-if="showTotalItemsSample" class="dashboard-sample-overlay" @click.self="closeTotalItemsModal">
                <div class="dashboard-sample-modal">
                    <div class="dashboard-sample-header">
                        <h6>Total Items – First 10 (for troubleshooting)</h6>
                        <button type="button" class="btn-close btn-close-white" aria-label="Close" @click="closeTotalItemsModal"></button>
                    </div>
                    <div class="dashboard-sample-body">
                        <p class="text-muted mb-2" style="font-size:0.85em;">If Excluded=Yes but count still includes them → flawed logic. If Excluded=No but count seems wrong → likely orphaned items.</p>
                        <div v-if="sampleItemsLoading" class="text-center py-3"><span class="spinner-ring spinner-ring-sm"></span> Loading...</div>
                        <table v-else class="table-dark-custom">
                            <thead><tr><th>ID</th><th>IdPath</th><th>Name</th><th>Path</th><th>Template</th><th>Excluded</th></tr></thead>
                            <tbody>
                                <tr v-for="it in sampleItems" :key="it.id" :class="{ 'text-danger': it.excluded }">
                                    <td class="mono" style="font-size:0.8em;">{{ it.id || '-' }}</td>
                                    <td class="mono" style="font-size:0.75em; max-width:200px; overflow:hidden; text-overflow:ellipsis;" :title="it.idPath">{{ it.idPath || '-' }}</td>
                                    <td>{{ it.name }}</td>
                                    <td class="mono" style="font-size:0.85em;">{{ it.path || '-' }}</td>
                                    <td>{{ it.template || '-' }}</td>
                                    <td><span :class="it.excluded ? 'chip chip-danger' : 'chip chip-success'">{{ it.excluded ? 'Yes' : 'No' }}</span></td>
                                </tr>
                                <tr v-if="!sampleItemsLoading && sampleItems.length === 0">
                                    <td colspan="6" style="text-align: center; color: var(--text-muted);">No items (Sitecore only)</td>
                                </tr>
                            </tbody>
                        </table>
                        <p class="text-muted mt-2 mb-0" style="font-size:0.85em;">Showing {{ sampleItems.length }} of {{ totalItems }}.</p>
                    </div>
                </div>
            </div>
            </template>
        </div>
    `
});
