import { OnInit, OnDestroy, ChangeDetectorRef, ElementRef, NgZone } from '@angular/core';
import { Subject } from 'rxjs';
import { BaseResourceComponent } from '@memberjunction/ng-shared';
import { CompositeKey, RunQueryResult } from '@memberjunction/core';
import { TreeBranchConfig } from '@memberjunction/ng-trees';
import { ResourceData, MJQueryEntityExtended, MJQueryCategoryEntity } from '@memberjunction/core-entities';
import { QueryEntityLinkClickEvent, QueryRowClickEvent } from '@memberjunction/ng-query-viewer';
import { CompositionTokenClickEvent } from '@memberjunction/ng-code-editor';
import { MJConfirmService } from '@memberjunction/ng-ui-components';
import * as i0 from "@angular/core";
/**
 * Tree node for the query category hierarchy
 */
interface CategoryNode {
    category: MJQueryCategoryEntity;
    children: CategoryNode[];
    queries: MJQueryEntityExtended[];
    expanded: boolean;
    level: number;
}
/**
 * A resource component for browsing and executing stored queries.
 * Features:
 * - Hierarchical category navigation
 * - Query search
 * - Query viewer with parameter input
 * - Entity linking for clickable record IDs
 */
export declare class QueryBrowserResourceComponent extends BaseResourceComponent implements OnInit, OnDestroy {
    private cdr;
    private elementRef;
    private zone;
    private confirmService;
    private static readonly SETTINGS_KEY;
    private static readonly STATUS_FILTERS_KEY;
    private static readonly EXPANDED_STATE_KEY;
    private static readonly DEFAULT_PANEL_WIDTH;
    private static readonly MIN_PANEL_WIDTH;
    private static readonly MAX_PANEL_WIDTH;
    isLoading: boolean;
    categories: MJQueryCategoryEntity[];
    categoryTree: CategoryNode[];
    /** All queries the user has permission to run */
    queries: MJQueryEntityExtended[];
    filteredQueries: MJQueryEntityExtended[];
    private filteredQueryIds;
    selectedQuery: MJQueryEntityExtended | null;
    searchText: string;
    PanelWidth: number;
    IsResizing: boolean;
    /** Status filter toggles — which statuses to show in the tree */
    StatusFilters: Record<string, boolean>;
    /** Ordered list of all possible statuses for the filter bar */
    readonly AllStatuses: string[];
    /** Tracks expanded state by category ID — persisted across sessions */
    private expandedState;
    /**
     * The id/name of the most recent query executed via an agent execution tool
     * (RunStoredQuery / PageQueryResults). Published in the agent context so the
     * agent has continuity ("the query I just ran") WITHOUT ever putting result
     * data or SQL into the always-on snapshot. Null until the first execution.
     */
    private lastExecutedQueryId;
    private lastExecutedQueryName;
    /**
     * The embedded query VIEWER's executed state for the CURRENTLY SELECTED
     * query, captured from its QueryComplete output. The viewer auto-runs on
     * select (when params are satisfied) or on user-run, at which point it emits
     * its result and we record the TRUE total row count here. Reset to "not run"
     * whenever the selection changes so the published context never reports a
     * stale count for a freshly-selected query.
     *
     * 🚨 SAFETY: only the COUNT + a has-run flag are kept — never SQL, never the
     * result rows. These feed `SelectedQueryHasRun` / `SelectedQueryRowCount`
     * in the agent context so the agent can answer "how many rows" from context
     * WITHOUT re-running, while honoring the same no-SQL / no-rows boundary.
     */
    private selectedQueryHasRun;
    private selectedQueryRowCount;
    private metadata;
    protected destroy$: Subject<void>;
    private dataLoaded;
    private boundOnResizeMove;
    private boundOnResizeEnd;
    ShowQueryDrawer: boolean;
    DrawerMode: 'create' | 'edit';
    DrawerQueryId: string | null;
    DrawerName: string;
    DrawerSQL: string;
    private drawerSqlEditor;
    DrawerDescription: string;
    DrawerCategoryID: string;
    DrawerStatus: 'Pending' | 'Approved' | 'Rejected' | 'Expired';
    DrawerReusable: boolean;
    IsSavingDrawer: boolean;
    DrawerNameError: boolean;
    DrawerSaveError: string | null;
    /** Ordered status options for the drawer dropdown — all valid Query statuses */
    readonly DrawerStatuses: Array<'Pending' | 'Approved' | 'Rejected' | 'Expired'>;
    private initialDrawerSnapshot;
    /** The category ID of the most recently interacted-with folder in the tree */
    private activeCategoryID;
    /** Tree dropdown config for Query Categories (branches only, no leaves) */
    CategoryBranchConfig: TreeBranchConfig;
    /** The DrawerCategoryID as a CompositeKey for the tree dropdown binding */
    get DrawerCategoryIDAsKey(): CompositeKey | null;
    constructor(cdr: ChangeDetectorRef, elementRef: ElementRef, zone: NgZone, confirmService: MJConfirmService);
    ngOnInit(): void;
    /**
     * Publish the current Query Browser state to the AI agent. Re-invoked on
     * every meaningful state change (selection, search, refresh, filter). Only
     * catalog METADATA is exposed — query NAMES, CATEGORY names, counts, and the
     * active filter state — NEVER SQL text or query RESULTS. Name lists are
     * bounded (see {@link AGENT_CONTEXT_NAME_LIST_CAP}); companion total/filtered
     * counts tell the agent the true sizes when the lists are truncated.
     */
    private publishAgentContext;
    /**
     * Register the read-only / navigational client tools the agent may invoke.
     * Every Handler is tolerant: validates input and returns
     * `{ Success: false, ErrorMessage }` rather than throwing. No tool here runs
     * a query.
     */
    private registerAgentClientTools;
    private handleSearchTool;
    private handleFilterByStatusTool;
    /**
     * Resolve an agent-supplied identifier (query NAME or ID) to a query the
     * current user can view. Prefers an exact ID match, then a case-insensitive
     * NAME match — mirrors DataExplorer's SelectView resolution. Returns null
     * when nothing matches.
     */
    private resolveQuery;
    private handleSelectQueryTool;
    private handleOpenQueryTool;
    private handleFilterByCategoryTool;
    private handleClearFiltersTool;
    private handleExpandAllTool;
    private handleCollapseAllTool;
    private handleRefreshTool;
    /** Tolerant result shape for the stored-query execution tools. */
    private resolveRunnableQuery;
    /**
     * Execute a stored query with a bounded row count and optional StartRow
     * offset, returning a tolerant, hard-capped result. Centralizes the
     * RunQuery call + double row-bounding shared by RunStoredQuery and
     * PageQueryResults. Never throws; never sets RunQueryParams.SQL.
     */
    private executeStoredQuery;
    private handleRunStoredQueryTool;
    private handlePageQueryResultsTool;
    /**
     * Return a stored query's parameter + result-field definitions so the agent
     * knows what to pass and what it gets back. Read-only — NEVER returns SQL.
     */
    private handleGetQueryMetadataTool;
    ngOnDestroy(): void;
    GetResourceDisplayName(data: ResourceData): Promise<string>;
    GetResourceIconClass(data: ResourceData): Promise<string>;
    private loadData;
    private buildCategoryTree;
    onSearchChange(value: string): void;
    clearSearch(): void;
    /** Toggle a status filter on/off and rebuild the tree */
    toggleStatusFilter(status: string): void;
    /** Get the count of queries with a given status */
    getStatusCount(status: string): number;
    /** Get the CSS color for a query status */
    getStatusColor(status: string): string;
    /** Get the Font Awesome icon for a query status */
    getStatusIcon(status: string): string;
    /** Apply both status and search filters to produce filteredQueries */
    private applyFilters;
    /** Load saved status filter preferences */
    private loadSavedStatusFilters;
    /** Save status filter preferences with debouncing */
    private saveStatusFilters;
    /** Load saved expanded/collapsed state for category nodes */
    private loadSavedExpandedState;
    /** Save expanded/collapsed state with debouncing */
    private saveExpandedState;
    toggleExpand(node: CategoryNode, event?: Event): void;
    expandAll(): void;
    collapseAll(): void;
    selectQuery(query: MJQueryEntityExtended, event?: Event): void;
    isQueryVisible(query: MJQueryEntityExtended): boolean;
    hasVisibleContent(node: CategoryNode): boolean;
    onEntityLinkClick(event: QueryEntityLinkClickEvent): void;
    onRowDoubleClick(event: QueryRowClickEvent): void;
    /**
     * Capture the embedded viewer's executed row count when it finishes running
     * the SELECTED query (auto-run on select, or user-run). We read the TRUE
     * total (TotalRowCount, falling back to the returned row count) so the agent
     * can answer "how many rows?" from context without re-running.
     *
     * 🚨 SAFETY: we store ONLY the count + a has-run flag here — never the SQL,
     * never the result rows. The published context honors the same boundary.
     */
    onViewerQueryComplete(result: RunQueryResult): void;
    /**
     * Reset the SELECTED query's executed-run state. Called whenever the
     * selection changes so the published context never reports a stale row count
     * for a freshly-selected (not-yet-run) query.
     */
    private resetSelectedQueryRunState;
    onOpenQueryRecord(event: {
        queryId: string;
        queryName: string;
    }): void;
    onCompositionTokenClick(event: CompositionTokenClickEvent): void;
    /**
     * Find a query by its composition path (e.g., "Demos/Active Users").
     * Matches the last segment as query name and preceding segments as category hierarchy.
     */
    private findQueryByCompositionPath;
    /**
     * Expand category tree nodes to reveal a specific query.
     */
    private expandTreeToQuery;
    /** No-results message for the query list (echoes the search term). */
    get NoQueryResultsMessage(): string;
    /** True when the current user has permission to create new queries. */
    get CanCreateQuery(): boolean;
    /** True when the current user has permission to edit queries. */
    get CanEditQuery(): boolean;
    /** Close the drawer when Escape is pressed (if open). */
    OnEscapeKey(): void;
    /** Open the drawer in create mode, optionally pre-selecting a category. */
    OpenCreateDrawer(categoryID?: string): void;
    /**
     * Open the drawer in edit mode, pre-populated from a MJQueryEntityExtended.
     * Stops event propagation so clicking the edit icon doesn't also select the query.
     */
    OpenEditDrawer(query: MJQueryEntityExtended, event?: Event): void;
    /**
     * Close the drawer. If dirty, ask for confirmation unless force=true.
     */
    CloseDrawer(force?: boolean): Promise<void>;
    /** Close drawer when clicking the backdrop. */
    OnDrawerBackdropClick(): void;
    /** Update DrawerSQL when the code editor emits a change. */
    OnDrawerSQLChange(value: string): void;
    /** Update DrawerCategoryID when the tree dropdown selection changes. */
    OnDrawerCategoryChange(value: CompositeKey | CompositeKey[] | null): void;
    private get currentDrawerSnapshot();
    private captureDrawerSnapshot;
    get IsDrawerDirty(): boolean;
    /** Save the drawer form (create or edit). */
    SaveDrawer(): Promise<void>;
    /** Open the full entity form in a new tab (for sub-entity management). */
    OpenFullRecord(): void;
    getTotalQueryCount(): number;
    getNodeQueryCount(node: CategoryNode): number;
    refresh(): void;
    trackByCategory(index: number, node: CategoryNode): string;
    trackByQuery(index: number, query: MJQueryEntityExtended): string;
    /**
     * Select a query by ID, expanding the tree to show it.
     * Clears selection if no matching query is found.
     */
    private selectQueryById;
    /**
     * React to back/forward navigation or deep-link activation.
     * Called by the base class when the URL query params change externally.
     */
    protected OnQueryParamsChanged(params: Record<string, string>, source: 'popstate' | 'deeplink'): void;
    /**
     * Expands the category tree to show the given query
     */
    private expandCategoryForQuery;
    /**
     * Load saved panel width from user settings
     */
    private loadSavedPanelWidth;
    /**
     * Start resizing the left panel via drag handle
     */
    onResizeStart(event: MouseEvent): void;
    private onResizeMove;
    private onResizeEnd;
    /** Case-insensitive UUID check whether a query is the currently selected query. */
    IsQuerySelected(query: MJQueryEntityExtended): boolean;
    static ɵfac: i0.ɵɵFactoryDeclaration<QueryBrowserResourceComponent, never>;
    static ɵcmp: i0.ɵɵComponentDeclaration<QueryBrowserResourceComponent, "mj-query-browser-resource", never, {}, {}, never, never, false, never>;
}
export {};
//# sourceMappingURL=query-browser-resource.component.d.ts.map