/**
 * Code Quality Dashboard Component
 * Manages the code quality dashboard page
 */

// ✅ Use centralized logger
const codeQualityLog = window.LogConfig.createLogger('CODE-QUALITY');

function codeQualityDashboard() {
    return {
        // Extend base data
        ...data(),

        // Set current page for navigation
        currentPage: 'code-quality',

        // Dashboard-specific data
        loading: false,
        scanning: false,
        error: null,
        successMessage: null,
        stats: {
            total_violations: 0,
            errors: 0,
            warnings: 0,
            open: 0,
            assigned: 0,
            resolved: 0,
            ignored: 0,
            technical_debt_score: 100,
            trend: [],
            by_severity: {},
            by_rule: {},
            by_module: {},
            top_files: [],
            last_scan: null
        },

        async init() {
            await this.loadStats();
        },

        async loadStats() {
            this.loading = true;
            this.error = null;

            try {
                const stats = await apiClient.get('/admin/code-quality/stats');
                this.stats = stats;
            } catch (err) {
                codeQualityLog.error('Failed to load stats:', err);
                this.error = err.message;

                // Redirect to login if unauthorized
                if (err.message.includes('Unauthorized')) {
                    window.location.href = '/admin/login';
                }
            } finally {
                this.loading = false;
            }
        },

        async runScan() {
            this.scanning = true;
            this.error = null;
            this.successMessage = null;

            try {
                const scan = await apiClient.post('/admin/code-quality/scan');
                this.successMessage = `Scan completed: ${scan.total_violations} violations found (${scan.errors} errors, ${scan.warnings} warnings)`;

                // Reload stats after scan
                await this.loadStats();

                // Clear success message after 5 seconds
                setTimeout(() => {
                    this.successMessage = null;
                }, 5000);
            } catch (err) {
                codeQualityLog.error('Failed to run scan:', err);
                this.error = err.message;

                // Redirect to login if unauthorized
                if (err.message.includes('Unauthorized')) {
                    window.location.href = '/admin/login';
                }
            } finally {
                this.scanning = false;
            }
        },

        async refresh() {
            await this.loadStats();
        }
    };
}
