var __esDecorate = (this && this.__esDecorate) || function (ctor, descriptorIn, decorators, contextIn, initializers, extraInitializers) {
    function accept(f) { if (f !== void 0 && typeof f !== "function") throw new TypeError("Function expected"); return f; }
    var kind = contextIn.kind, key = kind === "getter" ? "get" : kind === "setter" ? "set" : "value";
    var target = !descriptorIn && ctor ? contextIn["static"] ? ctor : ctor.prototype : null;
    var descriptor = descriptorIn || (target ? Object.getOwnPropertyDescriptor(target, contextIn.name) : {});
    var _, done = false;
    for (var i = decorators.length - 1; i >= 0; i--) {
        var context = {};
        for (var p in contextIn) context[p] = p === "access" ? {} : contextIn[p];
        for (var p in contextIn.access) context.access[p] = contextIn.access[p];
        context.addInitializer = function (f) { if (done) throw new TypeError("Cannot add initializers after decoration has completed"); extraInitializers.push(accept(f || null)); };
        var result = (0, decorators[i])(kind === "accessor" ? { get: descriptor.get, set: descriptor.set } : descriptor[key], context);
        if (kind === "accessor") {
            if (result === void 0) continue;
            if (result === null || typeof result !== "object") throw new TypeError("Object expected");
            if (_ = accept(result.get)) descriptor.get = _;
            if (_ = accept(result.set)) descriptor.set = _;
            if (_ = accept(result.init)) initializers.unshift(_);
        }
        else if (_ = accept(result)) {
            if (kind === "field") initializers.unshift(_);
            else descriptor[key] = _;
        }
    }
    if (target) Object.defineProperty(target, contextIn.name, descriptor);
    done = true;
};
var __runInitializers = (this && this.__runInitializers) || function (thisArg, initializers, value) {
    var useValue = arguments.length > 2;
    for (var i = 0; i < initializers.length; i++) {
        value = useValue ? initializers[i].call(thisArg, value) : initializers[i].call(thisArg);
    }
    return useValue ? value : void 0;
};
import * as plugins from '../../plugins.js';
import * as shared from '../shared/index.js';
import * as appstate from '../../appstate.js';
import { DeesElement, customElement, html, state, css, cssManager, } from '@design.estate/dees-element';
import {} from '@design.estate/dees-catalog';
let OpsViewOverview = (() => {
    let _classDecorators = [customElement('ops-view-overview')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _statsState_decorators;
    let _statsState_initializers = [];
    let _statsState_extraInitializers = [];
    let _logState_decorators;
    let _logState_initializers = [];
    let _logState_extraInitializers = [];
    var OpsViewOverview = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _statsState_decorators = [state()];
            _logState_decorators = [state()];
            __esDecorate(this, null, _statsState_decorators, { kind: "accessor", name: "statsState", static: false, private: false, access: { has: obj => "statsState" in obj, get: obj => obj.statsState, set: (obj, value) => { obj.statsState = value; } }, metadata: _metadata }, _statsState_initializers, _statsState_extraInitializers);
            __esDecorate(this, null, _logState_decorators, { kind: "accessor", name: "logState", static: false, private: false, access: { has: obj => "logState" in obj, get: obj => obj.logState, set: (obj, value) => { obj.logState = value; } }, metadata: _metadata }, _logState_initializers, _logState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewOverview = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #statsState_accessor_storage = __runInitializers(this, _statsState_initializers, {
            serverStats: null,
            emailStats: null,
            dnsStats: null,
            securityMetrics: null,
            radiusStats: null,
            vpnStats: null,
            lastUpdated: 0,
            isLoading: false,
            error: null,
        });
        get statsState() { return this.#statsState_accessor_storage; }
        set statsState(value) { this.#statsState_accessor_storage = value; }
        #logState_accessor_storage = (__runInitializers(this, _statsState_extraInitializers), __runInitializers(this, _logState_initializers, {
            recentLogs: [],
            isStreaming: false,
            filters: {},
        }));
        get logState() { return this.#logState_accessor_storage; }
        set logState(value) { this.#logState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _logState_extraInitializers);
            const statsSub = appstate.statsStatePart
                .select((stateArg) => stateArg)
                .subscribe((statsState) => {
                this.statsState = statsState;
            });
            this.rxSubscriptions.push(statsSub);
            const logSub = appstate.logStatePart
                .select((stateArg) => stateArg)
                .subscribe((logState) => {
                this.logState = logState;
            });
            this.rxSubscriptions.push(logSub);
        }
        async connectedCallback() {
            super.connectedCallback();
            // Ensure logs are fetched for the overview charts
            if (this.logState.recentLogs.length === 0) {
                appstate.logStatePart.dispatchAction(appstate.fetchRecentLogsAction, { limit: 100 });
            }
        }
        static styles = [
            cssManager.defaultStyles,
            shared.viewHostCss,
            css `
      .chartGrid {
        display: grid;
        grid-template-columns: repeat(2, 1fr);
        grid-gap: 16px;
        margin-top: 32px;
      }

      .loadingMessage {
        text-align: center;
        padding: 40px;
        color: ${cssManager.bdTheme('#666', '#999')};
      }

      .errorMessage {
        background-color: ${cssManager.bdTheme('#fee', '#4a1f1f')};
        border: 1px solid ${cssManager.bdTheme('#fcc', '#6a2f2f')};
        border-radius: 4px;
        padding: 16px;
        color: ${cssManager.bdTheme('#c00', '#ff6666')};
        margin: 16px 0;
      }

      dees-statsgrid {
        margin-bottom: 32px;
      }
    `,
        ];
        render() {
            return html `
      <dees-heading level="3">Stats</dees-heading>
      
      ${this.statsState.isLoading ? html `
        <div class="loadingMessage">
          <dees-spinner></dees-spinner>
          <p>Loading statistics...</p>
        </div>
      ` : this.statsState.error ? html `
        <div class="errorMessage">
          Error loading statistics: ${this.statsState.error}
        </div>
      ` : html `
        ${this.renderServerStats()}

        ${this.renderEmailStats()}

        ${this.renderDnsStats()}

        ${this.renderRadiusStats()}

        ${this.renderVpnStats()}

        <dees-heading level="hr">Activity Charts</dees-heading>
        <div class="chartGrid">
          <dees-chart-area
            .label=${'Email Traffic (24h)'}
            .series=${this.getEmailTrafficSeries()}
            .realtimeMode=${true}
            .rollingWindow=${86400000}
            .yAxisFormatter=${(val) => `${val}`}
          ></dees-chart-area>
          <dees-chart-area
            .label=${'DNS Queries (24h)'}
            .series=${this.getDnsQuerySeries()}
            .realtimeMode=${true}
            .rollingWindow=${86400000}
            .yAxisFormatter=${(val) => `${val}`}
          ></dees-chart-area>
          <dees-chart-log
            .label=${'Recent Events'}
            .logEntries=${this.getRecentEventEntries()}
          ></dees-chart-log>
          <dees-chart-log
            .label=${'DNS Queries'}
            .logEntries=${this.getDnsQueryEntries()}
          ></dees-chart-log>
        </div>
      `}
    `;
        }
        formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const minutes = Math.floor((seconds % 3600) / 60);
            const secs = Math.floor(seconds % 60);
            if (days > 0) {
                return `${days}d ${hours}h ${minutes}m ${secs}s`;
            }
            else if (hours > 0) {
                return `${hours}h ${minutes}m ${secs}s`;
            }
            else if (minutes > 0) {
                return `${minutes}m ${secs}s`;
            }
            else {
                return `${secs}s`;
            }
        }
        formatBytes(bytes) {
            const units = ['B', 'KB', 'MB', 'GB', 'TB'];
            let size = bytes;
            let unitIndex = 0;
            while (size >= 1024 && unitIndex < units.length - 1) {
                size /= 1024;
                unitIndex++;
            }
            return `${size.toFixed(1)} ${units[unitIndex]}`;
        }
        formatBitsPerSecond(bytesPerSecond) {
            const bitsPerSecond = bytesPerSecond * 8;
            const units = ['bit/s', 'kbit/s', 'Mbit/s', 'Gbit/s'];
            let size = bitsPerSecond;
            let unitIndex = 0;
            while (size >= 1000 && unitIndex < units.length - 1) {
                size /= 1000;
                unitIndex++;
            }
            return `${size.toFixed(1)} ${units[unitIndex]}`;
        }
        renderServerStats() {
            if (!this.statsState.serverStats)
                return html ``;
            const cpuUsage = Math.round(this.statsState.serverStats.cpuUsage.user);
            const memoryUsage = this.statsState.serverStats.memoryUsage.actualUsagePercentage !== undefined
                ? Math.round(this.statsState.serverStats.memoryUsage.actualUsagePercentage)
                : Math.round((this.statsState.serverStats.memoryUsage.heapUsed / this.statsState.serverStats.memoryUsage.heapTotal) * 100);
            const tiles = [
                {
                    id: 'status',
                    title: 'Server Status',
                    value: this.statsState.serverStats.uptime ? 'Online' : 'Offline',
                    type: 'text',
                    icon: 'lucide:Server',
                    color: this.statsState.serverStats.uptime ? '#22c55e' : '#ef4444',
                    description: `Uptime: ${this.formatUptime(this.statsState.serverStats.uptime)}`,
                },
                {
                    id: 'connections',
                    title: 'Active Connections',
                    value: this.statsState.serverStats.activeConnections,
                    type: 'number',
                    icon: 'lucide:Network',
                    color: '#3b82f6',
                    description: `Total: ${this.statsState.serverStats.totalConnections}`,
                },
                {
                    id: 'throughputIn',
                    title: 'Throughput In',
                    value: this.formatBitsPerSecond(this.statsState.serverStats.throughput?.bytesInPerSecond || 0),
                    type: 'text',
                    icon: 'lucide:Download',
                    color: '#22c55e',
                    description: `Total: ${this.formatBytes(this.statsState.serverStats.throughput?.bytesIn || 0)}`,
                },
                {
                    id: 'throughputOut',
                    title: 'Throughput Out',
                    value: this.formatBitsPerSecond(this.statsState.serverStats.throughput?.bytesOutPerSecond || 0),
                    type: 'text',
                    icon: 'lucide:Upload',
                    color: '#8b5cf6',
                    description: `Total: ${this.formatBytes(this.statsState.serverStats.throughput?.bytesOut || 0)}`,
                },
                {
                    id: 'cpu',
                    title: 'CPU Usage',
                    value: cpuUsage,
                    type: 'gauge',
                    icon: 'lucide:Cpu',
                    gaugeOptions: {
                        min: 0,
                        max: 100,
                        thresholds: [
                            { value: 0, color: '#22c55e' },
                            { value: 60, color: '#f59e0b' },
                            { value: 80, color: '#ef4444' },
                        ],
                    },
                },
                {
                    id: 'memory',
                    title: 'Memory Usage',
                    value: memoryUsage,
                    type: 'percentage',
                    icon: 'lucide:MemoryStick',
                    color: memoryUsage > 80 ? '#ef4444' : memoryUsage > 60 ? '#f59e0b' : '#22c55e',
                    description: this.statsState.serverStats.memoryUsage.actualUsageBytes !== undefined && this.statsState.serverStats.memoryUsage.maxMemoryMB !== undefined
                        ? `${this.formatBytes(this.statsState.serverStats.memoryUsage.actualUsageBytes)} / ${this.formatBytes(this.statsState.serverStats.memoryUsage.maxMemoryMB * 1024 * 1024)}`
                        : `${this.formatBytes(this.statsState.serverStats.memoryUsage.rss)} / ${this.formatBytes(this.statsState.serverStats.memoryUsage.heapTotal)}`,
                },
            ];
            return html `
      <dees-statsgrid
        .tiles=${tiles}
        .gridActions=${[
                {
                    name: 'Refresh',
                    iconName: 'lucide:RefreshCw',
                    action: async () => {
                        await appstate.statsStatePart.dispatchAction(appstate.fetchAllStatsAction, null);
                    },
                },
            ]}
      ></dees-statsgrid>
    `;
        }
        renderEmailStats() {
            if (!this.statsState.emailStats)
                return html ``;
            const deliveryRate = this.statsState.emailStats.deliveryRate || 0;
            const bounceRate = this.statsState.emailStats.bounceRate || 0;
            const tiles = [
                {
                    id: 'sent',
                    title: 'Emails Sent',
                    value: this.statsState.emailStats.sent,
                    type: 'number',
                    icon: 'lucide:Send',
                    color: '#22c55e',
                    description: `Delivery rate: ${(deliveryRate * 100).toFixed(1)}%`,
                },
                {
                    id: 'received',
                    title: 'Emails Received',
                    value: this.statsState.emailStats.received,
                    type: 'number',
                    icon: 'lucide:Mail',
                    color: '#3b82f6',
                },
                {
                    id: 'queued',
                    title: 'Queued',
                    value: this.statsState.emailStats.queued,
                    type: 'number',
                    icon: 'lucide:Clock',
                    color: '#f59e0b',
                    description: 'Pending delivery',
                },
                {
                    id: 'failed',
                    title: 'Failed',
                    value: this.statsState.emailStats.failed,
                    type: 'number',
                    icon: 'lucide:TriangleAlert',
                    color: '#ef4444',
                    description: `Bounce rate: ${(bounceRate * 100).toFixed(1)}%`,
                },
            ];
            return html `
      <dees-heading level="hr">Email Statistics</dees-heading>
      <dees-statsgrid .tiles=${tiles}></dees-statsgrid>
    `;
        }
        renderDnsStats() {
            if (!this.statsState.dnsStats)
                return html ``;
            const cacheHitRate = Math.round(this.statsState.dnsStats.cacheHitRate * 100);
            const tiles = [
                {
                    id: 'queries',
                    title: 'DNS Queries',
                    value: this.statsState.dnsStats.totalQueries,
                    type: 'number',
                    icon: 'lucide:Globe',
                    color: '#3b82f6',
                    description: 'Total queries handled',
                },
                {
                    id: 'cacheRate',
                    title: 'Cache Hit Rate',
                    value: cacheHitRate,
                    type: 'percentage',
                    icon: 'lucide:Database',
                    color: cacheHitRate > 80 ? '#22c55e' : cacheHitRate > 60 ? '#f59e0b' : '#ef4444',
                    description: `${this.statsState.dnsStats.cacheHits} hits / ${this.statsState.dnsStats.cacheMisses} misses`,
                },
                {
                    id: 'domains',
                    title: 'Active Domains',
                    value: this.statsState.dnsStats.activeDomains,
                    type: 'number',
                    icon: 'lucide:Network',
                    color: '#8b5cf6',
                },
                {
                    id: 'responseTime',
                    title: 'Avg Response Time',
                    value: this.statsState.dnsStats.averageResponseTime.toFixed(1),
                    unit: 'ms',
                    type: 'number',
                    icon: 'lucide:History',
                    color: this.statsState.dnsStats.averageResponseTime < 50 ? '#22c55e' : '#f59e0b',
                },
            ];
            return html `
      <dees-heading level="hr">DNS Statistics</dees-heading>
      <dees-statsgrid .tiles=${tiles}></dees-statsgrid>
    `;
        }
        renderRadiusStats() {
            if (!this.statsState.radiusStats)
                return html ``;
            const stats = this.statsState.radiusStats;
            const authTotal = stats.authRequests || 0;
            const acceptRate = authTotal > 0 ? ((stats.authAccepts / authTotal) * 100).toFixed(1) : '0.0';
            const tiles = [
                {
                    id: 'radiusStatus',
                    title: 'RADIUS Status',
                    value: stats.running ? 'Running' : 'Stopped',
                    type: 'text',
                    icon: 'lucide:ShieldCheck',
                    color: stats.running ? '#22c55e' : '#ef4444',
                    description: stats.running ? `Uptime: ${this.formatUptime(stats.uptime / 1000)}` : undefined,
                },
                {
                    id: 'authRequests',
                    title: 'Auth Requests',
                    value: stats.authRequests,
                    type: 'number',
                    icon: 'lucide:KeyRound',
                    color: '#3b82f6',
                    description: `Accept rate: ${acceptRate}% (${stats.authAccepts} / ${stats.authRejects} rejected)`,
                },
                {
                    id: 'activeSessions',
                    title: 'Active Sessions',
                    value: stats.activeSessions,
                    type: 'number',
                    icon: 'lucide:Users',
                    color: '#8b5cf6',
                },
                {
                    id: 'radiusTraffic',
                    title: 'Data Transfer',
                    value: this.formatBytes(stats.totalInputBytes + stats.totalOutputBytes),
                    type: 'text',
                    icon: 'lucide:ArrowLeftRight',
                    color: '#f59e0b',
                    description: `In: ${this.formatBytes(stats.totalInputBytes)} / Out: ${this.formatBytes(stats.totalOutputBytes)}`,
                },
            ];
            return html `
      <dees-heading level="hr">RADIUS Statistics</dees-heading>
      <dees-statsgrid .tiles=${tiles}></dees-statsgrid>
    `;
        }
        renderVpnStats() {
            if (!this.statsState.vpnStats)
                return html ``;
            const stats = this.statsState.vpnStats;
            const tiles = [
                {
                    id: 'vpnStatus',
                    title: 'VPN Status',
                    value: stats.running ? 'Running' : 'Stopped',
                    type: 'text',
                    icon: 'lucide:Shield',
                    color: stats.running ? '#22c55e' : '#ef4444',
                    description: `Subnet: ${stats.subnet}`,
                },
                {
                    id: 'connectedClients',
                    title: 'Connected Clients',
                    value: stats.connectedClients,
                    type: 'number',
                    icon: 'lucide:Wifi',
                    color: '#3b82f6',
                    description: `${stats.registeredClients} registered`,
                },
                {
                    id: 'wgPort',
                    title: 'WireGuard Port',
                    value: stats.wgListenPort,
                    type: 'number',
                    icon: 'lucide:Network',
                    color: '#8b5cf6',
                },
            ];
            return html `
      <dees-heading level="hr">VPN Statistics</dees-heading>
      <dees-statsgrid .tiles=${tiles}></dees-statsgrid>
    `;
        }
        // --- Chart data helpers ---
        getRecentEventEntries() {
            return this.logState.recentLogs.map((log) => ({
                timestamp: new Date(log.timestamp).toISOString(),
                level: log.level,
                message: log.message,
                source: log.category,
            }));
        }
        getSecurityAlertEntries() {
            const events = this.statsState.securityMetrics?.recentEvents || [];
            return events.map((evt) => ({
                timestamp: new Date(evt.timestamp).toISOString(),
                level: evt.level === 'critical' || evt.level === 'error' ? 'error' : evt.level === 'warn' ? 'warn' : 'info',
                message: evt.message,
                source: evt.type,
            }));
        }
        getDnsQueryEntries() {
            const queries = this.statsState.dnsStats?.recentQueries || [];
            return queries.map((q) => ({
                timestamp: new Date(q.timestamp).toISOString(),
                level: q.answered ? 'info' : 'warn',
                message: `${q.type} ${q.domain} (${q.responseTimeMs}ms)`,
                source: 'dns',
            }));
        }
        getEmailTrafficSeries() {
            const ts = this.statsState.emailStats?.timeSeries;
            if (!ts)
                return [];
            return [
                { name: 'Sent', color: '#22c55e', data: (ts.sent || []).map((p) => ({ x: p.timestamp, y: p.value })) },
                { name: 'Received', color: '#3b82f6', data: (ts.received || []).map((p) => ({ x: p.timestamp, y: p.value })) },
            ];
        }
        getDnsQuerySeries() {
            const ts = this.statsState.dnsStats?.timeSeries;
            if (!ts)
                return [];
            return [
                { name: 'Queries', color: '#8b5cf6', data: (ts.queries || []).map((p) => ({ x: p.timestamp, y: p.value })) },
            ];
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewOverview = _classThis;
})();
export { OpsViewOverview };
//# sourceMappingURL=data:application/json;base64, 