/* Mapping view — cross-framework control mapping and jurisdiction profiles */
const MappingView = {
    _jurisdictions: [],
    _activeJurisdiction: null,

    async render() {
        const app = document.getElementById('app');
        app.innerHTML = `
        <div class="page-header">
            <h2>Cross-Framework Control Mapping</h2>
            <p>See how one capability satisfies controls across multiple frameworks</p>
        </div>
        <div id="jurisdiction-bar"></div>
        <div id="mapping-content"><div class="loading"><span class="spinner"></span> Loading mapping...</div></div>
        <div id="priorities-content"></div>`;

        await this.loadJurisdictions();
        await this.loadMapping();
        await this.loadPriorities();
    },

    async loadJurisdictions() {
        const bar = document.getElementById('jurisdiction-bar');
        if (!bar) return;
        try {
            this._jurisdictions = await complyApi.getJurisdictions();
            let html = '<div style="display:flex;gap:8px;flex-wrap:wrap;margin-bottom:16px">';
            html += `<button class="btn btn-sm${!this._activeJurisdiction ? ' btn-primary' : ''}"
                onclick="MappingView.selectJurisdiction(null)">All</button>`;
            for (const j of this._jurisdictions) {
                const active = this._activeJurisdiction === j.id;
                html += `<button class="btn btn-sm${active ? ' btn-primary' : ''}"
                    onclick="MappingView.selectJurisdiction('${j.id}')"
                    title="${j.description}">${j.label}</button>`;
            }
            html += '</div>';
            bar.innerHTML = html;
        } catch (e) {
            bar.innerHTML = '';
        }
    },

    async selectJurisdiction(id) {
        this._activeJurisdiction = id;
        await this.loadJurisdictions();
        await this.loadMapping();
    },

    async loadMapping() {
        const container = document.getElementById('mapping-content');
        if (!container) return;
        container.innerHTML = '<div class="loading"><span class="spinner"></span> Loading...</div>';

        try {
            let frameworks = null;
            if (this._activeJurisdiction) {
                const j = this._jurisdictions.find(p => p.id === this._activeJurisdiction);
                if (j) frameworks = j.frameworks.join(',');
            }
            const mapping = await complyApi.getMapping(frameworks);
            container.innerHTML = this._renderMappingTable(mapping);
        } catch (e) {
            container.innerHTML = `<div class="alert alert-error">${e.message}</div>`;
        }
    },

    _renderMappingTable(mapping) {
        const caps = mapping.capabilities || [];
        const fws = mapping.frameworks || [];

        if (!caps.length) {
            return '<div class="empty-state"><h3>No capabilities found</h3></div>';
        }

        let html = `
        <div class="card">
            <div class="card-header">Control Mapping
                <span style="font-weight:normal;font-size:12px;color:var(--text-muted)">
                    ${mapping.totalCapabilities} capabilities &middot; ${fws.length} frameworks &middot; ${mapping.totalControls} controls
                </span>
            </div>
            <div style="overflow-x:auto">
            <table style="width:100%;border-collapse:collapse;font-size:13px">
                <thead>
                    <tr style="border-bottom:2px solid var(--border-color)">
                        <th style="text-align:left;padding:8px;white-space:nowrap">Capability</th>
                        <th style="text-align:center;padding:8px;width:40px">#</th>`;

        for (const fw of fws) {
            const short = fw.replace(/_/g, ' ').replace(/\b\w/g, c => c.toUpperCase());
            html += `<th style="text-align:center;padding:8px;font-size:11px;white-space:nowrap">${short}</th>`;
        }
        html += '</tr></thead><tbody>';

        for (const cap of caps) {
            html += `<tr style="border-bottom:1px solid var(--border-color)">
                <td style="padding:8px;font-weight:500">${cap.name}</td>
                <td style="text-align:center;padding:8px;color:var(--text-muted)">${cap.framework_count}</td>`;

            for (const fw of fws) {
                const ctrls = (cap.controls || []).filter(c => c.framework === fw);
                if (ctrls.length) {
                    const ids = ctrls.map(c => c.controlId).join(', ');
                    html += `<td style="text-align:center;padding:8px;font-size:11px"
                        title="${ctrls.map(c => c.requirement).join('\n')}">${ids}</td>`;
                } else {
                    html += '<td style="text-align:center;padding:8px;color:var(--text-muted)">&mdash;</td>';
                }
            }
            html += '</tr>';
        }

        html += '</tbody></table></div></div>';
        return html;
    },

    async loadPriorities() {
        const container = document.getElementById('priorities-content');
        if (!container) return;

        try {
            const priorities = await complyApi.getMappingPriorities();
            if (!priorities || !priorities.length) {
                container.innerHTML = '';
                return;
            }

            let html = `
            <div class="card" style="margin-top:16px">
                <div class="card-header">Remediation Priorities
                    <span style="font-weight:normal;font-size:12px;color:var(--text-muted)">
                        Fix one capability to improve multiple frameworks
                    </span>
                </div>
                <div style="display:flex;flex-direction:column;gap:12px;margin-top:8px">`;

            for (const p of priorities) {
                const color = p.impact_count >= 3 ? 'var(--red)' : p.impact_count >= 2 ? 'var(--yellow)' : 'var(--text-muted)';
                const ctrls = (p.controls || []).slice(0, 4);
                const ctrlList = ctrls.map(c => {
                    const sColor = c.status === 'gap' ? 'var(--red)' : 'var(--yellow)';
                    return `<span style="font-size:11px;color:${sColor}">${c.framework}:${c.controlId}</span>`;
                }).join(' &middot; ');
                const more = (p.controls || []).length > 4
                    ? `<span style="font-size:11px;color:var(--text-muted)"> +${p.controls.length - 4} more</span>` : '';

                html += `
                <div style="padding:10px;border-left:3px solid ${color};background:var(--bg-primary);border-radius:4px">
                    <div style="display:flex;justify-content:space-between;align-items:center">
                        <strong>${p.name}</strong>
                        <span style="color:${color};font-size:12px;font-weight:600">${p.impact_count} framework${p.impact_count !== 1 ? 's' : ''}</span>
                    </div>
                    <div style="margin-top:4px">${ctrlList}${more}</div>
                </div>`;
            }

            html += '</div></div>';
            container.innerHTML = html;
        } catch (e) {
            container.innerHTML = '';
        }
    },
};
