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 { DeesElement, html, customElement, css, state, cssManager, } from '@design.estate/dees-element';
import * as appstate from '../../appstate.js';
import * as interfaces from '../../../dist_ts_interfaces/index.js';
import { viewHostCss } from '../shared/css.js';
const RECORD_TYPES = [
    'A',
    'AAAA',
    'CNAME',
    'MX',
    'TXT',
    'NS',
    'CAA',
];
let OpsViewDns = (() => {
    let _classDecorators = [customElement('ops-view-dns')];
    let _classDescriptor;
    let _classExtraInitializers = [];
    let _classThis;
    let _classSuper = DeesElement;
    let _domainsState_decorators;
    let _domainsState_initializers = [];
    let _domainsState_extraInitializers = [];
    var OpsViewDns = class extends _classSuper {
        static { _classThis = this; }
        static {
            const _metadata = typeof Symbol === "function" && Symbol.metadata ? Object.create(_classSuper[Symbol.metadata] ?? null) : void 0;
            _domainsState_decorators = [state()];
            __esDecorate(this, null, _domainsState_decorators, { kind: "accessor", name: "domainsState", static: false, private: false, access: { has: obj => "domainsState" in obj, get: obj => obj.domainsState, set: (obj, value) => { obj.domainsState = value; } }, metadata: _metadata }, _domainsState_initializers, _domainsState_extraInitializers);
            __esDecorate(null, _classDescriptor = { value: _classThis }, _classDecorators, { kind: "class", name: _classThis.name, metadata: _metadata }, null, _classExtraInitializers);
            OpsViewDns = _classThis = _classDescriptor.value;
            if (_metadata) Object.defineProperty(_classThis, Symbol.metadata, { enumerable: true, configurable: true, writable: true, value: _metadata });
        }
        #domainsState_accessor_storage = __runInitializers(this, _domainsState_initializers, appstate.domainsStatePart.getState());
        get domainsState() { return this.#domainsState_accessor_storage; }
        set domainsState(value) { this.#domainsState_accessor_storage = value; }
        constructor() {
            super();
            __runInitializers(this, _domainsState_extraInitializers);
            const sub = appstate.domainsStatePart.select().subscribe((newState) => {
                this.domainsState = newState;
            });
            this.rxSubscriptions.push(sub);
        }
        async connectedCallback() {
            await super.connectedCallback();
            await appstate.domainsStatePart.dispatchAction(appstate.fetchDomainsAndProvidersAction, null);
            // If a domain is already selected (e.g. via "View Records" navigation), refresh its records
            const selected = this.domainsState.selectedDomainId;
            if (selected) {
                await appstate.domainsStatePart.dispatchAction(appstate.fetchDnsRecordsForDomainAction, {
                    domainId: selected,
                });
            }
        }
        static styles = [
            cssManager.defaultStyles,
            viewHostCss,
            css `
      .dnsContainer {
        display: flex;
        flex-direction: column;
        gap: 24px;
      }

      .domainPicker {
        display: flex;
        align-items: center;
        gap: 12px;
        padding: 12px 16px;
        background: ${cssManager.bdTheme('#f9fafb', '#111827')};
        border-radius: 8px;
      }

      .sourceBadge {
        display: inline-flex;
        align-items: center;
        padding: 2px 8px;
        border-radius: 4px;
        font-size: 11px;
        font-weight: 500;
      }

      .sourceBadge.local {
        background: ${cssManager.bdTheme('#e0e7ff', '#1e1b4b')};
        color: ${cssManager.bdTheme('#3730a3', '#a5b4fc')};
      }

      .sourceBadge.synced {
        background: ${cssManager.bdTheme('#fef3c7', '#451a03')};
        color: ${cssManager.bdTheme('#92400e', '#fde047')};
      }
    `,
        ];
        render() {
            const domains = this.domainsState.domains;
            const selectedId = this.domainsState.selectedDomainId;
            const records = this.domainsState.records;
            return html `
      <dees-heading level="3">DNS Records</dees-heading>
      <div class="dnsContainer">
        <div class="domainPicker">
          <dees-input-dropdown
            .label=${'Domain'}
            .options=${domains.map((d) => ({ option: d.name, key: d.id }))}
            .selectedOption=${selectedId
                ? { option: domains.find((d) => d.id === selectedId)?.name || '', key: selectedId }
                : undefined}
            @selectedOption=${async (e) => {
                const id = e.detail?.key;
                if (!id)
                    return;
                await appstate.domainsStatePart.dispatchAction(appstate.fetchDnsRecordsForDomainAction, { domainId: id });
            }}
          ></dees-input-dropdown>
        </div>

        ${selectedId
                ? html `
              <dees-table
                .heading1=${'DNS Records'}
                .heading2=${this.domainHint(selectedId)}
                .data=${records}
                .showColumnFilters=${true}
                .displayFunction=${(r) => ({
                    Name: r.name,
                    Type: r.type,
                    Value: r.value,
                    TTL: r.ttl,
                    Source: html `<span class="sourceBadge ${r.source}">${r.source}</span>`,
                })}
                .dataActions=${[
                    {
                        name: 'Add Record',
                        iconName: 'lucide:plus',
                        type: ['header'],
                        actionFunc: async () => {
                            await this.showCreateRecordDialog(selectedId);
                        },
                    },
                    {
                        name: 'Refresh',
                        iconName: 'lucide:rotateCw',
                        type: ['header'],
                        actionFunc: async () => {
                            await appstate.domainsStatePart.dispatchAction(appstate.fetchDnsRecordsForDomainAction, { domainId: selectedId });
                        },
                    },
                    {
                        name: 'Edit',
                        iconName: 'lucide:pencil',
                        type: ['inRow', 'contextmenu'],
                        actionFunc: async (actionData) => {
                            const rec = actionData.item;
                            await this.showEditRecordDialog(rec);
                        },
                    },
                    {
                        name: 'Delete',
                        iconName: 'lucide:trash2',
                        type: ['inRow', 'contextmenu'],
                        actionFunc: async (actionData) => {
                            const rec = actionData.item;
                            await appstate.domainsStatePart.dispatchAction(appstate.deleteDnsRecordAction, { id: rec.id, domainId: rec.domainId });
                        },
                    },
                ]}
              ></dees-table>
            `
                : html `<p style="opacity: 0.7;">Pick a domain above to view its records.</p>`}
      </div>
    `;
        }
        domainHint(domainId) {
            const domain = this.domainsState.domains.find((d) => d.id === domainId);
            if (!domain)
                return '';
            if (domain.source === 'dcrouter') {
                return 'Records are served by dcrouter (authoritative).';
            }
            return 'Records are stored at the provider — changes here are pushed via the provider API.';
        }
        async showCreateRecordDialog(domainId) {
            const { DeesModal } = await import('@design.estate/dees-catalog');
            DeesModal.createAndShow({
                heading: 'Add DNS Record',
                content: html `
        <dees-form>
          <dees-input-text .key=${'name'} .label=${'Name'} .description=${'Fully qualified domain name'} .required=${true}></dees-input-text>
          <dees-input-dropdown
            .key=${'type'}
            .label=${'Type'}
            .options=${RECORD_TYPES.map((t) => ({ option: t, key: t }))}
            .required=${true}
          ></dees-input-dropdown>
          <dees-input-text
            .key=${'value'}
            .label=${'Value'}
            .description=${'For MX records use priority format, e.g. "10 mail.example.com"'}
            .required=${true}
          ></dees-input-text>
          <dees-input-text .key=${'ttl'} .label=${'TTL'} .description=${'Time to live in seconds'} .value=${'300'}></dees-input-text>
        </dees-form>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (modalArg) => modalArg.destroy() },
                    {
                        name: 'Create',
                        action: async (modalArg) => {
                            const form = modalArg.shadowRoot
                                ?.querySelector('.content')
                                ?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            const type = (data.type?.key ?? data.type);
                            await appstate.domainsStatePart.dispatchAction(appstate.createDnsRecordAction, {
                                domainId,
                                name: String(data.name),
                                type,
                                value: String(data.value),
                                ttl: parseInt(String(data.ttl || '300'), 10),
                            });
                            modalArg.destroy();
                        },
                    },
                ],
            });
        }
        async showEditRecordDialog(rec) {
            const { DeesModal } = await import('@design.estate/dees-catalog');
            DeesModal.createAndShow({
                heading: `Edit ${rec.type} ${rec.name}`,
                content: html `
        <dees-form>
          <dees-input-text .key=${'name'} .label=${'Name'} .description=${'Fully qualified domain name'} .value=${rec.name}></dees-input-text>
          <dees-input-text .key=${'value'} .label=${'Value'} .value=${rec.value}></dees-input-text>
          <dees-input-text .key=${'ttl'} .label=${'TTL'} .description=${'Time to live in seconds'} .value=${String(rec.ttl)}></dees-input-text>
        </dees-form>
      `,
                menuOptions: [
                    { name: 'Cancel', action: async (modalArg) => modalArg.destroy() },
                    {
                        name: 'Save',
                        action: async (modalArg) => {
                            const form = modalArg.shadowRoot
                                ?.querySelector('.content')
                                ?.querySelector('dees-form');
                            if (!form)
                                return;
                            const data = await form.collectFormData();
                            await appstate.domainsStatePart.dispatchAction(appstate.updateDnsRecordAction, {
                                id: rec.id,
                                domainId: rec.domainId,
                                name: String(data.name),
                                value: String(data.value),
                                ttl: parseInt(String(data.ttl || '300'), 10),
                            });
                            modalArg.destroy();
                        },
                    },
                ],
            });
        }
        static {
            __runInitializers(_classThis, _classExtraInitializers);
        }
    };
    return OpsViewDns = _classThis;
})();
export { OpsViewDns };
//# sourceMappingURL=data:application/json;base64, 