<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Interactive Demo WebApp</title>
    <link rel="stylesheet" href="{{ url_for('static', filename='styles.css') }}">
</head>
<body>
    
    <div class="main-layout">
        <!-- Left Sidebar -->
        <div class="left-sidebar">
            <div class="logo-section">
                <a href="https://elsci.org">
                    <img src="https://raw.githubusercontent.com/pdfosborne/elsciRL-Wiki/refs/heads/main/Resources/images/elsciRL_octlogo_black_outline_transparent.png" alt="elsciRL-Logo">
                </a>
                        </div>

            <!-- Home Block -->
            <div class="sidebar-block">
                <div class="sidebar-block-header" onclick="toggleBlock(this)">
                    <span>Help</span>
                    <span class="toggle-icon">▼</span>
                    </div>
                <div class="sidebar-block-content">
                    <div id="interfaceGuideContent">
                        <div class="loading-message">
                            <p>Loading interface guide...</p>
                </div>
            </div>
                            </div>
                        </div>

            <!-- Applications Block -->
            <div class="sidebar-block">
                <div class="sidebar-block-header active" onclick="toggleBlock(this)">
                    <span>Applications</span>
                    <span class="toggle-icon">▼</span>
                        </div>
                <div class="sidebar-block-content active">
                    <div class="config-group">
                        <h3>Available Applications</h3>
                        <div class="button-group button-group-margin-bottom">
                            <button onclick="checkAllUpdates()">Check Updates</button>
                </div>
                        <div id="updateStatus" class="update-status"></div>
                        <div id="applicationsList">
                            <p>Loading applications...</p>
                        </div>
                    </div>
                    
                    <div class="config-group">
                        <h3>Download Applications</h3>
                        <div id="downloadableApps">
                            <p>Loading available applications...</p>
                </div>
            </div>
                                </div>
                                </div>
                    
            <!-- Experiment Block -->
            <div class="sidebar-block">
                <div class="sidebar-block-header" onclick="toggleBlock(this)">
                    <span>Experiment</span>
                    <span class="toggle-icon">▼</span>
                            </div>
                <div class="sidebar-block-content">
                    <div class="config-group">
                        <h3>Application Selection</h3>
                            <div class="select-container">
                            <label for="applicationSelect">Select Application:</label>
                            <select id="applicationSelect" onchange="loadApplicationData()">
                                <option value="">Loading applications...</option>
                                    </select>
                                </div>
                        <div id="applicationInfo" class="application-info">
                            <p><strong>Status:</strong> <span id="appStatus"></span></p>
                            <p><strong>Last Updated:</strong> <span id="appLastUpdated"></span></p>
                            <p><strong>Components:</strong> <span id="appComponents"></span></p>
                                </div>
                            </div>

                    <div class="config-group">
                        <h3>Configuration</h3>
                        
                        <!-- Local Config Selection -->
                        <div class="select-container">
                            <label for="localConfigSelect">Local Configuration:</label>
                            <select id="localConfigSelect" onchange="updateConfigSummary()">
                                <option value="">Select application first</option>
                            </select>
                        </div>
                        
                        <!-- Observed States Selection -->
                        <div class="select-container">
                            <label for="observedStateSelect">Observed States:</label>
                            <select id="observedStateSelect" onchange="updateConfigSummary()">
                                <option value="">Select application first</option>
                            </select>
                        </div>
                        
                        <!-- Analysis Plot Selection -->
                        <div class="select-container">
                            <label for="plotSelect">Analysis Plot:</label>
                            <select id="plotSelect" onchange="updateConfigSummary()">
                                <option value="">Select application first</option>
                            </select>
                        </div>
                        
                    </div>

                    <div class="config-group">
                        <h3>Training Parameters</h3>
                            <div class="training-params">
                            <label for="trainingEpisodes">Episodes:</label>
                            <input type="number" id="trainingEpisodes" value="1000" min="1">
                            </div>
                            <div class="training-params">
                            <label for="trainingRepeats">Repeats:</label>
                            <input type="number" id="trainingRepeats" value="5" min="1">
                            </div>
                            <div class="training-params">
                            <label for="testEpisodes">Test Episodes:</label>
                            <input type="number" id="testEpisodes" value="200" min="1">
                            </div>
                            <div class="training-params">
                            <label for="testRepeats">Test Repeats:</label>
                            <input type="number" id="testRepeats" value="10" min="1">
                        </div>
                    </div>

                    <div class="config-group">
                        <h3>Configuration Management</h3>
                        <div class="button-group">
                            <button onclick="exportConfig()">Export Config</button>
                            <button onclick="document.getElementById('importConfigFile').click()">Import Config</button>
                            <input type="file" id="importConfigFile" accept=".json" class="import-config-file" onchange="importConfig(this)">
                                    </div>
                                </div>
                                    </div>
                                </div>  

            <!-- Config Block -->
            <div class="sidebar-block">
                <div class="sidebar-block-header" onclick="toggleBlock(this)">
                    <span>Agent Config</span>
                    <span class="toggle-icon">▼</span>
                                    </div>
                <div class="sidebar-block-content">
                    <div class="config-group">
                        <h3>Agent Selection</h3>
                        <div id="agentSelection">
                            <div class="checkbox-container">
                                <input type="checkbox" id="agent_Qlearntab" value="Qlearntab" checked onchange="updateAgentConfig()">
                                <label for="agent_Qlearntab">Q-Learning</label>
                                </div>
                            <div class="checkbox-container">
                                <input type="checkbox" id="agent_DQN" value="DQN" onchange="updateAgentConfig()">
                                <label for="agent_DQN">Deep Q-Network</label>
                                    </div>
                            <div class="checkbox-container">
                                <input type="checkbox" id="agent_PPO" value="PPO" onchange="updateAgentConfig()">
                                <label for="agent_PPO">PPO</label>
                            </div>
                            <p class="agent-warning" id="ppoWarning" style="display:none;color:#c0392b;font-size:0.9em;margin:4px 0 0 0;">
                                PPO requires selecting instructions; use the Instructions tab and re-run after validation.
                            </p>
                            <div class="checkbox-container">
                                <input type="checkbox" id="agent_LLM_Ollama" value="LLM_Ollama" onchange="updateAgentConfig()">
                                <label for="agent_LLM_Ollama">LLM Ollama</label>
                                </div>
                                    </div>
                                    </div>

                    <div class="config-group">
                        <h3>Adapter Selection</h3>
                        <div id="adapterSelection">
                            <p>Select an application and at least one agent to see available adapters.</p>
                            </div>
                        </div>

                    <div id="agentConfigContainer">
                        <!-- Agent configuration forms will be dynamically loaded here -->
                            </div>
                        </div>
                        </div>
                    </div>

        <!-- Main Content Area -->
        <div class="main-content">
            <!-- Tab Navigation -->
            <div class="tab-navigation">
                <button class="tab-btn active" onclick="switchTab('applicationOverview', this)">Application Overview</button>
                <button class="tab-btn" onclick="switchTab('agentAdapters', this)">Adapter Preview</button>
                <button class="tab-btn" onclick="switchTab('instructions', this)">Instructions</button>
                <button class="tab-btn" onclick="switchTab('results', this)">Results</button>
                <button class="tab-btn" onclick="switchTab('policyRender', this)">Policy Render</button>
            </div>

            <!-- Application Overview Tab -->
            <div id="applicationOverview" class="tab-content active">
                <div class="tab-content-inner">
                    <h2>Application Overview</h2>
                    <div id="applicationOverviewContent">
                        <div class="loading-message">
                            <p>Loading application overview...</p>
                </div>
            </div>
                        </div>
                    </div>

            <!-- Agent/Adapters Tab -->
            <div id="agentAdapters" class="tab-content">
                <div class="tab-content-inner">
                    <h2>Adapter Preview (Language Adapters)</h2>
                    <p style="font-size: 0.95em; color: #666; margin-bottom: 20px;">
                        <strong>Click a language adapter</strong> to view its source code and see sample observed states. Use the <strong> Agent Config </strong> in the sidebar to match your adapter selection with an agent.
                    </p>
                    
                    <div class="adapter-preview-layout">
                        <!-- Adapters List -->
                        <div class="adapter-list-panel">
                            <h3>Available Adapters</h3>
                            <div id="adaptersList" class="adapters-grid">
                                <p style="text-align: center; color: #666; padding: 20px;">Select an application to see available adapters.</p>
                            </div>
                        </div>

                        <!-- Preview Panel -->
                        <div class="adapter-preview-panel">
                            <div id="adapterPreviewContent">
                                <div class="preview-placeholder">
                                    <div class="preview-placeholder-icon">📄</div>
                                    <h3>No Adapter Selected</h3>
                                    <p>Click on an adapter from the list to view its source code and sample data.</p>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Instructions Tab -->
            <div id="instructions" class="tab-content">
                <div class="tab-content-inner">
                    <h2>Instructions</h2>
                    <div class="input-console-container">
                        <div class="input-section">
                            
                            <h3>Enter Your Instructions</h3>
                            <textarea id="userInput" placeholder="Enter your task instructions here..."></textarea>
                            <div class="button-group">
                                <button id="processInputBtn" onclick="processInput()">Process Instructions</button>
                                <button id="retryBtn" onclick="newInstruction()" class="retry-btn-hidden">New Instruction</button>
                            </div>
                            
                            <!-- LLM Settings -->
                            <div class="config-group config-group-margin-top">
                                <h3>LLM Settings</h3>
                                <div id="ollamaStatusMessage" class="ollama-status-message" style="display: none;">
                                    <p style="color: #dc3545; font-weight: bold; margin: 10px 0; padding: 10px; background-color: #f8d7da; border: 1px solid #f5c6cb; border-radius: 4px;">
                                        ⚠️ Ollama is missing that is required to use LLM tools
                                    </p>
                                </div>
                                <div class="checkbox-container">
                                    <input type="checkbox" id="enableLLMPlanner">
                                    <label for="enableLLMPlanner">Enable LLM Instruction Planner</label>
                                </div>
                                <div class="input-group">
                                    <label for="llmModelSelect">LLM Model:</label>
                                    <div class="llm-model-container">
                                        <select id="llmModelSelect">
                                            <option value="">Loading models...</option>
                                        </select>
                                        <button type="button" onclick="refreshOllamaModels()" class="ollama-refresh-btn">Refresh</button>
                                    </div>
                                </div>
                                <div class="input-group">
                                    <label for="llmContextLength">Context Length:</label>
                                    <input type="number" id="llmContextLength" value="1000" min="100" max="4000">
                                </div>
                                <div class="input-group">
                                    <label for="llmNumInstructions">Number of Instructions:</label>
                                    <input type="number" id="llmNumInstructions" value="1" min="1" max="10">
                                </div>
                        </div>
                    </div>
                        
                        <div class="console-section">
                            <!-- Observed States Selection -->
                            <div class="config-group config-group-margin-bottom">
                                <div class="select-container">
                                    <label for="instructionsObservedStateSelect">Select Adapter:</label>
                                    <select id="instructionsObservedStateSelect" onchange="updateInstructionsObservedStates()">
                                        <option value="">Select an application first</option>
                                    </select>
                                </div>
                                <div id="instructionsObservedStatesInfo" class="instructions-observed-states-info">
                                    <!-- <p><strong>Selected States:</strong> <span id="instructionsObservedStatesSummary">None</span></p> -->
                                    <div id="instructionsObservedStatesPreview" class="instructions-observed-states-preview">
                                        <div class="preview-text">Preview of what the agent sees:</div>
                                        <pre id="instructionsObservedStatesContent" class="preview-content"></pre>
                                    </div>
                                </div>
                            </div>
                            <!---Instruction Match Plots-->
                            <h3>Results</h3>
                        <div id="consoleOutput"></div>
                            <div id="confirmationBlock" class="confirmation-block-hidden">
                            <p>Was the result correct?</p>
                                <div class="button-group">
                                <button id="correctBtn" onclick="confirmResult(true)">Correct</button>
                                <button id="incorrectBtn" onclick="confirmResult(false)">Incorrect</button>
                        </div>
                        <div id="confirmationResult"></div>
                    </div>
                </div>
                        
                        <div class="image-section">
                            <h3>Instruction Match Plots</h3>
                            <div id="instructionMatchPlots"></div>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Results Tab -->
            <div id="results" class="tab-content">
                <div class="tab-content-inner">
                    <h2>Results</h2>
                    <div id="resultsContent">
                        <div class="results-header">
                            <h3>Variance Analysis Results</h3>
                            <button onclick="loadVarianceResults()" class="refresh-results-btn">Refresh Results</button>
                        </div>
                        <div id="varianceResults">
                            <p>Click "Refresh Results" to load variance analysis results from the uploads directory.</p>
                        </div>
                    </div>
                </div>
            </div>

            <!-- Policy Render Tab -->
            <div id="policyRender" class="tab-content">
                <div class="tab-content-inner">
                    <h2>Policy Render</h2>
                    <div id="policyRenderContent">
                        <div class="results-header">
                            <h3>Policy Render Videos</h3>
                            <button onclick="loadPolicyRenders()" class="refresh-results-btn">Refresh Renders</button>
                        </div>
                        <div id="policyRenderResults">
                            <p>Click "Refresh Renders" to load policy render GIFs from the uploads directory.</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>

        <!-- Right Sidebar -->
        <div class="right-sidebar">
            <div class="right-sidebar-section">
                <h3>Train Model</h3>
                <p>Start training with or without instructions. Select agents and click to begin.</p>
                <button id="trainModelBtn" onclick="startTraining()" class="train-model-btn">
                    Train Model
                </button>
                <div id="trainingStatus" class="training-status">
                    <div class="loading-circle-left"></div>
                    <span>Training in progress...</span>
                </div>
                <hr class="sidebar-divider">
            </div>

            <div class="right-sidebar-section">
                <h3>Preset Instructions</h3>
                <p>Load preset instruction plans for the selected application.</p>
                <div class="input-group input-group-margin-bottom">
                    <label for="presetSelect" class="preset-label">Select preset:</label>
                    <select id="presetSelect" onchange="onPresetSelectChange()" class="preset-select">
                        <option value="">Choose a preset...</option>
                    </select>
                </div>
                <div id="presetDescription" class="preset-description"></div>
                <div class="button-group button-group-flex">
                    <button onclick="loadSelectedPreset()" id="loadPresetBtn" disabled class="load-preset-btn">Load</button>
                    <button onclick="clearPreset()" id="clearPresetBtn" class="clear-preset-btn">Clear</button>
                </div>
            </div>

            <div class="right-sidebar-section">
                <h3>Experiment Configuration</h3>
                <p>Select a preset experiment configuration for the chosen application.</p>
                <div class="input-group input-group-margin-bottom">
                    <label for="experimentConfigSelect" class="preset-label">Select configuration:</label>
                    <select id="experimentConfigSelect" onchange="onExperimentConfigSelectChange()" class="preset-select">
                        <option value="">Select application first</option>
                    </select>
                </div>
                <div id="experimentConfigDescription" class="preset-description"></div>
                <div class="button-group button-group-flex">
                    <button onclick="loadExperimentConfig()" id="loadExperimentConfigBtn" disabled class="load-preset-btn">Load</button>
                    <button onclick="resetExperimentConfig()" id="resetExperimentConfigBtn" class="clear-preset-btn">Reset</button>
                </div>
                <hr class="sidebar-divider">
            </div>

            <div class="right-sidebar-section">
                <h3>Status</h3>
                <div id="statusInfo">
                    <p><strong>Instructions:</strong> <span id="instructionCount">0</span></p>
                    <p><strong>Applications:</strong> <span id="appCount">0</span></p>
                    <p><strong>Last Update:</strong> <span id="lastUpdate">Never</span></p>
                    </div>
                </div>

            <div class="right-sidebar-section">
                <h3>Community</h3>
                <div class="social-links">
                    <a href="https://github.com/pdfosborne/elsciRL" target="_blank" rel="noopener noreferrer" class="social-link" title="GitHub">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M12 0c-6.626 0-12 5.373-12 12 0 5.302 3.438 9.8 8.207 11.387.599.111.793-.261.793-.577v-2.234c-3.338.726-4.033-1.416-4.033-1.416-.546-1.387-1.333-1.756-1.333-1.756-1.089-.745.083-.729.083-.729 1.205.084 1.839 1.237 1.839 1.237 1.07 1.834 2.807 1.304 3.492.997.107-.775.418-1.305.762-1.604-2.665-.305-5.467-1.334-5.467-5.931 0-1.311.469-2.381 1.236-3.221-.124-.303-.535-1.524.117-3.176 0 0 1.008-.322 3.301 1.23.957-.266 1.983-.399 3.003-.404 1.02.005 2.047.138 3.006.404 2.291-1.552 3.297-1.23 3.297-1.23.653 1.653.242 2.874.118 3.176.77.84 1.235 1.911 1.235 3.221 0 4.609-2.807 5.624-5.479 5.921.43.372.823 1.102.823 2.222v3.293c0 .319.192.694.801.576 4.765-1.589 8.199-6.086 8.199-11.386 0-6.627-5.373-12-12-12z"/>
                        </svg>
                    </a>
                    <a href="https://www.youtube.com/@DrPhilipOsborne" target="_blank" rel="noopener noreferrer" class="social-link" title="YouTube">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M19.615 3.184c-3.604-.246-11.631-.245-15.23 0-3.897.266-4.356 2.62-4.385 8.816.029 6.185.484 8.549 4.385 8.816 3.6.245 11.626.246 15.23 0 3.897-.266 4.356-2.62 4.385-8.816-.029-6.185-.484-8.549-4.385-8.816zm-10.615 12.816v-8l8 3.993-8 4.007z"/>
                        </svg>
                    </a>
                    <a href="https://discord.gg/GgaqcrYCxt" target="_blank" rel="noopener noreferrer" class="social-link" title="Discord">
                        <svg xmlns="http://www.w3.org/2000/svg" width="24" height="24" viewBox="0 0 24 24" fill="currentColor">
                            <path d="M20.317 4.492c-1.53-.69-3.17-1.2-4.885-1.49a.075.075 0 0 0-.079.036c-.21.369-.444.85-.608 1.23a18.566 18.566 0 0 0-5.487 0 12.36 12.36 0 0 0-.617-1.23A.077.077 0 0 0 8.562 3c-1.714.29-3.354.8-4.885 1.491a.07.07 0 0 0-.032.027C.533 9.093-.32 13.555.099 17.961a.08.08 0 0 0 .031.055 20.03 20.03 0 0 0 5.993 2.98.078.078 0 0 0 .084-.026 13.83 13.83 0 0 0 1.226-1.963.074.074 0 0 0-.041-.104 13.201 13.201 0 0 1-1.872-.878.075.075 0 0 1-.008-.125c.126-.093.252-.19.372-.287a.075.075 0 0 1 .078-.01c3.927 1.764 8.18 1.764 12.061 0a.075.075 0 0 1 .079.009c.12.098.245.195.372.288a.075.075 0 0 1-.006.125c-.598.344-1.22.635-1.873.877a.075.075 0 0 0-.041.105c.36.687.772 1.341 1.225 1.962a.077.077 0 0 0 .084.028 19.963 19.963 0 0 0 6.002-2.981.076.076 0 0 0 .032-.054c.5-5.094-.838-9.52-3.549-13.442a.06.06 0 0 0-.031-.028zM8.02 15.278c-1.182 0-2.157-1.069-2.157-2.38 0-1.312.956-2.38 2.157-2.38 1.21 0 2.176 1.077 2.157 2.38 0 1.312-.956 2.38-2.157 2.38zm7.975 0c-1.183 0-2.157-1.069-2.157-2.38 0-1.312.955-2.38 2.157-2.38 1.21 0 2.176 1.077 2.157 2.38 0 1.312-.946 2.38-2.157 2.38z"/>
                        </svg>
                    </a>
                </div>
            </div>
        </div>
    </div>

    <script>
        // Global variables
        let instructionPresetActive = false;
        let currentJobId = null;
        let agentDefinitions = {};
        let availableAdapters = [];
        let connections = {}; // { agentId: [adapter1, adapter2, ...] }
        let selectedAgent = null;
        let canvas = null;
        let ctx = null;
        
        // Agent metadata with descriptions
        const agentMetadata = {
            'Qlearntab': {
                name: 'Q-Learning',
                fullName: 'Q-Learning (Tabular)',
                description: 'Classic tabular Q-learning algorithm. Best for discrete state spaces with moderate size.',
                icon: '📊',
                type: 'Value-Based'
            },
            'DQN': {
                name: 'Deep Q-Network',
                fullName: 'Deep Q-Network (DQN)',
                description: 'Neural network-based Q-learning. Suitable for large or continuous state spaces.',
                icon: '🧠',
                type: 'Deep RL'
            },
            'LLM_Ollama': {
                name: 'LLM Agent',
                fullName: 'LLM Ollama Agent',
                description: 'Language model-based agent. Uses natural language understanding for decision making.',
                icon: '💬',
                type: 'Language Model'
            }
        };

        // Initialize the application
        document.addEventListener('DOMContentLoaded', function() {
            loadApplications();
            loadAllApplicationsInfo();
            loadAllOptions();
            loadOllamaModels();
            loadAgentDefinitions();
            updateAdapterSelection(); // Initialize adapter selection with first option selected
            initializeAdapterPreview(); // Initialize Agent/Adapters tab
            loadInterfaceGuide(); // Load the interface guide
            loadApplicationOverview(); // Load the application overview
            updateStatus();
        });

        // Toggle sidebar blocks
        function toggleBlock(header) {
            const content = header.nextElementSibling;
            const isActive = content.classList.contains('active');
            
            // Close all other blocks
            document.querySelectorAll('.sidebar-block-content').forEach(block => {
                block.classList.remove('active');
            });
            document.querySelectorAll('.sidebar-block-header').forEach(h => {
                h.classList.remove('active');
            });
            
            // Toggle current block
            if (!isActive) {
                content.classList.add('active');
                header.classList.add('active');
            }
        }

        // Switch tabs
        function switchTab(tabId, eventElement = null) {
            // Remove active class from all tabs and tab buttons
            document.querySelectorAll('.tab-content').forEach(tab => {
                tab.classList.remove('active');
            });
            document.querySelectorAll('.tab-btn').forEach(btn => {
                btn.classList.remove('active');
            });
            
            // Add active class to selected tab and button
            document.getElementById(tabId).classList.add('active');
            if (eventElement) {
                eventElement.classList.add('active');
            } else {
                // Find the corresponding tab button and activate it
                const tabButtons = document.querySelectorAll('.tab-btn');
                tabButtons.forEach(btn => {
                    if (btn.getAttribute('onclick') && btn.getAttribute('onclick').includes(tabId)) {
                        btn.classList.add('active');
                    }
                });
            }
            
            // If switching to Adapter Preview tab, open the Agent Config sidebar
            if (tabId === 'agentAdapters') {
                // Find the Agent Config sidebar block header
                const sidebarHeaders = document.querySelectorAll('.sidebar-block-header');
                sidebarHeaders.forEach(header => {
                    const headerText = header.querySelector('span');
                    if (headerText && headerText.textContent === 'Agent Config') {
                        const content = header.nextElementSibling;
                        
                        // Close all other blocks first
                        document.querySelectorAll('.sidebar-block-content').forEach(block => {
                            block.classList.remove('active');
                        });
                        document.querySelectorAll('.sidebar-block-header').forEach(h => {
                            h.classList.remove('active');
                        });
                        
                        // Open Agent Config block
                        content.classList.add('active');
                        header.classList.add('active');
                    }
                });
            }
        }

        // Toggle main content sections (legacy function - keeping for compatibility)
        function toggleMainSection(sectionId) {
            document.querySelectorAll('.main-content-section').forEach(section => {
                section.classList.remove('active');
            });
            document.getElementById(sectionId).classList.add('active');
        }

        // Load applications
        async function loadApplications() {
            try {
                const response = await fetch('/get_applications');
                const data = await response.json();
                
                const select = document.getElementById('applicationSelect');
                select.innerHTML = '<option value="">Select an application...</option>';
                    
                    data.applications.forEach(app => {
                        const option = document.createElement('option');
                        option.value = app;
                        option.textContent = app;
                        select.appendChild(option);
                    });
                    
                document.getElementById('appCount').textContent = data.applications.length;
            } catch (error) {
                console.error('Error loading applications:', error);
            }
        }

        // Load all applications info for management
        async function loadAllApplicationsInfo() {
            try {
                const response = await fetch('/get_all_applications_info');
                const data = await response.json();
                
                // Update downloaded applications list
                const applicationsList = document.getElementById('applicationsList');
                applicationsList.innerHTML = '';
                
                if (data.applications && data.applications.length > 0) {
                    data.applications.forEach(app => {
                        if (app.is_downloaded) {
                            const appDiv = document.createElement('div');
                            appDiv.className = 'application-item';
                            // Create GitHub link if repository info is available
                            const githubLink = app.github_user && app.repository ? 
                                `<a href="https://github.com/${app.github_user}/${app.repository}" target="_blank" class="github-link">🔗 GitHub</a>` : '';
                            
                            appDiv.innerHTML = `
                                <div class="app-flex">
                                    <strong>${app.name}</strong>
                                    <div class="app-name">
                                        ${app.has_updates ? '🔄 Updates available' : '✅ Up to date'}
                                        ${app.last_updated ? ` • Last updated: ${formatTimestamp(app.last_updated)}` : ''}
                                        ${githubLink}
                                    </div>
                                </div>
                                ${app.has_updates ? `<button onclick="downloadApplication('${app.name}', true)" class="update-btn">Update</button>` : ''}
                            `;
                            applicationsList.appendChild(appDiv);
                        }
                    });
                } else {
                    applicationsList.innerHTML = '<p>No applications downloaded yet.</p>';
                }

                // Update downloadable applications list
                const downloadableApps = document.getElementById('downloadableApps');
                downloadableApps.innerHTML = '';
                
                if (data.applications && data.applications.length > 0) {
                    data.applications.forEach(app => {
                        if (!app.is_downloaded) {
                            const appDiv = document.createElement('div');
                            appDiv.className = 'application-item';
                            
                            // Create GitHub link if repository info is available
                            const githubLink = app.github_user && app.repository ? 
                                `<a href="https://github.com/${app.github_user}/${app.repository}" target="_blank" class="github-link">🔗 GitHub</a>` : '';
                            
                            appDiv.innerHTML = `
                                <div class="app-flex">
                                    <strong>${app.name}</strong>
                                    <div class="app-name">
                                        ${app.adapters_count} adapters • ${app.configs_count} configs • ${app.experiment_configs_count} experiments
                                        ${githubLink}
                                    </div>
                                </div>
                                <button onclick="downloadApplication('${app.name}', false)" class="download-btn-small">
                                    Download
                                </button>
                            `;
                            downloadableApps.appendChild(appDiv);
                        }
                    });
                } else {
                    downloadableApps.innerHTML = '<p>No applications available for download.</p>';
                }

            } catch (error) {
                console.error('Error loading all applications info:', error);
                document.getElementById('applicationsList').innerHTML = '<p>Error loading applications.</p>';
                document.getElementById('downloadableApps').innerHTML = '<p>Error loading applications.</p>';
            }
        }

        // Download application
        async function downloadApplication(appName, forceUpdate = false) {
            try {
                // Show loading overlay
                showLoadingOverlay(`Downloading ${appName}...`);
                
                const response = await fetch('/download_application', {
                                method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                                body: JSON.stringify({
                        application_name: appName, 
                        force_update: forceUpdate 
                    })
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    // Update loading message
                    const overlay = document.getElementById('loadingOverlay');
                    if (overlay) {
                        const messageElement = overlay.querySelector('.loading-message');
                        if (messageElement) {
                            messageElement.textContent = `Successfully ${forceUpdate ? 'updated' : 'downloaded'} ${appName}! Refreshing data...`;
                        }
                    }
                    
                    // Refresh application data in backend first
                    await refreshApplicationData();
                    // Then refresh the frontend displays
                    loadAllApplicationsInfo(); // Refresh the lists
                    loadApplications(); // Refresh the dropdown
                    loadApplicationOverview(); // Refresh the application overview tab
                    
                    // Hide loading overlay after a brief delay to show success message
                    setTimeout(() => {
                        hideLoadingOverlay();
                        alert(`Successfully ${forceUpdate ? 'updated' : 'downloaded'} ${appName}!`);
                    }, 1000);
                    
                } else if (data.status === 'needs_confirmation') {
                    // Hide loading overlay for confirmation dialog
                    hideLoadingOverlay();
                    
                    if (confirm(`${data.message}\n\nDo you want to proceed with the update?`)) {
                        // User confirmed, try again with force update
                        downloadApplication(appName, true);
                    }
                } else {
                    // Hide loading overlay and show error
                    hideLoadingOverlay();
                    alert(`Error: ${data.message}`);
                }
            } catch (error) {
                console.error('Error downloading application:', error);
                // Hide loading overlay and show error
                hideLoadingOverlay();
                alert('An error occurred while downloading the application.');
            }
        }

        // Load application data
        async function loadApplicationData() {
            const selectedApp = document.getElementById('applicationSelect').value;
            if (!selectedApp) return;

            try {
                // First refresh application data to ensure we have the latest cached data
                await refreshApplicationData();
                // Load configs, observed states, plots, adapters, and experiment configs
                const [configsRes, statesRes, plotsRes, adaptersRes, experimentConfigsRes] = await Promise.all([
                    fetch('/get_local_configs', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: selectedApp })
                    }),
                    fetch('/get_observed_states', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ applications: [selectedApp] })
                    }),
                    fetch('/get_plot_options', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: selectedApp })
                    }),
                    fetch('/get_adapters', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: selectedApp })
                    }),
                    fetch('/get_all_options', {
                        method: 'GET'
                    })
                ]);

                const [configsData, statesData, plotsData, adaptersData, allOptionsData] = await Promise.all([
                    configsRes.json(),
                    statesRes.json(),
                    plotsRes.json(),
                    adaptersRes.json(),
                    experimentConfigsRes.json()
                ]);

                // Load configuration options as dropdowns
                loadConfigurationDropdowns(selectedApp, configsData, statesData, plotsData, allOptionsData);
                
                // Load observed states for instructions tab
                loadInstructionsObservedStates(selectedApp, statesData);
                
                // Update adapters
                availableAdapters = adaptersData.adapters || [];
                updateAdapterSelection();
                updateAdaptersPreviewList(); // Update Agent/Adapters tab with new adapters

                // Update selection in application overview
                updateApplicationOverviewSelection(selectedApp);

                // Load preset instructions for this application
                loadPresetInstructions();

                // Clear experiment configuration description
                const experimentConfigDescription = document.getElementById('experimentConfigDescription');
                if (experimentConfigDescription) {
                    experimentConfigDescription.textContent = '';
                }

            } catch (error) {
                console.error('Error loading application data:', error);
            }
        }

        // Update application overview selection to match dropdown selection
        function updateApplicationOverviewSelection(selectedApp) {
            // Remove previous selection from both old and new card types
            document.querySelectorAll('.app-card, .app-card-compact').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Find and select the corresponding card
            const appCards = document.querySelectorAll('.app-card, .app-card-compact');
            appCards.forEach(card => {
                const appName = card.querySelector('h4').textContent;
                if (appName === selectedApp) {
                    card.classList.add('selected');
                }
            });
            
            // Show configuration section and load options
            const configSection = document.getElementById('applicationConfigSection');
            if (configSection) {
                configSection.style.display = 'block';
                loadOverviewConfigurationOptions(selectedApp);
            }
        }

        // Update select dropdown
        function updateSelect(selectId, options) {
            const select = document.getElementById(selectId);
            select.innerHTML = '<option value="">Select an option...</option>';
            options.forEach(option => {
                const optionElement = document.createElement('option');
                optionElement.value = option;
                optionElement.textContent = option;
                select.appendChild(optionElement);
            });
            
            // Auto-select the first option if options are available
            if (options.length > 0) {
                select.selectedIndex = 1; // Index 1 because index 0 is the placeholder
                
                // Trigger change event for dropdowns that have onchange handlers
                if (selectId === 'localConfigSelect') {
                    loadConfigData();
                }
            }
        }

        // Load all options
        async function loadAllOptions() {
            try {
                const response = await fetch('/get_all_options');
                const data = await response.json();
                console.log('All options loaded:', data);
            } catch (error) {
                console.error('Error loading all options:', error);
            }
        }

        // Process input
        async function processInput() {
            const userInput = document.getElementById('userInput').value;
            if (!userInput.trim()) {
                alert('Please enter some instructions.');
                return;
            }

            const selectedApp = document.getElementById('applicationSelect').value;
            if (!selectedApp) {
                alert('Please select an application first.');
                return;
            }

            const submitBtn = document.getElementById('processInputBtn');
            const retryBtn = document.getElementById('retryBtn');
            
            submitBtn.disabled = true;
            submitBtn.innerHTML = 'Processing... <div class="loading-circle"></div>';

            try {
                const formData = {
                    userInput: userInput,
                    selectedApps: [selectedApp],
                    localConfigInput: document.getElementById('localConfigSelect').value,
                    observedStateInput: document.getElementById('observedStateSelect').value,
                    enableLLMPlanner: document.getElementById('enableLLMPlanner').checked,
                    llmModelSelect: document.getElementById('llmModelSelect').value,
                    LLMContextLength: document.getElementById('llmContextLength').value,
                    llmNumInstructions: document.getElementById('llmNumInstructions').value
                };

                const response = await fetch('/process_input', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });

                const data = await response.json();
                
                if (data.error) {
                    alert('Error: ' + data.error);
                    return;
                }

                // Update console output
                document.getElementById('consoleOutput').innerHTML = data.console_output;
                
                // Update match plots
                const plotsContainer = document.getElementById('instructionMatchPlots');
                plotsContainer.innerHTML = '';
                if (data.matchPlots && data.matchPlots.length > 0) {
                    data.matchPlots.forEach(plotPath => {
                        const img = document.createElement('img');
                        img.src = '/' + plotPath;
                        img.style.maxWidth = '100%';
                        img.style.margin = '10px';
                        plotsContainer.appendChild(img);
                    });
                }

                // Show confirmation block
                document.getElementById('confirmationBlock').classList.remove('confirmation-block-hidden');
                
                // Update buttons
                submitBtn.style.display = 'none';
                retryBtn.classList.remove('retry-btn-hidden');

            } catch (error) {
                console.error('Error processing input:', error);
                alert('An error occurred while processing your input.');
            } finally {
                submitBtn.disabled = false;
                submitBtn.innerHTML = 'Process Instructions';
            }
        }

        // Confirm result
        async function confirmResult(isCorrect) {
            const userInput = document.getElementById('userInput').value;
            const selectedApp = document.getElementById('applicationSelect').value;
            const enableLLMPlanner = document.getElementById('enableLLMPlanner').checked;

            try {
                const response = await fetch('/confirm_result', {
                method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        userInput: userInput,
                        selectedApps: [selectedApp],
                        isCorrect: isCorrect,
                        enableLLMPlanner: enableLLMPlanner,
                        isLLMValidation: false
                    })
                });

                const data = await response.json();
                document.getElementById('confirmationResult').innerHTML = data.message;
                
                // Update instruction count
                updateStatus();

            } catch (error) {
                console.error('Error confirming result:', error);
                alert('An error occurred while confirming the result.');
            }
        }

        // New instruction
        function newInstruction() {
            document.getElementById('userInput').value = '';
            document.getElementById('consoleOutput').innerHTML = '';
            document.getElementById('instructionMatchPlots').innerHTML = '';
            document.getElementById('confirmationResult').innerHTML = '';
            document.getElementById('confirmationBlock').classList.add('confirmation-block-hidden');
            document.getElementById('processInputBtn').style.display = 'inline-block';
            document.getElementById('retryBtn').classList.add('retry-btn-hidden');

            fetch('/new_instruction', {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ instruction: document.getElementById('userInput').value })
            })
            .then(response => response.json())
            .then(data => {
                console.log('New instruction processed:', data);
            })
            .catch(error => console.error('Error processing new instruction:', error));
        }

        // Start training
        async function startTraining() {
            const selectedApp = document.getElementById('applicationSelect').value;
            if (!selectedApp) {
                alert('Please select an application first.');
                return;
            }
            
            // Check if at least one agent is selected
            const selectedAgents = Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked')).map(cb => cb.value);
            if (selectedAgents.length === 0) {
                alert('Please select at least one agent to train.');
                return;
            }
            
            const trainBtn = document.getElementById('trainModelBtn');
            const trainingStatus = document.getElementById('trainingStatus');
            
            trainBtn.disabled = true;
            trainingStatus.classList.remove('training-status');

            try {
                const formData = {
                selectedApps: [selectedApp],
                    localConfigInput: document.getElementById('localConfigSelect').value,
                    observedStateInput: document.getElementById('observedStateSelect').value,
                    selectedPlot: document.getElementById('plotSelect').value,
                    trainingEpisodes: parseInt(document.getElementById('trainingEpisodes').value),
                    trainingRepeats: parseInt(document.getElementById('trainingRepeats').value),
                    testEpisodes: parseInt(document.getElementById('testEpisodes').value),
                    testRepeats: parseInt(document.getElementById('testRepeats').value),
                    selectedAgents: Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked')).map(cb => cb.value),
                    agent_adapter_dict: getAgentAdapterDict()
                };
                
                console.log('Form data being sent:', formData);

                // Add agent parameters
                const selectedAgents = Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked')).map(cb => cb.value);
                selectedAgents.forEach(agentId => {
                    if (agentDefinitions[agentId]) {
                        Object.keys(agentDefinitions[agentId].params).forEach(paramKey => {
                            const fieldId = `${agentId}_${paramKey}`;
                            const field = document.getElementById(fieldId);
                            if (field) {
                                if (field.type === 'checkbox') {
                                    formData[fieldId] = field.checked;
                                } else if (field.type === 'range') {
                                    // Handle slider values - convert step index back to actual value
                                    const steps = generateSliderSteps();
                                    const stepIndex = parseInt(field.value);
                                    formData[fieldId] = steps[stepIndex];
                                } else {
                                    formData[fieldId] = field.value;
                                }
                            }
                        });
                    }
                });

                const response = await fetch('/train_model', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(formData)
                });

                console.log('Training response status:', response.status);
                console.log('Training response headers:', response.headers);
                
                if (!response.ok) {
                    throw new Error(`HTTP error! status: ${response.status}`);
                }

                const data = await response.json();
                console.log('Training response data:', data);
                
                if (data.job_id) {
                currentJobId = data.job_id;
                    switchTab('results');
                    
                    // Check if there are validated instructions
                    let hasInstructions = false;
                    try {
                        const instructionsResponse = await fetch('/get_correct_instructions');
                        const instructionsData = await instructionsResponse.json();
                        hasInstructions = instructionsData.correctInstructions && instructionsData.correctInstructions.length > 0;
                    } catch (error) {
                        console.log('Could not check instruction status:', error);
                        hasInstructions = false;
                    }
                    
                    // Show training started message
                    const resultsContainer = document.getElementById('varianceResults');
                    resultsContainer.innerHTML = `
                        <div class="loading-message">
                            <p><strong>Training started!</strong></p>
                            <p>Job ID: ${data.job_id}</p>
                            <p><strong>Agents:</strong> ${selectedAgents.join(', ')}</p>
                            <p><strong>Mode:</strong> ${hasInstructions ? 'Instruction-guided + Standard RL' : 'Standard RL only'}</p>
                            <p>Training is running in the background. Results will be automatically refreshed when training completes.</p>
                        </div>
                    `;
                    
                    // Start monitoring the job for completion
                    monitorJobCompletion(data.job_id);
                } else {
                    alert('Error starting training: ' + (data.error || 'Unknown error'));
                }

            } catch (error) {
                console.error('Error starting training:', error);
                console.error('Error details:', error.message);
                console.error('Error stack:', error.stack);
                alert(`An error occurred while starting training: ${error.message}`);
            } finally {
                trainBtn.disabled = false;
                trainingStatus.classList.add('training-status');
            }
        }

        // Monitor job completion and refresh results when done
        async function monitorJobCompletion(jobId) {
            const checkInterval = 2000; // Check every 2 seconds
            const maxChecks = 300; // Maximum 10 minutes of checking
            let checkCount = 0;
            
            const checkJobStatus = async () => {
                try {
                    const response = await fetch(`/get_job_status/${jobId}`);
                    const data = await response.json();
                    
                    if (data.status === 'completed') {
                        console.log('Training completed! Refreshing results...');
                        // Refresh the results
                        await loadVarianceResults();
                        return; // Stop monitoring
                    } else if (data.status === 'failed') {
                        console.log('Training failed!');
                        const resultsContainer = document.getElementById('varianceResults');
                        resultsContainer.innerHTML = `
                            <div class="error-message">
                                <p><strong>Training failed!</strong></p>
                                <p>Job ID: ${jobId}</p>
                                <p>Please check the console for error details and try again.</p>
                            </div>
                        `;
                        return; // Stop monitoring
                    }
                    
                    checkCount++;
                    if (checkCount < maxChecks) {
                        setTimeout(checkJobStatus, checkInterval);
                    } else {
                        console.log('Job monitoring timeout reached');
                        const resultsContainer = document.getElementById('varianceResults');
                        resultsContainer.innerHTML = `
                            <div class="loading-message">
                                <p><strong>Training in progress...</strong></p>
                                <p>Job ID: ${jobId}</p>
                                <p>Monitoring timeout reached. Click "Refresh Results" to check for completed results.</p>
                            </div>
                        `;
                    }
                } catch (error) {
                    console.error('Error checking job status:', error);
                    checkCount++;
                    if (checkCount < maxChecks) {
                        setTimeout(checkJobStatus, checkInterval);
                    }
                }
            };
            
            // Start monitoring
            setTimeout(checkJobStatus, checkInterval);
        }

        // Reset all instructions
        async function resetAllInstructions() {
            if (!confirm("Are you sure you want to reset all instructions and their validation states? This action cannot be undone.")) {
                return;
            }
            
            try {
                const response = await fetch('/reset_all_instructions', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                if (data.status === 'success') {
                    newInstruction();
                    alert(data.message);
                    updateStatus();
                } else {
                    alert("Failed to reset instructions: " + (data.message || 'Unknown error'));
                }
            } catch (error) {
                console.error('Error resetting instructions:', error);
                alert('An error occurred while trying to reset instructions.');
            }
        }

        // Load data
        async function loadData() {
            try {
                const response = await fetch('/load_data', {
                method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                if (data.status === 'success') {
                    loadApplications();
                    loadAllOptions();
                    updateStatus();
                    alert('Data reloaded successfully.');
                }
            } catch (error) {
                console.error('Error loading data:', error);
                alert('An error occurred while loading data.');
            }
        }

        // Update status
        function updateStatus() {
            document.getElementById('lastUpdate').textContent = new Date().toLocaleString();
        }

        // Export config
        async function exportConfig() {
            const config = {
                application: document.getElementById('applicationSelect').value,
                localConfig: document.getElementById('localConfigSelect').value,
                observedState: document.getElementById('observedStateSelect').value,
                plot: document.getElementById('plotSelect').value,
                trainingEpisodes: document.getElementById('trainingEpisodes').value,
                trainingRepeats: document.getElementById('trainingRepeats').value,
                testEpisodes: document.getElementById('testEpisodes').value,
                testRepeats: document.getElementById('testRepeats').value,
                selectedAgents: Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked')).map(cb => cb.value),
                llmSettings: {
                    enabled: document.getElementById('enableLLMPlanner').checked,
                    model: document.getElementById('llmModelSelect').value,
                    contextLength: document.getElementById('llmContextLength').value,
                    numInstructions: document.getElementById('llmNumInstructions').value
                }
            };

            try {
                const response = await fetch('/export_config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify(config)
                });

                const data = await response.json();
                if (data.status === 'success') {
                    alert('Configuration exported successfully!');
                    } else {
                    alert('Error exporting configuration: ' + data.message);
                }
            } catch (error) {
                console.error('Error exporting config:', error);
                alert('An error occurred while exporting configuration.');
            }
        }

        // Import config
        async function importConfig(input) {
            const file = input.files[0];
            if (!file) return;

            try {
            const formData = new FormData();
                formData.append('file', file);

                const response = await fetch('/import_config', {
                    method: 'POST',
                    body: formData
                });

                const data = await response.json();
                if (data.status === 'success') {
                    // Apply the imported configuration
                    const config = data.config;
                    if (config.application) document.getElementById('applicationSelect').value = config.application;
                    if (config.localConfig) document.getElementById('localConfigSelect').value = config.localConfig;
                    if (config.observedState) document.getElementById('observedStateSelect').value = config.observedState;
                    if (config.plot) document.getElementById('plotSelect').value = config.plot;
                    if (config.trainingEpisodes) document.getElementById('trainingEpisodes').value = config.trainingEpisodes;
                    if (config.trainingRepeats) document.getElementById('trainingRepeats').value = config.trainingRepeats;
                    if (config.testEpisodes) document.getElementById('testEpisodes').value = config.testEpisodes;
                    if (config.testRepeats) document.getElementById('testRepeats').value = config.testRepeats;
                    
                    // Update agent checkboxes
                    document.querySelectorAll('#agentSelection input[type="checkbox"]').forEach(cb => {
                        cb.checked = config.selectedAgents && config.selectedAgents.includes(cb.value);
                    });
                    
                    // Update LLM settings
                    if (config.llmSettings) {
                        document.getElementById('enableLLMPlanner').checked = config.llmSettings.enabled || false;
                        if (config.llmSettings.model) document.getElementById('llmModelSelect').value = config.llmSettings.model;
                        if (config.llmSettings.contextLength) document.getElementById('llmContextLength').value = config.llmSettings.contextLength;
                        if (config.llmSettings.numInstructions) document.getElementById('llmNumInstructions').value = config.llmSettings.numInstructions;
                    }
                    
                    alert('Configuration imported successfully!');
                } else {
                    alert('Error importing configuration: ' + data.message);
                }
            } catch (error) {
                console.error('Error importing config:', error);
                alert('An error occurred while importing configuration.');
            }

            // Reset file input
            input.value = '';
        }

        // Load available Ollama models
        async function loadOllamaModels() {
            try {
                const response = await fetch('/get_ollama_models');
                const data = await response.json();
                
                const selectElement = document.getElementById('llmModelSelect');
                const statusMessage = document.getElementById('ollamaStatusMessage');
                const enableLLMCheckbox = document.getElementById('enableLLMPlanner');
                const contextLengthInput = document.getElementById('llmContextLength');
                const numInstructionsInput = document.getElementById('llmNumInstructions');
                const refreshButton = document.querySelector('.ollama-refresh-btn');
                
                if (!selectElement) return;
                
                // Clear existing options
                selectElement.innerHTML = '';
                
                // Check if Ollama is available
                if (data.status === 'success' && data.models.length > 0) {
                    // Ollama is available - enable all LLM settings
                    if (statusMessage) statusMessage.style.display = 'none';
                    
                    // Enable all LLM controls
                    if (enableLLMCheckbox) enableLLMCheckbox.disabled = false;
                    if (contextLengthInput) contextLengthInput.disabled = false;
                    if (numInstructionsInput) numInstructionsInput.disabled = false;
                    if (refreshButton) refreshButton.disabled = false;
                    
                    // Add models to select
                    data.models.forEach(model => {
                        const option = document.createElement('option');
                        option.value = model.name;
                        option.textContent = model.display_name;
                        selectElement.appendChild(option);
                    });
                    
                    // Set default selection if none exists
                    if (!selectElement.value && data.models.length > 0) {
                        selectElement.value = data.models[0].name;
                    }
                } else {
                    // Ollama is not available - disable all LLM settings
                    if (statusMessage) statusMessage.style.display = 'block';
                    
                    // Disable all LLM controls
                    if (enableLLMCheckbox) {
                        enableLLMCheckbox.disabled = true;
                        enableLLMCheckbox.checked = false;
                    }
                    if (contextLengthInput) contextLengthInput.disabled = true;
                    if (numInstructionsInput) numInstructionsInput.disabled = true;
                    if (refreshButton) refreshButton.disabled = true;
                    
                    // Show error message in select
                    const option = document.createElement('option');
                    option.value = '';
                    option.textContent = 'Ollama not available';
                    option.disabled = true;
                    selectElement.appendChild(option);
                }
            } catch (error) {
                console.error('Error loading Ollama models:', error);
                
                // On error, assume Ollama is not available
                const selectElement = document.getElementById('llmModelSelect');
                const statusMessage = document.getElementById('ollamaStatusMessage');
                const enableLLMCheckbox = document.getElementById('enableLLMPlanner');
                const contextLengthInput = document.getElementById('llmContextLength');
                const numInstructionsInput = document.getElementById('llmNumInstructions');
                const refreshButton = document.querySelector('.ollama-refresh-btn');
                
                if (statusMessage) statusMessage.style.display = 'block';
                
                // Disable all LLM controls
                if (enableLLMCheckbox) {
                    enableLLMCheckbox.disabled = true;
                    enableLLMCheckbox.checked = false;
                }
                if (contextLengthInput) contextLengthInput.disabled = true;
                if (numInstructionsInput) numInstructionsInput.disabled = true;
                if (refreshButton) refreshButton.disabled = true;
                
                if (selectElement) {
                    selectElement.innerHTML = '<option value="" disabled>Error loading models</option>';
                }
            }
        }

        // Refresh Ollama models
        async function refreshOllamaModels() {
            const selectElement = document.getElementById('llmModelSelect');
            const refreshButton = document.querySelector('.ollama-refresh-btn');
            const statusMessage = document.getElementById('ollamaStatusMessage');
            
            if (selectElement) {
                selectElement.innerHTML = '<option value="">Loading models...</option>';
            }
            
            if (refreshButton) {
                refreshButton.disabled = true;
                refreshButton.textContent = 'Loading...';
            }
            
            // Hide status message while loading
            if (statusMessage) {
                statusMessage.style.display = 'none';
            }
            
            try {
                await loadOllamaModels();
            } finally {
                // Note: loadOllamaModels will handle enabling/disabling the refresh button
                // based on Ollama availability, so we don't need to re-enable it here
            }
        }

        // Refresh application data in backend
        async function refreshApplicationData() {
            try {
                console.log('Refreshing application data...');
                const response = await fetch('/refresh_application_data', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                
                if (data.status === 'success') {
                    console.log('Application data refreshed successfully');
                    return true;
                } else {
                    console.error('Error refreshing application data:', data.message);
                    return false;
                }
            } catch (error) {
                console.error('Error refreshing application data:', error);
                return false;
            }
        }

        // Refresh applications
        async function refreshApplications() {
            try {
                const response = await fetch('/refresh_application_data', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                if (data.status === 'success') {
                    loadApplications();
                    loadAllApplicationsInfo();
                    loadApplicationOverview(); // Refresh the application overview tab
                    alert('Applications refreshed successfully!');
                } else {
                    alert('Error refreshing applications: ' + data.message);
                }
            } catch (error) {
                console.error('Error refreshing applications:', error);
                alert('An error occurred while refreshing applications.');
            }
        }

        // Check all updates
        async function checkAllUpdates() {
            try {
                // Show loading overlay
                showLoadingOverlay('Checking for updates...');
                
                const response = await fetch('/check_all_application_updates', {
                method: 'POST',
                    headers: { 'Content-Type': 'application/json' }
                });
                
                const data = await response.json();
                const updateStatus = document.getElementById('updateStatus');
                
                // Update loading message
                const overlay = document.getElementById('loadingOverlay');
                if (overlay) {
                    const messageElement = overlay.querySelector('.loading-message');
                    if (messageElement) {
                        messageElement.textContent = 'Refreshing application data...';
                    }
                }
                
                // Refresh the applications info to show updated status
                await loadAllApplicationsInfo();
                loadApplicationOverview(); // Refresh the application overview tab
                
                // Hide loading overlay and show results
                hideLoadingOverlay();
                
                if (data.has_any_updates) {
                    updateStatus.innerHTML = '<p style="color: orange;">Updates available for some applications.</p>';
                    updateStatus.style.display = 'block';
                } else {
                    updateStatus.innerHTML = '<p style="color: green;">All applications are up to date.</p>';
                    updateStatus.style.display = 'block';
                }
            } catch (error) {
                console.error('Error checking updates:', error);
                // Hide loading overlay and show error
                hideLoadingOverlay();
                alert('An error occurred while checking for updates.');
            }
        }

        // Load config data
        async function loadConfigData() {
            // This function can be expanded to load specific configuration data
            // when a local config is selected
        }

        // Load agent definitions
        async function loadAgentDefinitions() {
            try {
                const response = await fetch('/get_agent_definitions');
                agentDefinitions = await response.json();
                updateAgentConfig();
            } catch (error) {
                console.error('Error loading agent definitions:', error);
            }
        }

        // Load interface guide
        async function loadInterfaceGuide() {
            try {
                const response = await fetch('/get_interface_guide');
                const data = await response.json();
                
                const contentDiv = document.getElementById('interfaceGuideContent');
                if (data.content) {
                    contentDiv.innerHTML = data.content;
                } else if (data.error) {
                    contentDiv.innerHTML = `
                        <div class="error-message">
                            <h3>Welcome to elsciRL</h3>
                            <p>This web application helps you run reinforcement learning experiments with various agents and adapters.</p>
                            <p><strong>Error loading interface guide:</strong> ${data.error}</p>
                            <p>Please check your internet connection or try refreshing the page.</p>
                        </div>
                    `;
                }
            } catch (error) {
                console.error('Error loading interface guide:', error);
                const contentDiv = document.getElementById('interfaceGuideContent');
                contentDiv.innerHTML = `
                    <div class="error-message">
                        <h3>Welcome to elsciRL</h3>
                        <p>This web application helps you run reinforcement learning experiments with various agents and adapters.</p>
                        <p><strong>Error loading interface guide:</strong> ${error.message}</p>
                        <p>Please check your internet connection or try refreshing the page.</p>
                    </div>
                `;
            }
        }

        // Load preset instruction options when application changes
        async function loadPresetInstructions() {
            const selectedApp = document.getElementById('applicationSelect').value;
            const presetSelect = document.getElementById('presetSelect');
            const presetDescription = document.getElementById('presetDescription');
            const loadPresetBtn = document.getElementById('loadPresetBtn');
            const userInput = document.getElementById('userInput');
            const processInputBtn = document.getElementById('processInputBtn');
            const retryBtn = document.getElementById('retryBtn');
            
            // Clear any previously loaded preset and unlock Instructions tab
            userInput.value = '';
            userInput.disabled = false;
            userInput.style.backgroundColor = '';
            userInput.style.cursor = '';
            processInputBtn.disabled = false;
            retryBtn.disabled = false;
            presetDescription.textContent = '';
            
            if (!selectedApp) {
                presetSelect.innerHTML = '<option value="">Select an application first...</option>';
                loadPresetBtn.disabled = true;
                return;
            }
            
            try {
                const response = await fetch('/get_available_instruction_presets', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ application: selectedApp })
                });
                
                const data = await response.json();
                
                if (data.error) {
                    presetSelect.innerHTML = `<option value="">Error: ${data.error}</option>`;
                    loadPresetBtn.disabled = true;
                    return;
                }
                
                presetSelect.innerHTML = '<option value="">Choose a preset...</option>';
                
                if (data.presets && data.presets.length > 0) {
                    data.presets.forEach(preset => {
                        const option = document.createElement('option');
                        option.value = preset.name;
                        option.textContent = preset.description;
                        presetSelect.appendChild(option);
                    });
                    presetDescription.textContent = `${data.count} preset(s) available for ${selectedApp}`;
                } else {
                    presetSelect.innerHTML = '<option value="">No presets available for this application</option>';
                    presetDescription.textContent = 'No preset instruction plans available for this application.';
                }
                
                loadPresetBtn.disabled = true;
                
            } catch (error) {
                console.error('Error loading preset instructions:', error);
                presetSelect.innerHTML = '<option value="">Error loading presets</option>';
                presetDescription.textContent = 'Error loading preset instructions.';
                loadPresetBtn.disabled = true;
            }
        }

        // Load the selected preset instruction
        async function loadSelectedPreset() {
            const selectedApp = document.getElementById('applicationSelect').value;
            const presetSelect = document.getElementById('presetSelect');
            const presetName = presetSelect.value;
            const userInput = document.getElementById('userInput');
            const clearPresetBtn = document.getElementById('clearPresetBtn');
            const processInputBtn = document.getElementById('processInputBtn');
            const retryBtn = document.getElementById('retryBtn');
            
            if (!presetName) return;
            
            try {
                const response = await fetch('/load_instruction_preset', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        application: selectedApp,
                        preset_name: presetName
                    })
                });
                
                const data = await response.json();
                
                if (data.error) {
                    alert(`Error loading preset: ${data.error}`);
                    return;
                }
                
                // Display the formatted instruction descriptions
                const instructionText = data.instruction_descriptions || 'No instruction descriptions available';
                userInput.value = instructionText;
                
                // Lock the Instructions tab controls
                userInput.disabled = true;
                userInput.style.backgroundColor = '#f5f5f5';
                userInput.style.cursor = 'not-allowed';
                processInputBtn.disabled = true;
                retryBtn.disabled = true;
                
                clearPresetBtn.classList.remove('clear-preset-btn');
                
                // Show success message
                const presetDescription = document.getElementById('presetDescription');
                presetDescription.innerHTML = `
                    <div style="color: #28a745; font-weight: 500;">
                        ✓ Loaded preset: ${presetName}<br>
                        <small style="color: #666;">This preset will be used for instruction-guided training when you click "Train Model"</small><br>
                        <small style="color: #e67e22; margin-top: 5px; display: block;">⚠️ Instructions tab is locked while preset is active. Click "Clear" to edit instructions manually.</small>
                    </div>
                `;
                
            } catch (error) {
                console.error('Error loading preset:', error);
                alert('Error loading preset instruction plan.');
            }
        }

        // Clear the loaded preset
        async function clearPreset() {
            const userInput = document.getElementById('userInput');
            const presetSelect = document.getElementById('presetSelect');
            const clearPresetBtn = document.getElementById('clearPresetBtn');
            const presetDescription = document.getElementById('presetDescription');
            const processInputBtn = document.getElementById('processInputBtn');
            const retryBtn = document.getElementById('retryBtn');
            const selectedApp = document.getElementById('applicationSelect').value;
            
            // Clear frontend
            userInput.value = '';
            presetSelect.value = '';
            clearPresetBtn.classList.add('clear-preset-btn');
            presetDescription.textContent = '';
            
            // Unlock the Instructions tab controls
            userInput.disabled = false;
            userInput.style.backgroundColor = '';
            userInput.style.cursor = '';
            processInputBtn.disabled = false;
            retryBtn.disabled = false;
            
            // Clear backend stored preset
            if (selectedApp) {
                try {
                    await fetch('/clear_instruction_preset', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: selectedApp })
                    });
                } catch (error) {
                    console.error('Error clearing preset from backend:', error);
                }
            }
        }

        // Handle preset selection change
        function onPresetSelectChange() {
            const presetSelect = document.getElementById('presetSelect');
            const loadPresetBtn = document.getElementById('loadPresetBtn');
            
            if (presetSelect.value) {
                loadPresetBtn.disabled = false;
            } else {
                loadPresetBtn.disabled = true;
            }
        }

        // Load application overview
        async function loadApplicationOverview() {
            try {
                const response = await fetch('/get_all_applications_info');
                const data = await response.json();
                
                const contentDiv = document.getElementById('applicationOverviewContent');
                if (data.applications && data.applications.length > 0) {
                    let html = '<div class="applications-overview">';
                    
                    // Filter to only show downloaded applications and sort alphabetically
                    const downloadedApps = data.applications.filter(app => app.is_downloaded).sort((a, b) => a.name.localeCompare(b.name));
                    
                    if (downloadedApps.length > 0) {
                        html += `
                            <div class="overview-layout">
                                <div class="applications-section">
                                    <h3>Downloaded Applications</h3>
                                    <div class="app-grid-compact">
                        `;
                        
                        downloadedApps.forEach(app => {
                            html += `
                                <div class="app-card-compact" onclick="selectApplication('${app.name}', this)">
                                    <h4>${app.name}</h4>
                                    <div class="app-details-compact">
                                        <p><strong>Components:</strong> ${app.adapters_count} adapters, ${app.configs_count} configs, ${app.experiment_configs_count} experiments</p>
                                        ${app.description ? `<p><strong>Description:</strong> ${app.description}</p>` : ''}
                                        ${app.github_user ? `<p><strong>Author:</strong> ${app.github_user}</p>` : ''}
                                    </div>
                                </div>
                            `;
                        });
                        
                        html += `
                                    </div>
                                </div>
                                
                                <div class="configuration-section">
                                    <h3>Configuration Selection</h3>
                                    <div id="applicationConfigSection" class="config-selection-compact">
                                        <div class="config-selection-grid">
                                            <!-- Local Config Selection -->
                                            <div class="config-selection-card">
                                                <h4>Local Configuration</h4>
                                                <div id="overviewLocalConfigOptions" class="config-options-container">
                                                    <p style="color: #666; font-style: italic;">Select an application to see available configurations</p>
                                                </div>
                                            </div>
                                        </div>
                                        
                                        <!-- Selected Configuration Summary -->
                                        <div id="overviewConfigSummary" style="display: none; padding: 15px; background-color: #f8f9fa; border-radius: 8px; border: 1px solid var(--border-color); margin-top: 15px;">
                                            <div id="overviewSelectedConfigs">
                                                <div id="overviewLocalConfigSummary" style="padding: 15px; background-color: white; border-radius: 8px; border: 1px solid var(--border-color); box-shadow: 0 2px 4px rgba(0,0,0,0.1);">
                                                    <h5 style="margin: 0 0 10px 0; color: var(--button-color); font-size: 1.1em; display: flex; align-items: center;">
                                                        Local Configuration
                                                    </h5>
                                                    <div id="overviewLocalConfigValue" style="color: #333; font-size: 1.2em; font-weight: 500; margin-bottom: 8px; padding: 8px; background-color: #f8f9fa; border-radius: 4px; border-left: 3px solid var(--button-color);">None selected</div>
                                                    <div id="overviewLocalConfigContent" style="display: none; margin-top: 10px;">
                                                        <div style="color: #666; font-size: 0.9em; margin-bottom: 8px;">Configuration Details:</div>
                                                        <pre id="overviewLocalConfigJson" style="background-color: #f8f9fa; border: 1px solid #e9ecef; border-radius: 4px; padding: 12px; font-size: 0.85em; color: #333; overflow-x: auto; max-height: 300px; overflow-y: auto; white-space: pre-wrap; word-wrap: break-word;"></pre>
                                                    </div>
                                                    <div style="color: #666; font-size: 0.9em;">Configuration file for the selected application</div>
                                                </div>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                            
                            <!-- Selected Application Details Section -->
                            <div id="selectedApplicationDetails" style="display: none; margin-top: 30px;">
                                <h3>Selected Application Details</h3>
                                <div id="selectedAppContent">
                                    <p>Select an application to view details, prerender image, and README.</p>
                                </div>
                            </div>
                        `;
                    }
                    
                    html += '</div>';
                    contentDiv.innerHTML = html;
                } else {
                    contentDiv.innerHTML = '<p>No applications available.</p>';
                }
            } catch (error) {
                console.error('Error loading application overview:', error);
                const contentDiv = document.getElementById('applicationOverviewContent');
                contentDiv.innerHTML = `
                    <div class="error-message">
                        <p><strong>Error loading application overview:</strong> ${error.message}</p>
                        <p>Please try refreshing the page.</p>
                    </div>
                `;
            }
        }

        // Configuration selection functions
        function showConfigDropdown(configType) {
            // Hide all other dropdowns
            document.querySelectorAll('.config-dropdown').forEach(dropdown => {
                dropdown.classList.remove('show');
            });
            
            // Show the selected dropdown
            const dropdown = document.getElementById(configType + 'Dropdown');
            if (dropdown) {
                dropdown.classList.add('show');
            }
        }

        function hideConfigDropdown(configType) {
            const dropdown = document.getElementById(configType + 'Dropdown');
            if (dropdown) {
                dropdown.classList.remove('show');
            }
        }

        function applyConfig(configType) {
            const selectElement = document.getElementById(configType + 'Select');
            const selectedValue = selectElement.value;
            const displayElement = document.getElementById('selected' + configType.charAt(0).toUpperCase() + configType.slice(1));
            
            if (selectedValue) {
                displayElement.textContent = `${configType.charAt(0).toUpperCase() + configType.slice(1)}: ${selectedValue}`;
                
                // Update the main application form if it exists
                updateMainApplicationForm(configType, selectedValue);
            }
            
            // Hide the dropdown
            hideConfigDropdown(configType);
        }

        function updateMainApplicationForm(configType, selectedValue) {
            // Update the main application form dropdowns
            if (configType === 'localConfig') {
                const localConfigSelect = document.getElementById('localConfigInput');
                if (localConfigSelect) {
                    localConfigSelect.value = selectedValue;
                }
            } else if (configType === 'observedStates') {
                const observedStatesSelect = document.getElementById('observedStateInput');
                if (observedStatesSelect) {
                    observedStatesSelect.value = selectedValue;
                }
            } else if (configType === 'plotOptions') {
                const plotSelect = document.getElementById('selectedPlot');
                if (plotSelect) {
                    plotSelect.value = selectedValue;
                }
            }
        }

        async function loadApplicationConfigurations(applicationName) {
            try {
                // Show loading state
                const configButtons = document.querySelectorAll('.config-button');
                configButtons.forEach(button => {
                    button.disabled = true;
                    button.textContent = 'Loading...';
                });
                
                // Load local configs
                const localConfigsResponse = await fetch('/get_local_configs', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ application: applicationName })
                });
                const localConfigsData = await localConfigsResponse.json();
                
                const localConfigSelect = document.getElementById('localConfigSelect');
                if (localConfigSelect && localConfigsData.localConfigs[applicationName]) {
                    localConfigSelect.innerHTML = '<option value="">Select a local config...</option>';
                    localConfigsData.localConfigs[applicationName].forEach(config => {
                        localConfigSelect.innerHTML += `<option value="${config}">${config}</option>`;
                    });
                } else {
                    localConfigSelect.innerHTML = '<option value="">No local configs available</option>';
                }

                // Load observed states
                const observedStatesResponse = await fetch('/get_observed_states', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ applications: [applicationName] })
                });
                const observedStatesData = await observedStatesResponse.json();
                
                const observedStatesSelect = document.getElementById('observedStatesSelect');
                if (observedStatesSelect && observedStatesData.observedStates[applicationName]) {
                    observedStatesSelect.innerHTML = '<option value="">Select observed states...</option>';
                    observedStatesData.observedStates[applicationName].forEach(state => {
                        observedStatesSelect.innerHTML += `<option value="${state}">${state}</option>`;
                    });
                } else {
                    observedStatesSelect.innerHTML = '<option value="">No observed states available</option>';
                }

                // Load plot options
                const plotOptionsResponse = await fetch('/get_plot_options', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ application: applicationName })
                });
                const plotOptionsData = await plotOptionsResponse.json();
                
                const plotOptionsSelect = document.getElementById('plotOptionsSelect');
                if (plotOptionsSelect && plotOptionsData.plotOptions[applicationName]) {
                    plotOptionsSelect.innerHTML = '<option value="">Select a plot option...</option>';
                    plotOptionsData.plotOptions[applicationName].forEach(plot => {
                        plotOptionsSelect.innerHTML += `<option value="${plot}">${plot}</option>`;
                    });
                } else {
                    plotOptionsSelect.innerHTML = '<option value="">No plot options available</option>';
                }

                // Restore button states
                const configButtonsRestore = document.querySelectorAll('.config-button');
                configButtonsRestore.forEach(button => {
                    button.disabled = false;
                });
                
                // Restore specific button text
                const localConfigBtn = document.querySelector('button[onclick="showConfigDropdown(\'localConfig\')"]');
                const observedStatesBtn = document.querySelector('button[onclick="showConfigDropdown(\'observedStates\')"]');
                const plotOptionsBtn = document.querySelector('button[onclick="showConfigDropdown(\'plotOptions\')"]');
                
                if (localConfigBtn) localConfigBtn.textContent = 'Select Local Config';
                if (observedStatesBtn) observedStatesBtn.textContent = 'Select Observed States';
                if (plotOptionsBtn) plotOptionsBtn.textContent = 'Select Analysis Plot';

            } catch (error) {
                console.error('Error loading application configurations:', error);
                
                // Restore button states even on error
                const configButtonsError = document.querySelectorAll('.config-button');
                configButtonsError.forEach(button => {
                    button.disabled = false;
                });
            }
        }

        function applyAllConfigurations() {
            // Apply all currently selected configurations to the main form
            const localConfigValue = document.getElementById('localConfigSelect').value;
            const observedStatesValue = document.getElementById('observedStatesSelect').value;
            const plotOptionsValue = document.getElementById('plotOptionsSelect').value;
            
            if (localConfigValue) {
                updateMainApplicationForm('localConfig', localConfigValue);
            }
            if (observedStatesValue) {
                updateMainApplicationForm('observedStates', observedStatesValue);
            }
            if (plotOptionsValue) {
                updateMainApplicationForm('plotOptions', plotOptionsValue);
            }
            
            // Show success message
            alert('All selected configurations have been applied to the experiment form!');
        }

        function clearAllConfigurations() {
            // Clear all selected configurations
            document.getElementById('selectedLocalConfigSummary').textContent = 'Local Config: None';
            document.getElementById('selectedObservedStatesSummary').textContent = 'Observed States: None';
            document.getElementById('selectedPlotOptionsSummary').textContent = 'Analysis Plot: None';
            
            // Clear button selections
            document.querySelectorAll('.config-option-button').forEach(button => {
                button.classList.remove('selected');
            });
            
            // Hide clear button and summary
            document.querySelector('.config-clear-btn').style.display = 'none';
            document.getElementById('selectedConfigSummary').style.display = 'none';
        }

        // Load configuration dropdowns
        function loadConfigurationDropdowns(selectedApp, configsData, statesData, plotsData, allOptionsData) {
            // Load local configs
            loadConfigDropdown('localConfigSelect', configsData.localConfigs[selectedApp] || []);
            
            // Load observed states
            loadConfigDropdown('observedStateSelect', statesData.observedStates[selectedApp] || []);
            
            // Load plot options
            loadConfigDropdown('plotSelect', plotsData.plotOptions[selectedApp] || []);
            
            // Load experiment configurations
            loadConfigDropdown('experimentConfigSelect', allOptionsData.experimentConfigs[selectedApp] || []);
            
            // Reset experiment config selection and disable Load button
            const experimentConfigSelect = document.getElementById('experimentConfigSelect');
            const loadExperimentConfigBtn = document.getElementById('loadExperimentConfigBtn');
            const experimentConfigDescription = document.getElementById('experimentConfigDescription');
            if (experimentConfigSelect) {
                experimentConfigSelect.value = '';
            }
            if (loadExperimentConfigBtn) {
                loadExperimentConfigBtn.disabled = true;
            }
            if (experimentConfigDescription) {
                experimentConfigDescription.textContent = '';
            }
        }

        // Load configuration dropdown
        function loadConfigDropdown(selectId, options) {
            const select = document.getElementById(selectId);
            select.innerHTML = '<option value="">Select an option...</option>';
            
            if (options && options.length > 0) {
                // Reverse the order so most recent options appear first
                const reversedOptions = [...options].reverse();
                reversedOptions.forEach(option => {
                    const optionElement = document.createElement('option');
                    optionElement.value = option;
                    optionElement.textContent = option;
                    select.appendChild(optionElement);
                });
                
                // Default to first option
                select.selectedIndex = 1; // Index 1 because index 0 is the placeholder
            } else {
                select.innerHTML = '<option value="">No options available</option>';
            }
            
            // Update summary after loading
            updateConfigSummary();
        }

        // Load observed states for instructions tab
        function loadInstructionsObservedStates(selectedApp, statesData) {
            const select = document.getElementById('instructionsObservedStateSelect');
            select.innerHTML = '<option value="">Select an option...</option>';
            
            const states = statesData.observedStates[selectedApp] || [];
            
            if (states.length > 0) {
                // Reverse the order so most recent options appear first
                const reversedStates = [...states].reverse();
                reversedStates.forEach(state => {
                    const optionElement = document.createElement('option');
                    optionElement.value = state;
                    optionElement.textContent = state;
                    select.appendChild(optionElement);
                });
                
                // Default to first option
                select.selectedIndex = 1; // Index 1 because index 0 is the placeholder
                updateInstructionsObservedStates();
            } else {
                select.innerHTML = '<option value="">No observed states available</option>';
            }
        }

        // Update instructions observed states display
        function updateInstructionsObservedStates() {
            const selectedState = document.getElementById('instructionsObservedStateSelect').value;
            const summaryElement = document.getElementById('instructionsObservedStatesSummary');
            const infoElement = document.getElementById('instructionsObservedStatesInfo');
            const previewElement = document.getElementById('instructionsObservedStatesPreview');
            const contentElement = document.getElementById('instructionsObservedStatesContent');
            
            if (summaryElement) {
                summaryElement.textContent = selectedState || 'None';
            }
            
            if (infoElement) {
                infoElement.style.display = selectedState ? 'block' : 'none';
            }
            
            // Show/hide preview section
            if (previewElement) {
                previewElement.style.display = selectedState ? 'block' : 'none';
            }
            
            // Fetch and display preview if a state is selected
            if (selectedState) {
                fetchObservedStatesPreview(selectedState);
            } else if (contentElement) {
                contentElement.textContent = '';
            }
            
            // Update the main experiment form dropdown for compatibility
            const mainSelect = document.getElementById('observedStateSelect');
            if (mainSelect) {
                mainSelect.value = selectedState;
            }
        }

        // Fetch observed states preview content
        async function fetchObservedStatesPreview(stateFileName) {
            const selectedApp = document.getElementById('applicationSelect').value;
            if (!selectedApp || !stateFileName) return;

            const contentElement = document.getElementById('instructionsObservedStatesContent');
            if (!contentElement) return;

            // Show loading state
            contentElement.textContent = 'Loading observed states preview...';
            contentElement.style.color = '#666';
            contentElement.style.fontStyle = 'italic';

            try {
                const response = await fetch('/get_observed_states_content', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        application: selectedApp,
                        state_file: stateFileName
                    })
                });

                const data = await response.json();
                
                if (data.error) {
                    console.error('Error fetching observed states content:', data.error);
                    contentElement.textContent = `Error: ${data.error}`;
                    contentElement.style.color = '#dc3545';
                    contentElement.style.fontStyle = 'normal';
                } else {
                    displayObservedStatesPreview(data.content, data.is_encoded || false);
                }
            } catch (error) {
                console.error('Error fetching observed states content:', error);
                contentElement.textContent = 'Failed to load observed states preview';
                contentElement.style.color = '#dc3545';
                contentElement.style.fontStyle = 'normal';
            }
        }

        // Display observed states preview content
        function displayObservedStatesPreview(content, isEncoded = false) {
            const contentElement = document.getElementById('instructionsObservedStatesContent');
            if (!contentElement) return;

            try {
                let previewContent = '';
                
                if (isEncoded) {
                    // Handle encoded tensor data as "Adapter State" (encoded representation)
                    if (Array.isArray(content)) {
                        if (content.length > 0) {
                            const firstElement = content[0];
                            const shape = `[${content.length}]`;
                            
                            previewContent = `Raw State: (Encoded as tensor)\n\nAdapter State (Encoded - Shape: ${shape}):\n${JSON.stringify(firstElement, null, 2)}`;
                            
                            if (Array.isArray(firstElement) && firstElement.length > 0) {
                                previewContent += `\n\nFirst ${Math.min(10, firstElement.length)} elements: ${JSON.stringify(firstElement.slice(0, Math.min(10, firstElement.length)))}`;
                                if (firstElement.length > 10) {
                                    previewContent += `\n... (${firstElement.length - 10} more elements)`;
                                }
                            }
                        } else {
                            previewContent = 'Raw State: (Not available)\n\nAdapter State: (Empty)';
                        }
                    } else {
                        previewContent = `Raw State: (Not available)\n\nAdapter State (Encoded):\n${JSON.stringify(content, null, 2)}`;
                    }
                } else {
                    // Handle regular data (text/JSON adapter output)
                    let parsedContent = content;
                    
                    // Parse if string
                    if (typeof content === 'string') {
                        try {
                            parsedContent = JSON.parse(content);
                        } catch (e) {
                            parsedContent = content;
                        }
                    }
                    
                    // Check if content has explicit "raw" and "adapter"/"adapted" keys
                    if (typeof parsedContent === 'object' && parsedContent !== null) {
                        if ('raw' in parsedContent && ('adapter' in parsedContent || 'adapted' in parsedContent)) {
                            // Structured format with both raw and adapter states
                            const rawState = parsedContent.raw;
                            const adapterState = parsedContent.adapter || parsedContent.adapted;
                            previewContent = `Raw State:\n${typeof rawState === 'string' ? rawState : JSON.stringify(rawState, null, 2)}\n\nAdapter State:\n${typeof adapterState === 'string' ? adapterState : JSON.stringify(adapterState, null, 2)}`;
                        } else if (Array.isArray(parsedContent) && parsedContent.length > 0) {
                            // Array of states - show first one
                            const firstState = parsedContent[0];
                            previewContent = `Raw State: (State index/ID not specified)\n\nAdapter State:\n${typeof firstState === 'string' ? firstState : JSON.stringify(firstState, null, 2)}`;
                        } else {
                            // Dictionary of states - show first key-value pair
                            const keys = Object.keys(parsedContent);
                            if (keys.length > 0) {
                                const firstKey = keys[0];
                                const firstValue = parsedContent[firstKey];
                                previewContent = `Raw State: ${firstKey}\n\nAdapter State:\n${typeof firstValue === 'string' ? firstValue : JSON.stringify(firstValue, null, 2)}`;
                            } else {
                                previewContent = 'Raw State: (Not available)\n\nAdapter State: (Empty)';
                            }
                        }
                    } else {
                        // Simple value
                        previewContent = `Raw State: (Not available)\n\nAdapter State:\n${typeof parsedContent === 'string' ? parsedContent : JSON.stringify(parsedContent, null, 2)}`;
                    }
                }

                contentElement.textContent = previewContent;
                contentElement.style.color = '#333';
                contentElement.style.fontStyle = 'normal';
            } catch (error) {
                console.error('Error formatting observed states preview:', error);
                contentElement.textContent = 'Error formatting preview content';
                contentElement.style.color = '#dc3545';
                contentElement.style.fontStyle = 'normal';
            }
        }

        // Handle experiment config selection change
        function onExperimentConfigSelectChange() {
            const experimentConfigSelect = document.getElementById('experimentConfigSelect');
            const loadExperimentConfigBtn = document.getElementById('loadExperimentConfigBtn');
            
            if (experimentConfigSelect.value) {
                loadExperimentConfigBtn.disabled = false;
            } else {
                loadExperimentConfigBtn.disabled = true;
            }
        }

        // Load experiment configuration
        async function loadExperimentConfig() {
            const selectedApp = document.getElementById('applicationSelect').value;
            const selectedConfig = document.getElementById('experimentConfigSelect').value;
            const descriptionElement = document.getElementById('experimentConfigDescription');
            
            if (!selectedApp || !selectedConfig) {
                if (descriptionElement) {
                    descriptionElement.textContent = '';
                }
                return;
            }
            
            try {
                const response = await fetch('/get_experiment_config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        application: selectedApp, 
                        config: selectedConfig 
                    })
                });
                
                const data = await response.json();
                
                if (data.error) {
                    console.error('Error loading experiment config:', data.error);
                    if (descriptionElement) {
                        descriptionElement.textContent = `Error: ${data.error}`;
                        descriptionElement.style.color = '#dc3545';
                    }
                    return;
                }
                
                // Apply the experiment configuration to the form
                applyExperimentConfig(data.config);
                
                // Show success message in description
                if (descriptionElement) {
                    descriptionElement.innerHTML = `
                        <div style="color: #28a745; font-weight: 500;">
                            ✓ Loaded configuration: ${selectedConfig}<br>
                            <small style="color: #666;">This configuration has been applied to the training parameters below</small>
                        </div>
                    `;
                }
                
            } catch (error) {
                console.error('Error loading experiment config:', error);
                if (descriptionElement) {
                    descriptionElement.textContent = `Error: ${error.message}`;
                    descriptionElement.style.color = '#dc3545';
                }
            }
        }
        
        // Reset experiment configuration to defaults
        function resetExperimentConfig() {
            const descriptionElement = document.getElementById('experimentConfigDescription');
            const experimentConfigSelect = document.getElementById('experimentConfigSelect');
            
            // Reset the dropdown to default
            experimentConfigSelect.value = '';
            
            // Disable the Load button
            const loadExperimentConfigBtn = document.getElementById('loadExperimentConfigBtn');
            loadExperimentConfigBtn.disabled = true;
            
            // Reset training parameters to defaults
            document.getElementById('trainingEpisodes').value = 1000;
            document.getElementById('trainingRepeats').value = 5;
            document.getElementById('testEpisodes').value = 200;
            document.getElementById('testRepeats').value = 10;
            
            // Uncheck all agent checkboxes
            document.querySelectorAll('input[type="checkbox"][id^="agent_"]').forEach(checkbox => {
                checkbox.checked = false;
            });
            
            // Update agent configuration
            updateAgentConfig();
            
            // Clear description
            if (descriptionElement) {
                descriptionElement.innerHTML = `
                    <div style="color: #28a745; font-weight: 500;">
                        ✓ Configuration reset to defaults
                    </div>
                `;
                
                // Clear the message after 3 seconds
                setTimeout(() => {
                    descriptionElement.textContent = '';
                }, 3000);
            }
        }
        
        // Load experiment configuration from overview tab
        async function loadExperimentConfigFromOverview(selectedConfig) {
            const selectedApp = document.getElementById('applicationSelect').value;
            
            if (!selectedApp || !selectedConfig) return;
            
            try {
                const response = await fetch('/get_experiment_config', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({ 
                        application: selectedApp, 
                        config: selectedConfig 
                    })
                });
                
                const data = await response.json();
                
                if (data.error) {
                    console.error('Error loading experiment config from overview:', data.error);
                    return;
                }
                
                // Apply the experiment configuration to the form
                applyExperimentConfig(data.config);
                
            } catch (error) {
                console.error('Error loading experiment config from overview:', error);
            }
        }
        
        // Apply experiment configuration to form fields
        function applyExperimentConfig(config) {
            // Update training parameters
            if (config.number_training_episodes) {
                document.getElementById('trainingEpisodes').value = config.number_training_episodes;
            }
            if (config.number_training_repeats) {
                document.getElementById('trainingRepeats').value = config.number_training_repeats;
            }
            if (config.number_test_episodes) {
                document.getElementById('testEpisodes').value = config.number_test_episodes;
            }
            if (config.number_test_repeats) {
                document.getElementById('testRepeats').value = config.number_test_repeats;
            }
            
            // Update agent selection
            if (config.agent_select && Array.isArray(config.agent_select)) {
                // Clear all agent checkboxes first
                document.querySelectorAll('input[type="checkbox"][id^="agent_"]').forEach(checkbox => {
                    checkbox.checked = false;
                });
                
                // Check the agents specified in the config
                config.agent_select.forEach(agent => {
                    const checkbox = document.getElementById(`agent_${agent}`);
                    if (checkbox) {
                        checkbox.checked = true;
                    }
                });
                
                // Update agent configuration
                updateAgentConfig();
            }
            
            // Update agent parameters
            if (config.agent_parameters) {
                Object.keys(config.agent_parameters).forEach(agentId => {
                    const agentParams = config.agent_parameters[agentId];
                    Object.keys(agentParams).forEach(paramKey => {
                        const formFieldName = `${agentId}_${paramKey}`;
                        const input = document.getElementById(formFieldName);
                        if (input) {
                            if (input.type === 'range') {
                                // Handle slider values - convert actual value to step index
                                const steps = generateSliderSteps();
                                const stepIndex = valueToSliderStep(agentParams[paramKey], steps);
                                input.value = stepIndex;
                                // Update the value display
                                const valueDisplay = document.getElementById(formFieldName + '_value');
                                if (valueDisplay) {
                                    valueDisplay.textContent = agentParams[paramKey].toFixed(2);
                                }
                                // Update the slider's visual progress
                                const progress = (stepIndex / (steps.length - 1)) * 100;
                                input.style.setProperty('--slider-progress', progress + '%');
                            } else {
                                input.value = agentParams[paramKey];
                            }
                        }
                    });
                });
            }
            
            // Update adapter selection
            if (config.adapter_input_dict) {
                // This would need to be implemented based on how adapters are handled in the UI
                console.log('Adapter configuration:', config.adapter_input_dict);
            }
            
            // Show success message
            console.log('Experiment configuration loaded successfully');
            
            // Update config summary
            updateConfigSummary();
        }

        // Update configuration summary
        function updateConfigSummary() {
            const localConfig = document.getElementById('localConfigSelect').value;
            const observedState = document.getElementById('observedStateSelect').value;
            const plot = document.getElementById('plotSelect').value;
            const experimentConfig = document.getElementById('experimentConfigSelect').value;
            
            // Update summary display if it exists
            const localConfigSummary = document.getElementById('selectedLocalConfigSummary');
            const observedStatesSummary = document.getElementById('selectedObservedStatesSummary');
            const plotSummary = document.getElementById('selectedPlotOptionsSummary');
            const experimentConfigSummary = document.getElementById('selectedExperimentConfigSummary');
            
            if (localConfigSummary) {
                localConfigSummary.textContent = `Local Config: ${localConfig || 'None'}`;
            }
            if (observedStatesSummary) {
                observedStatesSummary.textContent = `Observed States: ${observedState || 'None'}`;
            }
            if (plotSummary) {
                plotSummary.textContent = `Analysis Plot: ${plot || 'None'}`;
            }
            if (experimentConfigSummary) {
                experimentConfigSummary.textContent = `Experiment Config: ${experimentConfig || 'None'}`;
            }
        }

        // New button-based configuration functions (for overview tab)
        function loadConfigurationOptions(selectedApp, configsData, statesData, plotsData) {
            // Load local configs
            loadConfigSection('localConfig', configsData.localConfigs[selectedApp] || []);
            
            // Load observed states
            loadConfigSection('observedStates', statesData.observedStates[selectedApp] || []);
            
            // Load plot options
            loadConfigSection('plotOptions', plotsData.plotOptions[selectedApp] || []);
        }

        function loadConfigSection(configType, options) {
            const section = document.getElementById(configType + 'Section');
            const grid = document.getElementById(configType + 'Grid');
            
            if (!options || options.length === 0) {
                section.style.display = 'none';
                return;
            }
            
            section.style.display = 'block';
            grid.innerHTML = '';
            
            options.forEach(option => {
                const button = document.createElement('div');
                button.className = 'config-option-button';
                button.onclick = () => selectConfigOption(configType, option, button);
                
                // Create summary information based on config type
                let title, description, meta;
                switch(configType) {
                    case 'localConfig':
                        title = option;
                        description = `Configuration file for ${option}`;
                        meta = 'Local configuration';
                        break;
                    case 'observedStates':
                        title = option;
                        description = `Observed states data: ${option}`;
                        meta = 'State data';
                        break;
                    case 'plotOptions':
                        title = option;
                        description = `Analysis plot: ${option}`;
                        meta = 'Visualization';
                        break;
                }
                
                button.innerHTML = `
                    <div class="config-option-title">${title}</div>
                    <div class="config-option-description">${description}</div>
                    <div class="config-option-meta">${meta}</div>
                `;
                
                grid.appendChild(button);
            });
        }

        function selectConfigOption(configType, option, buttonElement) {
            // Remove selection from other buttons in the same section
            const section = buttonElement.closest('.config-option-grid');
            section.querySelectorAll('.config-option-button').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            // Select this button
            buttonElement.classList.add('selected');
            
            // Update summary
            const summaryElement = document.getElementById('selected' + configType.charAt(0).toUpperCase() + configType.slice(1) + 'Summary');
            summaryElement.textContent = `${configType.charAt(0).toUpperCase() + configType.slice(1)}: ${option}`;
            
            // Show summary and clear button
            document.getElementById('selectedConfigSummary').style.display = 'block';
            document.querySelector('.config-clear-btn').style.display = 'inline-block';
            
            // Update the hidden form fields for compatibility
            updateHiddenFormFields(configType, option);
        }

        function updateHiddenFormFields(configType, option) {
            // Update hidden form fields for compatibility with existing code
            if (configType === 'localConfig') {
                const hiddenSelect = document.getElementById('localConfigSelect');
                if (hiddenSelect) {
                    hiddenSelect.value = option;
                }
            } else if (configType === 'observedStates') {
                const hiddenSelect = document.getElementById('observedStateSelect');
                if (hiddenSelect) {
                    hiddenSelect.value = option;
                }
            } else if (configType === 'plotOptions') {
                const hiddenSelect = document.getElementById('plotSelect');
                if (hiddenSelect) {
                    hiddenSelect.value = option;
                }
            }
        }

        // Simple markdown parser for README content
        function parseMarkdown(markdown) {
            return markdown
                // Headers
                .replace(/^### (.*$)/gim, '<h3>$1</h3>')
                .replace(/^## (.*$)/gim, '<h2>$1</h2>')
                .replace(/^# (.*$)/gim, '<h1>$1</h1>')
                // Bold
                .replace(/\*\*(.*)\*\*/gim, '<strong>$1</strong>')
                .replace(/__(.*)__/gim, '<strong>$1</strong>')
                // Italic
                .replace(/\*(.*)\*/gim, '<em>$1</em>')
                .replace(/_(.*)_/gim, '<em>$1</em>')
                // Code blocks
                .replace(/```([\s\S]*?)```/gim, '<pre><code>$1</code></pre>')
                .replace(/`([^`]*)`/gim, '<code>$1</code>')
                // Links
                .replace(/\[([^\]]*)\]\(([^)]*)\)/gim, '<a href="$2" target="_blank">$1</a>')
                // Line breaks
                .replace(/\n\n/gim, '</p><p>')
                .replace(/\n/gim, '<br>')
                // Wrap in paragraphs
                .replace(/^(.*)$/gim, '<p>$1</p>')
                // Clean up empty paragraphs
                .replace(/<p><\/p>/gim, '')
                .replace(/<p><br><\/p>/gim, '');
        }

        // Format timestamp for display
        function formatTimestamp(timestamp) {
            if (!timestamp) return '';
            
            try {
                // Handle both Unix timestamp (number) and ISO string formats
                let date;
                if (typeof timestamp === 'number') {
                    // Unix timestamp (seconds)
                    date = new Date(timestamp * 1000);
                } else if (typeof timestamp === 'string') {
                    // ISO string format
                    date = new Date(timestamp);
                            } else {
                    return '';
                }
                
                // Check if date is valid
                if (isNaN(date.getTime())) {
                    return '';
                }
                
                // Format as readable date and time
                return date.toLocaleString('en-US', {
                    year: 'numeric',
                    month: 'short',
                    day: 'numeric',
                    hour: '2-digit',
                    minute: '2-digit',
                    second: '2-digit'
                });
            } catch (error) {
                console.error('Error formatting timestamp:', error);
                return '';
            }
        }

        // Select application and load its details
        async function selectApplication(applicationName, eventElement = null) {
            try {
                // Show loading overlay
                showLoadingOverlay('Loading application data...');
                
                const selectedAppDiv = document.getElementById('selectedApplicationDetails');
                const selectedAppContent = document.getElementById('selectedAppContent');
                const configSection = document.getElementById('applicationConfigSection');
                
                // Remove previous selection from both old and new card types
                document.querySelectorAll('.app-card, .app-card-compact').forEach(card => {
                    card.classList.remove('selected');
                });
                
                // Add selection to clicked card
                if (eventElement) {
                    eventElement.classList.add('selected');
                } else {
                    // Find the card by application name if eventElement not provided
                    const cards = document.querySelectorAll('.app-card, .app-card-compact');
                    cards.forEach(card => {
                        const cardTitle = card.querySelector('h4');
                        if (cardTitle && cardTitle.textContent === applicationName) {
                            card.classList.add('selected');
                        }
                    });
                }
                
                // Update the application dropdown in the Experiment block
                const applicationSelect = document.getElementById('applicationSelect');
                if (applicationSelect) {
                    applicationSelect.value = applicationName;
                    // Trigger the change event to load application data
                    loadApplicationData();
                }
                
                // Open the Experiment sidebar block
                const sidebarHeaders = document.querySelectorAll('.sidebar-block-header');
                sidebarHeaders.forEach(header => {
                    const headerText = header.querySelector('span');
                    if (headerText && headerText.textContent === 'Experiment') {
                        const content = header.nextElementSibling;
                        
                        // Close all other blocks first
                        document.querySelectorAll('.sidebar-block-content').forEach(block => {
                            block.classList.remove('active');
                        });
                        document.querySelectorAll('.sidebar-block-header').forEach(h => {
                            h.classList.remove('active');
                        });
                        
                        // Open Experiment block
                        content.classList.add('active');
                        header.classList.add('active');
                    }
                });
                
                // Show configuration section; defer loading options until DOM is injected below
                if (configSection) {
                    configSection.style.display = 'block';
                }
                
                // Show loading state
                selectedAppContent.innerHTML = '<div class="loading-message"><p>Loading application details...</p></div>';
                selectedAppDiv.style.display = 'block';
                
                // Fetch prerender image and README
                const [imageResponse, readmeResponse] = await Promise.all([
                    fetch('/get_prerender_image', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: applicationName })
                    }),
                    fetch('/get_application_readme', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: applicationName })
                    })
                ]);

                // Safely parse JSON responses (fallback to defaults on error)
                let imageData = { imagePaths: [] };
                let readmeData = {};

                try {
                    if (imageResponse.ok) {
                        imageData = await imageResponse.json();
                    } else {
                        // Try parse error JSON if provided
                        const text = await imageResponse.text();
                        try { imageData = JSON.parse(text); } catch (_) { imageData = { imagePaths: [] }; }
                    }
                } catch (_) {
                    imageData = { imagePaths: [] };
                }

                try {
                    if (readmeResponse.ok) {
                        readmeData = await readmeResponse.json();
                    } else {
                        const text = await readmeResponse.text();
                        try { readmeData = JSON.parse(text); } catch (_) { readmeData = {}; }
                    }
                } catch (_) {
                    readmeData = {};
                }
                
                let html = `<h4>${applicationName}</h4>`;
                
                // Add prerender image if available
                if (imageData.imagePaths && imageData.imagePaths.length > 0) {
                    html += '<div class="prerender-image-section">';
                    html += '<h5>Prerender Image</h5>';
                    imageData.imagePaths.forEach(imagePath => {
                        html += `<img src="/${imagePath}" alt="Prerender image for ${applicationName}" class="prerender-image">`;
                    });
                    html += '</div>';
                } else {
                    html += '<div class="prerender-image-section">';
                    html += '<h5>Prerender Image</h5>';
                    html += '<p>No prerender image available for this application.</p>';
                    html += '</div>';
                }
                
                // Add README if available
                if (readmeData.readme_content) {
                    html += '<div class="readme-section">';
                    html += `<h5>README (${readmeData.readme_name})</h5>`;
                    html += '<div class="readme-content">';
                    // Convert markdown to HTML using a simple markdown parser
                    const markdownHtml = parseMarkdown(readmeData.readme_content);
                    html += markdownHtml;
                    html += '</div>';
                    html += '</div>';
                } else {
                    html += '<div class="readme-section">';
                    html += '<h5>README</h5>';
                    html += '<p>No README available for this application.</p>';
                    html += '</div>';
                }
                
                
                selectedAppContent.innerHTML = html;

                // Now that the DOM is present, load and auto-select default config/options
                await loadOverviewConfigurationOptions(applicationName);

                // Hide loading overlay when all data is loaded
                hideLoadingOverlay();
                
            } catch (error) {
                console.error('Error loading application details:', error);
                const selectedAppContent = document.getElementById('selectedAppContent');
                selectedAppContent.innerHTML = `
                    <div class="error-message">
                        <p><strong>Error loading application details:</strong> ${error.message}</p>
                        <p>Please try again.</p>
                    </div>
                `;
                
                // Hide loading overlay even on error
                hideLoadingOverlay();
            }
        }

        // Generate 25-step values for sliders (0, 0.01, 0.02, ..., 0.25, 0.30, ..., 1.00)
        function generateSliderSteps() {
            const steps = [];
            // First 25 steps: 0.00 to 0.25 (0.01 increments)
            for (let i = 0; i <= 25; i++) {
                steps.push(i * 0.01);
            }
            // Remaining steps: 0.30 to 1.00 (0.05 increments)
            for (let i = 6; i <= 20; i++) {
                steps.push(i * 0.05);
            }
            return steps;
        }

        // Convert value to slider step index
        function valueToSliderStep(value, steps) {
            const closestStep = steps.reduce((prev, curr) => 
                Math.abs(curr - value) < Math.abs(prev - value) ? curr : prev
            );
            return steps.indexOf(closestStep);
        }

        // Convert slider step index to value
        function sliderStepToValue(stepIndex, steps) {
            return steps[stepIndex];
        }

        // Check if parameter should use slider (Q-Learning parameters between 0 and 1)
        function shouldUseSlider(paramConfig) {
            return paramConfig.type === 'number' && 
                   paramConfig.min === 0 && 
                   paramConfig.max === 1 && 
                   (paramConfig.step === 0.01 || paramConfig.step === 0.05 || paramConfig.step === 0.001 || !paramConfig.step);
        }

        // Update agent configuration forms
        function updateAgentConfig() {
            const container = document.getElementById('agentConfigContainer');
            container.innerHTML = '';

            // Get selected agents
            const selectedAgents = Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked'))
                .map(cb => cb.value);

            selectedAgents.forEach(agentId => {
                if (agentDefinitions[agentId]) {
                    const agentDef = agentDefinitions[agentId];
                    const agentDiv = document.createElement('div');
                    agentDiv.className = 'config-group';
                    agentDiv.innerHTML = `<h3>${agentDef.display_name} Configuration</h3>`;
                    
                    const paramsDiv = document.createElement('div');
                    paramsDiv.className = 'agent-params';
                    
                    Object.entries(agentDef.params).forEach(([paramKey, paramConfig]) => {
                        const paramDiv = document.createElement('div');
                        paramDiv.className = 'input-group';
                        
                        const fieldId = `${agentId}_${paramKey}`;
                        let inputHtml = '';
                        
                        if (shouldUseSlider(paramConfig)) {
                            // Use slider for Q-Learning parameters
                            const steps = generateSliderSteps();
                            const defaultValue = paramConfig.default || 0;
                            const defaultStepIndex = valueToSliderStep(defaultValue, steps);
                            
                            inputHtml = `
                                <div class="slider-container">
                                    <div class="slider-label">
                                        <span class="slider-label-text">${paramConfig.label}:</span>
                                        <span class="slider-value" id="${fieldId}_value">${defaultValue.toFixed(2)}</span>
                                    </div>
                                    <div class="slider-wrapper">
                                        <input type="range" 
                                               class="slider-input" 
                                               id="${fieldId}" 
                                               min="0" 
                                               max="${steps.length - 1}" 
                                               step="1" 
                                               value="${defaultStepIndex}"
                                               oninput="updateSliderValue('${fieldId}', ${JSON.stringify(steps).replace(/"/g, '&quot;')})">
                                    </div>
                                </div>
                            `;
                        } else if (paramConfig.type === 'number') {
                            inputHtml = `
                                <label for="${fieldId}">${paramConfig.label}:</label>
                                <input type="number" id="${fieldId}" 
                                       min="${paramConfig.min || ''}" 
                                       max="${paramConfig.max || ''}" 
                                       step="${paramConfig.step || ''}" 
                                       value="${paramConfig.default || ''}">
                            `;
                        } else if (paramConfig.type === 'text') {
                            inputHtml = `
                                <label for="${fieldId}">${paramConfig.label}:</label>
                                <input type="text" id="${fieldId}" value="${paramConfig.default || ''}">
                            `;
                        } else if (paramConfig.type === 'textarea') {
                            inputHtml = `
                                <label for="${fieldId}">${paramConfig.label}:</label>
                                <textarea id="${fieldId}" rows="${paramConfig.rows || 3}" 
                                          placeholder="${paramConfig.placeholder || ''}">${paramConfig.default || ''}</textarea>
                            `;
                        } else if (paramConfig.type === 'checkbox') {
                            inputHtml = `
                                <div class="checkbox-container">
                                    <input type="checkbox" id="${fieldId}" ${paramConfig.default ? 'checked' : ''}>
                                    <label for="${fieldId}">${paramConfig.label}</label>
                                </div>
                            `;
                        }
                        
                        paramDiv.innerHTML = inputHtml;
                        paramsDiv.appendChild(paramDiv);
                    });
                    
                    agentDiv.appendChild(paramsDiv);
                    container.appendChild(agentDiv);
                }
            });

            // Also update adapter selection when agent config changes
            updateAdapterSelection();
        }

        // Initialize adapter preview interface
        function initializeAdapterPreview() {
            // No initialization needed for now
        }
        
        // Update adapters preview list
        function updateAdaptersPreviewList() {
            const container = document.getElementById('adaptersList');
            if (!container) return;
            
            const selectedApp = document.getElementById('applicationSelect').value;
            
            if (!selectedApp) {
                container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">Select an application to see available adapters.</p>';
                return;
            }
            
            if (availableAdapters.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">No adapters available for the selected application.</p>';
                return;
            }
            
            // Filter to only show language-based adapters
            const languageAdapters = availableAdapters.filter(adapter => isLanguageAdapter(adapter));
            
            if (languageAdapters.length === 0) {
                container.innerHTML = '<p style="text-align: center; color: #666; padding: 20px;">No language-based adapters available for the selected application.</p>';
                return;
            }
            
            // Reverse the order so most recent adapters appear first
            const reversedLanguageAdapters = [...languageAdapters].reverse();
            
            container.innerHTML = '';
            reversedLanguageAdapters.forEach(adapter => {
                const card = document.createElement('div');
                card.className = 'adapter-card';
                card.setAttribute('data-adapter-name', adapter);
                
                // Add click handler to show preview
                card.onclick = () => selectAdapterForPreview(adapter, selectedApp);
                
                const description = getAdapterDescription(adapter);
                
                card.innerHTML = `
                    <div class="adapter-card-icon">📦</div>
                    <div class="adapter-card-content">
                        <div class="adapter-card-name">${adapter}</div>
                        <div class="adapter-card-description">${description}</div>
                    </div>
                `;
                
                container.appendChild(card);
            });
        }
        
        // Select adapter for preview
        async function selectAdapterForPreview(adapterName, applicationName) {
            // Remove previous selection
            document.querySelectorAll('.adapter-card').forEach(card => {
                card.classList.remove('selected');
            });
            
            // Set new selection
            const card = document.querySelector(`.adapter-card[data-adapter-name="${adapterName}"]`);
            if (card) {
                card.classList.add('selected');
            }
            
            // Show loading state
            const previewContent = document.getElementById('adapterPreviewContent');
            previewContent.innerHTML = `
                <div class="preview-loading">
                    <div class="loading-spinner"></div>
                    <p>Loading adapter preview...</p>
                </div>
            `;
            
            try {
                // Fetch adapter source code and observed states
                const [sourceResponse, statesResponse] = await Promise.all([
                    fetch('/get_adapter_source', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            application: applicationName, 
                            adapter: adapterName 
                        })
                    }),
                    fetch('/get_adapter_observed_states', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ 
                            application: applicationName, 
                            adapter: adapterName 
                        })
                    })
                ]);
                
                const sourceData = await sourceResponse.json();
                const statesData = await statesResponse.json();
                
                // Display preview
                displayAdapterPreview(adapterName, sourceData, statesData);
                
            } catch (error) {
                console.error('Error loading adapter preview:', error);
                previewContent.innerHTML = `
                    <div class="preview-error">
                        <div class="preview-error-icon">⚠️</div>
                        <h3>Error Loading Preview</h3>
                        <p>${error.message}</p>
                    </div>
                `;
            }
        }
        
        // Display adapter preview
        function displayAdapterPreview(adapterName, sourceData, statesData) {
            const previewContent = document.getElementById('adapterPreviewContent');
            
            let html = `
                <div class="preview-sections">
            `;
            
            // Observed states section (moved to first)
            if (statesData.sample) {
                html += `
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h4>Sample Observed States</h4>
                            <span class="preview-section-meta">${statesData.filename || 'Preview'}</span>
                        </div>
                        <div class="preview-states-container">
                            <pre class="preview-states"><code>${escapeHtml(JSON.stringify(statesData.sample, null, 2))}</code></pre>
                        </div>
                        ${statesData.total_count ? `<p class="preview-states-info">Showing sample from ${statesData.total_count} total states</p>` : ''}
                    </div>
                `;
            } else if (statesData.error) {
                html += `
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h4>Sample Observed States</h4>
                        </div>
                        <div class="preview-error-message">
                            <p>⚠️ ${statesData.error}</p>
                        </div>
                    </div>
                `;
            }
            
            // Source code section (moved to second)
            if (sourceData.source_code) {
                html += `
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h4>Source Code</h4>
                            <span class="preview-section-meta">${sourceData.filename || adapterName + '.py'}</span>
                        </div>
                        <div class="preview-code-container">
                            <pre class="preview-code"><code>${escapeHtml(sourceData.source_code)}</code></pre>
                        </div>
                    </div>
                `;
            } else if (sourceData.error) {
                html += `
                    <div class="preview-section">
                        <div class="preview-section-header">
                            <h4>Source Code</h4>
                        </div>
                        <div class="preview-error-message">
                            <p>⚠️ ${sourceData.error}</p>
                        </div>
                    </div>
                `;
            }
            
            html += `
                </div>
            `;
            
            previewContent.innerHTML = html;
        }
        
        // Escape HTML to prevent XSS
        function escapeHtml(text) {
            const div = document.createElement('div');
            div.textContent = text;
            return div.innerHTML;
        }
        
        // Check if adapter is language-based
        function isLanguageAdapter(adapterName) {
            const lowerName = adapterName.toLowerCase();
            return lowerName.includes('language') || lowerName.includes('llm');
        }
        
        // Get adapter description based on name
        function getAdapterDescription(adapterName) {
            const lowerName = adapterName.toLowerCase();
            
            if (lowerName.includes('language') || lowerName.includes('llm')) {
                return 'Natural language text representation';
            } else if (lowerName.includes('default') || lowerName.includes('numeric')) {
                return 'Numeric state representation';
            } else if (lowerName.includes('encoded') || lowerName.includes('embed')) {
                return 'Encoded state representation';
            } else if (lowerName.includes('image') || lowerName.includes('visual')) {
                return 'Visual/image representation';
            } else {
                return 'Custom adapter for state representation';
            }
        }

        // Update slider value display
        function updateSliderValue(fieldId, steps) {
            const slider = document.getElementById(fieldId);
            const valueDisplay = document.getElementById(fieldId + '_value');
            const stepIndex = parseInt(slider.value);
            const actualValue = steps[stepIndex];
            
            valueDisplay.textContent = actualValue.toFixed(2);
            
            // Update the slider's visual progress
            const progress = (stepIndex / (steps.length - 1)) * 100;
            slider.style.setProperty('--slider-progress', progress + '%');
        }

        // Update adapter selection
        function updateAdapterSelection() {
            const container = document.getElementById('adapterSelection');
            container.innerHTML = '';

            // Get selected agents
            const selectedAgents = Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked'))
                .map(cb => cb.value);

            // Check if application is selected
            const selectedApp = document.getElementById('applicationSelect').value;

            if (!selectedApp) {
                container.innerHTML = '<p>Select an application first to see available adapters.</p>';
                return;
            }

            if (selectedAgents.length === 0) {
                container.innerHTML = '<p>Select at least one agent to configure adapters.</p>';
                return;
            }

            if (availableAdapters.length === 0) {
                container.innerHTML = '<p>No adapters available for the selected application.</p>';
                return;
            }

            selectedAgents.forEach(agentId => {
                const agentDiv = document.createElement('div');
                agentDiv.className = 'agent-adapter-group';
                
                // Show adapters in original order (oldest to newest)
                const orderedAdapters = [...availableAdapters];
                
                agentDiv.innerHTML = `
                    <h4>${agentDefinitions[agentId]?.display_name || agentId} Adapters</h4>
                    <div class="adapter-checkboxes" id="adapters_${agentId}">
                        ${orderedAdapters.map((adapter, index) => `
                            <div class="checkbox-container">
                                <input type="checkbox" id="${agentId}_${adapter}" value="${adapter}" ${index === 0 ? 'checked' : ''}>
                                <label for="${agentId}_${adapter}">${adapter}</label>
                            </div>
                        `).join('')}
                    </div>
                `;
                container.appendChild(agentDiv);
            });
        }

        // Get agent adapter dictionary for training
        function getAgentAdapterDict() {
            const agentAdapterDict = {};
            const selectedAgents = Array.from(document.querySelectorAll('#agentSelection input[type="checkbox"]:checked'))
                .map(cb => cb.value);

            selectedAgents.forEach(agentId => {
                const adapterCheckboxes = document.querySelectorAll(`#adapters_${agentId} input[type="checkbox"]:checked`);
                agentAdapterDict[agentId] = Array.from(adapterCheckboxes).map(cb => cb.value);
            });

            return agentAdapterDict;
        }

        // Load variance results from uploads directory
        async function loadVarianceResults() {
            try {
                const response = await fetch('/get_variance_results');
                const data = await response.json();
                
                const resultsContainer = document.getElementById('varianceResults');
                
                if (data.error) {
                    resultsContainer.innerHTML = `
                        <div class="error-message">
                            <p><strong>Error loading results:</strong> ${data.error}</p>
                        </div>
                    `;
                    return;
                }
                
                if (!data.results || data.results.length === 0) {
                    resultsContainer.innerHTML = `
                        <div class="no-results-message">
                            <p>No variance analysis results found in the uploads directory.</p>
                            <p>Run a training experiment to generate variance analysis plots.</p>
                        </div>
                    `;
                return;
                }
                
                let html = `<div class="variance-results-grid">`;
                
                data.results.forEach(result => {
                    const modifiedDate = new Date(result.modified * 1000).toLocaleString();
                    const fileSizeKB = Math.round(result.size / 1024);
                    
                    html += `
                        <div class="variance-result-card">
                            <h4>${result.analysis_type}</h4>
                            <img src="/${result.path}" alt="${result.analysis_type}" onclick="openImageModal('/${result.path}')">
                            <div class="variance-result-info">
                                <p><strong>File:</strong> ${result.filename}</p>
                                <p><strong>Generated:</strong> ${modifiedDate}</p>
                                <p><strong>Size:</strong> ${fileSizeKB} KB</p>
                            </div>
                        </div>
                    `;
                });
                
                html += '</div>';
                resultsContainer.innerHTML = html;
                
            } catch (error) {
                console.error('Error loading variance results:', error);
                const resultsContainer = document.getElementById('varianceResults');
                resultsContainer.innerHTML = `
                    <div class="error-message">
                        <p><strong>Error loading variance results:</strong> ${error.message}</p>
                        <p>Please try again.</p>
                    </div>
                `;
            }
        }

        // Load policy render GIFs from uploads directory
        async function loadPolicyRenders() {
            try {
                const response = await fetch('/get_policy_renders');
                const data = await response.json();
                
                const resultsContainer = document.getElementById('policyRenderResults');
                
                if (data.error) {
                    resultsContainer.innerHTML = `
                        <div class="error-message">
                            <p><strong>Error loading renders:</strong> ${data.error}</p>
                        </div>
                    `;
                    return;
                }
                
                if (!data.renders || data.renders.length === 0) {
                    resultsContainer.innerHTML = `
                        <div class="no-results-message">
                            <p>No policy render GIFs found in the uploads directory.</p>
                            <p>Run a training experiment with rendering enabled to generate policy renders.</p>
                        </div>
                    `;
                    return;
                }
                
                let html = `<div class="variance-results-grid">`;
                
                data.renders.forEach(render => {
                    const modifiedDate = new Date(render.modified * 1000).toLocaleString();
                    const fileSizeKB = Math.round(render.size / 1024);
                    
                    html += `
                        <div class="variance-result-card">
                            <h4>${render.display_name}</h4>
                            <img src="/${render.path}" alt="${render.display_name}" onclick="openImageModal('/${render.path}')">
                            <div class="variance-result-info">
                                <p><strong>File:</strong> ${render.filename}</p>
                                <p><strong>Generated:</strong> ${modifiedDate}</p>
                                <p><strong>Size:</strong> ${fileSizeKB} KB</p>
                            </div>
                        </div>
                    `;
                });
                
                html += '</div>';
                resultsContainer.innerHTML = html;
                
            } catch (error) {
                console.error('Error loading policy renders:', error);
                const resultsContainer = document.getElementById('policyRenderResults');
                resultsContainer.innerHTML = `
                    <div class="error-message">
                        <p><strong>Error loading policy renders:</strong> ${error.message}</p>
                        <p>Please try again.</p>
                    </div>
                `;
            }
        }

        // Load configuration options for the overview tab
        async function loadOverviewConfigurationOptions(applicationName) {
            try {
                // Update loading message
                const overlay = document.getElementById('loadingOverlay');
                if (overlay) {
                    const messageElement = overlay.querySelector('.loading-message');
                    if (messageElement) {
                        messageElement.textContent = 'Loading configuration options...';
                    }
                }
                
                // Clear previous configuration summary
                const configSummary = document.getElementById('overviewConfigSummary');
                if (configSummary) {
                    configSummary.style.display = 'none';
                }
                
                // Clear previous configuration content
                const configContent = document.getElementById('overviewLocalConfigContent');
                if (configContent) {
                    configContent.style.display = 'none';
                }
                
                // First refresh application data to ensure we have the latest cached data
                await refreshApplicationData();
                // Load configuration data (only local configs)
                const [configsRes, allOptionsRes] = await Promise.all([
                    fetch('/get_local_configs', {
                        method: 'POST',
                        headers: { 'Content-Type': 'application/json' },
                        body: JSON.stringify({ application: applicationName })
                    }),
                    fetch('/get_all_options', {
                        method: 'GET'
                    })
                ]);

                const [configsData, allOptionsData] = await Promise.all([
                    configsRes.json(),
                    allOptionsRes.json()
                ]);

                // Load local configs
                loadOverviewConfigSection('overviewLocalConfigOptions', 'localConfig', configsData.localConfigs[applicationName] || []);
                
                // Load experiment configurations
                loadOverviewConfigSection('overviewExperimentConfigOptions', 'experimentConfig', allOptionsData.experimentConfigs[applicationName] || []);
                
                // Auto-select first options if available
                const localConfigs = configsData.localConfigs[applicationName] || [];
                const experimentConfigs = allOptionsData.experimentConfigs[applicationName] || [];
                
                if (localConfigs.length > 0) {
                    // Update loading message
                    const overlay = document.getElementById('loadingOverlay');
                    if (overlay) {
                        const messageElement = overlay.querySelector('.loading-message');
                        if (messageElement) {
                            messageElement.textContent = 'Loading configuration preview...';
                        }
                    }
                    
                    // Select first local config
                    const firstConfig = localConfigs[0];
                    console.log('Auto-selecting first config:', firstConfig, 'for application:', applicationName);
                    updateOverviewConfigDisplay('localConfig', firstConfig);
                    updateHiddenFormFields('localConfig', firstConfig);
                    
                    // Show the configuration summary section
                    document.getElementById('overviewConfigSummary').style.display = 'block';
                    
                    // Await the config content fetch to ensure it loads before hiding overlay
                    await fetchConfigContent(firstConfig, applicationName);
                }
                
                if (experimentConfigs.length > 0) {
                    // Select first experiment config
                    const firstExperimentConfig = experimentConfigs[0];
                    updateOverviewConfigDisplay('experimentConfig', firstExperimentConfig);
                    updateHiddenFormFields('experimentConfig', firstExperimentConfig);
                    // Load the experiment configuration
                    loadExperimentConfigFromOverview(firstExperimentConfig);
                } else {
                    // Clear experiment config selection if no options available
                    updateOverviewConfigDisplay('experimentConfig', '');
                    updateHiddenFormFields('experimentConfig', '');
                }
                
                // Show summary section if there are any configurations available
                const hasConfigs = localConfigs.length > 0;
                if (hasConfigs) {
                    document.getElementById('overviewConfigSummary').style.display = 'block';
                }

            } catch (error) {
                console.error('Error loading overview configuration options:', error);
            }
        }

        // Load configuration section for overview
        function loadOverviewConfigSection(containerId, configType, options) {
            const container = document.getElementById(containerId);
            
            if (!options || options.length === 0) {
                container.innerHTML = '<p style="color: #666; font-style: italic;">No options available</p>';
                return;
            }
            
            let html = '<div style="display: flex; flex-wrap: wrap; gap: 8px;">';
            
            options.forEach((option, index) => {
                // Add 'selected' class to the first option
                const selectedClass = index === 0 ? ' selected' : '';
                html += `
                    <button class="config-option-btn${selectedClass}" 
                            onclick="selectOverviewConfig('${configType}', '${option}', this)">
                        ${option}
                    </button>
                `;
            });
            
            html += '</div>';
            container.innerHTML = html;
        }

        // Select configuration option in overview
        function selectOverviewConfig(configType, option, buttonElement) {
            // Remove selection from other buttons in the same section
            const container = buttonElement.parentElement;
            container.querySelectorAll('.config-option-btn').forEach(btn => {
                btn.classList.remove('selected');
            });
            
            // Select this button
            buttonElement.classList.add('selected');
            
            // Update summary with pretty format
            updateOverviewConfigDisplay(configType, option);
            
            // Show summary section
            document.getElementById('overviewConfigSummary').style.display = 'block';
            
            // If it's a local config, fetch and display the JSON content
            if (configType === 'localConfig') {
                // Get the current application from the selected card
                const selectedCard = document.querySelector('.app-card-compact.selected');
                const applicationName = selectedCard ? selectedCard.querySelector('h4').textContent : null;
                fetchConfigContent(option, applicationName);
            }
            
            // Update the hidden form fields for compatibility (only for localConfig and plotOptions)
            if (configType === 'localConfig' || configType === 'plotOptions') {
                updateHiddenFormFields(configType, option);
            }
        }

        // Fetch configuration content from backend
        async function fetchConfigContent(configName, applicationName = null) {
            const selectedApp = applicationName || document.getElementById('applicationSelect').value;
            console.log('fetchConfigContent called with:', { configName, applicationName, selectedApp });
            if (!selectedApp || !configName) {
                console.log('fetchConfigContent: Missing required parameters');
                return;
            }

            // Show loading state
            const contentDiv = document.getElementById('overviewLocalConfigContent');
            const jsonPre = document.getElementById('overviewLocalConfigJson');
            
            if (contentDiv && jsonPre) {
                contentDiv.style.display = 'block';
                jsonPre.textContent = 'Loading configuration...';
                jsonPre.style.color = '#666';
                jsonPre.style.fontStyle = 'italic';
            }

            try {
                const response = await fetch('/get_local_config_content', {
                    method: 'POST',
                    headers: { 'Content-Type': 'application/json' },
                    body: JSON.stringify({
                        application: selectedApp,
                        config: configName
                    })
                });

                const data = await response.json();
                
                if (data.error) {
                    console.error('Error fetching config content:', data.error);
                    displayConfigError(data.error);
                } else {
                    displayConfigContent(data.config);
                }
            } catch (error) {
                console.error('Error fetching config content:', error);
                displayConfigError('Failed to load configuration content');
            }
        }

        // Display configuration content
        function displayConfigContent(configData) {
            console.log('displayConfigContent called with:', configData);
            const contentDiv = document.getElementById('overviewLocalConfigContent');
            const jsonPre = document.getElementById('overviewLocalConfigJson');
            
            console.log('Elements found:', { contentDiv, jsonPre });
            
            if (contentDiv && jsonPre) {
                // Format JSON with proper indentation
                const formattedJson = JSON.stringify(configData, null, 2);
                jsonPre.textContent = formattedJson;
                jsonPre.style.color = '#333';
                jsonPre.style.fontStyle = 'normal';
                contentDiv.style.display = 'block';
                console.log('Configuration content displayed');
            } else {
                console.log('Missing elements for displaying config content');
            }
        }

        // Display configuration error
        function displayConfigError(errorMessage) {
            const contentDiv = document.getElementById('overviewLocalConfigContent');
            const jsonPre = document.getElementById('overviewLocalConfigJson');
            
            if (contentDiv && jsonPre) {
                jsonPre.textContent = `Error: ${errorMessage}`;
                jsonPre.style.color = '#dc3545';
                contentDiv.style.display = 'block';
            }
        }

        // Show loading overlay
        function showLoadingOverlay(message = 'Loading...') {
            // Remove existing overlay if any
            hideLoadingOverlay();
            
            const overlay = document.createElement('div');
            overlay.id = 'loadingOverlay';
            overlay.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.5);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 9999;
                backdrop-filter: blur(2px);
            `;
            
            const loadingContent = document.createElement('div');
            loadingContent.style.cssText = `
                background-color: white;
                padding: 30px;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.3);
                text-align: center;
                max-width: 300px;
                width: 90%;
            `;
            
            const spinner = document.createElement('div');
            spinner.style.cssText = `
                border: 4px solid #f3f3f3;
                border-top: 4px solid var(--button-color);
                border-radius: 50%;
                width: 40px;
                height: 40px;
                animation: spin 1s linear infinite;
                margin: 0 auto 20px auto;
            `;
            
            const messageElement = document.createElement('p');
            messageElement.textContent = message;
            messageElement.className = 'loading-message';
            messageElement.style.cssText = `
                margin: 0;
                color: var(--text-color);
                font-size: 16px;
                font-weight: 500;
            `;
            
            loadingContent.appendChild(spinner);
            loadingContent.appendChild(messageElement);
            overlay.appendChild(loadingContent);
            document.body.appendChild(overlay);
        }

        // Hide loading overlay
        function hideLoadingOverlay() {
            const overlay = document.getElementById('loadingOverlay');
            if (overlay) {
                overlay.remove();
            }
        }

        // Update overview configuration display with pretty format
        function updateOverviewConfigDisplay(configType, option) {
            if (configType === 'localConfig') {
                const valueElement = document.getElementById('overviewLocalConfigValue');
                const contentDiv = document.getElementById('overviewLocalConfigContent');
                
                if (valueElement) {
                    valueElement.textContent = option;
                    valueElement.style.color = 'var(--button-color)';
                    valueElement.style.backgroundColor = '#e3f2fd';
                    valueElement.style.borderLeftColor = 'var(--button-color)';
                }
            } else if (configType === 'plotOptions') {
                const valueElement = document.getElementById('overviewPlotValue');
                if (valueElement) {
                    if (option) {
                        valueElement.textContent = option;
                        valueElement.style.color = 'var(--button-color)';
                        valueElement.style.backgroundColor = '#e3f2fd';
                        valueElement.style.borderLeftColor = 'var(--button-color)';
                    } else {
                        // Clear the display when no option is selected
                        valueElement.textContent = 'None selected';
                        valueElement.style.color = '#666';
                        valueElement.style.backgroundColor = '#f8f9fa';
                        valueElement.style.borderLeftColor = 'var(--button-color)';
                    }
                }
            }
        }

        // Reset overview configuration display
        function resetOverviewConfigDisplay() {
            const localConfigValue = document.getElementById('overviewLocalConfigValue');
            const plotValue = document.getElementById('overviewPlotValue');
            const contentDiv = document.getElementById('overviewLocalConfigContent');
            
            if (localConfigValue) {
                localConfigValue.textContent = 'None selected';
                localConfigValue.style.color = '#666';
                localConfigValue.style.backgroundColor = '#f8f9fa';
                localConfigValue.style.borderLeftColor = 'var(--button-color)';
            }
            if (plotValue) {
                plotValue.textContent = 'None selected';
                plotValue.style.color = '#666';
                plotValue.style.backgroundColor = '#f8f9fa';
                plotValue.style.borderLeftColor = 'var(--button-color)';
            }
            
            // Hide JSON content
            if (contentDiv) {
                contentDiv.style.display = 'none';
            }
            
            // Hide summary section
            const summarySection = document.getElementById('overviewConfigSummary');
            if (summarySection) {
                summarySection.style.display = 'none';
            }
        }

        // Open image in modal for better viewing
        function openImageModal(imagePath) {
            // Create modal overlay
            const modal = document.createElement('div');
            modal.style.cssText = `
                position: fixed;
                top: 0;
                left: 0;
                width: 100%;
                height: 100%;
                background-color: rgba(0, 0, 0, 0.8);
                display: flex;
                justify-content: center;
                align-items: center;
                z-index: 1000;
                cursor: pointer;
            `;
            
            // Create image
            const img = document.createElement('img');
            img.src = imagePath;
            img.style.cssText = `
                max-width: 90%;
                max-height: 90%;
                border-radius: 8px;
                box-shadow: 0 4px 20px rgba(0, 0, 0, 0.5);
            `;
            
            // Close modal on click
            modal.onclick = () => document.body.removeChild(modal);
            
            modal.appendChild(img);
            document.body.appendChild(modal);
        }
    </script>
</body>
</html>
