{% extends "base.html" %}
{% from 'components/_macros.html' import status_badge, empty_state %}

{% block content %}
<script>
    // Pre-render Jinja2 data for Alpine.js
    window.workflowsData = {
        executionIds: {{ executions | map(attribute='execution_id') | list | tojson | safe }},
        executionCount: {{ executions | length }},
        allExecutions: {{ executions | tojson | safe }}
    };

    function workflowsComponent() {
        return {
            selectedExecutions: [],
            currentExecutionId: null,
            currentExecution: null,
            loading: false,
            filterWorkflow: '',
            allExecutions: window.workflowsData.allExecutions,
            pollInterval: null,

            init() {
                // Wait for Alpine to finish rendering before selecting execution
                this.$nextTick(() => {
                    const hash = window.location.hash.slice(1);
                    if (hash) {
                        this.selectExecution(hash);
                    } else {
                        const firstExecution = this.$el.querySelector('[data-execution-id]');
                        if (firstExecution) {
                            this.selectExecution(firstExecution.dataset.executionId);
                        }
                    }
                });

                // Start polling for updates
                if (!document.hidden) {
                    this.startPolling();
                }

                // Pause polling when tab is hidden to save resources
                document.addEventListener('visibilitychange', () => {
                    if (document.hidden) {
                        this.stopPolling();
                    } else {
                        this.startPolling();
                    }
                });
            },

            startPolling() {
                this.stopPolling();

                // Poll immediately
                this.fetchExecutions();

                // Then poll every 0.5 seconds
                this.pollInterval = setInterval(() => {
                    this.fetchExecutions();
                }, 500);
            },

            stopPolling() {
                if (this.pollInterval) {
                    clearInterval(this.pollInterval);
                    this.pollInterval = null;
                }
            },

            async fetchExecutions() {
                try {
                    const response = await fetch('/api/executions?limit=100');
                    if (!response.ok) return;

                    const executions = await response.json();
                    this.allExecutions = executions;

                    // Refresh current execution details if one is selected
                    if (this.currentExecutionId) {
                        const currentExists = executions.find(
                            ex => ex.execution_id === this.currentExecutionId
                        );
                        if (currentExists) {
                            // Refresh details view
                            this.selectExecution(this.currentExecutionId);
                        } else {
                            this.currentExecutionId = null;
                            this.currentExecution = null;
                            window.location.hash = '';
                        }
                    }
                } catch (error) {
                    // Silently fail - will retry on next poll
                    console.error('Poll error:', error);
                }
            },

            get uniqueWorkflowNames() {
                const names = [...new Set(this.allExecutions.map(ex => ex.workflow_name))];
                return names.sort();
            },

            get filteredExecutions() {
                if (!this.filterWorkflow) {
                    return this.allExecutions;
                }
                return this.allExecutions.filter(ex => ex.workflow_name === this.filterWorkflow);
            },

            get hasSelectedExecutions() {
                return this.selectedExecutions.length > 0;
            },

            get allSelected() {
                return this.selectedExecutions.length === this.filteredExecutions.length;
            },

            toggleSelectAll() {
                if (this.allSelected) {
                    this.selectedExecutions = [];
                } else {
                    this.selectedExecutions = this.filteredExecutions.map(ex => ex.execution_id);
                }
            },

            async selectExecution(executionId) {
                if (this.currentExecutionId === executionId) return;

                this.currentExecutionId = executionId;
                this.loading = true;

                // Update URL hash
                window.location.hash = executionId;

                try {
                    const response = await fetch(`/api/executions/${executionId}`);
                    if (!response.ok) throw new Error('Failed to fetch execution');

                    this.currentExecution = await response.json();
                } catch (error) {
                    console.error('Error loading execution:', error);
                    this.currentExecution = { error: error.message };
                } finally {
                    this.loading = false;
                }
            },

            async timeTravel(workflowName, stepName) {
                if (!confirm(`Resume workflow from step '${stepName}'?`)) return;

                try {
                    const response = await fetch(`/workflows/${workflowName}/resume?step_name=${stepName}`, {
                        method: 'POST',
                        headers: {'Content-Type': 'application/json'},
                        body: '{}'
                    });

                    if (!response.ok) throw new Error(`HTTP error! status: ${response.status}`);

                    const data = await response.json();
                    alert(`✓ New execution created!\nExecution ID: ${data.execution_id}\nStatus: ${data.status}`);

                    // Reload page to show new execution
                    window.location.reload();
                } catch (error) {
                    alert(`Time travel failed: ${error.message}`);
                }
            },

            async deleteSelected() {
                if (this.selectedExecutions.length === 0) return;

                const confirmed = confirm(`Are you sure you want to delete ${this.selectedExecutions.length} execution(s)? This cannot be undone.`);
                if (!confirmed) return;

                try {
                    const response = await fetch('/api/executions', {
                        method: 'DELETE',
                        headers: {'Content-Type': 'application/json'},
                        body: JSON.stringify(this.selectedExecutions)
                    });

                    if (response.ok) {
                        const result = await response.json();
                        alert(result.message);
                        this.selectedExecutions = [];
                        this.fetchExecutions();
                    } else {
                        const error = await response.json();
                        alert('Error: ' + error.detail);
                    }
                } catch (error) {
                    alert('Failed to delete executions: ' + error);
                }
            },

            handleKeydown(e) {
                if (['ArrowUp', 'ArrowDown'].includes(e.key)) {
                    e.preventDefault();
                    const currentIdx = this.filteredExecutions.findIndex(ex => ex.execution_id === this.currentExecutionId);
                    let newIdx = -1;
                    
                    if (e.key === 'ArrowUp') {
                        newIdx = currentIdx > 0 ? currentIdx - 1 : this.filteredExecutions.length - 1;
                    } else {
                        newIdx = currentIdx < this.filteredExecutions.length - 1 ? currentIdx + 1 : 0;
                    }
                    
                    if (newIdx !== -1) {
                        const nextId = this.filteredExecutions[newIdx].execution_id;
                        this.selectExecution(nextId);
                        
                        // Scroll into view
                        this.$nextTick(() => {
                            const el = document.querySelector(`[data-execution-id='${nextId}']`);
                            if (el) el.scrollIntoView({ block: 'nearest' });
                        });
                    }
                }
            },

            copyToClipboard(text) {
                navigator.clipboard.writeText(JSON.stringify(text, null, 2));
            }
        }
    }
