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 appstate from '../../appstate.js';
import { viewHostCss } from '../shared/css.js';
import { DeesElement, customElement, html, state, css, cssManager, } from '@design.estate/dees-element';
import {} from '@design.estate/dees-catalog';
let OpsViewSecurityOverview = (() => {
    let _classDecorators = [customElement('ops-view-security-overview')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _statsState_decorators;
    let _statsState_initializers = [];
    let _statsState_extraInitializers = [];
    var OpsViewSecurityOverview = 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()];
            __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(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewSecurityOverview = _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, appstate.statsStatePart.getState());
        get statsState() { return this.#statsState_accessor_storage; }
        set statsState(value) { this.#statsState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _statsState_extraInitializers);
            const sub = appstate.statsStatePart
                .select((s) => s)
                .subscribe((s) => {
                this.statsState = s;
            });
            this.rxSubscriptions.push(sub);
        }
        static styles = [
            cssManager.defaultStyles,
            viewHostCss,
            css `
      h2 {
        margin: 32px 0 16px 0;
        font-size: 24px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#333', '#ccc')};
      }
      dees-statsgrid {
        margin-bottom: 32px;
      }
    `,
        ];
        render() {
            const metrics = this.statsState.securityMetrics;
            if (!metrics) {
                return html `
        <div class="loadingMessage">
          <p>Loading security metrics...</p>
        </div>
      `;
            }
            const threatLevel = this.calculateThreatLevel(metrics);
            const threatScore = this.getThreatScore(metrics);
            // Derive active sessions from recent successful auth events (last hour)
            const allEvents = metrics.recentEvents || [];
            const oneHourAgo = Date.now() - 3600000;
            const recentAuthSuccesses = allEvents.filter((evt) => evt.type === 'authentication' && evt.success === true && evt.timestamp >= oneHourAgo).length;
            const tiles = [
                {
                    id: 'threatLevel',
                    title: 'Threat Level',
                    value: threatScore,
                    type: 'gauge',
                    icon: 'lucide:Shield',
                    gaugeOptions: {
                        min: 0,
                        max: 100,
                        thresholds: [
                            { value: 0, color: '#ef4444' },
                            { value: 30, color: '#f59e0b' },
                            { value: 70, color: '#22c55e' },
                        ],
                    },
                    description: `Status: ${threatLevel.toUpperCase()}`,
                },
                {
                    id: 'blockedThreats',
                    title: 'Blocked Threats',
                    value: (metrics.blockedIPs?.length || 0) + metrics.spamDetected,
                    type: 'number',
                    icon: 'lucide:ShieldCheck',
                    color: '#ef4444',
                    description: 'Total threats blocked today',
                },
                {
                    id: 'activeSessions',
                    title: 'Active Sessions',
                    value: recentAuthSuccesses,
                    type: 'number',
                    icon: 'lucide:Users',
                    color: '#22c55e',
                    description: 'Authenticated in last hour',
                },
                {
                    id: 'authFailures',
                    title: 'Auth Failures',
                    value: metrics.authenticationFailures,
                    type: 'number',
                    icon: 'lucide:LockOpen',
                    color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
                    description: 'Failed login attempts today',
                },
            ];
            return html `
      <dees-heading level="3">Overview</dees-heading>

      <dees-statsgrid
        .tiles=${tiles}
        .minTileWidth=${200}
      ></dees-statsgrid>

      <h2>Recent Security Events</h2>
      <dees-table
        .heading1=${'Security Events'}
        .heading2=${'Last 24 hours'}
        .data=${this.getSecurityEvents(metrics)}
        .displayFunction=${(item) => ({
                'Time': new Date(item.timestamp).toLocaleTimeString(),
                'Event': item.event,
                'Severity': item.severity,
                'Details': item.details,
            })}
      ></dees-table>
    `;
        }
        calculateThreatLevel(metrics) {
            const score = this.getThreatScore(metrics);
            if (score < 30)
                return 'alert';
            if (score < 70)
                return 'warning';
            return 'success';
        }
        getThreatScore(metrics) {
            // Simple scoring algorithm
            let score = 100;
            const blockedCount = Array.isArray(metrics.blockedIPs) ? metrics.blockedIPs.length : (metrics.blockedIPs || 0);
            score -= blockedCount * 2;
            score -= (metrics.authenticationFailures || 0) * 1;
            score -= (metrics.spamDetected || 0) * 0.5;
            score -= (metrics.malwareDetected || 0) * 3;
            score -= (metrics.phishingDetected || 0) * 3;
            score -= (metrics.suspiciousActivities || 0) * 2;
            return Math.max(0, Math.min(100, Math.round(score)));
        }
        getSecurityEvents(metrics) {
            const events = metrics.recentEvents || [];
            return events.map((evt) => ({
                timestamp: evt.timestamp,
                event: evt.message,
                severity: evt.level === 'critical' ? 'critical' : evt.level === 'error' ? 'high' : evt.level === 'warn' ? 'warning' : 'info',
                details: evt.ipAddress ? `IP: ${evt.ipAddress}` : evt.domain ? `Domain: ${evt.domain}` : evt.type,
            }));
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewSecurityOverview = _classThis;
})();
export { OpsViewSecurityOverview };
//# sourceMappingURL=data:application/json;base64, 