/**
 * @file    monitor.js
 * @brief   实时监控页面 — WebSocket 流量环形缓冲区
 */


Router.register('#monitor', function(c) {
	c.innerHTML = '<div class="card">'
		+ '<div class="card-header"><span>' + I18n.t('mon.title') + '</span>'
		+ '<div class="btn-group">'
		+ '<button class="btn btn-sm" onclick="MonitorRing.clear()">' + I18n.t('mon.clear') + '</button>'
		+ '<button class="btn btn-sm" id="mon-pause-btn" onclick="MonitorRing.togglePause()">' + I18n.t('mon.pause') + '</button>'
		+ '</div></div>'
		+ '<div class="monitor-stats" id="mon-stats"></div>'
		+ '<div class="monitor-list" id="mon-list"></div></div>';
	MonitorRing.render();
});

var MonitorRing = {
	ring: [], max: 500, paused: false,

	push: function(dir, msg) {
		if (this.paused) return;
		var ts = new Date().toLocaleTimeString();
		this.ring.push({ dir: dir, ts: ts, msg: typeof msg === 'string' ? msg : JSON.stringify(msg).substring(0, 200) });
		if (this.ring.length > this.max) { this.ring.shift(); }
		this.render();
	},

	clear: function() {
		this.ring = [];
		this.render();
	},

	togglePause: function() {
		this.paused = !this.paused;
		var btn = document.getElementById('mon-pause-btn');
		if (btn) { btn.textContent = this.paused ? I18n.t('mon.resume') : I18n.t('mon.pause'); }
	},

	render: function() {
		var stats = document.getElementById('mon-stats');
		var list  = document.getElementById('mon-list');
		if (!stats || !list) return;

		var up = 0, down = 0;
		this.ring.forEach(function(r) { r.dir === '\u2191' ? up++ : down++; });

		stats.innerHTML = '<div class="monitor-stat"><div class="monitor-stat-val">' + (up + down) + '</div>' + I18n.t('mon.total') + '</div>'
			+ '<div class="monitor-stat"><div class="monitor-stat-val" style="color:var(--accent2)">' + up + '</div>' + I18n.t('mon.sent') + ' \u2191</div>'
			+ '<div class="monitor-stat"><div class="monitor-stat-val" style="color:var(--accent)">' + down + '</div>' + I18n.t('mon.recv') + ' \u2193</div>';

		list.innerHTML = this.ring.map(function(r) {
			return '<div class="monitor-item">'
				+ '<span class="monitor-dir ' + (r.dir === '\u2191' ? 'up' : 'down') + '">' + r.dir + '</span>'
				+ '<span class="monitor-ts">' + r.ts + '</span>'
				+ '<span class="monitor-msg">' + r.msg + '</span></div>';
		}).reverse().join('');

		list.scrollTop = list.scrollHeight;
	}
};
