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 OpsViewSecurity = (() => {
    let _classDecorators = [customElement('ops-view-security')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _statsState_decorators;
    let _statsState_initializers = [];
    let _statsState_extraInitializers = [];
    let _selectedTab_decorators;
    let _selectedTab_initializers = [];
    let _selectedTab_extraInitializers = [];
    var OpsViewSecurity = 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()];
            _selectedTab_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, _selectedTab_decorators, { kind: "accessor", name: "selectedTab", static: false, private: false, access: { has: obj => "selectedTab" in obj, get: obj => obj.selectedTab, set: (obj, value) => { obj.selectedTab = value; } }, metadata: _metadata }, _selectedTab_initializers, _selectedTab_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewSecurity = _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,
            lastUpdated: 0,
            isLoading: false,
            error: null,
        });
        get statsState() { return this.#statsState_accessor_storage; }
        set statsState(value) { this.#statsState_accessor_storage = value; }
        #selectedTab_accessor_storage = (__runInitializers(this, _statsState_extraInitializers), __runInitializers(this, _selectedTab_initializers, 'overview'));
        get selectedTab() { return this.#selectedTab_accessor_storage; }
        set selectedTab(value) { this.#selectedTab_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _selectedTab_extraInitializers);
            const subscription = appstate.statsStatePart
                .select((stateArg) => stateArg)
                .subscribe((statsState) => {
                this.statsState = statsState;
            });
            this.rxSubscriptions.push(subscription);
        }
        static styles = [
            cssManager.defaultStyles,
            shared.viewHostCss,
            css `
      .tabs {
        display: flex;
        gap: 8px;
        margin-bottom: 24px;
        border-bottom: 2px solid ${cssManager.bdTheme('#e9ecef', '#333')};
      }

      .tab {
        padding: 12px 24px;
        background: none;
        border: none;
        border-bottom: 2px solid transparent;
        cursor: pointer;
        font-size: 16px;
        color: ${cssManager.bdTheme('#666', '#999')};
        transition: all 0.2s ease;
      }

      .tab:hover {
        color: ${cssManager.bdTheme('#333', '#ccc')};
      }

      .tab.active {
        color: ${cssManager.bdTheme('#2196F3', '#4a90e2')};
        border-bottom-color: ${cssManager.bdTheme('#2196F3', '#4a90e2')};
      }

      h2 {
        margin: 32px 0 16px 0;
        font-size: 24px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#333', '#ccc')};
      }

      dees-statsgrid {
        margin-bottom: 32px;
      }

      .securityCard {
        background: ${cssManager.bdTheme('#fff', '#222')};
        border: 1px solid ${cssManager.bdTheme('#e9ecef', '#333')};
        border-radius: 8px;
        padding: 24px;
        position: relative;
        overflow: hidden;
      }

      .securityCard.alert {
        border-color: ${cssManager.bdTheme('#f44336', '#ff6666')};
        background: ${cssManager.bdTheme('#ffebee', '#4a1f1f')};
      }

      .securityCard.warning {
        border-color: ${cssManager.bdTheme('#ff9800', '#ffaa33')};
        background: ${cssManager.bdTheme('#fff3e0', '#4a3a1f')};
      }

      .securityCard.success {
        border-color: ${cssManager.bdTheme('#4caf50', '#66cc66')};
        background: ${cssManager.bdTheme('#e8f5e9', '#1f3f1f')};
      }

      .cardHeader {
        display: flex;
        justify-content: space-between;
        align-items: center;
        margin-bottom: 16px;
      }

      .cardTitle {
        font-size: 18px;
        font-weight: 600;
        color: ${cssManager.bdTheme('#333', '#ccc')};
      }

      .cardStatus {
        font-size: 14px;
        padding: 4px 12px;
        border-radius: 16px;
        font-weight: 500;
      }

      .status-critical {
        background: ${cssManager.bdTheme('#f44336', '#ff6666')};
        color: ${cssManager.bdTheme('#fff', '#fff')};
      }

      .status-warning {
        background: ${cssManager.bdTheme('#ff9800', '#ffaa33')};
        color: ${cssManager.bdTheme('#fff', '#fff')};
      }

      .status-good {
        background: ${cssManager.bdTheme('#4caf50', '#66cc66')};
        color: ${cssManager.bdTheme('#fff', '#fff')};
      }

      .metricValue {
        font-size: 32px;
        font-weight: 700;
        margin-bottom: 8px;
      }

      .metricLabel {
        font-size: 14px;
        color: ${cssManager.bdTheme('#666', '#999')};
      }

      .actionButton {
        margin-top: 16px;
      }

      .blockedIpList {
        max-height: 400px;
        overflow-y: auto;
      }

      .blockedIpItem {
        display: flex;
        justify-content: space-between;
        align-items: center;
        padding: 12px;
        border-bottom: 1px solid ${cssManager.bdTheme('#e9ecef', '#333')};
      }

      .blockedIpItem:last-child {
        border-bottom: none;
      }

      .ipAddress {
        font-family: 'Consolas', 'Monaco', monospace;
        font-weight: 600;
      }

      .blockReason {
        font-size: 14px;
        color: ${cssManager.bdTheme('#666', '#999')};
      }

      .blockTime {
        font-size: 12px;
        color: ${cssManager.bdTheme('#999', '#666')};
      }
    `,
        ];
        render() {
            return html `
      <ops-sectionheading>Security</ops-sectionheading>
      
      <div class="tabs">
        <button 
          class="tab ${this.selectedTab === 'overview' ? 'active' : ''}"
          @click=${() => this.selectedTab = 'overview'}
        >
          Overview
        </button>
        <button 
          class="tab ${this.selectedTab === 'blocked' ? 'active' : ''}"
          @click=${() => this.selectedTab = 'blocked'}
        >
          Blocked IPs
        </button>
        <button 
          class="tab ${this.selectedTab === 'authentication' ? 'active' : ''}"
          @click=${() => this.selectedTab = 'authentication'}
        >
          Authentication
        </button>
        <button 
          class="tab ${this.selectedTab === 'email-security' ? 'active' : ''}"
          @click=${() => this.selectedTab = 'email-security'}
        >
          Email Security
        </button>
      </div>

      ${this.renderTabContent()}
    `;
        }
        renderTabContent() {
            const metrics = this.statsState.securityMetrics;
            if (!metrics) {
                return html `
        <div class="loadingMessage">
          <p>Loading security metrics...</p>
        </div>
      `;
            }
            switch (this.selectedTab) {
                case 'overview':
                    return this.renderOverview(metrics);
                case 'blocked':
                    return this.renderBlockedIPs(metrics);
                case 'authentication':
                    return this.renderAuthentication(metrics);
                case 'email-security':
                    return this.renderEmailSecurity(metrics);
            }
        }
        renderOverview(metrics) {
            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-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>
    `;
        }
        renderBlockedIPs(metrics) {
            return html `
      <div class="securityCard">
        <div class="cardHeader">
          <h3 class="cardTitle">Blocked IP Addresses</h3>
          <dees-button @click=${() => this.clearBlockedIPs()}>
            Clear All
          </dees-button>
        </div>
        
        <div class="blockedIpList">
          ${metrics.blockedIPs && metrics.blockedIPs.length > 0 ? metrics.blockedIPs.map((ipAddress, index) => html `
            <div class="blockedIpItem">
              <div>
                <div class="ipAddress">${ipAddress}</div>
                <div class="blockReason">Suspicious activity</div>
                <div class="blockTime">Blocked</div>
              </div>
              <dees-button @click=${() => this.unblockIP(ipAddress)}>
                Unblock
              </dees-button>
            </div>
          `) : html `
            <p>No blocked IPs</p>
          `}
        </div>
      </div>
    `;
        }
        renderAuthentication(metrics) {
            // Derive auth events from recentEvents
            const allEvents = metrics.recentEvents || [];
            const authEvents = allEvents.filter((evt) => evt.type === 'authentication');
            const successfulLogins = authEvents.filter((evt) => evt.success === true).length;
            const tiles = [
                {
                    id: 'authFailures',
                    title: 'Authentication Failures',
                    value: metrics.authenticationFailures,
                    type: 'number',
                    icon: 'lucide:LockOpen',
                    color: metrics.authenticationFailures > 10 ? '#ef4444' : '#f59e0b',
                    description: 'Failed authentication attempts today',
                },
                {
                    id: 'successfulLogins',
                    title: 'Successful Logins',
                    value: successfulLogins,
                    type: 'number',
                    icon: 'lucide:Lock',
                    color: '#22c55e',
                    description: 'Successful logins today',
                },
            ];
            // Map auth events to login history table data
            const loginHistory = authEvents.map((evt) => ({
                timestamp: evt.timestamp,
                username: evt.details?.username || 'unknown',
                ipAddress: evt.ipAddress || 'unknown',
                success: evt.success ?? false,
                reason: evt.success ? '' : evt.message || 'Authentication failed',
            }));
            return html `
      <dees-statsgrid
        .tiles=${tiles}
        .minTileWidth=${200}
      ></dees-statsgrid>

      <h2>Recent Login Attempts</h2>
      <dees-table
        .heading1=${'Login History'}
        .heading2=${'Recent authentication attempts'}
        .data=${loginHistory}
        .displayFunction=${(item) => ({
                'Time': new Date(item.timestamp).toLocaleString(),
                'Username': item.username,
                'IP Address': item.ipAddress,
                'Status': item.success ? 'Success' : 'Failed',
                'Reason': item.reason || '-',
            })}
      ></dees-table>
    `;
        }
        renderEmailSecurity(metrics) {
            const tiles = [
                {
                    id: 'malware',
                    title: 'Malware Detection',
                    value: metrics.malwareDetected,
                    type: 'number',
                    icon: 'lucide:BugOff',
                    color: metrics.malwareDetected > 0 ? '#ef4444' : '#22c55e',
                    description: 'Malware detected',
                },
                {
                    id: 'phishing',
                    title: 'Phishing Detection',
                    value: metrics.phishingDetected,
                    type: 'number',
                    icon: 'lucide:Fish',
                    color: metrics.phishingDetected > 0 ? '#ef4444' : '#22c55e',
                    description: 'Phishing attempts detected',
                },
                {
                    id: 'suspicious',
                    title: 'Suspicious Activities',
                    value: metrics.suspiciousActivities,
                    type: 'number',
                    icon: 'lucide:TriangleAlert',
                    color: metrics.suspiciousActivities > 5 ? '#ef4444' : '#f59e0b',
                    description: 'Suspicious activities detected',
                },
                {
                    id: 'spam',
                    title: 'Spam Detection',
                    value: metrics.spamDetected,
                    type: 'number',
                    icon: 'lucide:Ban',
                    color: '#f59e0b',
                    description: 'Spam emails blocked',
                },
            ];
            return html `
      <dees-statsgrid
        .tiles=${tiles}
        .minTileWidth=${200}
      ></dees-statsgrid>

      <h2>Email Security Configuration</h2>
      <div class="securityCard">
        <dees-form>
          <dees-input-checkbox 
            .key=${'enableSPF'} 
            .label=${'Enable SPF checking'} 
            .value=${true}
          ></dees-input-checkbox>
          <dees-input-checkbox 
            .key=${'enableDKIM'} 
            .label=${'Enable DKIM validation'} 
            .value=${true}
          ></dees-input-checkbox>
          <dees-input-checkbox 
            .key=${'enableDMARC'} 
            .label=${'Enable DMARC policy enforcement'} 
            .value=${true}
          ></dees-input-checkbox>
          <dees-input-checkbox 
            .key=${'enableSpamFilter'} 
            .label=${'Enable spam filtering'} 
            .value=${true}
          ></dees-input-checkbox>
        </dees-form>
        <dees-button 
          class="actionButton"
          type="highlighted"
          @click=${() => this.saveEmailSecuritySettings()}
        >
          Save Settings
        </dees-button>
      </div>
    `;
        }
        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,
            }));
        }
        async clearBlockedIPs() {
            // SmartProxy manages IP blocking — not yet exposed via API
            alert('Clearing blocked IPs is not yet supported from the UI.');
        }
        async unblockIP(ip) {
            // SmartProxy manages IP blocking — not yet exposed via API
            alert(`Unblocking IP ${ip} is not yet supported from the UI.`);
        }
        async saveEmailSecuritySettings() {
            // Config is read-only from the UI for now
            alert('Email security settings are read-only. Update the dcrouter configuration file to change these settings.');
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewSecurity = _classThis;
})();
export { OpsViewSecurity };
//# sourceMappingURL=data:application/json;base64, 