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 { appRouter } from '../../router.js';
import { DeesElement, customElement, html, state, css, cssManager, } from '@design.estate/dees-element';
let OpsViewConfig = (() => {
    let _classDecorators = [customElement('ops-view-config')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _configState_decorators;
    let _configState_initializers = [];
    let _configState_extraInitializers = [];
    var OpsViewConfig = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _configState_decorators = [state()];
            __esDecorate(this, null, _configState_decorators, { kind: "accessor", name: "configState", static: false, private: false, access: { has: obj => "configState" in obj, get: obj => obj.configState, set: (obj, value) => { obj.configState = value; } }, metadata: _metadata }, _configState_initializers, _configState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewConfig = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #configState_accessor_storage = __runInitializers(this, _configState_initializers, {
            config: null,
            isLoading: false,
            error: null,
        });
        get configState() { return this.#configState_accessor_storage; }
        set configState(value) { this.#configState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _configState_extraInitializers);
            const subscription = appstate.configStatePart
                .select((stateArg) => stateArg)
                .subscribe((configState) => {
                this.configState = configState;
            });
            this.rxSubscriptions.push(subscription);
        }
        static styles = [
            cssManager.defaultStyles,
            shared.viewHostCss,
            css `
      .loadingMessage {
        text-align: center;
        padding: 40px;
        color: ${cssManager.bdTheme('#71717a', '#a1a1aa')};
      }

      .errorMessage {
        background: ${cssManager.bdTheme('#fee2e2', 'rgba(239,68,68,0.1)')};
        border: 1px solid ${cssManager.bdTheme('#fecaca', 'rgba(239,68,68,0.3)')};
        border-radius: 8px;
        padding: 16px;
        color: ${cssManager.bdTheme('#dc2626', '#ef4444')};
        margin: 16px 0;
      }
    `,
        ];
        render() {
            return html `
      <dees-heading level="3">Configuration</dees-heading>

      ${this.configState.isLoading
                ? html `
            <div class="loadingMessage">
              <dees-spinner></dees-spinner>
              <p>Loading configuration...</p>
            </div>
          `
                : this.configState.error
                    ? html `
              <div class="errorMessage">
                Error loading configuration: ${this.configState.error}
              </div>
            `
                    : this.configState.config
                        ? this.renderConfig()
                        : html `<div class="errorMessage">No configuration loaded</div>`}
    `;
        }
        renderConfig() {
            const cfg = this.configState.config;
            return html `
      <sz-config-overview
        infoText="This view displays the current running configuration. DcRouter is configured through code or remote management."
        @navigate=${(e) => {
                if (e.detail?.view) {
                    appRouter.navigateToView(e.detail.view, e.detail.subview);
                }
            }}
      >
        ${this.renderSystemSection(cfg.system)}
        ${this.renderSmartProxySection(cfg.smartProxy)}
        ${this.renderEmailSection(cfg.email)}
        ${this.renderDnsSection(cfg.dns)}
        ${this.renderTlsSection(cfg.tls)}
        ${this.renderCacheSection(cfg.cache)}
        ${this.renderRadiusSection(cfg.radius)}
        ${this.renderRemoteIngressSection(cfg.remoteIngress)}
      </sz-config-overview>
    `;
        }
        renderSystemSection(sys) {
            // Annotate proxy IPs with source hint when Remote Ingress is active
            const ri = this.configState.config?.remoteIngress;
            let proxyIpValues = sys.proxyIps.length > 0 ? [...sys.proxyIps] : null;
            if (proxyIpValues && ri?.enabled && proxyIpValues.includes('127.0.0.1')) {
                proxyIpValues = proxyIpValues.map(ip => ip === '127.0.0.1' ? '127.0.0.1 (Remote Ingress)' : ip);
            }
            const fields = [
                { key: 'Base Directory', value: sys.baseDir },
                { key: 'Data Directory', value: sys.dataDir },
                { key: 'Public IP', value: sys.publicIp },
                { key: 'Proxy IPs', value: proxyIpValues, type: 'pills' },
                { key: 'Uptime', value: this.formatUptime(sys.uptime) },
                { key: 'Storage Backend', value: sys.storageBackend, type: 'badge' },
                { key: 'Storage Path', value: sys.storagePath },
            ];
            return html `
      <sz-config-section
        title="System"
        subtitle="Base paths and infrastructure"
        icon="lucide:server"
        status="enabled"
        .fields=${fields}
      ></sz-config-section>
    `;
        }
        renderSmartProxySection(proxy) {
            const fields = [
                { key: 'Route Count', value: proxy.routeCount },
            ];
            if (proxy.acme) {
                fields.push({ key: 'ACME Enabled', value: proxy.acme.enabled, type: 'boolean' }, { key: 'Account Email', value: proxy.acme.accountEmail || null }, { key: 'Use Production', value: proxy.acme.useProduction, type: 'boolean' }, { key: 'Auto Renew', value: proxy.acme.autoRenew, type: 'boolean' }, { key: 'Renew Threshold', value: `${proxy.acme.renewThresholdDays} days` });
            }
            const actions = [
                { label: 'View Routes', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'network', subview: 'routes' } },
            ];
            return html `
      <sz-config-section
        title="SmartProxy"
        subtitle="HTTP/HTTPS and TCP/SNI reverse proxy"
        icon="lucide:network"
        .status=${proxy.enabled ? 'enabled' : 'disabled'}
        .fields=${fields}
        .actions=${actions}
      ></sz-config-section>
    `;
        }
        renderEmailSection(email) {
            const fields = [
                { key: 'Ports', value: email.ports.length > 0 ? email.ports.map(String) : null, type: 'pills' },
                { key: 'Hostname', value: email.hostname },
                { key: 'Domains', value: email.domains.length > 0 ? email.domains : null, type: 'pills' },
                { key: 'Email Routes', value: email.emailRouteCount },
                { key: 'Received Emails Path', value: email.receivedEmailsPath },
            ];
            if (email.portMapping) {
                const mappingStr = Object.entries(email.portMapping)
                    .map(([ext, int]) => `${ext} → ${int}`)
                    .join(', ');
                fields.splice(1, 0, { key: 'Port Mapping', value: mappingStr, type: 'code' });
            }
            const actions = [
                { label: 'View Emails', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'email', subview: 'log' } },
            ];
            return html `
      <sz-config-section
        title="Email Server"
        subtitle="SMTP email handling with smartmta"
        icon="lucide:mail"
        .status=${email.enabled ? 'enabled' : 'disabled'}
        .fields=${fields}
        .actions=${actions}
      ></sz-config-section>
    `;
        }
        renderDnsSection(dns) {
            const fields = [
                { key: 'Port', value: dns.port },
                { key: 'NS Domains', value: dns.nsDomains.length > 0 ? dns.nsDomains : null, type: 'pills' },
                { key: 'Scopes', value: dns.scopes.length > 0 ? dns.scopes : null, type: 'pills' },
                { key: 'Record Count', value: dns.recordCount },
                { key: 'DNS Challenge', value: dns.dnsChallenge, type: 'boolean' },
            ];
            return html `
      <sz-config-section
        title="DNS Server"
        subtitle="Authoritative DNS with smartdns"
        icon="lucide:globe"
        .status=${dns.enabled ? 'enabled' : 'disabled'}
        .fields=${fields}
      ></sz-config-section>
    `;
        }
        renderTlsSection(tls) {
            const fields = [
                { key: 'Contact Email', value: tls.contactEmail },
                { key: 'Domain', value: tls.domain },
                { key: 'Source', value: tls.source, type: 'badge' },
                { key: 'Certificate Path', value: tls.certPath },
                { key: 'Key Path', value: tls.keyPath },
            ];
            const status = tls.source === 'none' ? 'not-configured' : 'enabled';
            const actions = [
                { label: 'View Certificates', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'domains', subview: 'certificates' } },
            ];
            return html `
      <sz-config-section
        title="TLS / Certificates"
        subtitle="Certificate management and ACME"
        icon="lucide:shield-check"
        .status=${status}
        .fields=${fields}
        .actions=${actions}
      ></sz-config-section>
    `;
        }
        renderCacheSection(cache) {
            const fields = [
                { key: 'Storage Path', value: cache.storagePath },
                { key: 'DB Name', value: cache.dbName },
                { key: 'Default TTL', value: `${cache.defaultTTLDays} days` },
                { key: 'Cleanup Interval', value: `${cache.cleanupIntervalHours} hours` },
            ];
            if (cache.ttlConfig && Object.keys(cache.ttlConfig).length > 0) {
                for (const [key, val] of Object.entries(cache.ttlConfig)) {
                    fields.push({ key: `TTL: ${key}`, value: `${val} days` });
                }
            }
            return html `
      <sz-config-section
        title="Cache Database"
        subtitle="Persistent caching with smartdata"
        icon="lucide:database"
        .status=${cache.enabled ? 'enabled' : 'disabled'}
        .fields=${fields}
      ></sz-config-section>
    `;
        }
        renderRadiusSection(radius) {
            const fields = [
                { key: 'Auth Port', value: radius.authPort },
                { key: 'Accounting Port', value: radius.acctPort },
                { key: 'Bind Address', value: radius.bindAddress },
                { key: 'Client Count', value: radius.clientCount },
            ];
            if (radius.vlanDefaultVlan !== null) {
                fields.push({ key: 'Default VLAN', value: radius.vlanDefaultVlan }, { key: 'Allow Unknown MACs', value: radius.vlanAllowUnknownMacs, type: 'boolean' }, { key: 'VLAN Mappings', value: radius.vlanMappingCount });
            }
            const status = radius.enabled ? 'enabled' : 'not-configured';
            return html `
      <sz-config-section
        title="RADIUS Server"
        subtitle="Network authentication and VLAN assignment"
        icon="lucide:wifi"
        .status=${status}
        .fields=${fields}
      ></sz-config-section>
    `;
        }
        renderRemoteIngressSection(ri) {
            const fields = [
                { key: 'Tunnel Port', value: ri.tunnelPort },
                { key: 'Hub Domain', value: ri.hubDomain },
                { key: 'TLS Mode', value: ri.tlsMode, type: 'badge' },
                { key: 'Connected Edge IPs', value: ri.connectedEdgeIps?.length > 0 ? ri.connectedEdgeIps : null, type: 'pills' },
            ];
            if (ri.performance) {
                fields.push({ key: 'Performance Profile', value: ri.performance.profile || null, type: 'badge' }, { key: 'Max Connections / Edge', value: ri.performance.maxStreamsPerEdge ?? null }, { key: 'Client Write Timeout', value: ri.performance.clientWriteTimeoutMs ? `${ri.performance.clientWriteTimeoutMs} ms` : null }, { key: 'First Data Timeout', value: ri.performance.firstDataConnectTimeoutMs ? `${ri.performance.firstDataConnectTimeoutMs} ms` : null }, { key: 'Server-first Ports', value: ri.performance.serverFirstPorts?.length ? ri.performance.serverFirstPorts.map(String) : null, type: 'pills' });
            }
            const actions = [
                { label: 'View Remote Ingress', icon: 'lucide:arrow-right', event: 'navigate', detail: { view: 'network', subview: 'remoteingress' } },
            ];
            return html `
      <sz-config-section
        title="Remote Ingress"
        subtitle="Edge tunnel nodes"
        icon="lucide:cloud"
        .status=${ri.enabled ? 'enabled' : 'disabled'}
        .fields=${fields}
        .actions=${actions}
      ></sz-config-section>
    `;
        }
        formatUptime(seconds) {
            const days = Math.floor(seconds / 86400);
            const hours = Math.floor((seconds % 86400) / 3600);
            const mins = Math.floor((seconds % 3600) / 60);
            const parts = [];
            if (days > 0)
                parts.push(`${days}d`);
            if (hours > 0)
                parts.push(`${hours}h`);
            parts.push(`${mins}m`);
            return parts.join(' ');
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewConfig = _classThis;
})();
export { OpsViewConfig };
//# sourceMappingURL=data:application/json;base64, 