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, ChangeDetectionStrategy, ViewChild } from '@angular/core';
import { Subject } from 'rxjs';
import { RegisterClass } from '@memberjunction/global';
import { BaseResourceComponent } from '@memberjunction/ng-shared';
import { DataExplorerDashboardComponent } from './data-explorer-dashboard.component';
import * as i0 from "@angular/core";
import * as i1 from "./data-explorer-dashboard.component";
/**
 * Resource component for the Data Explorer.
 * Wraps DataExplorerDashboardComponent as a BaseResourceComponent for use
 * in application nav items with ResourceType: "Custom".
 */
let DataExplorerResourceComponent = class DataExplorerResourceComponent extends BaseResourceComponent {
    cdr;
    // ========================================
    // State
    // ========================================
    entityFilter = null;
    contextName = null;
    contextIcon = null;
    /** Initial query params from the URL, forwarded to the dashboard */
    initialQueryParams = {};
    dataExplorer;
    _destroy$ = new Subject();
    _dataLoaded = false;
    // ========================================
    // Constructor
    // ========================================
    constructor(cdr) {
        super();
        this.cdr = cdr;
    }
    // ========================================
    // Data Property Override
    // ========================================
    set Data(value) {
        const previousConfig = JSON.stringify(super.Data?.Configuration || {});
        super.Data = value;
        const newConfig = JSON.stringify(value?.Configuration || {});
        // Load on first set, or when the configuration has changed
        if (!this._dataLoaded || previousConfig !== newConfig) {
            this._dataLoaded = true;
            this.loadConfiguration();
        }
    }
    get Data() {
        return super.Data;
    }
    // ========================================
    // Lifecycle
    // ========================================
    ngOnInit() {
        super.ngOnInit();
        // Configuration loaded via Data setter
    }
    /**
     * Forward query param changes from the framework to the inner dashboard.
     * The shell delivers params here (on the resource wrapper), but the dashboard
     * needs them for deep linking (entity, viewId, filter, view mode, map mode).
     */
    OnQueryParamsChanged(params, source) {
        if (this.dataExplorer) {
            this.dataExplorer.HandleQueryParamsChanged(params, source);
        }
    }
    ngOnDestroy() {
        super.ngOnDestroy();
        this._destroy$.next();
        this._destroy$.complete();
    }
    // ========================================
    // BaseResourceComponent Implementation
    // ========================================
    async GetResourceDisplayName(data) {
        return data.Name || 'Data';
    }
    async GetResourceIconClass(data) {
        return 'fa-solid fa-table-cells';
    }
    // ========================================
    // Private Methods
    // ========================================
    loadConfiguration() {
        const data = this.Data;
        if (!data) {
            this.NotifyLoadComplete();
            return;
        }
        const config = data.Configuration || {};
        // Extract configuration options
        this.entityFilter = config['entityFilter'] || null;
        this.contextName = config['appName'] || null;
        this.contextIcon = config['appIcon'] || null;
        // Build initial query params: start with workspace-saved params, then let
        // browser URL params override. The URL is the source of truth for user intent —
        // if the user navigates to a URL with specific params, those should take priority
        // over potentially stale workspace state from a prior session.
        const workspaceParams = config['queryParams'] || {};
        const browserParams = new URLSearchParams(window.location.search);
        const merged = { ...workspaceParams };
        browserParams.forEach((value, key) => {
            merged[key] = value;
        });
        this.initialQueryParams = merged;
        this.cdr.detectChanges();
        // Setup LoadCompleteEvent after view initializes
        setTimeout(() => {
            if (this.dataExplorer) {
                this.dataExplorer.LoadCompleteEvent = () => {
                    this.NotifyLoadComplete();
                };
                // Initialize with minimal config (no database dashboard)
                const dashboardConfig = {
                    dashboard: null,
                    userState: {}
                };
                this.dataExplorer.Config = dashboardConfig;
                this.dataExplorer.Refresh();
                // RACE GUARD: BaseDashboard.ngOnInit() calls NotifyLoadComplete() almost immediately
                // (after the no-op loadData), firing the inner dashboard's LoadCompleteEvent. But this
                // wiring runs in a setTimeout(0) MACROtask, while the dashboard's NotifyLoadComplete runs
                // in a MICROtask — so the dashboard finishes loading BEFORE we attach the handler above,
                // and the completion signal is lost. The shell then waits forever ("Gathering your
                // tools…" hangs) — reproduced on direct-URL refresh. If the dashboard already completed,
                // forward completion to the shell now.
                if (this.dataExplorer.LoadComplete) {
                    this.NotifyLoadComplete();
                }
            }
            else {
                this.NotifyLoadComplete();
            }
        }, 0);
    }
    // ========================================
    // Event Handlers
    // ========================================
    onOpenEntityRecord(event) {
        if (event && event.EntityName && event.RecordPKey) {
            this.navigationService.OpenEntityRecord(event.EntityName, event.RecordPKey);
        }
    }
    onDisplayNameChanged(name) {
        this.NotifyDisplayNameChanged(name);
    }
    static ɵfac = function DataExplorerResourceComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || DataExplorerResourceComponent)(i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); };
    static ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: DataExplorerResourceComponent, selectors: [["mj-data-explorer-resource"]], viewQuery: function DataExplorerResourceComponent_Query(rf, ctx) { if (rf & 1) {
            i0.ɵɵviewQuery(DataExplorerDashboardComponent, 5);
        } if (rf & 2) {
            let _t;
            i0.ɵɵqueryRefresh(_t = i0.ɵɵloadQuery()) && (ctx.dataExplorer = _t.first);
        } }, standalone: false, features: [i0.ɵɵInheritDefinitionFeature], decls: 2, vars: 5, consts: [[1, "data-explorer-resource-container"], [3, "OpenEntityRecord", "DisplayNameChanged", "ParentTabId", "entityFilter", "contextName", "contextIcon", "initialQueryParams"]], template: function DataExplorerResourceComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵelementStart(0, "div", 0)(1, "mj-data-explorer-dashboard", 1);
            i0.ɵɵlistener("OpenEntityRecord", function DataExplorerResourceComponent_Template_mj_data_explorer_dashboard_OpenEntityRecord_1_listener($event) { return ctx.onOpenEntityRecord($event); })("DisplayNameChanged", function DataExplorerResourceComponent_Template_mj_data_explorer_dashboard_DisplayNameChanged_1_listener($event) { return ctx.onDisplayNameChanged($event); });
            i0.ɵɵelementEnd()();
        } if (rf & 2) {
            i0.ɵɵadvance();
            i0.ɵɵproperty("ParentTabId", ctx.getTabId())("entityFilter", ctx.entityFilter)("contextName", ctx.contextName)("contextIcon", ctx.contextIcon)("initialQueryParams", ctx.initialQueryParams);
        } }, dependencies: [i1.DataExplorerDashboardComponent], styles: ["[_nghost-%COMP%] {\n            display: block;\n            width: 100%;\n            height: 100%;\n        }\n        .data-explorer-resource-container[_ngcontent-%COMP%] {\n            width: 100%;\n            height: 100%;\n        }"], changeDetection: 0 });
};
DataExplorerResourceComponent = __decorate([
    RegisterClass(BaseResourceComponent, 'DataExplorerResource')
], DataExplorerResourceComponent);
export { DataExplorerResourceComponent };
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(DataExplorerResourceComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-data-explorer-resource', template: `
        <div class="data-explorer-resource-container">
            <mj-data-explorer-dashboard
                [ParentTabId]="getTabId()"
                [entityFilter]="entityFilter"
                [contextName]="contextName"
                [contextIcon]="contextIcon"
                [initialQueryParams]="initialQueryParams"
                (OpenEntityRecord)="onOpenEntityRecord($event)"
                (DisplayNameChanged)="onDisplayNameChanged($event)">
            </mj-data-explorer-dashboard>
        </div>
    `, changeDetection: ChangeDetectionStrategy.OnPush, styles: ["\n        :host {\n            display: block;\n            width: 100%;\n            height: 100%;\n        }\n        .data-explorer-resource-container {\n            width: 100%;\n            height: 100%;\n        }\n    "] }]
    }], () => [{ type: i0.ChangeDetectorRef }], { dataExplorer: [{
            type: ViewChild,
            args: [DataExplorerDashboardComponent]
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(DataExplorerResourceComponent, { className: "DataExplorerResourceComponent", filePath: "src/DataExplorer/data-explorer-resource.component.ts", lineNumber: 44 }); })();
//# sourceMappingURL=data-explorer-resource.component.js.map