var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
import { Component, ViewChild } from '@angular/core';
import { BaseDashboard } from '@memberjunction/ng-shared';
import { RegisterClass, UUIDsEqual } from '@memberjunction/global';
import { CompositeKey } from '@memberjunction/core';
import { Subject } from 'rxjs';
import { debounceTime } from 'rxjs/operators';
import { UserInfoEngine } from '@memberjunction/core-entities';
import * as i0 from "@angular/core";
import * as i1 from "@memberjunction/ng-ui-components";
import * as i2 from "@memberjunction/ng-shared-generic";
import * as i3 from "@memberjunction/ng-entity-relationship-diagram";
const _c0 = ["erdComposite"];
function EntityAdminDashboardComponent_Conditional_10_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 9);
    i0.ɵɵelement(1, "mj-loading", 12);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵproperty("text", ctx_r0.loadingMessage);
} }
function EntityAdminDashboardComponent_Conditional_11_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 10)(1, "p", 13);
    i0.ɵɵtext(2);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵadvance(2);
    i0.ɵɵtextInterpolate(ctx_r0.error);
} }
function EntityAdminDashboardComponent_Conditional_12_Template(rf, ctx) { if (rf & 1) {
    const _r2 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "div", 11)(1, "mj-erd-composite", 14, 0);
    i0.ɵɵlistener("stateChange", function EntityAdminDashboardComponent_Conditional_12_Template_mj_erd_composite_stateChange_1_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r0.onStateChange($event)); })("userStateChange", function EntityAdminDashboardComponent_Conditional_12_Template_mj_erd_composite_userStateChange_1_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r0.onUserStateChange($event)); })("entityOpened", function EntityAdminDashboardComponent_Conditional_12_Template_mj_erd_composite_entityOpened_1_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r0.onEntityOpened($event)); })("openRecord", function EntityAdminDashboardComponent_Conditional_12_Template_mj_erd_composite_openRecord_1_listener($event) { i0.ɵɵrestoreView(_r2); const ctx_r0 = i0.ɵɵnextContext(); return i0.ɵɵresetView(ctx_r0.onOpenRecord($event)); });
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r0 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵproperty("isRefreshingERD", ctx_r0.isRefreshingERD);
} }
/** Settings key for ERD state persistence */
const ERD_SETTINGS_KEY = 'MJ.Admin.Entity.ERD';
let EntityAdminDashboardComponent = class EntityAdminDashboardComponent extends BaseDashboard {
    erdComposite;
    isLoading = false;
    isRefreshingERD = false;
    loadingMessage = '';
    error = null;
    // Filter panel visibility for header controls
    filterPanelVisible = true;
    selectedEntity = null;
    filteredEntities = [];
    /** Total unfiltered entity count — feeds the chrome's X-of-Y badge. */
    get TotalEntityCount() {
        return this.erdComposite?.entities?.length ?? 0;
    }
    // State management
    userStateChangeSubject = new Subject();
    hasLoadedUserState = false;
    metadata = this.ProviderToUse;
    userSettingEntity = null;
    ngAfterViewInit() {
        // Setup debounced state persistence to MJ: User Settings
        this.userStateChangeSubject.pipe(debounceTime(1000)).subscribe(state => {
            this.saveStateToUserSettings(state);
        });
    }
    async GetResourceDisplayName(data) {
        return "Entity Administration";
    }
    ngOnDestroy() {
        this.userStateChangeSubject.complete();
        super.ngOnDestroy();
    }
    initDashboard() {
        // Initialize dashboard - called by BaseDashboard
    }
    loadData() {
        // Data loading is handled by ERDCompositeComponent
    }
    toggleFilterPanel() {
        this.filterPanelVisible = !this.filterPanelVisible;
        if (this.erdComposite) {
            this.erdComposite.onToggleFilterPanel();
        }
    }
    onStateChange(state) {
        // Update local state to keep header controls in sync
        this.filterPanelVisible = state.filterPanelVisible;
        this.filteredEntities = this.erdComposite?.filteredEntities || [];
        if (state.selectedEntityId && this.erdComposite) {
            this.selectedEntity = this.erdComposite.entities.find(e => UUIDsEqual(e.ID, state.selectedEntityId)) || null;
        }
        else {
            this.selectedEntity = null;
        }
        // Load user state when data becomes available for the first time
        if (this.erdComposite?.isDataLoaded && !this.hasLoadedUserState) {
            this.hasLoadedUserState = true;
            this.loadStateFromUserSettings();
        }
    }
    onUserStateChange(state) {
        // Queue state for debounced persistence
        this.userStateChangeSubject.next(state);
    }
    onEntityOpened(entity) {
        this.openEntity(entity);
    }
    onOpenRecord(event) {
        this.OpenEntityRecord.emit({
            EntityName: event.EntityName,
            RecordPKey: new CompositeKey([{ FieldName: 'ID', Value: event.RecordID }])
        });
    }
    openEntity(entity) {
        this.Interaction.emit({
            type: 'openEntity',
            entity: entity,
            data: { entityId: entity.ID, entityName: entity.Name }
        });
    }
    /**
     * Load ERD state from MJ: User Settings entity using UserInfoEngine for cached access
     */
    async loadStateFromUserSettings() {
        try {
            const userId = this.metadata.CurrentUser?.ID;
            if (!userId) {
                this.NotifyLoadComplete();
                return;
            }
            const engine = UserInfoEngine.Instance;
            // Find setting from cached user settings
            const setting = engine.UserSettings.find(s => s.Setting === ERD_SETTINGS_KEY);
            if (setting) {
                this.userSettingEntity = setting;
                if (this.userSettingEntity.Value) {
                    const savedState = JSON.parse(this.userSettingEntity.Value);
                    if (this.erdComposite) {
                        this.erdComposite.loadUserState(savedState);
                    }
                }
            }
            this.NotifyLoadComplete();
        }
        catch (error) {
            console.warn('Failed to load ERD state from User Settings:', error);
            this.NotifyLoadComplete();
        }
    }
    /**
     * Save ERD state to MJ: User Settings entity using UserInfoEngine for cached lookup
     */
    async saveStateToUserSettings(state) {
        try {
            const userId = this.metadata.CurrentUser?.ID;
            if (!userId)
                return;
            // Find existing setting from cached user settings if not already loaded
            if (!this.userSettingEntity) {
                const engine = UserInfoEngine.Instance;
                const setting = engine.UserSettings.find(s => s.Setting === ERD_SETTINGS_KEY);
                if (setting) {
                    this.userSettingEntity = setting;
                }
                else {
                    this.userSettingEntity = await this.metadata.GetEntityObject('MJ: User Settings');
                    this.userSettingEntity.UserID = userId;
                    this.userSettingEntity.Setting = ERD_SETTINGS_KEY;
                }
            }
            // Save the state as JSON
            this.userSettingEntity.Value = JSON.stringify(state);
            await this.userSettingEntity.Save();
        }
        catch (error) {
            console.warn('Failed to save ERD state to User Settings:', error);
        }
    }
    static ɵfac = /*@__PURE__*/ (() => { let ɵEntityAdminDashboardComponent_BaseFactory; return function EntityAdminDashboardComponent_Factory(__ngFactoryType__) { return (ɵEntityAdminDashboardComponent_BaseFactory || (ɵEntityAdminDashboardComponent_BaseFactory = i0.ɵɵgetInheritedFactory(EntityAdminDashboardComponent)))(__ngFactoryType__ || EntityAdminDashboardComponent); }; })();
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: EntityAdminDashboardComponent, selectors: [["mj-entity-admin-dashboard"]], viewQuery: function EntityAdminDashboardComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(_c0, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.erdComposite = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 13, vars: 8, consts: [["erdComposite", ""], ["Title", "Entity Admin", "Icon", "fa-solid fa-database", "Subtitle", "Browse and configure entity definitions"], ["meta", ""], ["Label", "entities", 3, "Count", "Total"], ["actions", ""], ["mjButton", "", "size", "sm", "title", "Toggle Filters", 3, "click", "variant"], [1, "fa-solid", "fa-filter"], [1, "action-btn-label"], [3, "Flex", "Padding"], [1, "loading-container"], [1, "error-container"], [1, "dashboard-content"], ["size", "large", 3, "text"], [1, "error-message"], [3, "stateChange", "userStateChange", "entityOpened", "openRecord", "isRefreshingERD"]], template: function EntityAdminDashboardComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "mj-page-layout")(1, "mj-page-header", 1)(2, "div", 2);
            i0.ɵɵelement(3, "mj-stat-badge", 3);
            i0.ɵɵelementEnd();
            i0.ɵɵelementStart(4, "div", 4)(5, "button", 5);
            i0.ɵɵlistener("click", function EntityAdminDashboardComponent_Template_button_click_5_listener() { return ctx.toggleFilterPanel(); });
            i0.ɵɵelement(6, "i", 6);
            i0.ɵɵelementStart(7, "span", 7);
            i0.ɵɵtext(8, "Filters");
            i0.ɵɵelementEnd()()()();
            i0.ɵɵelementStart(9, "mj-page-body", 8);
            i0.ɵɵconditionalCreate(10, EntityAdminDashboardComponent_Conditional_10_Template, 2, 1, "div", 9);
            i0.ɵɵconditionalCreate(11, EntityAdminDashboardComponent_Conditional_11_Template, 3, 1, "div", 10);
            i0.ɵɵconditionalCreate(12, EntityAdminDashboardComponent_Conditional_12_Template, 3, 1, "div", 11);
            i0.ɵɵelementEnd()();
        } if (rf & 2) {
            i0.ɵɵadvance(3);
            i0.ɵɵproperty("Count", ctx.filteredEntities.length)("Total", ctx.TotalEntityCount);
            i0.ɵɵadvance(2);
            i0.ɵɵproperty("variant", ctx.filterPanelVisible ? "primary" : "secondary");
            i0.ɵɵadvance(4);
            i0.ɵɵproperty("Flex", true)("Padding", false);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.isLoading ? 10 : -1);
            i0.ɵɵadvance();
            i0.ɵɵconditional(ctx.error ? 11 : -1);
            i0.ɵɵadvance();
            i0.ɵɵconditional(!ctx.isLoading && !ctx.error ? 12 : -1);
        } }, dependencies: [i1.MJButtonDirective, i1.MJPageHeaderComponent, i1.MJPageLayoutComponent, i1.MJPageBodyComponent, i1.MJStatBadgeComponent, i2.LoadingComponent, i3.ERDCompositeComponent], styles: ["\n\n\n\n\n\n\n\n.loading-container[_ngcontent-%COMP%], \n.error-container[_ngcontent-%COMP%] {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  background: var(--mj-bg-surface-sunken);\n  flex: 1;\n  border-radius: var(--mj-radius-lg);\n}\n\n.loading-container[_ngcontent-%COMP%]   p[_ngcontent-%COMP%], \n.error-container[_ngcontent-%COMP%]   p[_ngcontent-%COMP%] {\n  font-size: var(--mj-text-sm);\n  font-weight: var(--mj-font-normal);\n  color: var(--mj-text-secondary);\n}\n\n\n\n.error-message[_ngcontent-%COMP%] {\n  color: var(--mj-status-error-text);\n  font-weight: var(--mj-font-medium);\n}\n\n\n\n.dashboard-content[_ngcontent-%COMP%] {\n  overflow: hidden;\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  min-height: 0;\n}\n\n\n\n.loading-content[_ngcontent-%COMP%] {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: var(--mj-space-4);\n}\n\n.loading-spinner[_ngcontent-%COMP%] {\n  position: relative;\n  width: 60px;\n  height: 60px;\n}\n\n.spinner-ring[_ngcontent-%COMP%] {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  border: 3px solid transparent;\n  border-radius: 50%;\n  animation: _ngcontent-%COMP%_spin 1.5s linear infinite;\n}\n\n.spinner-ring[_ngcontent-%COMP%]:nth-child(1) {\n  border-top-color: var(--mj-brand-primary);\n  animation-delay: 0s;\n}\n\n.spinner-ring[_ngcontent-%COMP%]:nth-child(2) {\n  border-top-color: var(--mj-brand-tertiary);\n  animation-delay: 0.3s;\n  transform: scale(0.8);\n}\n\n.spinner-ring[_ngcontent-%COMP%]:nth-child(3) {\n  border-top-color: var(--mj-brand-accent);\n  animation-delay: 0.6s;\n  transform: scale(0.6);\n}\n\n.loading-text[_ngcontent-%COMP%] {\n  font-size: var(--mj-text-sm);\n  font-weight: var(--mj-font-medium);\n  color: var(--mj-text-secondary);\n  text-align: center;\n}\n\n@keyframes _ngcontent-%COMP%_spin {\n  0% {\n    transform: rotate(0deg);\n  }\n  100% {\n    transform: rotate(360deg);\n  }\n}"] });
};
EntityAdminDashboardComponent = __decorate([
    RegisterClass(BaseDashboard, 'EntityAdmin')
], EntityAdminDashboardComponent);
export { EntityAdminDashboardComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(EntityAdminDashboardComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-entity-admin-dashboard', template: "<mj-page-layout>\n  <mj-page-header\n    Title=\"Entity Admin\"\n    Icon=\"fa-solid fa-database\"\n    Subtitle=\"Browse and configure entity definitions\">\n    <!-- X-of-Y filtered count earns its meta spot per chrome conventions \u00A72. -->\n    <div meta>\n      <mj-stat-badge\n        [Count]=\"filteredEntities.length\"\n        [Total]=\"TotalEntityCount\"\n        Label=\"entities\">\n      </mj-stat-badge>\n    </div>\n    <div actions>\n      <button\n        mjButton\n        [variant]=\"filterPanelVisible ? 'primary' : 'secondary'\"\n        size=\"sm\"\n        (click)=\"toggleFilterPanel()\"\n        title=\"Toggle Filters\">\n        <i class=\"fa-solid fa-filter\"></i> <span class=\"action-btn-label\">Filters</span>\n      </button>\n    </div>\n  </mj-page-header>\n\n  <mj-page-body [Flex]=\"true\" [Padding]=\"false\">\n    @if (isLoading) {\n      <div class=\"loading-container\">\n        <mj-loading [text]=\"loadingMessage\" size=\"large\"></mj-loading>\n      </div>\n    }\n\n    @if (error) {\n      <div class=\"error-container\">\n        <p class=\"error-message\">{{ error }}</p>\n      </div>\n    }\n\n    @if (!isLoading && !error) {\n      <div class=\"dashboard-content\">\n        <mj-erd-composite\n          #erdComposite\n          [isRefreshingERD]=\"isRefreshingERD\"\n          (stateChange)=\"onStateChange($event)\"\n          (userStateChange)=\"onUserStateChange($event)\"\n          (entityOpened)=\"onEntityOpened($event)\"\n          (openRecord)=\"onOpenRecord($event)\"\n          >\n        </mj-erd-composite>\n      </div>\n    }\n  </mj-page-body>\n</mj-page-layout>", styles: ["/**\n * Entity Admin Dashboard Component - MJ Design Token Styled\n * Reference implementation for MJ design token usage\n */\n\n/* Loading and Error Containers */\n.loading-container,\n.error-container {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  background: var(--mj-bg-surface-sunken);\n  flex: 1;\n  border-radius: var(--mj-radius-lg);\n}\n\n.loading-container p,\n.error-container p {\n  font-size: var(--mj-text-sm);\n  font-weight: var(--mj-font-normal);\n  color: var(--mj-text-secondary);\n}\n\n/* Error Message */\n.error-message {\n  color: var(--mj-status-error-text);\n  font-weight: var(--mj-font-medium);\n}\n\n/* Dashboard Content */\n.dashboard-content {\n  overflow: hidden;\n  flex: 1;\n  display: flex;\n  flex-direction: column;\n  min-height: 0;\n}\n\n/* Loading Spinner */\n.loading-content {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  gap: var(--mj-space-4);\n}\n\n.loading-spinner {\n  position: relative;\n  width: 60px;\n  height: 60px;\n}\n\n.spinner-ring {\n  position: absolute;\n  width: 100%;\n  height: 100%;\n  border: 3px solid transparent;\n  border-radius: 50%;\n  animation: spin 1.5s linear infinite;\n}\n\n.spinner-ring:nth-child(1) {\n  border-top-color: var(--mj-brand-primary);\n  animation-delay: 0s;\n}\n\n.spinner-ring:nth-child(2) {\n  border-top-color: var(--mj-brand-tertiary);\n  animation-delay: 0.3s;\n  transform: scale(0.8);\n}\n\n.spinner-ring:nth-child(3) {\n  border-top-color: var(--mj-brand-accent);\n  animation-delay: 0.6s;\n  transform: scale(0.6);\n}\n\n.loading-text {\n  font-size: var(--mj-text-sm);\n  font-weight: var(--mj-font-medium);\n  color: var(--mj-text-secondary);\n  text-align: center;\n}\n\n@keyframes spin {\n  0% {\n    transform: rotate(0deg);\n  }\n  100% {\n    transform: rotate(360deg);\n  }\n}\n"] }]
    }], null, { erdComposite: [{
            type: ViewChild,
            args: ['erdComposite', { static: false }]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(EntityAdminDashboardComponent, { className: "EntityAdminDashboardComponent", filePath: "src/EntityAdmin/entity-admin-dashboard.component.ts", lineNumber: 21 }); })();
//# sourceMappingURL=entity-admin-dashboard.component.js.map