/* Gate view — CI/CD compliance gate decisions and runner */
const GateView = {
    async render() {
        const app = document.getElementById('app');
        app.innerHTML = `
            <div class="view-header">
                <h2>Compliance Gate</h2>
                <p class="subtitle">CI/CD pass/fail decisions for deployment pipelines</p>
            </div>

            <div id="gate-summary" class="card-row" style="margin-bottom:1.5rem"></div>

            <div class="card" style="margin-bottom:1.5rem">
                <h3>Run Gate Check</h3>
                <form id="gate-form" class="form-grid" style="display:grid;grid-template-columns:repeat(auto-fill,minmax(200px,1fr));gap:0.75rem;align-items:end">
                    <label class="form-field">
                        <span>Repo Path</span>
                        <input type="text" id="gate-repo" value="." placeholder="/path/to/repo" />
                    </label>
                    <label class="form-field">
                        <span>Framework</span>
                        <select id="gate-framework">
                            <option value="eu_ai_act">EU AI Act</option>
                        </select>
                    </label>
                    <label class="form-field">
                        <span>Min Score</span>
                        <input type="number" id="gate-threshold" value="0" min="0" max="100" step="0.1" />
                    </label>
                    <label class="form-field">
                        <span>Max Gaps</span>
                        <input type="number" id="gate-max-gaps" value="-1" min="-1" />
                    </label>
                    <label class="form-field" style="display:flex;flex-direction:row;align-items:center;gap:0.5rem">
                        <input type="checkbox" id="gate-regression" />
                        <span>Fail on Regression</span>
                    </label>
                    <button type="submit" class="btn btn-primary" id="gate-run-btn">Run Gate</button>
                </form>
                <div id="gate-result" style="margin-top:1rem"></div>
            </div>

            <div class="card">
                <h3>Decision History</h3>
                <div id="gate-decisions" class="table-wrap">
                    <div class="loading">Loading...</div>
                </div>
            </div>
        `;

        this._bindForm();
        this._loadFrameworks();
        this._loadSummary();
        this._loadDecisions();
    },

    _bindForm() {
        const form = document.getElementById('gate-form');
        form.addEventListener('submit', async (e) => {
            e.preventDefault();
            const btn = document.getElementById('gate-run-btn');
            const resultDiv = document.getElementById('gate-result');
            btn.disabled = true;
            btn.textContent = 'Scanning...';
            resultDiv.innerHTML = '<div class="loading">Running gate check...</div>';

            try {
                const result = await complyApi.runGate(
                    document.getElementById('gate-repo').value,
                    document.getElementById('gate-framework').value,
                    parseFloat(document.getElementById('gate-threshold').value) || 0,
                    document.getElementById('gate-regression').checked,
                    parseInt(document.getElementById('gate-max-gaps').value, 10),
                );
                this._showResult(result);
                this._loadSummary();
                this._loadDecisions();
            } catch (err) {
                resultDiv.innerHTML = `<div class="alert alert-error">Error: ${err.message}</div>`;
            } finally {
                btn.disabled = false;
                btn.textContent = 'Run Gate';
            }
        });
    },

    _showResult(r) {
        const div = document.getElementById('gate-result');
        const cls = r.decision === 'pass' ? 'alert-success' : 'alert-error';
        const icon = r.decision === 'pass' ? '\u2713' : '\u2717';
        const sha = (r.commitSha || '').substring(0, 8) || '-';
        const maxG = r.maxCriticalGaps < 0 ? 'unlimited' : r.maxCriticalGaps;
        div.innerHTML = `
            <div class="alert ${cls}" style="font-family:monospace;line-height:1.8">
                <strong>${r.decision.toUpperCase()} ${icon}</strong><br/>
                Score: ${(r.score || 0).toFixed(1)}% (threshold: ${(r.thresholdScore || 0).toFixed(1)}%)<br/>
                Regression: ${r.regressionDetected ? 'DETECTED' : 'none'}<br/>
                Gaps: ${r.criticalGapCount} (limit: ${maxG})<br/>
                Commit: ${sha} &middot; Scan: ${r.scanId || '-'}<br/>
                <em>${r.reason}</em>
            </div>
        `;
    },

    async _loadFrameworks() {
        try {
            const fws = await complyApi.getFrameworks();
            const sel = document.getElementById('gate-framework');
            sel.innerHTML = '';
            for (const fw of fws) {
                const opt = document.createElement('option');
                opt.value = fw.id.replace(/-/g, '_');
                opt.textContent = fw.name || fw.id;
                sel.appendChild(opt);
            }
        } catch (e) { /* keep default */ }
    },

    async _loadSummary() {
        try {
            const s = await complyApi.getGateSummary();
            const div = document.getElementById('gate-summary');
            div.innerHTML = `
                <div class="stat-card"><div class="stat-value">${s.total || 0}</div><div class="stat-label">Total Checks</div></div>
                <div class="stat-card"><div class="stat-value" style="color:var(--color-success,#22c55e)">${s.passed || 0}</div><div class="stat-label">Passed</div></div>
                <div class="stat-card"><div class="stat-value" style="color:var(--color-error,#ef4444)">${s.failed || 0}</div><div class="stat-label">Failed</div></div>
                <div class="stat-card"><div class="stat-value">${s.passRate || 0}%</div><div class="stat-label">Pass Rate</div></div>
                <div class="stat-card"><div class="stat-value">${(s.avgScore || 0).toFixed(1)}%</div><div class="stat-label">Avg Score</div></div>
            `;
        } catch (e) {
            document.getElementById('gate-summary').innerHTML = '';
        }
    },

    async _loadDecisions() {
        const container = document.getElementById('gate-decisions');
        try {
            const decisions = await complyApi.listGateDecisions(null, null, 50);
            if (!decisions.length) {
                container.innerHTML = '<p class="empty">No gate decisions yet. Run a gate check above.</p>';
                return;
            }
            let html = `<table class="data-table"><thead><tr>
                <th>Time</th><th>Framework</th><th>Decision</th><th>Score</th>
                <th>Threshold</th><th>Gaps</th><th>Regression</th><th>Commit</th>
            </tr></thead><tbody>`;
            for (const d of decisions) {
                const ts = (d.createdAt || '').substring(0, 19).replace('T', ' ');
                const badge = d.decision === 'pass'
                    ? '<span class="badge badge-success">PASS</span>'
                    : '<span class="badge badge-error">FAIL</span>';
                const sha = (d.commitSha || '').substring(0, 8) || '-';
                const reg = d.regressionDetected ? 'Yes' : '-';
                const maxG = d.maxCriticalGaps < 0 ? '-' : d.maxCriticalGaps;
                html += `<tr>
                    <td>${ts}</td>
                    <td>${d.framework || ''}</td>
                    <td>${badge}</td>
                    <td>${(d.score || 0).toFixed(1)}%</td>
                    <td>${(d.thresholdScore || 0).toFixed(1)}%</td>
                    <td>${d.criticalGapCount || 0}${maxG !== '-' ? ' / ' + maxG : ''}</td>
                    <td>${reg}</td>
                    <td><code>${sha}</code></td>
                </tr>`;
            }
            html += '</tbody></table>';
            container.innerHTML = html;
        } catch (e) {
            container.innerHTML = `<p class="error">Failed to load decisions: ${e.message}</p>`;
        }
    },
};
