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';
let ObViewNetwork = (() => {
    let _classDecorators = [customElement('ob-view-network')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _networkState_decorators;
    let _networkState_initializers = [];
    let _networkState_extraInitializers = [];
    let _currentTab_decorators;
    let _currentTab_initializers = [];
    let _currentTab_extraInitializers = [];
    let _selectedDomain_decorators;
    let _selectedDomain_initializers = [];
    let _selectedDomain_extraInitializers = [];
    var ObViewNetwork = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _networkState_decorators = [state()];
            _currentTab_decorators = [state()];
            _selectedDomain_decorators = [state()];
            __esDecorate(this, null, _networkState_decorators, { kind: "accessor", name: "networkState", static: false, private: false, access: { has: obj => "networkState" in obj, get: obj => obj.networkState, set: (obj, value) => { obj.networkState = value; } }, metadata: _metadata }, _networkState_initializers, _networkState_extraInitializers);
            __esDecorate(this, null, _currentTab_decorators, { kind: "accessor", name: "currentTab", static: false, private: false, access: { has: obj => "currentTab" in obj, get: obj => obj.currentTab, set: (obj, value) => { obj.currentTab = value; } }, metadata: _metadata }, _currentTab_initializers, _currentTab_extraInitializers);
            __esDecorate(this, null, _selectedDomain_decorators, { kind: "accessor", name: "selectedDomain", static: false, private: false, access: { has: obj => "selectedDomain" in obj, get: obj => obj.selectedDomain, set: (obj, value) => { obj.selectedDomain = value; } }, metadata: _metadata }, _selectedDomain_initializers, _selectedDomain_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            ObViewNetwork = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #networkState_accessor_storage = __runInitializers(this, _networkState_initializers, {
            targets: [],
            stats: null,
            statsResource: { phase: 'idle', error: null, lastSuccessAt: null },
            trafficStats: null,
            dnsRecords: [],
            domains: [],
            gatewayDomains: [],
            gatewayDnsRecords: [],
            certificates: [],
        });
        get networkState() { return this.#networkState_accessor_storage; }
        set networkState(value) { this.#networkState_accessor_storage = value; }
        #currentTab_accessor_storage = (__runInitializers(this, _networkState_extraInitializers), __runInitializers(this, _currentTab_initializers, 'proxy'));
        get currentTab() { return this.#currentTab_accessor_storage; }
        set currentTab(value) { this.#currentTab_accessor_storage = value; }
        #selectedDomain_accessor_storage = (__runInitializers(this, _currentTab_extraInitializers), __runInitializers(this, _selectedDomain_initializers, ''));
        get selectedDomain() { return this.#selectedDomain_accessor_storage; }
        set selectedDomain(value) { this.#selectedDomain_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _selectedDomain_extraInitializers);
            const networkSub = appstate.networkStatePart
                .select((s) => s)
                .subscribe((newState) => {
                this.networkState = newState;
            });
            this.rxSubscriptions.push(networkSub);
        }
        static styles = [
            cssManager.defaultStyles,
            shared.viewHostCss,
            css `
      .status-panel {
        padding: 18px;
        border: 1px solid ${cssManager.bdTheme('#e4e4e7', '#3f3f46')};
        border-radius: 10px;
        color: ${cssManager.bdTheme('#52525b', '#a1a1aa')};
        background: ${cssManager.bdTheme('#fafafa', '#18181b')};
      }

      .status-panel button {
        margin-left: 12px;
        padding: 6px 10px;
        border: 0;
        border-radius: 6px;
        cursor: pointer;
      }

      .stale-warning {
        margin-bottom: 10px;
        padding: 8px 10px;
        border-radius: 8px;
        color: ${cssManager.bdTheme('#92400e', '#fbbf24')};
        background: ${cssManager.bdTheme('#fffbeb', '#422006')};
      }
    `,
        ];
        async connectedCallback() {
            super.connectedCallback();
            await Promise.allSettled([
                appstate.dispatchProtectedAction(appstate.fetchNetworkTargetsAction, null),
                appstate.fetchNetworkStats(),
                appstate.dispatchProtectedAction(appstate.fetchTrafficStatsAction, null),
                appstate.dispatchProtectedAction(appstate.fetchDnsRecordsAction, null),
                appstate.dispatchProtectedAction(appstate.fetchDomainsAction, null),
                appstate.dispatchProtectedAction(appstate.fetchCertificatesAction, null),
            ]);
        }
        render() {
            switch (this.currentTab) {
                case 'dns':
                    return this.renderDnsView();
                case 'domains':
                    return this.renderDomainsView();
                case 'domain-detail':
                    return this.renderDomainDetailView();
                default:
                    return this.renderProxyView();
            }
        }
        renderProxyView() {
            const stats = this.networkState.stats;
            const resource = this.networkState.statsResource;
            if (!stats || stats.proxy.running === null || stats.proxy.state === 'failed') {
                return html `
        <ob-sectionheading>Network</ob-sectionheading>
        ${resource.phase === 'stale'
                    ? html `<div class="stale-warning">Showing the last known proxy status. Refresh failed.</div>`
                    : ''}
        <div class="status-panel">
          ${stats?.proxy.state === 'failed'
                    ? 'Reverse proxy status: Failed.'
                    : stats?.proxy.state === 'starting'
                        ? 'Reverse proxy is starting…'
                        : resource.phase === 'loading'
                            ? 'Loading reverse proxy status…'
                            : 'Reverse proxy status is unavailable.'}
          <button @click=${() => void appstate.fetchNetworkStats()}>Retry</button>
        </div>
      `;
            }
            return html `
      <ob-sectionheading>Network</ob-sectionheading>
      ${resource.phase === 'stale'
                ? html `<div class="stale-warning">Showing the last known proxy status. Refresh failed.</div>`
                : ''}
      <sz-network-proxy-view
        .proxyStatus=${stats.proxy.running ? 'running' : 'stopped'}
        .routeCount=${String(stats.proxy.routes)}
        .certificateCount=${String(stats.proxy.certificates)}
        .targetCount=${String(this.networkState.targets.length)}
        .targets=${this.networkState.targets.map((targetArg) => ({
                type: targetArg.type,
                name: targetArg.name,
                domain: targetArg.domain,
                target: `${targetArg.targetHost}:${targetArg.targetPort}`,
                status: targetArg.status,
            }))}
        .logs=${[]}
        @refresh=${() => {
                void appstate.dispatchProtectedAction(appstate.fetchNetworkTargetsAction, null);
                void appstate.fetchNetworkStats();
            }}
      ></sz-network-proxy-view>
    `;
        }
        renderDnsView() {
            return html `
      <ob-sectionheading>DNS Records</ob-sectionheading>
      <sz-network-dns-view
        .records=${this.networkState.dnsRecords}
        @sync=${() => {
                appstate.dispatchProtectedAction(appstate.syncDnsAction, null);
            }}
        @delete=${(e) => {
                console.log('Delete DNS record:', e.detail);
            }}
      ></sz-network-dns-view>
    `;
        }
        renderDomainsView() {
            const certs = this.networkState.certificates;
            return html `
      <ob-sectionheading>Domains</ob-sectionheading>
      <sz-network-domains-view
        .domains=${this.networkState.domains.map((d) => {
                const domainName = d.domain.domain;
                const cert = certs.find((c) => c.certDomain === domainName);
                let certStatus = 'pending';
                if (cert) {
                    if (!cert.isValid)
                        certStatus = 'expired';
                    else if (cert.expiryDate && cert.expiryDate - Date.now() < 30 * 24 * 60 * 60 * 1000)
                        certStatus = 'expiring';
                    else
                        certStatus = 'valid';
                }
                return {
                    domain: domainName,
                    provider: d.domain.dnsProvider || 'manual',
                    serviceCount: d.serviceCount,
                    certificateStatus: certStatus,
                };
            })}
        @sync=${() => {
                appstate.dispatchProtectedAction(appstate.fetchDomainsAction, null);
            }}
        @view=${(e) => {
                this.selectedDomain = e.detail.domain || e.detail;
                this.currentTab = 'domain-detail';
            }}
      ></sz-network-domains-view>
    `;
        }
        renderDomainDetailView() {
            const domainDetail = this.networkState.domains.find((d) => d.domain.domain === this.selectedDomain);
            const cert = this.networkState.certificates.find((c) => c.certDomain === this.selectedDomain);
            return html `
      <ob-sectionheading>Domain Details</ob-sectionheading>
      <sz-domain-detail-view
        .domain=${domainDetail
                ? {
                    id: this.selectedDomain,
                    name: this.selectedDomain,
                    status: 'active',
                    verified: true,
                    createdAt: '',
                }
                : null}
        .certificate=${cert
                ? {
                    id: cert.domainId,
                    domain: cert.certDomain,
                    issuer: cert.issuer,
                    validFrom: cert.createdAt ? new Date(cert.createdAt).toISOString() : '',
                    validUntil: cert.expiryDate ? new Date(cert.expiryDate).toISOString() : '',
                    daysRemaining: cert.expiryDate
                        ? Math.floor((cert.expiryDate - Date.now()) / (24 * 60 * 60 * 1000))
                        : 0,
                    status: cert.isValid ? 'valid' : 'expired',
                    autoRenew: true,
                }
                : null}
        .dnsRecords=${this.networkState.dnsRecords
                .filter((r) => r.domain?.includes(this.selectedDomain))
                .map((r) => ({
                id: r.id || '',
                type: r.type,
                name: r.domain,
                value: r.value,
                ttl: 3600,
            }))}
        @renew-certificate=${() => {
                appstate.dispatchProtectedAction(appstate.renewCertificateAction, {
                    domain: this.selectedDomain,
                });
            }}
      ></sz-domain-detail-view>
    `;
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return ObViewNetwork = _classThis;
})();
export { ObViewNetwork };
//# sourceMappingURL=data:application/json;base64, 