/* Monitor view — daemon status, monitor CRUD, events, alerts */
const MonitorView = {
    async render() {
        const app = document.getElementById('app');
        app.innerHTML = '<div class="loading">Loading monitors...</div>';

        try {
            const [daemonStatus, monitors, recentEvents, recentAlerts] = await Promise.all([
                complyApi.getMonitorDaemonStatus(),
                complyApi.getMonitors(),
                complyApi.getMonitorRecentEvents(20),
                complyApi.getMonitorRecentAlerts(20),
            ]);

            app.innerHTML = `
                <div class="view-header">
                    <h2>Continuous Monitoring</h2>
                </div>

                ${this._renderDaemonBanner(daemonStatus)}
                ${this._renderCreateForm()}
                ${this._renderMonitorCards(monitors)}
                ${this._renderEventsTable(recentEvents)}
                ${this._renderAlertsTable(recentAlerts)}
            `;

            this._bindEvents();
        } catch (err) {
            app.innerHTML = `<div class="error-box">Failed to load monitors: ${err.message}</div>`;
        }
    },

    _renderDaemonBanner(status) {
        const running = status.running;
        const cls = running ? 'banner-ok' : 'banner-warn';
        const label = running ? 'Running' : 'Stopped';
        return `
            <div class="banner ${cls}">
                <span class="banner-dot ${running ? 'dot-green' : 'dot-gray'}"></span>
                <strong>Daemon: ${label}</strong>
                <span class="banner-detail">
                    Active monitors: ${status.activeMonitors} &middot;
                    Queue: ${status.queueDepth}
                </span>
            </div>
        `;
    },

    _renderCreateForm() {
        return `
            <div class="card" id="create-monitor-card">
                <h3>Create Monitor</h3>
                <form id="create-monitor-form" class="form-row">
                    <input type="text" id="mon-repo" placeholder="Repository path" required class="input" />
                    <select id="mon-framework" class="input">
                        <option value="eu_ai_act">EU AI Act</option>
                        <option value="nist_ai_rmf">NIST AI RMF</option>
                        <option value="iso_42001">ISO 42001</option>
                        <option value="soc2_ai">SOC 2 AI</option>
                        <option value="owasp_llm_top10">OWASP LLM Top 10</option>
                    </select>
                    <input type="number" id="mon-interval" value="300" min="30" placeholder="Interval (s)" class="input input-sm" />
                    <input type="text" id="mon-webhook" placeholder="Webhook URL (optional)" class="input" />
                    <button type="submit" class="btn btn-primary">Create</button>
                </form>
            </div>
        `;
    },

    _renderMonitorCards(monitors) {
        if (!monitors || monitors.length === 0) {
            return '<div class="card"><p class="muted">No monitors configured yet.</p></div>';
        }
        const cards = monitors.map(m => {
            const statusCls = m.status === 'running' ? 'status-running'
                : m.status === 'error' ? 'status-error' : 'status-stopped';
            const score = m.last_scan_id ? `${m.last_score.toFixed(1)}%` : '-';
            const sha = m.last_sha ? m.last_sha.substring(0, 8) : '-';
            const repo = m.repo_path.length > 40
                ? '...' + m.repo_path.slice(-37) : m.repo_path;

            return `
                <div class="card monitor-card" data-id="${m.id}">
                    <div class="monitor-header">
                        <span class="monitor-id">${m.id}</span>
                        <span class="badge ${statusCls}">${m.status}</span>
                    </div>
                    <div class="monitor-body">
                        <div class="monitor-detail"><strong>Repo:</strong> ${repo}</div>
                        <div class="monitor-detail"><strong>Framework:</strong> ${m.framework}</div>
                        <div class="monitor-detail"><strong>Interval:</strong> ${m.interval_secs}s</div>
                        <div class="monitor-detail"><strong>Score:</strong> ${score}</div>
                        <div class="monitor-detail"><strong>SHA:</strong> ${sha}</div>
                        ${m.last_error ? `<div class="monitor-detail error-text"><strong>Error:</strong> ${m.last_error}</div>` : ''}
                    </div>
                    <div class="monitor-actions">
                        ${m.status !== 'running'
                            ? `<button class="btn btn-sm btn-success mon-start" data-id="${m.id}">Start</button>`
                            : `<button class="btn btn-sm btn-warn mon-stop" data-id="${m.id}">Stop</button>`
                        }
                        <button class="btn btn-sm btn-danger mon-delete" data-id="${m.id}">Delete</button>
                    </div>
                </div>
            `;
        }).join('');

        return `<div class="card-grid">${cards}</div>`;
    },

    _renderEventsTable(events) {
        if (!events || events.length === 0) {
            return '';
        }
        const rows = events.map(e => {
            const ts = (e.created_at || '').substring(0, 19);
            const sha = (e.commit_sha || '').substring(0, 8) || '-';
            const score = e.scan_id ? `${e.score.toFixed(1)}%` : '-';
            const typeCls = e.event_type === 'regression' ? 'text-danger'
                : e.event_type === 'error' ? 'text-warn' : '';
            return `<tr>
                <td>${ts}</td>
                <td>${e.monitor_id}</td>
                <td class="${typeCls}">${e.event_type}</td>
                <td><code>${sha}</code></td>
                <td>${score}</td>
            </tr>`;
        }).join('');

        return `
            <div class="card">
                <h3>Recent Events</h3>
                <table class="data-table">
                    <thead><tr>
                        <th>Time</th><th>Monitor</th><th>Type</th><th>SHA</th><th>Score</th>
                    </tr></thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        `;
    },

    _renderAlertsTable(alerts) {
        if (!alerts || alerts.length === 0) {
            return '';
        }
        const rows = alerts.map(a => {
            const ts = (a.created_at || '').substring(0, 19);
            const dispatched = a.dispatched ? 'Yes' : 'No';
            const sevCls = a.severity === 'high' ? 'text-danger'
                : a.severity === 'medium' ? 'text-warn' : '';
            return `<tr>
                <td>${ts}</td>
                <td>${a.monitor_id}</td>
                <td>${a.alert_type}</td>
                <td class="${sevCls}">${a.severity}</td>
                <td>${dispatched}</td>
                <td>${a.response_code || '-'}</td>
            </tr>`;
        }).join('');

        return `
            <div class="card">
                <h3>Alert History</h3>
                <table class="data-table">
                    <thead><tr>
                        <th>Time</th><th>Monitor</th><th>Type</th><th>Severity</th><th>Sent</th><th>Code</th>
                    </tr></thead>
                    <tbody>${rows}</tbody>
                </table>
            </div>
        `;
    },

    _bindEvents() {
        // Create form
        const form = document.getElementById('create-monitor-form');
        if (form) {
            form.addEventListener('submit', async (e) => {
                e.preventDefault();
                const repo = document.getElementById('mon-repo').value;
                const fw = document.getElementById('mon-framework').value;
                const interval = parseInt(document.getElementById('mon-interval').value) || 300;
                const webhook = document.getElementById('mon-webhook').value;
                try {
                    await complyApi.createMonitor(repo, fw, 'content', interval, 500, webhook);
                    this.render();
                } catch (err) {
                    alert('Failed to create monitor: ' + err.message);
                }
            });
        }

        // Start buttons
        document.querySelectorAll('.mon-start').forEach(btn => {
            btn.addEventListener('click', async () => {
                try {
                    await complyApi.startMonitor(btn.dataset.id);
                    this.render();
                } catch (err) {
                    alert('Failed to start: ' + err.message);
                }
            });
        });

        // Stop buttons
        document.querySelectorAll('.mon-stop').forEach(btn => {
            btn.addEventListener('click', async () => {
                try {
                    await complyApi.stopMonitor(btn.dataset.id);
                    this.render();
                } catch (err) {
                    alert('Failed to stop: ' + err.message);
                }
            });
        });

        // Delete buttons
        document.querySelectorAll('.mon-delete').forEach(btn => {
            btn.addEventListener('click', async () => {
                if (!confirm('Delete this monitor and all its history?')) return;
                try {
                    await complyApi.deleteMonitor(btn.dataset.id);
                    this.render();
                } catch (err) {
                    alert('Failed to delete: ' + err.message);
                }
            });
        });
    },
};
