import { Component, Input, Output, EventEmitter, ChangeDetectionStrategy } from '@angular/core';
import { Subject, combineLatest, interval, of, from } from 'rxjs';
import { takeUntil, map, shareReplay, switchMap, filter } from 'rxjs/operators';
import { RunView } from '@memberjunction/core';
import { AIAgentRunDataHelper } from './ai-agent-run-data.service';
import { AIEngineBase } from '@memberjunction/ai-engine-base';
import { UUIDsEqual } from '@memberjunction/global';
import * as i0 from "@angular/core";
const _c0 = a0 => ({ $implicit: a0 });
function AIAgentRunTimelineComponent_Conditional_0_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 1);
    i0.ɵɵelement(1, "mj-loading", 4);
    i0.ɵɵelementEnd();
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_0_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 8);
    i0.ɵɵelement(1, "i", 11);
    i0.ɵɵtext(2, " Loading sub-agent steps... ");
    i0.ɵɵelementEnd();
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 9);
    i0.ɵɵelement(1, "i", 12);
    i0.ɵɵtext(2, " No sub-agent steps found ");
    i0.ɵɵelementEnd();
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_2_ng_container_0_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementContainer(0);
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵtemplate(0, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_2_ng_container_0_Template, 1, 0, "ng-container", 13);
} if (rf & 2) {
    const item_r2 = i0.ɵɵnextContext(2).$implicit;
    i0.ɵɵnextContext(3);
    const recursiveSteps_r4 = i0.ɵɵreference(6);
    i0.ɵɵproperty("ngTemplateOutlet", recursiveSteps_r4)("ngTemplateOutletContext", i0.ɵɵpureFunction1(2, _c0, item_r2.children));
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_3_Template(rf, ctx) { if (rf & 1) {
    const _r5 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-ai-agent-run-timeline", 14);
    i0.ɵɵlistener("itemSelected", function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_3_Template_mj_ai_agent_run_timeline_itemSelected_0_listener($event) { i0.ɵɵrestoreView(_r5); const ctx_r2 = i0.ɵɵnextContext(5); return i0.ɵɵresetView(ctx_r2.selectItem($event)); })("navigateToEntity", function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_3_Template_mj_ai_agent_run_timeline_navigateToEntity_0_listener($event) { i0.ɵɵrestoreView(_r5); const ctx_r2 = i0.ɵɵnextContext(5); return i0.ɵɵresetView(ctx_r2.navigateToEntity.emit($event)); });
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const item_r2 = i0.ɵɵnextContext(2).$implicit;
    const ctx_r2 = i0.ɵɵnextContext(3);
    i0.ɵɵproperty("aiAgentRunId", item_r2.data.ID)("dataHelper", ctx_r2.createSubRunDataHelper())("autoRefresh", false);
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵconditionalCreate(0, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_0_Template, 3, 0, "div", 8);
    i0.ɵɵconditionalCreate(1, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_1_Template, 3, 0, "div", 9);
    i0.ɵɵconditionalCreate(2, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_2_Template, 1, 4, "ng-container");
    i0.ɵɵconditionalCreate(3, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Conditional_3_Template, 1, 3, "mj-ai-agent-run-timeline", 10);
} if (rf & 2) {
    const item_r2 = i0.ɵɵnextContext().$implicit;
    i0.ɵɵconditional(item_r2.type === "step" && (item_r2.data == null ? null : item_r2.data.StepType) === "Sub-Agent" && !item_r2.childrenLoaded ? 0 : -1);
    i0.ɵɵadvance();
    i0.ɵɵconditional(item_r2.type === "step" && (item_r2.data == null ? null : item_r2.data.StepType) === "Sub-Agent" && item_r2.childrenLoaded && item_r2.hasNoChildren ? 1 : -1);
    i0.ɵɵadvance();
    i0.ɵɵconditional(item_r2.children && item_r2.children.length > 0 ? 2 : -1);
    i0.ɵɵadvance();
    i0.ɵɵconditional(item_r2.type === "subrun" && (item_r2.data == null ? null : item_r2.data.ID) ? 3 : -1);
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Template(rf, ctx) { if (rf & 1) {
    const _r1 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-ai-agent-run-step-node", 7);
    i0.ɵɵlistener("itemClick", function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Template_mj_ai_agent_run_step_node_itemClick_0_listener() { const item_r2 = i0.ɵɵrestoreView(_r1).$implicit; const ctx_r2 = i0.ɵɵnextContext(3); return i0.ɵɵresetView(ctx_r2.selectItem(item_r2)); })("expandToggle", function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Template_mj_ai_agent_run_step_node_expandToggle_0_listener($event) { const item_r2 = i0.ɵɵrestoreView(_r1).$implicit; const ctx_r2 = i0.ɵɵnextContext(3); return i0.ɵɵresetView(ctx_r2.toggleItemExpansion(item_r2, $event)); })("navigateToEntity", function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Template_mj_ai_agent_run_step_node_navigateToEntity_0_listener($event) { i0.ɵɵrestoreView(_r1); const ctx_r2 = i0.ɵɵnextContext(3); return i0.ɵɵresetView(ctx_r2.navigateToEntity.emit($event)); });
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(1, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Conditional_1_Template, 4, 4);
} if (rf & 2) {
    const item_r2 = ctx.$implicit;
    const ctx_r2 = i0.ɵɵnextContext(3);
    i0.ɵɵproperty("item", item_r2)("isSelected", (ctx_r2.selectedItem == null ? null : ctx_r2.selectedItem.id) === item_r2.id);
    i0.ɵɵadvance();
    i0.ɵɵconditional(item_r2.isExpanded ? 1 : -1);
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 5);
    i0.ɵɵrepeaterCreate(1, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_For_2_Template, 2, 3, null, null, i0.ɵɵcomponentInstance().trackByItemId, true);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const items_r6 = i0.ɵɵnextContext();
    i0.ɵɵadvance();
    i0.ɵɵrepeater(items_r6);
} }
function AIAgentRunTimelineComponent_Conditional_2_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 6);
    i0.ɵɵelement(1, "i", 15);
    i0.ɵɵelementStart(2, "p");
    i0.ɵɵtext(3, "No execution steps found");
    i0.ɵɵelementEnd()();
} }
function AIAgentRunTimelineComponent_Conditional_2_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 2);
    i0.ɵɵconditionalCreate(1, AIAgentRunTimelineComponent_Conditional_2_Conditional_1_Template, 3, 0, "div", 5);
    i0.ɵɵconditionalCreate(2, AIAgentRunTimelineComponent_Conditional_2_Conditional_2_Template, 4, 0, "div", 6);
    i0.ɵɵelementEnd();
} if (rf & 2) {
    const items_r6 = ctx;
    i0.ɵɵadvance();
    i0.ɵɵconditional(items_r6.length > 0 ? 1 : -1);
    i0.ɵɵadvance();
    i0.ɵɵconditional(items_r6.length === 0 ? 2 : -1);
} }
function AIAgentRunTimelineComponent_Conditional_3_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 1);
    i0.ɵɵelement(1, "mj-loading", 4);
    i0.ɵɵelementEnd();
} }
function AIAgentRunTimelineComponent_Conditional_4_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementStart(0, "div", 3);
    i0.ɵɵelement(1, "i", 16);
    i0.ɵɵelementStart(2, "p");
    i0.ɵɵtext(3);
    i0.ɵɵelementEnd()();
} if (rf & 2) {
    const ctx_r2 = i0.ɵɵnextContext();
    i0.ɵɵadvance(3);
    i0.ɵɵtextInterpolate(ctx_r2.error);
} }
function AIAgentRunTimelineComponent_ng_template_5_For_1_Conditional_1_ng_container_0_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵelementContainer(0);
} }
function AIAgentRunTimelineComponent_ng_template_5_For_1_Conditional_1_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵtemplate(0, AIAgentRunTimelineComponent_ng_template_5_For_1_Conditional_1_ng_container_0_Template, 1, 0, "ng-container", 13);
} if (rf & 2) {
    const step_r8 = i0.ɵɵnextContext().$implicit;
    i0.ɵɵnextContext(2);
    const recursiveSteps_r4 = i0.ɵɵreference(6);
    i0.ɵɵproperty("ngTemplateOutlet", recursiveSteps_r4)("ngTemplateOutletContext", i0.ɵɵpureFunction1(2, _c0, step_r8.children));
} }
function AIAgentRunTimelineComponent_ng_template_5_For_1_Template(rf, ctx) { if (rf & 1) {
    const _r7 = i0.ɵɵgetCurrentView();
    i0.ɵɵelementStart(0, "mj-ai-agent-run-step-node", 7);
    i0.ɵɵlistener("itemClick", function AIAgentRunTimelineComponent_ng_template_5_For_1_Template_mj_ai_agent_run_step_node_itemClick_0_listener() { const step_r8 = i0.ɵɵrestoreView(_r7).$implicit; const ctx_r2 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r2.selectItem(step_r8)); })("expandToggle", function AIAgentRunTimelineComponent_ng_template_5_For_1_Template_mj_ai_agent_run_step_node_expandToggle_0_listener($event) { const step_r8 = i0.ɵɵrestoreView(_r7).$implicit; const ctx_r2 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r2.toggleItemExpansion(step_r8, $event)); })("navigateToEntity", function AIAgentRunTimelineComponent_ng_template_5_For_1_Template_mj_ai_agent_run_step_node_navigateToEntity_0_listener($event) { i0.ɵɵrestoreView(_r7); const ctx_r2 = i0.ɵɵnextContext(2); return i0.ɵɵresetView(ctx_r2.navigateToEntity.emit($event)); });
    i0.ɵɵelementEnd();
    i0.ɵɵconditionalCreate(1, AIAgentRunTimelineComponent_ng_template_5_For_1_Conditional_1_Template, 1, 4, "ng-container");
} if (rf & 2) {
    const step_r8 = ctx.$implicit;
    const ctx_r2 = i0.ɵɵnextContext(2);
    i0.ɵɵproperty("item", step_r8)("isSelected", (ctx_r2.selectedItem == null ? null : ctx_r2.selectedItem.id) === step_r8.id);
    i0.ɵɵadvance();
    i0.ɵɵconditional(step_r8.isExpanded && step_r8.children && step_r8.children.length > 0 ? 1 : -1);
} }
function AIAgentRunTimelineComponent_ng_template_5_Template(rf, ctx) { if (rf & 1) {
    i0.ɵɵrepeaterCreate(0, AIAgentRunTimelineComponent_ng_template_5_For_1_Template, 2, 3, null, null, i0.ɵɵcomponentInstance().trackByItemId, true);
} if (rf & 2) {
    const steps_r9 = ctx.$implicit;
    i0.ɵɵrepeater(steps_r9);
} }
export class AIAgentRunTimelineComponent {
    constructor(cdr) {
        this.cdr = cdr;
        this.autoRefresh = false;
        this.refreshInterval = 30000; // Minimum 30 seconds
        this.itemSelected = new EventEmitter();
        this.navigateToEntity = new EventEmitter();
        this.agentRunCompleted = new EventEmitter();
        this.destroy$ = new Subject();
        this.loading = true;
        this.error = null;
        this.selectedItem = null;
        this.refreshSubscription = null;
    }
    ngOnInit() {
        // Initialize observables from the data helper
        this.steps$ = this.dataHelper.steps$;
        this.subRuns$ = this.dataHelper.subRuns$;
        this.actionLogs$ = this.dataHelper.actionLogs$;
        this.promptRuns$ = this.dataHelper.promptRuns$;
        // Combine all data sources to build timeline.
        // Skip emissions where steps are empty but data is still loading —
        // the BehaviorSubjects initialise with [] so combineLatest fires
        // immediately with an empty array before the real data arrives.
        this.timelineItems$ = combineLatest([
            this.steps$,
            this.subRuns$,
            this.actionLogs$,
            this.promptRuns$,
            this.dataHelper.loading$
        ]).pipe(filter(([steps, _subRuns, _actionLogs, _promptRuns, isLoading]) => {
            // While loading, suppress the empty-array emission so the
            // template keeps showing the mj-loading indicator.
            return !(isLoading && steps.length === 0);
        }), map(([steps, subRuns, actionLogs, promptRuns]) => this.buildTimelineItems(steps, subRuns, actionLogs, promptRuns)), shareReplay(1));
        // Data loading is now handled by the parent component through the helper
        // Subscribe to loading state from helper
        this.dataHelper.loading$.pipe(takeUntil(this.destroy$)).subscribe(loading => {
            this.loading = loading;
            this.cdr.markForCheck();
        });
        this.dataHelper.error$.pipe(takeUntil(this.destroy$)).subscribe(error => {
            this.error = error;
            this.cdr.markForCheck();
        });
        // Auto-refresh logic
        if (this.autoRefresh) {
            this.startAutoRefresh();
        }
    }
    ngOnDestroy() {
        this.destroy$.next();
        this.destroy$.complete();
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
        }
    }
    startAutoRefresh() {
        // Ensure minimum 30 second interval
        const refreshIntervalMs = Math.max(30000, this.refreshInterval);
        // Don't create multiple subscriptions - subscribe once and use interval
        this.refreshSubscription = interval(refreshIntervalMs)
            .pipe(takeUntil(this.destroy$), 
        // Get the latest agent run status
        switchMap(() => {
            if (!this.aiAgentRunId)
                return of(null);
            const rv = new RunView();
            return from(rv.RunView({
                EntityName: 'MJ: AI Agent Runs',
                ExtraFilter: `ID = '${this.aiAgentRunId}'`,
                ResultType: 'simple'
            }));
        }), filter(result => result !== null && result.Success && result.Results?.length > 0), map(result => result.Results[0]))
            .subscribe(agentRun => {
            // Check if the agent run is still running
            if (agentRun.Status === 'Running') {
                // Reload data
                this.dataHelper.loadAgentRunData(this.aiAgentRunId);
            }
            else {
                // Agent run completed/failed - stop refresh
                console.log(`Agent run ${agentRun.Status} - stopping auto-refresh`);
                this.stopAutoRefresh();
                // Emit event to parent to update status
                this.agentRunCompleted.emit(agentRun.Status);
            }
        });
    }
    stopAutoRefresh() {
        if (this.refreshSubscription) {
            this.refreshSubscription.unsubscribe();
            this.refreshSubscription = null;
        }
        if (this.refreshTimer) {
            clearInterval(this.refreshTimer);
            this.refreshTimer = null;
        }
    }
    // This method is now just for compatibility - actual loading is done by parent
    async loadData() {
        if (!this.aiAgentRunId)
            return;
        // The parent component should handle data loading through the helper
        return this.dataHelper.loadAgentRunData(this.aiAgentRunId);
    }
    buildTimelineItems(steps, subRuns, actionLogs, promptRuns) {
        return this.buildHierarchicalItems(steps, 0, promptRuns);
    }
    buildHierarchicalItems(steps, baseLevel, promptRuns) {
        // Create a map of all timeline items by step ID
        const itemMap = new Map();
        // First pass: create all timeline items
        steps.forEach(step => {
            const item = this.createTimelineItemFromStep(step, baseLevel, promptRuns);
            itemMap.set(step.ID, item);
        });
        // Second pass: build parent-child relationships based on ParentID
        steps.forEach(step => {
            if (step.ParentID) {
                const parentItem = itemMap.get(step.ParentID);
                const childItem = itemMap.get(step.ID);
                if (parentItem && childItem) {
                    // Initialize children array if needed
                    if (!parentItem.children) {
                        parentItem.children = [];
                    }
                    // Set child's level based on parent's level
                    childItem.level = parentItem.level + 1;
                    // Add child to parent's children array
                    parentItem.children.push(childItem);
                }
            }
        });
        // Return only root-level items (those without a ParentID)
        const rootItems = [];
        steps.forEach(step => {
            if (!step.ParentID) {
                const item = itemMap.get(step.ID);
                if (item) {
                    rootItems.push(item);
                }
            }
        });
        return rootItems;
    }
    createTimelineItemFromStep(step, level, promptRuns) {
        let subtitle = `Type: ${step.StepType}`;
        // For prompt steps, try to find the associated prompt run to get model/vendor info
        if (step.StepType === 'Prompt' && step.TargetLogID && promptRuns) {
            const promptRun = promptRuns.find(pr => UUIDsEqual(pr.ID, step.TargetLogID));
            if (promptRun) {
                subtitle = `Model: ${promptRun.Model || 'Unknown'} | Vendor: ${promptRun.Vendor || 'Unknown'}`;
            }
        }
        // Get icon and logoUrl based on step type
        const iconInfo = this.getStepIconInfo(step);
        return {
            id: step.ID,
            type: 'step',
            title: step.StepName || `Step ${step.StepNumber}`,
            subtitle: subtitle,
            status: step.Status,
            startTime: step.StartedAt,
            endTime: step.CompletedAt || undefined,
            duration: this.calculateDuration(step.StartedAt, step.CompletedAt),
            icon: iconInfo.icon,
            logoUrl: iconInfo.logoUrl,
            color: this.getStatusColor(step.Status),
            data: step,
            children: [],
            level,
            isExpanded: false
        };
    }
    getStepIconInfo(step) {
        // For sub-agents, try to get agent-specific icon/logo
        if (step.StepType === 'Sub-Agent' && step.TargetID) {
            const agent = AIEngineBase.Instance.Agents.find(a => UUIDsEqual(a.ID, step.TargetID));
            if (agent) {
                // Prefer LogoURL - if present, use it with robot as fallback icon (icon won't be shown when logoUrl exists)
                if (agent.LogoURL) {
                    return { icon: 'fa-robot', logoUrl: agent.LogoURL };
                }
                // Next preference: IconClass from agent metadata
                else if (agent.IconClass) {
                    return { icon: agent.IconClass };
                }
                // Agent exists but has no custom icon or logo - use default robot icon
                else {
                    return { icon: 'fa-robot' };
                }
            }
        }
        // Default icons for each step type (includes fa-robot for sub-agents without agent metadata)
        const icon = this.getStepIcon(step.StepType);
        return { icon };
    }
    getStepIcon(stepType) {
        const iconMap = {
            'Prompt': 'fa-brain',
            'Tool': 'fa-tools',
            'Sub-Agent': 'fa-robot',
            'Decision': 'fa-code-branch',
            'Actions': 'fa-wrench',
            'Validation': 'fa-square-check',
            'ForEach': 'fa-repeat',
            'While': 'fa-rotate'
        };
        return iconMap[stepType] || 'fa-circle';
    }
    getStatusColor(status) {
        const colorMap = {
            'Running': 'info',
            'Completed': 'success',
            'Failed': 'error',
            'Cancelled': 'warning',
            'Paused': 'secondary'
        };
        return colorMap[status] || 'secondary';
    }
    calculateDuration(start, end) {
        if (!end)
            return 'Running...';
        const startTime = new Date(start).getTime();
        const endTime = new Date(end).getTime();
        const duration = endTime - startTime;
        if (duration < 1000)
            return `${duration}ms`;
        if (duration < 60000)
            return `${(duration / 1000).toFixed(1)}s`;
        if (duration < 3600000)
            return `${Math.floor(duration / 60000)}m ${Math.floor((duration % 60000) / 1000)}s`;
        return `${Math.floor(duration / 3600000)}h ${Math.floor((duration % 3600000) / 60000)}m`;
    }
    selectItem(item) {
        this.selectedItem = item;
        this.itemSelected.emit(item);
    }
    async toggleItemExpansion(item, event) {
        event.stopPropagation();
        // Toggle expansion state
        item.isExpanded = !item.isExpanded;
        // For Sub-Agent steps, load their run data on demand (requires DB query)
        if (item.isExpanded && !item.childrenLoaded && item.type === 'step' && item.data?.StepType === 'Sub-Agent') {
            await this.loadSubAgentChildren(item);
        }
        // For parent steps (loop containers like ForEach/While), children are already loaded via ParentID
        // Just toggle - no additional loading needed since we already have all steps from the run
        // The children were already attached in buildTimelineItems()
    }
    async loadSubAgentChildren(item) {
        try {
            const subAgentRunId = item.data?.TargetLogID;
            if (!subAgentRunId) {
                item.hasNoChildren = true;
                item.children = [];
                item.childrenLoaded = true;
                return;
            }
            // Load sub-agent data through service
            const data = await this.dataHelper.loadSubAgentData(subAgentRunId);
            if (!data.steps || data.steps.length === 0) {
                item.hasNoChildren = true;
                item.children = [];
                item.childrenLoaded = true;
                return;
            }
            // Build hierarchical timeline items with ParentID relationships
            // This ensures that loop steps (ForEach/While) within sub-agents also show their children
            item.children = this.buildHierarchicalItems(data.steps, item.level + 1, data.promptRuns);
            item.childrenLoaded = true;
            // Trigger change detection after updating the data
            this.cdr.markForCheck();
        }
        catch (error) {
            console.error('🔄 Timeline: Error loading sub-agent children:', error);
            item.hasNoChildren = true;
            item.childrenLoaded = true;
            // Trigger change detection for error state
            this.cdr.markForCheck();
        }
    }
    navigateToSubRun(runId, event) {
        event.stopPropagation();
        this.navigateToEntity.emit({ entityName: 'MJ: AI Agent Runs', recordId: runId });
    }
    navigateToActionLog(logId, event) {
        event.stopPropagation();
        this.navigateToEntity.emit({ entityName: 'MJ: Action Execution Logs', recordId: logId });
    }
    navigateToPromptRun(runId, event) {
        event.stopPropagation();
        this.navigateToEntity.emit({ entityName: 'MJ: AI Prompt Runs', recordId: runId });
    }
    /**
     * TrackBy function for timeline items
     */
    trackByItemId(index, item) {
        return item.id;
    }
    createSubRunDataHelper() {
        // Create a new data helper instance for sub-runs to prevent caching conflicts
        return new AIAgentRunDataHelper();
    }
    static { this.ɵfac = function AIAgentRunTimelineComponent_Factory(__ngFactoryType__) { return new (__ngFactoryType__ || AIAgentRunTimelineComponent)(i0.ɵɵdirectiveInject(i0.ChangeDetectorRef)); }; }
    static { this.ɵcmp = /*@__PURE__*/ i0.ɵɵdefineComponent({ type: AIAgentRunTimelineComponent, selectors: [["mj-ai-agent-run-timeline"]], inputs: { aiAgentRunId: "aiAgentRunId", autoRefresh: "autoRefresh", refreshInterval: "refreshInterval", dataHelper: "dataHelper" }, outputs: { itemSelected: "itemSelected", navigateToEntity: "navigateToEntity", agentRunCompleted: "agentRunCompleted" }, standalone: false, decls: 7, vars: 4, consts: [["recursiveSteps", ""], [1, "loading-state"], [1, "timeline-container"], [1, "error-state"], ["text", "Loading run steps...", "size", "medium"], [1, "timeline"], [1, "empty-state"], [3, "itemClick", "expandToggle", "navigateToEntity", "item", "isSelected"], [1, "loading-children"], [1, "no-children"], [3, "aiAgentRunId", "dataHelper", "autoRefresh"], [1, "fas", "fa-spinner", "fa-spin"], [1, "fas", "fa-info-circle"], [4, "ngTemplateOutlet", "ngTemplateOutletContext"], [3, "itemSelected", "navigateToEntity", "aiAgentRunId", "dataHelper", "autoRefresh"], [1, "fas", "fa-stream", "fa-3x"], [1, "fas", "fa-exclamation-triangle", "fa-2x"]], template: function AIAgentRunTimelineComponent_Template(rf, ctx) { if (rf & 1) {
            i0.ɵɵconditionalCreate(0, AIAgentRunTimelineComponent_Conditional_0_Template, 2, 0, "div", 1);
            i0.ɵɵpipe(1, "async");
            i0.ɵɵconditionalBranchCreate(2, AIAgentRunTimelineComponent_Conditional_2_Template, 3, 2, "div", 2)(3, AIAgentRunTimelineComponent_Conditional_3_Template, 2, 0, "div", 1);
            i0.ɵɵconditionalCreate(4, AIAgentRunTimelineComponent_Conditional_4_Template, 4, 1, "div", 3);
            i0.ɵɵtemplate(5, AIAgentRunTimelineComponent_ng_template_5_Template, 2, 0, "ng-template", null, 0, i0.ɵɵtemplateRefExtractor);
        } if (rf & 2) {
            let tmp_1_0;
            i0.ɵɵconditional(ctx.loading ? 0 : (tmp_1_0 = i0.ɵɵpipeBind1(1, 2, ctx.timelineItems$)) ? 2 : 3, tmp_1_0);
            i0.ɵɵadvance(4);
            i0.ɵɵconditional(ctx.error ? 4 : -1);
        } }, styles: [".timeline-container[_ngcontent-%COMP%] {\n  height: 100%;\n  overflow-y: auto;\n  padding: 20px;\n}\n\n.timeline[_ngcontent-%COMP%] {\n  position: relative;\n  padding-left: 40px; \n\n}\n\n.sub-timeline[_ngcontent-%COMP%] {\n  margin-left: 24px;\n  margin-top: 8px;\n  padding-left: 12px;\n  border-left: 2px dashed var(--mj-border-default);\n}\n\n\n\n.empty-state[_ngcontent-%COMP%], \n.loading-state[_ngcontent-%COMP%], \n.error-state[_ngcontent-%COMP%] {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  color: var(--mj-text-muted);\n  gap: 16px;\n}\n\n.error-state[_ngcontent-%COMP%] {\n  color: var(--mj-status-error);\n}\n\n\n\n.loading-children[_ngcontent-%COMP%], \n.no-children[_ngcontent-%COMP%] {\n  padding: 12px 20px;\n  margin-left: 60px;\n  color: var(--mj-text-muted);\n  font-size: 13px;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.loading-children[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  color: var(--mj-brand-primary);\n}\n\n.no-children[_ngcontent-%COMP%] {\n  color: var(--mj-text-disabled);\n  font-style: italic;\n}\n\n.no-children[_ngcontent-%COMP%]   i[_ngcontent-%COMP%] {\n  color: var(--mj-text-disabled);\n}\n\n\n\n.sub-run-steps[_ngcontent-%COMP%] {\n  margin-left: 20px;\n  padding-left: 20px;\n  border-left: 2px solid var(--mj-border-default);\n  margin-top: 8px;\n}"], changeDetection: 0 }); }
}
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassMetadata(AIAgentRunTimelineComponent, [{
        type: Component,
        args: [{ standalone: false, selector: 'mj-ai-agent-run-timeline', changeDetection: ChangeDetectionStrategy.OnPush, template: "@if (loading) {\n  <div class=\"loading-state\">\n    <mj-loading text=\"Loading run steps...\" size=\"medium\"></mj-loading>\n  </div>\n} @else if (timelineItems$ | async; as items) {\n  <div class=\"timeline-container\">\n    @if (items.length > 0) {\n      <div class=\"timeline\">\n        @for (item of items; track trackByItemId($index, item)) {\n          <!-- Main Timeline Item -->\n          <mj-ai-agent-run-step-node\n            [item]=\"item\"\n            [isSelected]=\"selectedItem?.id === item.id\"\n            (itemClick)=\"selectItem(item)\"\n            (expandToggle)=\"toggleItemExpansion(item, $event)\"\n            (navigateToEntity)=\"navigateToEntity.emit($event)\">\n          </mj-ai-agent-run-step-node>\n          <!-- Children Container (for both Sub-Agent and ParentID relationships) -->\n          @if (item.isExpanded) {\n            <!-- Show loading indicator while loading Sub-Agent children -->\n            @if (item.type === 'step' && item.data?.StepType === 'Sub-Agent' && !item.childrenLoaded) {\n              <div class=\"loading-children\">\n                <i class=\"fas fa-spinner fa-spin\"></i> Loading sub-agent steps...\n              </div>\n            }\n            <!-- Show no children message for Sub-Agents -->\n            @if (item.type === 'step' && item.data?.StepType === 'Sub-Agent' && item.childrenLoaded && item.hasNoChildren) {\n              <div class=\"no-children\">\n                <i class=\"fas fa-info-circle\"></i> No sub-agent steps found\n              </div>\n            }\n            <!-- Render children recursively (works for both Sub-Agent and ParentID children) -->\n            @if (item.children && item.children.length > 0) {\n              <ng-container *ngTemplateOutlet=\"recursiveSteps; context: { $implicit: item.children }\"></ng-container>\n            }\n            <!-- For actual sub-run items (from the initial load) - legacy support -->\n            @if (item.type === 'subrun' && item.data?.ID) {\n              <mj-ai-agent-run-timeline\n                [aiAgentRunId]=\"item.data.ID\"\n                [dataHelper]=\"createSubRunDataHelper()\"\n                [autoRefresh]=\"false\"\n                (itemSelected)=\"selectItem($event)\"\n                (navigateToEntity)=\"navigateToEntity.emit($event)\">\n              </mj-ai-agent-run-timeline>\n            }\n          }\n        }\n      </div>\n    }\n    @if (items.length === 0) {\n      <div class=\"empty-state\">\n        <i class=\"fas fa-stream fa-3x\"></i>\n        <p>No execution steps found</p>\n      </div>\n    }\n  </div>\n} @else {\n  <!-- timelineItems$ hasn't emitted yet -->\n  <div class=\"loading-state\">\n    <mj-loading text=\"Loading run steps...\" size=\"medium\"></mj-loading>\n  </div>\n}\n\n@if (error) {\n  <div class=\"error-state\">\n    <i class=\"fas fa-exclamation-triangle fa-2x\"></i>\n    <p>{{ error }}</p>\n  </div>\n}\n\n<!-- Recursive template for rendering nested children (ParentID relationships) -->\n<ng-template #recursiveSteps let-steps>\n  @for (step of steps; track trackByItemId($index, step)) {\n    <mj-ai-agent-run-step-node\n      [item]=\"step\"\n      [isSelected]=\"selectedItem?.id === step.id\"\n      (itemClick)=\"selectItem(step)\"\n      (expandToggle)=\"toggleItemExpansion(step, $event)\"\n      (navigateToEntity)=\"navigateToEntity.emit($event)\">\n    </mj-ai-agent-run-step-node>\n    <!-- Recursively render this step's children if expanded -->\n    @if (step.isExpanded && step.children && step.children.length > 0) {\n      <ng-container *ngTemplateOutlet=\"recursiveSteps; context: { $implicit: step.children }\"></ng-container>\n    }\n  }\n</ng-template>", styles: [".timeline-container {\n  height: 100%;\n  overflow-y: auto;\n  padding: 20px;\n}\n\n.timeline {\n  position: relative;\n  padding-left: 40px; /* Add padding to accommodate expand buttons */\n}\n\n.sub-timeline {\n  margin-left: 24px;\n  margin-top: 8px;\n  padding-left: 12px;\n  border-left: 2px dashed var(--mj-border-default);\n}\n\n/* State Displays */\n.empty-state,\n.loading-state,\n.error-state {\n  display: flex;\n  flex-direction: column;\n  align-items: center;\n  justify-content: center;\n  height: 100%;\n  color: var(--mj-text-muted);\n  gap: 16px;\n}\n\n.error-state {\n  color: var(--mj-status-error);\n}\n\n/* Loading and No Children States */\n.loading-children,\n.no-children {\n  padding: 12px 20px;\n  margin-left: 60px;\n  color: var(--mj-text-muted);\n  font-size: 13px;\n  display: flex;\n  align-items: center;\n  gap: 8px;\n}\n\n.loading-children i {\n  color: var(--mj-brand-primary);\n}\n\n.no-children {\n  color: var(--mj-text-disabled);\n  font-style: italic;\n}\n\n.no-children i {\n  color: var(--mj-text-disabled);\n}\n\n/* Sub-run steps container */\n.sub-run-steps {\n  margin-left: 20px;\n  padding-left: 20px;\n  border-left: 2px solid var(--mj-border-default);\n  margin-top: 8px;\n}"] }]
    }], () => [{ type: i0.ChangeDetectorRef }], { aiAgentRunId: [{
            type: Input
        }], autoRefresh: [{
            type: Input
        }], refreshInterval: [{
            type: Input
        }], dataHelper: [{
            type: Input
        }], itemSelected: [{
            type: Output
        }], navigateToEntity: [{
            type: Output
        }], agentRunCompleted: [{
            type: Output
        }] }); })();
(() => { (typeof ngDevMode === "undefined" || ngDevMode) && i0.ɵsetClassDebugInfo(AIAgentRunTimelineComponent, { className: "AIAgentRunTimelineComponent", filePath: "src/lib/custom/ai-agent-run/ai-agent-run-timeline.component.ts", lineNumber: 38 }); })();
//# sourceMappingURL=ai-agent-run-timeline.component.js.map