"use strict";
/**
 * @file
 * Provides JavaScript for the unified compliance dashboard.
 * Modernized version for React/TypeScript integration.
 */
Object.defineProperty(exports, "__esModule", { value: true });
exports.ComplianceDashboard = void 0;
class ComplianceDashboard {
    constructor(container, config = {}) {
        this.container = container;
        this.config = {
            refreshInterval: 300,
            autoRefresh: true,
            ...config,
        };
        this.isInitialized = false;
        this.refreshTimer = null;
    }
    /**
     * Initialize the dashboard.
     */
    async init() {
        if (this.isInitialized) {
            return;
        }
        try {
            await this.initializeSections();
            this.setupEventListeners();
            if (this.config.autoRefresh) {
                this.startAutoRefresh();
            }
            this.isInitialized = true;
        }
        catch (error) {
            console.error('Failed to initialize compliance dashboard:', error);
        }
    }
    /**
     * Initialize dashboard sections.
     */
    async initializeSections() {
        this.initSecurityOverview();
        this.initComplianceStatus();
        this.initCodeOwnership();
        this.initPolicyEnforcement();
        // Load initial data
        await this.refreshDashboard();
    }
    /**
     * Set up event listeners.
     */
    setupEventListeners() {
        const refreshButton = this.container.querySelector('#refresh-dashboard');
        if (refreshButton) {
            refreshButton.addEventListener('click', () => this.refreshDashboard());
        }
        // Framework details buttons
        this.container.addEventListener('click', (event) => {
            if (event.target.classList.contains('details-button')) {
                const framework = event.target.dataset.framework;
                this.showFrameworkDetails(framework);
            }
            if (event.target.classList.contains('close-modal')) {
                this.hideFrameworkDetails();
            }
        });
    }
    /**
     * Start auto-refresh timer.
     */
    startAutoRefresh() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
        }
        this.refreshTimer = setInterval(() => {
            this.refreshDashboard();
        }, this.config.refreshInterval * 1000);
    }
    /**
     * Stop auto-refresh timer.
     */
    stopAutoRefresh() {
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
        }
    }
    /**
     * Refresh dashboard data.
     */
    async refreshDashboard() {
        try {
            this.showLoading();
            const response = await fetch('/admin/reports/compliance-security/ajax', {
                method: 'GET',
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                },
            });
            if (!response.ok) {
                throw new Error(`HTTP error! status: ${response.status}`);
            }
            const data = await response.json();
            if (data.securityOverview) {
                this.updateSecurityOverview(data.securityOverview);
            }
            if (data.complianceStatus) {
                this.updateComplianceStatus(data.complianceStatus);
            }
            if (data.codeOwnership) {
                this.updateCodeOwnership(data.codeOwnership);
            }
            if (data.policyEnforcement) {
                this.updatePolicyEnforcement(data.policyEnforcement);
            }
            this.hideLoading();
        }
        catch (error) {
            console.error('Error refreshing dashboard:', error);
            this.showError('Failed to refresh dashboard data');
        }
    }
    /**
     * Initialize security overview section.
     */
    initSecurityOverview() {
        const container = this.container.querySelector('#security-overview-container');
        if (!container)
            return;
        container.innerHTML = `
      <div class="security-stats">
        <div class="stat-item">
          <h4>Audit Logs</h4>
          <div class="stat-value" id="audit-log-count">-</div>
        </div>
        <div class="stat-item">
          <h4>Active Alerts</h4>
          <div class="stat-value" id="active-alerts-count">-</div>
        </div>
        <div class="stat-item">
          <h4>Recent Violations</h4>
          <div class="stat-value" id="recent-violations-count">-</div>
        </div>
      </div>
      <div class="security-chart">
        <canvas id="security-activity-chart"></canvas>
      </div>
      <div class="recent-events">
        <h4>Recent Security Events</h4>
        <div id="recent-events-list"></div>
      </div>
    `;
    }
    /**
     * Initialize compliance status section.
     */
    initComplianceStatus() {
        const container = this.container.querySelector('#compliance-status-container');
        if (!container)
            return;
        container.innerHTML = `
      <div class="compliance-summary">
        <h4>Overall Compliance</h4>
        <div class="compliance-gauge">
          <canvas id="compliance-gauge-chart"></canvas>
        </div>
      </div>
      <div class="frameworks-status" id="frameworks-status">
      </div>
      <div id="framework-details-modal" class="framework-details-modal" style="display: none;">
        <div class="modal-content">
          <span class="close-modal">&times;</span>
          <h3 id="framework-details-title">Framework Details</h3>
          <div id="framework-details-content"></div>
        </div>
      </div>
    `;
    }
    /**
     * Initialize code ownership section.
     */
    initCodeOwnership() {
        const container = this.container.querySelector('#code-ownership-container');
        if (!container)
            return;
        container.innerHTML = `
      <div class="ownership-stats">
        <div class="stat-item">
          <h4>Knowledge Silos</h4>
          <div class="stat-value" id="knowledge-silos-count">-</div>
        </div>
        <div class="stat-item">
          <h4>Files with Owners</h4>
          <div class="stat-value" id="files-with-owners">-</div>
        </div>
        <div class="stat-item">
          <h4>Files without Owners</h4>
          <div class="stat-value" id="files-without-owners">-</div>
        </div>
      </div>
      <div class="ownership-visualization">
        <h4>Knowledge Distribution</h4>
        <canvas id="ownership-distribution-chart"></canvas>
      </div>
      <div class="silos-list">
        <h4>Knowledge Silos</h4>
        <div id="silos-list-content"></div>
      </div>
    `;
    }
    /**
     * Initialize policy enforcement section.
     */
    initPolicyEnforcement() {
        const container = this.container.querySelector('#policy-enforcement-container');
        if (!container)
            return;
        container.innerHTML = `
      <div class="policies-summary">
        <div class="stat-item">
          <h4>Active Policies</h4>
          <div class="stat-value" id="active-policies-count">-</div>
        </div>
        <div class="stat-item">
          <h4>Policy Compliance</h4>
          <div class="stat-value" id="policy-compliance-rate">-</div>
        </div>
        <div class="stat-item">
          <h4>Enforced Actions</h4>
          <div class="stat-value" id="enforced-actions-count">-</div>
        </div>
      </div>
      <div class="policies-list">
        <h4>Active Policies</h4>
        <div id="policies-list-content"></div>
      </div>
    `;
    }
    /**
     * Update security overview with new data.
     */
    updateSecurityOverview(data) {
        const updateElement = (id, value) => {
            const element = this.container.querySelector(`#${id}`);
            if (element)
                element.textContent = value || 0;
        };
        updateElement('audit-log-count', data.auditLogs);
        updateElement('active-alerts-count', data.activeAlerts);
        updateElement('recent-violations-count', data.recentViolations);
        // Update recent events
        const eventsList = this.container.querySelector('#recent-events-list');
        if (eventsList) {
            if (data.recentEvents && data.recentEvents.length > 0) {
                eventsList.innerHTML = data.recentEvents.map(event => `
          <div class="event-item ${event.severity || 'info'}">
            <div class="event-time">${event.time || ''}</div>
            <div class="event-message">${event.message || ''}</div>
            <div class="event-user">${event.user || ''}</div>
          </div>
        `).join('');
            }
            else {
                eventsList.innerHTML = '<div class="empty-message">No recent events</div>';
            }
        }
    }
    /**
     * Update compliance status with new data.
     */
    updateComplianceStatus(data) {
        const frameworksContainer = this.container.querySelector('#frameworks-status');
        if (!frameworksContainer)
            return;
        const frameworks = data.frameworks || {};
        frameworksContainer.innerHTML = Object.keys(frameworks).map(framework => {
            const status = frameworks[framework];
            return `
        <div class="framework-status" data-framework="${framework}">
          <h4>${framework}</h4>
          <div class="status-indicator ${status.status || 'unknown'}">
            <span class="status-label">${this.formatStatus(status.status || 'unknown')}</span>
            <span class="status-score">${status.score || 0}%</span>
          </div>
          <div class="status-details">
            <div class="issues-count">${(status.issues || []).length} issues</div>
            <button class="button details-button" data-framework="${framework}">Details</button>
          </div>
        </div>
      `;
        }).join('') || '<div class="empty-message">No compliance frameworks configured</div>';
    }
    /**
     * Update code ownership with new data.
     */
    updateCodeOwnership(data) {
        const updateElement = (id, value) => {
            const element = this.container.querySelector(`#${id}`);
            if (element)
                element.textContent = value || 0;
        };
        updateElement('knowledge-silos-count', (data.knowledgeSilos || []).length);
        updateElement('files-without-owners', (data.ownership?.filesWithoutOwners || []).length);
        const totalFiles = data.ownership?.totalFiles || 0;
        const filesWithoutOwners = (data.ownership?.filesWithoutOwners || []).length;
        const filesWithOwners = totalFiles - filesWithoutOwners;
        updateElement('files-with-owners', filesWithOwners);
        // Update silos list
        const silosList = this.container.querySelector('#silos-list-content');
        if (silosList) {
            const silos = data.knowledgeSilos || [];
            if (silos.length > 0) {
                silosList.innerHTML = silos.map(silo => `
          <div class="silo-item">
            <div class="silo-owner">${silo.owner || ''}</div>
            <div class="silo-score">${silo.score || 0}</div>
            <div class="silo-files">${silo.fileCount || 0} files</div>
          </div>
        `).join('');
            }
            else {
                silosList.innerHTML = '<div class="empty-message">No knowledge silos detected</div>';
            }
        }
    }
    /**
     * Update policy enforcement with new data.
     */
    updatePolicyEnforcement(data) {
        const updateElement = (id, value) => {
            const element = this.container.querySelector(`#${id}`);
            if (element)
                element.textContent = value;
        };
        updateElement('active-policies-count', data.activePolicies || 0);
        updateElement('policy-compliance-rate', `${data.complianceRate || 0}%`);
        updateElement('enforced-actions-count', data.enforcedActions || 0);
        // Update policies list
        const policiesList = this.container.querySelector('#policies-list-content');
        if (policiesList) {
            if (data.policies && data.policies.length > 0) {
                policiesList.innerHTML = data.policies.map(policy => `
          <div class="policy-item ${policy.status || 'unknown'}">
            <div class="policy-name">${policy.name || ''}</div>
            <div class="policy-status">${this.formatStatus(policy.status || 'unknown')}</div>
            <div class="policy-type">${policy.type || ''}</div>
          </div>
        `).join('');
            }
            else {
                policiesList.innerHTML = '<div class="empty-message">No active policies</div>';
            }
        }
    }
    /**
     * Show framework details modal.
     */
    showFrameworkDetails(framework) {
        const modal = this.container.querySelector('#framework-details-modal');
        const title = this.container.querySelector('#framework-details-title');
        const content = this.container.querySelector('#framework-details-content');
        if (!modal || !title || !content)
            return;
        // Get framework data from config or fetch it
        const data = this.config.complianceStatus?.[framework];
        if (!data) {
            content.innerHTML = '<div class="empty-message">No data available for this framework</div>';
        }
        else {
            let detailsHtml = `
        <div class="framework-details-header">
          <div class="status-indicator ${data.status || 'unknown'}">
            <span class="status-label">${this.formatStatus(data.status || 'unknown')}</span>
            <span class="status-score">${data.score || 0}%</span>
          </div>
        </div>
      `;
            if (data.issues && data.issues.length > 0) {
                detailsHtml += '<h4>Issues</h4><div class="issues-list">';
                detailsHtml += data.issues.map(issue => `
          <div class="issue-item ${issue.severity || 'medium'}">
            <div class="issue-severity">${issue.severity || 'medium'}</div>
            <div class="issue-message">${issue.message || ''}</div>
            <div class="issue-location">${issue.location || ''}</div>
          </div>
        `).join('');
                detailsHtml += '</div>';
            }
            else {
                detailsHtml += '<div class="empty-message">No issues found</div>';
            }
            content.innerHTML = detailsHtml;
        }
        title.textContent = `${framework} Compliance Details`;
        modal.style.display = 'block';
    }
    /**
     * Hide framework details modal.
     */
    hideFrameworkDetails() {
        const modal = this.container.querySelector('#framework-details-modal');
        if (modal) {
            modal.style.display = 'none';
        }
    }
    /**
     * Format status for display.
     */
    formatStatus(status) {
        const statusMap = {
            'passing': 'Passing',
            'warning': 'Warning',
            'failing': 'Failing',
            'critical': 'Critical',
            'exempt': 'Exempt',
            'compliant': 'Compliant',
            'non-compliant': 'Non-Compliant',
        };
        return statusMap[status] || 'Unknown';
    }
    /**
     * Show loading indicator.
     */
    showLoading() {
        this.container.classList.add('loading');
    }
    /**
     * Hide loading indicator.
     */
    hideLoading() {
        this.container.classList.remove('loading');
    }
    /**
     * Show error message.
     */
    showError(message) {
        this.hideLoading();
        console.error('Dashboard error:', message);
        // Could implement UI error display here
    }
    /**
     * Destroy the dashboard and clean up resources.
     */
    destroy() {
        this.stopAutoRefresh();
        this.isInitialized = false;
    }
}
exports.ComplianceDashboard = ComplianceDashboard;
// Export for use in other modules
exports.default = ComplianceDashboard;
//# sourceMappingURL=compliance-dashboard.js.map