</script>

<div
    x-data="workflowsComponent()"
    class="grid grid-cols-1 lg:grid-cols-12 gap-6 h-full"
    @keydown.window="handleKeydown($event)"
>
    <!-- LEFT SIDEBAR: Execution List -->
    <aside class="lg:col-span-4 xl:col-span-3 flex flex-col min-h-0">
        <!-- Sidebar Header -->
        <div class="flex-shrink-0 mb-4 pl-1 pr-2">
            <div class="flex items-center justify-between mb-4">
                <h2 class="text-xl font-bold text-terminal-text-bright">Runs</h2>
                <div class="flex items-center gap-3">
                    {% if executions %}
                    <button
                        @click="deleteSelected()"
                        :disabled="!hasSelectedExecutions"
                        class="p-2 text-terminal-text-muted hover:text-status-error transition-smooth disabled:opacity-30 disabled:cursor-not-allowed"
                        title="Delete Selected"
                    >
                        <svg xmlns="http://www.w3.org/2000/svg" class="h-5 w-5" viewBox="0 0 20 20" fill="currentColor">
                            <path fill-rule="evenodd" d="M9 2a1 1 0 00-.894.553L7.382 4H4a1 1 0 000 2v10a2 2 0 002 2h8a2 2 0 002-2V6a1 1 0 100-2h-3.382l-.724-1.447A1 1 0 0011 2H9zM7 8a1 1 0 012 0v6a1 1 0 11-2 0V8zm5-1a1 1 0 00-1 1v6a1 1 0 102 0V8a1 1 0 00-1-1z" clip-rule="evenodd" />
                        </svg>
                    </button>
                    <label class="flex items-center gap-2 cursor-pointer text-xs font-medium text-terminal-text-dim hover:text-terminal-text transition-smooth select-none">
                        <input
                            type="checkbox"
                            class="rounded border-terminal-border bg-terminal-bg text-accent-purple focus:ring-0 focus:ring-offset-0 w-4 h-4"
                            x-model="allSelected"
                            @change="toggleSelectAll()"
                        >
                        <span>All</span>
                    </label>
                    {% endif %}
                </div>
            </div>
            
            {% if executions %}
            <div class="relative">
                <select
                    x-model="filterWorkflow"
                    class="w-full appearance-none bg-terminal-bg px-4 py-2.5 pr-8 rounded-xl border border-transparent focus:border-accent-blue/50 focus:bg-terminal-bg-light outline-none text-sm text-terminal-text transition-smooth cursor-pointer"
                >
                    <option value="">All Workflows</option>
                    <template x-for="workflow in uniqueWorkflowNames" :key="workflow">
                        <option :value="workflow" x-text="workflow.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())"></option>
                    </template>
                </select>
                <div class="pointer-events-none absolute inset-y-0 right-0 flex items-center px-3 text-terminal-text-muted">
                    <svg class="h-4 w-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M19 9l-7 7-7-7"></path></svg>
                </div>
            </div>
            {% endif %}
        </div>

        <!-- Scrollable List -->
        <div class="flex-1 overflow-y-auto pr-2 space-y-2 custom-scrollbar">
        {% if executions %}
            <div id="executions-loading" class="py-10 text-center text-terminal-text-muted">
                <div class="animate-pulse">Loading runs...</div>
            </div>

            <div x-cloak class="space-y-2 pb-4">
                <template x-for="execution in filteredExecutions" :key="execution.execution_id">
                    <div
                        class="group relative p-4 rounded-xl cursor-pointer transition-all duration-200 border border-transparent"
                        :class="currentExecutionId === execution.execution_id 
                            ? 'bg-terminal-bg shadow-lg ring-1 ring-white/5' 
                            : 'bg-terminal-bg/30 hover:bg-terminal-bg hover:shadow-md'"
                        @click="selectExecution(execution.execution_id)"
                    >
                        <!-- Selection Checkbox (Absolute) -->
                        <div class="absolute left-4 top-1/2 -translate-y-1/2" @click.stop>
                            <input
                                type="checkbox"
                                class="w-4 h-4 rounded border-terminal-border bg-terminal-bg-dark text-accent-purple focus:ring-0 focus:ring-offset-0 opacity-0 group-hover:opacity-100 transition-opacity"
                                :class="{'opacity-100': selectedExecutions.includes(execution.execution_id)}"
                                x-model="selectedExecutions"
                                :value="execution.execution_id"
                            >
                        </div>

                        <!-- Content (Shifted for checkbox space on hover) -->
                        <div class="pl-6 transition-all">
                            <div class="flex justify-between items-start gap-3 mb-1.5">
                                <h3 class="font-semibold text-sm text-terminal-text group-hover:text-terminal-text-bright transition-colors truncate" 
                                    x-text="execution.workflow_name.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())">
                                </h3>
                                <span
                                    class="flex-shrink-0 w-2 h-2 rounded-full mt-1.5"
                                    :class="{
                                        'bg-status-success shadow-[0_0_8px_rgba(158,206,106,0.5)]': execution.status === 'completed',
                                        'bg-status-running shadow-[0_0_8px_rgba(122,162,247,0.5)] animate-pulse': execution.status === 'running',
                                        'bg-status-error shadow-[0_0_8px_rgba(247,118,142,0.5)]': execution.status === 'failed',
                                        'bg-status-pending': execution.status === 'pending'
                                    }"
                                ></span>
                            </div>
                            <div class="flex justify-between items-center text-xs text-terminal-text-muted font-mono">
                                <span x-text="execution.execution_id.substring(0, 8)"></span>
                                <span x-text="execution.started_at ? new Date(execution.started_at).toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false}) : ''"></span>
                            </div>
                        </div>
                    </div>
                </template>

                <!-- Empty Filter State -->
                <div x-show="filteredExecutions.length === 0" class="py-12 text-center">
                    <p class="text-terminal-text-muted">No runs match your filter.</p>
                </div>
            </div>
        {% else %}
            <!-- Empty State (No runs at all) -->
            <div class="py-20 text-center px-4">
                <div class="inline-flex items-center justify-center w-12 h-12 rounded-full bg-terminal-bg mb-4">
                    <svg class="w-6 h-6 text-terminal-text-muted" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M13 10V3L4 14h7v7l9-11h-7z"></path></svg>
                </div>
                <p class="text-terminal-text font-medium mb-2">No runs yet</p>
                <p class="text-xs text-terminal-text-muted mb-4">Start a workflow via the API to see it here.</p>
                <a href="/docs" class="inline-flex items-center gap-2 px-4 py-2 rounded-lg bg-accent-blue/10 text-accent-blue text-xs font-bold hover:bg-accent-blue/20 transition-smooth">
                    View API Docs
                </a>
            </div>
        {% endif %}
        </div>
    </aside>

    <!-- RIGHT PANEL: Main Content -->
    <section class="lg:col-span-8 xl:col-span-9 flex flex-col min-h-0 relative">
        <!-- Main Card Container -->
        <div class="flex-1 bg-terminal-bg rounded-3xl shadow-2xl flex flex-col overflow-hidden border border-white/5 relative">
            
            <!-- Loading Overlay -->
            <div x-show="loading" x-transition.opacity class="absolute inset-0 bg-terminal-bg/50 backdrop-blur-sm z-50 flex items-center justify-center">
                <div class="flex flex-col items-center gap-3">
                    <div class="w-6 h-6 border-2 border-accent-blue border-t-transparent rounded-full animate-spin"></div>
                    <span class="text-xs font-medium text-accent-blue">Loading details...</span>
                </div>
            </div>

            <!-- Empty State (No Selection) -->
            <div x-show="!currentExecution" class="flex-1 flex flex-col items-center justify-center text-center p-8 opacity-50">
                <div class="w-24 h-24 bg-terminal-bg-light rounded-full flex items-center justify-center mb-6 shadow-inner">
                    <svg class="w-10 h-10 text-terminal-text-dim" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="1.5" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2m-3 7h3m-3 4h3m-6-4h.01M9 16h.01"></path></svg>
                </div>
                <h3 class="text-lg font-medium text-terminal-text mb-1">Select a Run</h3>
                <p class="text-sm text-terminal-text-muted">Choose a workflow run from the sidebar to view its timeline and data.</p>
            </div>

            <!-- Content (Selection Active) -->
            <div x-show="currentExecution" x-cloak class="flex flex-col h-full">
                
                <!-- Header (Sticky) -->
                <div class="flex-shrink-0 px-8 py-6 border-b border-white/5 bg-terminal-bg/80 backdrop-blur z-10">
                    <div class="flex items-start justify-between gap-4">
                        <div>
                            <div class="flex items-center gap-3 mb-2">
                                <h2 class="text-2xl font-bold text-terminal-text-bright" x-text="currentExecution?.workflow_name.replace(/_/g, ' ').replace(/\b\w/g, l => l.toUpperCase())"></h2>
                                <span
                                    class="px-3 py-1 rounded-full text-xs font-bold tracking-wide uppercase"
                                    :class="{
                                        'bg-status-success/10 text-status-success ring-1 ring-status-success/20': currentExecution?.status === 'completed',
                                        'bg-status-running/10 text-status-running ring-1 ring-status-running/20': currentExecution?.status === 'running',
                                        'bg-status-error/10 text-status-error ring-1 ring-status-error/20': currentExecution?.status === 'failed',
                                        'bg-status-pending/10 text-status-pending ring-1 ring-status-pending/20': currentExecution?.status === 'pending'
                                    }"
                                    x-text="currentExecution?.status"
                                ></span>
                            </div>
                            <div class="flex items-center gap-4 text-xs text-terminal-text-muted font-mono">
                                <span class="flex items-center gap-1.5">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                    <span x-text="currentExecution?.started_at ? currentExecution.started_at.split('T')[1].split('.')[0] : ''"></span>
                                </span>
                                <span class="flex items-center gap-1.5 px-2 py-0.5 rounded bg-terminal-bg-dark/50">
                                    <svg class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M7 20l4-16m2 16l4-16M6 9h14M4 15h14"></path></svg>
                                    <span x-text="currentExecution?.execution_id"></span>
                                </span>
                            </div>
                        </div>
                        <!-- Actions -->
                        <div class="flex items-center gap-2">
                             <!-- Potential Rerun button here -->
                        </div>
                    </div>
                </div>

                <!-- Scrollable Details -->
                <div class="flex-1 overflow-y-auto p-8 custom-scrollbar space-y-8">
                    
                    <!-- Inputs & Outputs Grid -->
                    <div class="grid grid-cols-1 lg:grid-cols-2 gap-6">
                        <!-- Inputs -->
                        <div class="space-y-3">
                            <div class="flex justify-between items-end">
                                <h3 class="text-xs font-bold text-terminal-text-muted uppercase tracking-wider ml-1">Inputs</h3>
                                <div x-data="{ copied: false }">
                                    <button 
                                        @click="navigator.clipboard.writeText(JSON.stringify(currentExecution?.inputs, null, 2)); copied = true; setTimeout(() => copied = false, 2000)" 
                                        class="text-xs transition-colors" 
                                        :class="copied ? 'text-status-success' : 'text-terminal-text-muted hover:text-accent-blue'"
                                        :title="copied ? 'Copied!' : 'Copy JSON'"
                                    >
                                        <svg x-show="!copied" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                        <svg x-show="copied" x-cloak class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                    </button>
                                </div>
                            </div>
                            <div class="bg-terminal-bg-dark/50 rounded-xl p-4 border border-white/5 hover:border-white/10 transition-colors group">
                                <pre class="font-mono text-xs text-terminal-text-bright overflow-x-auto custom-scrollbar max-h-40 group-hover:text-white transition-colors" x-text="JSON.stringify(currentExecution?.inputs, null, 2)"></pre>
                            </div>
                        </div>

                        <!-- Outputs -->
                        <div class="space-y-3">
                            <div class="flex justify-between items-end">
                                <h3 class="text-xs font-bold text-terminal-text-muted uppercase tracking-wider ml-1">Outputs</h3>
                                <div x-show="currentExecution?.outputs" x-data="{ copied: false }">
                                    <button 
                                        @click="navigator.clipboard.writeText(JSON.stringify(currentExecution?.outputs, null, 2)); copied = true; setTimeout(() => copied = false, 2000)" 
                                        class="text-xs transition-colors" 
                                        :class="copied ? 'text-status-success' : 'text-terminal-text-muted hover:text-accent-blue'"
                                        :title="copied ? 'Copied!' : 'Copy JSON'"
                                    >
                                        <svg x-show="!copied" class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                        <svg x-show="copied" x-cloak class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                    </button>
                                </div>
                            </div>
                            <div class="rounded-xl overflow-hidden">
                                <div x-show="currentExecution?.error && !currentExecution?.outputs" class="bg-status-error/10 p-4 border border-status-error/20">
                                    <div class="flex gap-3">
                                        <div class="text-status-error mt-0.5">
                                            <svg class="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z"></path></svg>
                                        </div>
                                        <div class="min-w-0">
                                            <h4 class="text-xs font-bold text-status-error mb-1">Execution Failed</h4>
                                            <pre class="text-xs font-mono text-status-error/80 whitespace-pre-wrap break-words" x-text="currentExecution?.error"></pre>
                                        </div>
                                    </div>
                                </div>
                                <div x-show="currentExecution?.outputs" class="bg-terminal-bg-dark/50 p-4 border border-white/5 hover:border-white/10 transition-colors">
                                    <pre class="font-mono text-xs text-status-success/90 overflow-x-auto custom-scrollbar max-h-40" x-text="JSON.stringify(currentExecution?.outputs, null, 2)"></pre>
                                </div>
                            </div>
                        </div>
                    </div>

                    <!-- Timeline / Steps -->
                    <div class="space-y-4">
                        <h3 class="text-xs font-bold text-terminal-text-muted uppercase tracking-wider ml-1">Execution Timeline</h3>
                        
                        <div class="relative space-y-4">
                            <template x-for="(step, index) in currentExecution?.step_executions || []" :key="index">
                                <div class="relative pl-4 group">

                                    <!-- Card -->
                                    <div class="bg-terminal-bg-light rounded-xl p-5 border border-transparent hover:border-white/5 transition-all shadow-sm"
                                         :class="step.error ? 'ring-1 ring-status-error/30 bg-status-error/5' : ''">
                                        
                                        <!-- Step Header -->
                                        <div class="flex items-center justify-between mb-4">
                                            <div class="flex items-center gap-3">
                                                <h4 class="text-sm font-bold text-terminal-text-bright" x-text="step.step_name"></h4>
                                                <span x-show="step.error" class="px-2 py-0.5 bg-status-error/20 text-status-error text-[10px] rounded font-bold uppercase">Error</span>
                                            </div>
                                            <div class="flex items-center gap-3">
                                                 <span class="text-xs font-mono text-terminal-text-dim" x-text="new Date(step.timestamp).toLocaleTimeString('en-US', {hour: '2-digit', minute: '2-digit', second: '2-digit', hour12: false})"></span>
                                                 <button
                                                    @click="timeTravel(currentExecution.workflow_name, step.step_name)"
                                                    class="px-3 py-1.5 bg-accent-blue/10 text-accent-blue text-xs font-semibold rounded-lg hover:bg-accent-blue hover:text-white transition-all"
                                                    :title="step.error ? 'Retry workflow from this failed step' : 'Rerun workflow from this step'"
                                                    x-text="step.error ? '↺ Retry' : '↺ Resume'"
                                                >
                                                </button>
                                            </div>
                                        </div>

                                        <!-- Step Data -->
                                        <div class="grid grid-cols-1 md:grid-cols-2 gap-4 text-xs">
                                            <div class="space-y-1.5">
                                                <div class="flex justify-between items-end">
                                                    <span class="text-terminal-text-muted font-medium">Input</span>
                                                    <div x-data="{ copied: false }">
                                                        <button 
                                                            @click="navigator.clipboard.writeText(JSON.stringify(step.inputs, null, 2)); copied = true; setTimeout(() => copied = false, 2000)" 
                                                            class="text-xs transition-colors" 
                                                            :class="copied ? 'text-status-success' : 'text-terminal-text-muted hover:text-accent-blue'"
                                                            :title="copied ? 'Copied!' : 'Copy JSON'"
                                                        >
                                                            <svg x-show="!copied" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                                            <svg x-show="copied" x-cloak class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                                        </button>
                                                    </div>
                                                </div>
                                                <div class="bg-terminal-bg-dark/50 rounded-lg p-3 font-mono text-terminal-text overflow-x-auto custom-scrollbar">
                                                    <pre x-text="JSON.stringify(step.inputs, null, 2)"></pre>
                                                </div>
                                            </div>
                                            <div class="space-y-1.5">
                                                <div class="flex justify-between items-end">
                                                    <span class="text-terminal-text-muted font-medium">Result</span>
                                                    <!-- Copy Result Button (only if no error) -->
                                                    <div x-show="!step.error" x-data="{ copied: false }">
                                                        <button 
                                                            @click="navigator.clipboard.writeText(JSON.stringify(step.outputs, null, 2)); copied = true; setTimeout(() => copied = false, 2000)" 
                                                            class="text-xs transition-colors" 
                                                            :class="copied ? 'text-status-success' : 'text-terminal-text-muted hover:text-accent-blue'"
                                                            :title="copied ? 'Copied!' : 'Copy JSON'"
                                                        >
                                                            <svg x-show="!copied" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                                            <svg x-show="copied" x-cloak class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                                        </button>
                                                    </div>
                                                    <!-- Copy Error Button (only if error) -->
                                                    <div x-show="step.error" x-data="{ copied: false }">
                                                        <button 
                                                            @click="navigator.clipboard.writeText(step.error); copied = true; setTimeout(() => copied = false, 2000)" 
                                                            class="text-xs transition-colors" 
                                                            :class="copied ? 'text-status-success' : 'text-status-error hover:text-status-error/80'"
                                                            :title="copied ? 'Copied!' : 'Copy Error'"
                                                        >
                                                            <svg x-show="!copied" class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M8 16H6a2 2 0 01-2-2V6a2 2 0 012-2h8a2 2 0 012 2v2m-6 12h8a2 2 0 002-2v-8a2 2 0 00-2-2h-8a2 2 0 00-2 2v8a2 2 0 002 2z"></path></svg>
                                                            <svg x-show="copied" x-cloak class="w-3.5 h-3.5" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path stroke-linecap="round" stroke-linejoin="round" stroke-width="2" d="M5 13l4 4L19 7"></path></svg>
                                                        </button>
                                                    </div>
                                                </div>
                                                
                                                <!-- Output / Error Display -->
                                                <div class="rounded-lg overflow-hidden" 
                                                     :class="step.error ? 'bg-status-error/10 border border-status-error/20' : 'bg-terminal-bg-dark/50 border border-transparent'">
                                                    
                                                    <!-- Successful Output -->
                                                    <pre x-show="!step.error" 
                                                         class="p-3 font-mono text-terminal-text-bright overflow-x-auto custom-scrollbar"
                                                         x-text="JSON.stringify(step.outputs, null, 2)"></pre>
                                                    
                                                    <!-- Error Message -->
                                                    <div x-show="step.error" class="p-3">
                                                        <div class="flex items-start gap-2 text-status-error">
                                                            <span class="font-bold flex-shrink-0">Error:</span>
                                                            <pre class="font-mono text-xs whitespace-pre-wrap break-words" x-text="step.error"></pre>
                                                        </div>
                                                    </div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </template>
                        </div>

                        <!-- No steps state -->
                        <div x-show="!currentExecution?.step_executions?.length" class="text-center py-8 opacity-50">
                            <span class="text-sm text-terminal-text-muted">No steps recorded yet.</span>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </section>
</div>

<script>
    // Hide loading state once Alpine.js is ready
    document.addEventListener('alpine:init', () => {
        const loading = document.getElementById('executions-loading');
        if (loading) {
            loading.style.display = 'none';
        }
    });
</script>

<style>
    /* Custom Scrollbar for this page */
    .custom-scrollbar::-webkit-scrollbar {
        width: 6px;
        height: 6px;
    }
    .custom-scrollbar::-webkit-scrollbar-track {
        background: transparent;
    }
    .custom-scrollbar::-webkit-scrollbar-thumb {
        background: rgba(65, 72, 104, 0.5);
        border-radius: 3px;
    }
    .custom-scrollbar::-webkit-scrollbar-thumb:hover {
        background: rgba(122, 162, 247, 0.5);
    }
</style>
{% endblock %}