// =============================================================================
// SECURITY GATE FUNCTIONALITY
// =============================================================================

/**
 * Hardcoded security code for dashboard access
 * Change this value to set your own 6-digit code
 */
const SECURITY_CODE = "123456"

/**
 * Local storage key for access granted flag
 */
const ACCESS_GRANTED_KEY = "optimizationFactoryAccessGranted"

/**
 * Checks if user has previously entered the correct security code
 * @returns {boolean} True if access is already granted
 */
function hasAccessGranted() {
  return localStorage.getItem(ACCESS_GRANTED_KEY) === "true"
}

/**
 * Grants persistent access by setting localStorage flag
 */
function grantAccess() {
  localStorage.setItem(ACCESS_GRANTED_KEY, "true")
}

/**
 * Revokes access by removing localStorage flag
 */
function revokeAccess() {
  localStorage.removeItem(ACCESS_GRANTED_KEY)
}

/**
 * Validates the entered security code
 * @param {string} code - The code entered by the user
 * @returns {boolean} True if the code is correct
 */
function validateSecurityCode(code) {
  return code === SECURITY_CODE
}

/**
 * Shows error message for incorrect code entry
 * @param {string} message - Error message to display
 */
function showSecurityError(message) {
  const errorEl = document.getElementById("errorMessage")
  errorEl.textContent = message
  errorEl.style.display = "block"

  // Hide error after 3 seconds
  setTimeout(() => {
    errorEl.style.display = "none"
  }, 3000)
}

/**
 * Handles security code submission
 */
function handleSecuritySubmit() {
  const codeInput = document.getElementById("securityCode")
  const enteredCode = codeInput.value.trim()

  if (!enteredCode) {
    showSecurityError("Please enter a security code")
    return
  }

  if (enteredCode.length !== 6) {
    showSecurityError("Security code must be 6 digits")
    codeInput.value = ""
    return
  }

  if (validateSecurityCode(enteredCode)) {
    // Correct code - grant access and show dashboard
    grantAccess()
    showDashboard()
  } else {
    // Incorrect code - show error and clear input
    showSecurityError("Incorrect security code. Please try again.")
    codeInput.value = ""
    codeInput.focus()
  }
}

/**
 * Shows the main dashboard and hides the security gate
 */
function showDashboard() {
  const securityGate = document.getElementById("securityGate")
  const mainContent = document.getElementById("mainContent")

  securityGate.style.display = "none"
  mainContent.style.display = "block"

  // Initialize the application
  initializeApp()
}

// Global variables for search and filtering
let allRepos = []
let filteredRepos = []

// Global variables for pagination
let currentPage = 1
let pageSize = 25
let totalCount = 0
let filterRunning = false
let isRefreshing = false
let targetPage = 1 // Track the target page the user wants to navigate to

/**
 * Initialize the main application functionality
 */
function initializeApp() {
  console.log("[App] Initializing application...")

  // Load repositories
  refreshRepos()

  // Set up event listeners
  setupEventListeners()

  // Initialize search functionality
  initializeSearch()

  console.log("[App] Application initialized successfully")
}

/**
 * Set up all event listeners
 */
function setupEventListeners() {
  // Security gate event listeners
  document.getElementById("submitCode")?.addEventListener("click", handleSecuritySubmit)
  document.getElementById("securityCode")?.addEventListener("keypress", (e) => {
    if (e.key === "Enter") {
      handleSecuritySubmit()
    }
  })

  // Main application event listeners
  document.getElementById("refresh")?.addEventListener("click", refreshRepos)
  document.getElementById("cleanupInstances")?.addEventListener("click", manualCleanupInstances)
  document.getElementById("add")?.addEventListener("click", addRepo)
  document.getElementById("update")?.addEventListener("click", updateRepo)

  // Pagination controls
  document.getElementById("pageInput")?.addEventListener("change", (e) => {
    const page = parseInt(e.target.value) || 1
    navigateToPage(page)
  })
  document.getElementById("pageSizeSelect")?.addEventListener("change", (e) => {
    pageSize = parseInt(e.target.value) || 0
    navigateToPage(1)
  })
  document.getElementById("filterRunning")?.addEventListener("change", (e) => {
    filterRunning = e.target.value === "running"
    navigateToPage(1)
  })

  // Tab switching
  document.getElementById("singleTab")?.addEventListener("click", () => switchTab("single"))
  document.getElementById("bulkTab")?.addEventListener("click", () => switchTab("bulk"))

  // CSV handling
  document.getElementById("csvFile")?.addEventListener("change", handleCsvFile)
  document.getElementById("validateCsv")?.addEventListener("click", validateCsv)
  document.getElementById("uploadCsv")?.addEventListener("click", uploadCsv)
  document.getElementById("downloadTemplate")?.addEventListener("click", downloadTemplate)

  // Analysis modal
  document.getElementById("closeAnalysisModal")?.addEventListener("click", closeAnalysisModal)
  document.getElementById("applyAnalysis")?.addEventListener("click", applyAnalysis)

  // Analysis Editor Modal
  document
    .getElementById("closeAnalysisEditorModal")
    ?.addEventListener("click", closeAnalysisEditorModal)
  document
    .getElementById("cancelAnalysisChanges")
    ?.addEventListener("click", closeAnalysisEditorModal)
  document.getElementById("saveAnalysisChanges")?.addEventListener("click", saveAnalysisChanges)

  // Logs Viewer Modal
  document.getElementById("closeLogsViewerModal")?.addEventListener("click", closeLogsViewerModal)
  document.getElementById("closeLogsViewerModal2")?.addEventListener("click", closeLogsViewerModal)
  document.getElementById("downloadAllLogs")?.addEventListener("click", fetchCurrentInstanceLogs)

  // Instructions Modal
  document.getElementById("readInstructionsBtn")?.addEventListener("click", openInstructionsModal)
  document
    .getElementById("closeInstructionsModal")
    ?.addEventListener("click", closeInstructionsModal)
  document
    .getElementById("closeInstructionsModal2")
    ?.addEventListener("click", closeInstructionsModal)

  // Auto-Termination Modal
  document
    .getElementById("closeAutoTerminationModal")
    ?.addEventListener("click", closeAutoTerminationModal)
  document
    .getElementById("cancelAutoTerminationSettings")
    ?.addEventListener("click", closeAutoTerminationModal)
  document
    .getElementById("saveAutoTerminationSettings")
    ?.addEventListener("click", saveAutoTerminationSettings)

  // SSH Connect Modal
  document.getElementById("closeSshConnectModal")?.addEventListener("click", closeSshConnectModal)
  document.getElementById("closeSshConnectModal2")?.addEventListener("click", closeSshConnectModal)
  document.getElementById("copySshCommand")?.addEventListener("click", copySshCommand)

  // Modal overlay click handlers
  document.getElementById("analysisEditorModal")?.addEventListener("click", (e) => {
    if (e.target.id === "analysisEditorModal") {
      closeAnalysisEditorModal()
    }
  })

  document.getElementById("logsViewerModal")?.addEventListener("click", (e) => {
    if (e.target.id === "logsViewerModal") {
      closeLogsViewerModal()
    }
  })

  document.getElementById("autoTerminationModal")?.addEventListener("click", (e) => {
    if (e.target.id === "autoTerminationModal") {
      closeAutoTerminationModal()
    }
  })

  document.getElementById("instructionsModal")?.addEventListener("click", (e) => {
    if (e.target.id === "instructionsModal") {
      closeInstructionsModal()
    }
  })

  document.getElementById("sshConnectModal")?.addEventListener("click", (e) => {
    if (e.target.id === "sshConnectModal") {
      closeSshConnectModal()
    }
  })
}

/**
 * Switch between single and bulk tabs
 */
function switchTab(tab) {
  const singleTab = document.getElementById("singleTab")
  const bulkTab = document.getElementById("bulkTab")
  const singleForm = document.getElementById("singleForm")
  const bulkForm = document.getElementById("bulkForm")

  if (tab === "single") {
    singleTab.classList.add("active")
    bulkTab.classList.remove("active")
    singleForm.classList.add("active")
    bulkForm.classList.remove("active")
  } else {
    singleTab.classList.remove("active")
    bulkTab.classList.add("active")
    singleForm.classList.remove("active")
    bulkForm.classList.add("active")
  }
}

/**
 * API helper function
 */
async function api(url, options = {}) {
  try {
    const response = await fetch(url, {
      headers: {
        "Content-Type": "application/json",
        ...options.headers,
      },
      ...options,
    })

    if (!response.ok) {
      const errorData = await response.json().catch(() => ({}))
      throw new Error(errorData.error || `HTTP ${response.status}`)
    }

    return await response.json()
  } catch (error) {
    console.error(`[API] Error calling ${url}:`, error)
    throw error
  }
}

/**
 * Manual cleanup of terminated instances only
 */
async function manualCleanupInstances() {
  const button = document.getElementById("cleanupInstances")
  if (!button) return

  // Show loading state
  const originalContent = button.innerHTML
  button.disabled = true
  button.innerHTML = "<span>⏳</span> Cleaning..."
  button.style.opacity = "0.8"

  try {
    console.log("[Cleanup] Manual cleanup requested...")
    const response = await api("/api/cleanup-terminated-instances", {
      method: "POST",
    })

    if (response.ok) {
      console.log(`[Cleanup] Manual cleanup completed: ${response.cleaned_count} instances cleaned`)
      if (response.cleaned_count > 0) {
        showSuccess(`Cleaned up ${response.cleaned_count} terminated instances`)
        // Refresh the repositories list to show updated data
        await refreshRepos()
      } else {
        showSuccess("No terminated instances found to clean up")
      }
    } else {
      console.error("[Cleanup] Manual cleanup failed:", response.error)
      showError(`Cleanup failed: ${response.error}`)
    }
  } catch (error) {
    console.error("[Cleanup] Error during manual cleanup:", error)
    showError(`Cleanup error: ${error.message}`)
  } finally {
    // Restore button state
    button.disabled = false
    button.innerHTML = originalContent
    button.style.opacity = "1"
  }
}

/**
 * Initialize search functionality
 */
function initializeSearch() {
  const searchInput = document.getElementById("repoSearch")
  if (searchInput) {
    searchInput.addEventListener("input", handleSearch)
    console.log("[Search] Search functionality initialized")
  }
}

/**
 * Handle search input changes
 */
function handleSearch(event) {
  const searchTerm = event.target.value.toLowerCase().trim()
  console.log("[Search] Searching for:", searchTerm)

  // Reset to page 1 when searching
  navigateToPage(1)

  // Search is performed client-side on already loaded data
  console.log(`[Search] Searching within ${allRepos.length} loaded repositories`)
}

/**
 * Sort repositories with running optimizations at the top
 */
function sortRepositories(repos) {
  return repos.sort((a, b) => {
    // Check if repositories have running instances
    const aHasRunning = a.last_ec2_id && a.last_ec2_id !== "None"
    const bHasRunning = b.last_ec2_id && b.last_ec2_id !== "None"

    // Running instances first
    if (aHasRunning && !bHasRunning) return -1
    if (!aHasRunning && bHasRunning) return 1

    // If both have running instances or both don't, sort by repository URL
    return a.repo_url.localeCompare(b.repo_url)
  })
}

/**
 * Refresh repositories list with pagination and filtering
 */
async function refreshRepos() {
  // Prevent multiple simultaneous requests
  if (isRefreshing) {
    console.log(`[Repos] Already refreshing, skipping request for page ${targetPage}`)
    return
  }

  isRefreshing = true

  try {
    console.log(`[Repos] Starting refresh for page ${targetPage}`)

    // Build URL with query parameters
    const params = new URLSearchParams()
    if (pageSize > 0) {
      params.append("page", targetPage.toString())
      params.append("page_size", pageSize.toString())
    }
    if (filterRunning) {
      params.append("filter_running", "true")
    }

    const url = `/api/repos/enriched${params.toString() ? "?" + params.toString() : ""}`
    console.log(`[Repos] Fetching URL: ${url}`)
    const response = await api(url)

    if (response.ok) {
      // Store all repositories globally
      allRepos = response.repos
      totalCount = response.total_count || allRepos.length
      currentPage = targetPage // Update to show we're now on this page

      console.log(
        `[Repos] Response received. Loaded page ${currentPage}, totalCount: ${totalCount}`,
      )

      // Apply current search filter if any
      const searchInput = document.getElementById("repoSearch")
      const searchTerm = searchInput ? searchInput.value.toLowerCase().trim() : ""

      if (searchTerm === "") {
        filteredRepos = [...allRepos]
      } else {
        filteredRepos = allRepos.filter((repo) => {
          const repoUrl = repo.repo_url.toLowerCase()
          const moduleRoot = (repo.module_root || "").toLowerCase()
          const testsRoot = (repo.tests_root || "").toLowerCase()
          const ec2Id = (repo.last_ec2_id || "").toLowerCase()
          const ipAddress = (repo.last_ec2_ip || "").toLowerCase()

          return (
            repoUrl.includes(searchTerm) ||
            moduleRoot.includes(searchTerm) ||
            testsRoot.includes(searchTerm) ||
            ec2Id.includes(searchTerm) ||
            ipAddress.includes(searchTerm)
          )
        })
      }

      // Sort and render repositories
      const sortedRepos = sortRepositories(filteredRepos)
      renderRepos(sortedRepos)
      updatePaginationControls()

      console.log(
        `[Repos] Loaded ${totalCount} total repositories, showing page ${currentPage} (${sortedRepos.length} on this page)`,
      )
    } else {
      console.error("[Repos] Failed to load repositories:", response.error)
    }
  } catch (error) {
    console.error("[Repos] Error refreshing repositories:", error)
  } finally {
    isRefreshing = false
    console.log(`[Repos] Finished refresh. currentPage: ${currentPage}, targetPage: ${targetPage}`)

    // Check if the target page changed while we were loading
    if (targetPage !== currentPage) {
      console.log(`[Repos] Target page changed to ${targetPage}, making another request`)
      refreshRepos()
    }
  }
}

/**
 * Navigate to a specific page
 */
function navigateToPage(page) {
  console.log(`[Pagination] navigateToPage called with: ${page}`)

  const maxPage = Math.ceil(totalCount / (pageSize || totalCount)) || 1
  if (page < 1) page = 1
  if (page > maxPage) page = maxPage

  // Update target page
  targetPage = page
  currentPage = page

  // Update UI immediately
  const pageInput = document.getElementById("pageInput")
  if (pageInput) {
    pageInput.value = currentPage
  }

  // If already refreshing, just update the target and let the current refresh complete
  // The refreshRepos function will check if we need to load a different page
  if (!isRefreshing) {
    console.log(`[Pagination] Starting refresh for page ${page}`)
    refreshRepos()
  } else {
    console.log(`[Pagination] Already refreshing, target page is now ${page}`)
  }
}

/**
 * Update pagination controls UI
 */
function updatePaginationControls() {
  const maxPage = Math.ceil(totalCount / (pageSize || totalCount)) || 1

  // Update page input
  const pageInput = document.getElementById("pageInput")
  if (pageInput) {
    pageInput.value = currentPage
    pageInput.max = maxPage
  }

  // Update total pages display
  const totalPagesSpan = document.getElementById("totalPages")
  if (totalPagesSpan) {
    totalPagesSpan.textContent = `of ${maxPage}`
  }

  // Update page info
  const startIdx = pageSize > 0 ? (currentPage - 1) * pageSize + 1 : 1
  const endIdx = pageSize > 0 ? Math.min(currentPage * pageSize, totalCount) : totalCount
  const pageInfo = document.getElementById("pageInfo")
  if (pageInfo) {
    pageInfo.textContent = `Showing ${startIdx}-${endIdx} of ${totalCount}`
  }
}

/**
 * Render repositories in the table
 */
function renderRepos(repos) {
  const tbody = document.querySelector("#repos tbody")
  if (!tbody) {
    return
  }

  tbody.innerHTML = ""

  repos.forEach((repo, index) => {
    const row = document.createElement("tr")

    // Repository URL
    const repoCell = document.createElement("td")
    repoCell.className = "col-repo"
    const autoTermEnabled = repo.auto_terminate === "true"
    const autoTermBadge = autoTermEnabled ? "✅ Auto-Term ON" : "❌ Auto-Term OFF"
    const autoTermClass = autoTermEnabled ? "enabled" : "disabled"
    repoCell.innerHTML = `
      <div class="repo-cell-content">
        <div class="repo-url-container">
          <a href="${repo.repo_url}" target="_blank" rel="noopener noreferrer" class="repo-url-link" title="${repo.repo_url}">
            ${repo.repo_url}
          </a>
          <span class="auto-terminate-badge ${autoTermClass}" title="${autoTermBadge}">${autoTermBadge}</span>
        </div>
        <button class="btn btn-sm btn-secondary btn-view-analysis" onclick="viewAnalysis('${repo.repo_url}')" title="View Analysis">
          <span>📊</span> View Analysis
        </button>
      </div>
    `

    // Module Root
    const moduleCell = document.createElement("td")
    moduleCell.className = "col-module"
    moduleCell.textContent = repo.module_root || "auto"

    // Tests Root
    const testsCell = document.createElement("td")
    testsCell.className = "col-tests"
    testsCell.textContent = repo.tests_root || "auto"

    // Last EC2 ID
    const ec2Cell = document.createElement("td")
    ec2Cell.className = "col-ec2"
    ec2Cell.textContent = repo.last_ec2_id || "None"

    // IP Address
    const ipCell = document.createElement("td")
    ipCell.className = "col-ip"
    ipCell.textContent = repo.last_ec2_ip || "None"

    // Actions
    const actionsCell = document.createElement("td")
    actionsCell.className = "col-actions"

    // Only show SSH button if there's a running instance
    const sshButton =
      repo.last_ec2_id && repo.last_ec2_id !== "None"
        ? `<button class="btn btn-info btn-sm" onclick="openSshConnect('${repo.repo_url}', '${repo.last_ec2_ip}')" title="SSH Connect">
          🖥️ SSH
        </button>`
        : ""

    actionsCell.innerHTML = `
      <div class="action-buttons">
        <button class="btn btn-primary btn-sm" onclick="runRepo('${repo.repo_url}')" title="Run Optimization">
          🚀 Run
        </button>
        <button class="btn btn-success btn-sm" onclick="analyzeRepo('${repo.repo_url}')" title="Generate Analysis">
          🔍 Analyze
        </button>
        <button class="btn btn-warning btn-sm" onclick="terminateRepo('${repo.repo_url}')" title="Terminate Instance">
          ⏹️ Terminate
        </button>
        <button class="btn btn-info btn-sm" onclick="viewLogs('${repo.repo_url}')" title="View Logs">
          📁 Logs
        </button>
        <button class="btn btn-secondary btn-sm" onclick="configureAutoTermination('${repo.repo_url}')" title="Configure Auto-Termination">
          ⚙️ Auto-Term
        </button>
        ${sshButton}
        <button class="btn btn-danger btn-sm" onclick="deleteRepo('${repo.repo_url}')" title="Delete Repository">
          🗑️ Delete
        </button>
        <button class="btn btn-info btn-sm" onclick="openCustomRunModal('${repo.repo_url}')" title="Custom Run">
          ⚙️ Custom Run
        </button>
      </div>
    `

    row.appendChild(repoCell)
    row.appendChild(moduleCell)
    row.appendChild(testsCell)
    row.appendChild(ec2Cell)
    row.appendChild(ipCell)
    row.appendChild(actionsCell)

    tbody.appendChild(row)
  })

  console.log(`[UI Debug] Successfully rendered ${repos.length} repositories`)
}

/**
 * Run optimization for a specific repository with loading state
 */
async function runRepo(repoUrl) {
  // Find the run button for this repo and show loading state
  const runButtons = document.querySelectorAll(`button[onclick*="runRepo('${repoUrl}')"]`)
  const originalContents = []

  runButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Starting..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Run] Starting optimization for:", repoUrl)
    showLoading("Starting optimization...")

    const response = await api("/api/run", {
      method: "POST",
      body: JSON.stringify({ repo_url: repoUrl }),
    })

    if (response.ok) {
      console.log("[Run] Optimization started successfully")
      showSuccess(`Optimization started for ${repoUrl}!`)
      refreshRepos()
    } else {
      console.error("[Run] Failed to start optimization:", response.error)
      showError(`Failed to start optimization: ${response.error}`)
    }
  } catch (error) {
    console.error("[Run] Error starting optimization:", error)
    showError(`Error starting optimization: ${error.message}`)
  } finally {
    hideLoading()
    // Restore button states
    runButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * Terminate instance for a specific repository with loading state
 */
async function terminateRepo(repoUrl) {
  // Find the terminate button for this repo and show loading state
  const terminateButtons = document.querySelectorAll(
    `button[onclick*="terminateRepo('${repoUrl}')"]`,
  )
  const originalContents = []

  terminateButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Terminating..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Terminate] Terminating instance for:", repoUrl)
    showLoading("Terminating EC2 instance...")

    const response = await api("/api/terminate", {
      method: "POST",
      body: JSON.stringify({ repo_url: repoUrl }),
    })

    if (response.ok) {
      console.log("[Terminate] Instance terminated successfully")
      showSuccess(`Instance terminated for ${repoUrl}`)
      refreshRepos()
    } else {
      console.error("[Terminate] Failed to terminate instance:", response.error)
      showError(`Failed to terminate instance: ${response.error}`)
    }
  } catch (error) {
    console.error("[Terminate] Error terminating instance:", error)
    showError(`Error terminating instance: ${error.message}`)
  } finally {
    hideLoading()
    // Restore button states
    terminateButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * Add a new repository
 */
async function addRepo() {
  const repoUrl = document.getElementById("repo_url").value.trim()

  if (!repoUrl) {
    alert("Please enter a repository URL")
    return
  }

  try {
    console.log("[Add] Adding repository:", repoUrl)
    const response = await api("/api/repos", {
      method: "POST",
      body: JSON.stringify({ repo_url: repoUrl }),
    })

    if (response.ok) {
      console.log("[Add] Repository added successfully")
      document.getElementById("repo_url").value = ""
      refreshRepos()
    } else {
      console.error("[Add] Failed to add repository:", response.error)
    }
  } catch (error) {
    console.error("[Add] Error adding repository:", error)
  }
}

/**
 * Delete a repository with confirmation and loading state
 */
async function deleteRepo(repoUrl) {
  // Show confirmation dialog
  const confirmed = confirm(
    `Are you sure you want to delete this repository?\n\n` +
      `Repository: ${repoUrl}\n\n` +
      `This will:\n` +
      `• Remove the repository from the configuration\n` +
      `• Clean up any job mappings\n` +
      `• NOT terminate any running instances (you'll need to do that manually)\n\n` +
      `This action cannot be undone.`,
  )

  if (!confirmed) {
    console.log("[Delete] User cancelled deletion")
    return
  }

  // Find the delete button for this repo and show loading state
  const deleteButtons = document.querySelectorAll(`button[onclick*="deleteRepo('${repoUrl}')"]`)
  const originalContents = []

  deleteButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Deleting..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Delete] Deleting repository:", repoUrl)
    showLoading("Deleting repository...")

    const response = await api(`/api/repos/${encodeURIComponent(repoUrl)}`, {
      method: "DELETE",
    })

    if (response.ok) {
      console.log("[Delete] Repository deleted successfully")

      // Show success message with any warnings
      let message = "Repository deleted successfully!"
      if (response.warning) {
        message += `\n\n⚠️ Warning: ${response.warning}`
        message += `\nInstance ID: ${response.instance_id}`
        message += `\nYou may want to terminate this instance manually.`
      }

      showSuccess(message)

      // Refresh the repositories list
      await refreshRepos()
    } else {
      console.error("[Delete] Failed to delete repository:", response.error)
      showError(`Failed to delete repository: ${response.error}`)
    }
  } catch (error) {
    console.error("[Delete] Error deleting repository:", error)
    showError(`Error deleting repository: ${error.message}`)
  } finally {
    hideLoading()
    // Restore button states
    deleteButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * Update repository configuration
 */
async function updateRepo() {
  const repoUrl = document.getElementById("repo_url").value.trim()

  if (!repoUrl) {
    alert("Please enter a repository URL")
    return
  }

  try {
    console.log("[Update] Updating repository:", repoUrl)
    const response = await api("/api/repos", {
      method: "PUT",
      body: JSON.stringify({ repo_url: repoUrl }),
    })

    if (response.ok) {
      console.log("[Update] Repository updated successfully")
      refreshRepos()
    } else {
      console.error("[Update] Failed to update repository:", response.error)
    }
  } catch (error) {
    console.error("[Update] Error updating repository:", error)
  }
}

// =============================================================================
// ENHANCED UI/UX FUNCTIONALITY
// =============================================================================

/**
 * View and edit analysis results for a repository
 */
async function viewAnalysis(repoUrl) {
  console.log("[Analysis] Viewing analysis for:", repoUrl)

  try {
    const response = await api(`/api/repos/${encodeURIComponent(repoUrl)}/analysis`)

    if (response.ok) {
      displayAnalysisEditor(response.analysis, repoUrl)
    } else {
      console.error("[Analysis] Failed to load analysis:", response.error)
      alert(`Failed to load analysis: ${response.error}`)
    }
  } catch (error) {
    console.error("[Analysis] Error loading analysis:", error)
    alert(`Error loading analysis: ${error.message}`)
  }
}

/**
 * Display the analysis editor modal with editable fields
 */
function displayAnalysisEditor(analysis, repoUrl) {
  console.log("[Analysis] Displaying editor for:", repoUrl)

  const modal = document.getElementById("analysisEditorModal")
  const content = document.getElementById("analysisEditorContent")

  if (!modal || !content) {
    console.error("[Analysis] Modal elements not found!")
    return
  }

  // Store current analysis for saving
  window.currentAnalysis = analysis
  window.currentAnalysisRepo = repoUrl

  content.innerHTML = `
    <div class="analysis-section">
      <h4>📦 Package Manager</h4>
      <div class="analysis-field">
        <label for="packageManager">Package Manager</label>
        <select id="packageManager">
          <option value="pip" ${analysis.package_manager === "pip" ? "selected" : ""}>pip</option>
          <option value="conda" ${
            analysis.package_manager === "conda" ? "selected" : ""
          }>conda</option>
          <option value="poetry" ${
            analysis.package_manager === "poetry" ? "selected" : ""
          }>poetry</option>
          <option value="pipenv" ${
            analysis.package_manager === "pipenv" ? "selected" : ""
          }>pipenv</option>
          <option value="uv" ${analysis.package_manager === "uv" ? "selected" : ""}>uv</option>
        </select>
        <div class="help-text">The package manager used for this repository</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>🐍 Python Packages</h4>
      <div class="analysis-field">
        <label for="pythonPackages">Python Packages (JSON)</label>
        <textarea id="pythonPackages" placeholder='[{"name": "requests", "version_spec": ">=2.25.0"}, {"name": "numpy"}]'>${JSON.stringify(
          analysis.python_packages || [],
          null,
          2,
        )}</textarea>
        <div class="help-text">JSON array of Python packages with optional version specifications</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>🔧 System Packages</h4>
      <div class="analysis-field">
        <label for="systemPackages">System Packages</label>
        <input type="text" id="systemPackages" value="${
          analysis.system_packages || ""
        }" placeholder="build-essential git curl">
        <div class="help-text">Space-separated list of system packages to install</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>📁 Directory Structure</h4>
      <div class="analysis-field">
        <label for="moduleRoot">Module Root</label>
        <input type="text" id="moduleRoot" value="${
          analysis.codeflash?.module_root || ""
        }" placeholder="src">
        <div class="help-text">Root directory containing the main Python modules</div>
      </div>
      <div class="analysis-field">
        <label for="testsRoot">Tests Root</label>
        <input type="text" id="testsRoot" value="${
          analysis.codeflash?.tests_root || ""
        }" placeholder="tests">
        <div class="help-text">Root directory containing test files</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>🧪 Test Configuration</h4>
      <div class="analysis-field">
        <label for="testCommand">Test Command</label>
        <input type="text" id="testCommand" value="${
          analysis.tests?.test_command || ""
        }" placeholder="pytest tests/">
        <div class="help-text">Command to run tests</div>
      </div>
      <div class="analysis-field">
        <label for="testFramework">Test Framework</label>
        <select id="testFramework">
          <option value="pytest" ${
            analysis.tests?.test_framework === "pytest" ? "selected" : ""
          }>pytest</option>
          <option value="unittest" ${
            analysis.tests?.test_framework === "unittest" ? "selected" : ""
          }>unittest</option>
          <option value="nose" ${
            analysis.tests?.test_framework === "nose" ? "selected" : ""
          }>nose</option>
        </select>
        <div class="help-text">The test framework used by this project</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>🎨 Code Formatting</h4>
      <div class="analysis-field">
        <label for="formatterCommands">Formatter Commands (JSON)</label>
        <textarea id="formatterCommands" placeholder='["black .", "isort ."]'>${JSON.stringify(
          analysis.codeflash?.formatter_cmds || [],
          null,
          2,
        )}</textarea>
        <div class="help-text">JSON array of commands to format code</div>
      </div>
    </div>

    <div class="analysis-section">
      <h4>📊 Confidence & Metadata</h4>
      <div class="analysis-field">
        <label for="confidence">Confidence Score</label>
        <input type="number" id="confidence" min="0" max="1" step="0.1" value="${
          analysis.confidence || 0.5
        }">
        <div class="help-text">Confidence score from 0.0 to 1.0</div>
      </div>
    </div>
  `

  modal.style.display = "flex"
  console.log("[Analysis] Editor displayed successfully")
}

/**
 * Save analysis changes
 */
async function saveAnalysisChanges() {
  if (!window.currentAnalysis || !window.currentAnalysisRepo) {
    alert("No analysis data to save")
    return
  }

  try {
    console.log("[Analysis] Saving changes...")

    // Collect form data
    const updatedAnalysis = {
      ...window.currentAnalysis,
      package_manager: document.getElementById("packageManager").value,
      system_packages: document.getElementById("systemPackages").value,
      confidence: parseFloat(document.getElementById("confidence").value),
      codeflash: {
        ...window.currentAnalysis.codeflash,
        module_root: document.getElementById("moduleRoot").value,
        tests_root: document.getElementById("testsRoot").value,
        formatter_cmds: JSON.parse(document.getElementById("formatterCommands").value || "[]"),
      },
      tests: {
        ...window.currentAnalysis.tests,
        test_command: document.getElementById("testCommand").value,
        test_framework: document.getElementById("testFramework").value,
      },
      python_packages: JSON.parse(document.getElementById("pythonPackages").value || "[]"),
    }

    const response = await api(
      `/api/repos/${encodeURIComponent(window.currentAnalysisRepo)}/analysis`,
      {
        method: "PUT",
        body: JSON.stringify({ analysis: updatedAnalysis }),
      },
    )

    if (response.ok) {
      console.log("[Analysis] Changes saved successfully")
      alert("Analysis updated successfully!")
      closeAnalysisEditorModal()
      refreshRepos()
    } else {
      console.error("[Analysis] Failed to save changes:", response.error)
      alert(`Failed to save analysis: ${response.error}`)
    }
  } catch (error) {
    console.error("[Analysis] Error saving changes:", error)
    alert(`Error saving analysis: ${error.message}`)
  }
}

/**
 * Close the analysis editor modal
 */
function closeAnalysisEditorModal() {
  document.getElementById("analysisEditorModal").style.display = "none"
  window.currentAnalysis = null
  window.currentAnalysisRepo = null
}

/**
 * Close the logs viewer modal
 */
function closeLogsViewerModal() {
  const modal = document.getElementById("logsViewerModal")
  if (modal) {
    modal.style.display = "none"
  }
}

/**
 * View archived logs for a repository
 */
async function viewLogs(repoUrl) {
  console.log("[Logs] Viewing logs for:", repoUrl)

  // Show loading state immediately
  showLogsLoadingState(repoUrl)

  try {
    const response = await api(`/api/repos/${encodeURIComponent(repoUrl)}/logs`)

    if (response.ok) {
      await displayLogsViewer(response.logs, repoUrl)
    } else {
      console.error("[Logs] Failed to load logs:", response.error)
      hideLogsLoadingState()
      alert(`Failed to load logs: ${response.error}`)
    }
  } catch (error) {
    console.error("[Logs] Error loading logs:", error)
    hideLogsLoadingState()
    alert(`Error loading logs: ${error.message}`)
  }
}

/**
 * Show loading state for logs dialog
 */
function showLogsLoadingState(repoUrl) {
  const modal = document.getElementById("logsViewerModal")
  const content = document.getElementById("logsViewerContent")

  if (!modal || !content) return

  // Store current repo for downloads
  window.currentLogsRepo = repoUrl

  content.innerHTML = `
    <div style="text-align: center; padding: 60px; color: #6b7280;">
      <div style="font-size: 48px; margin-bottom: 16px; animation: spin 1s linear infinite;">⏳</div>
      <h3>Loading Logs...</h3>
      <p>Fetching archived logs for ${repoUrl}</p>
    </div>
  `

  modal.style.display = "flex"

  // Add CSS animation for spinner
  if (!document.getElementById("spinnerStyles")) {
    const style = document.createElement("style")
    style.id = "spinnerStyles"
    style.textContent = `
      @keyframes spin {
        0% { transform: rotate(0deg); }
        100% { transform: rotate(360deg); }
      }
    `
    document.head.appendChild(style)
  }
}

/**
 * Hide loading state for logs dialog
 */
function hideLogsLoadingState() {
  const modal = document.getElementById("logsViewerModal")
  if (modal) {
    modal.style.display = "none"
  }
}

/**
 * Display the logs viewer modal
 */
async function displayLogsViewer(logs, repoUrl) {
  console.log("[Logs] Displaying logs viewer for:", repoUrl)

  const modal = document.getElementById("logsViewerModal")
  const content = document.getElementById("logsViewerContent")

  if (!modal || !content) {
    console.error("[Logs] Modal elements not found!")
    return
  }

  // Store current repo for downloads
  window.currentLogsRepo = repoUrl

  // Check if there's a running instance for this repository
  let hasRunningInstance = false
  let instanceInfo = null

  try {
    const reposResponse = await api("/api/repos/enriched")
    if (reposResponse.ok) {
      const repo = reposResponse.repos.find((r) => r.repo_url === repoUrl)
      if (repo && repo.last_ec2_id && repo.last_ec2_id !== "None") {
        hasRunningInstance = true
        instanceInfo = {
          instance_id: repo.last_ec2_id,
          ip_address: repo.last_ec2_ip,
        }
      }
    }
  } catch (error) {
    console.error("[Logs] Error checking for running instance:", error)
  }

  // Update the fetch button state (check for existing fetch status)
  const currentlyFetching = isCurrentlyFetching(repoUrl)
  updateFetchLogsButton(hasRunningInstance, currentlyFetching)

  if (logs.length === 0) {
    content.innerHTML = `
      <div style="text-align: center; padding: 40px; color: #6b7280;">
        <div style="font-size: 48px; margin-bottom: 16px;">📁</div>
        <h3>No Logs Found</h3>
        <p>No archived logs found for this repository.</p>
        ${
          hasRunningInstance
            ? `
          <div style="margin-top: 20px; padding: 16px; background: #e3f2fd; border-radius: 8px; border-left: 4px solid #2196f3;">
            <strong>🔄 Running Instance Detected:</strong><br>
            <span style="font-family: monospace; font-size: 13px;">
              Instance ID: ${instanceInfo.instance_id}<br>
              IP Address: ${instanceInfo.ip_address}
            </span>
            <div style="margin-top: 8px; font-size: 13px; color: #1976d2;">
              Click "Fetch Current Instance Logs" to download and archive logs from this running instance.
            </div>
          </div>
        `
            : ""
        }
      </div>
    `
  } else {
    content.innerHTML = `
      <div style="margin-bottom: 20px;">
        <h4>📁 Archived Logs for ${repoUrl}</h4>
        <p style="color: #6b7280; margin: 8px 0;">Found ${logs.length} log session(s)</p>
        ${
          hasRunningInstance
            ? `
          <div style="margin-top: 12px; padding: 12px; background: #e8f5e8; border-radius: 6px; border-left: 4px solid #4caf50;">
            <strong>🔄 Running Instance:</strong> ${instanceInfo.instance_id} (${instanceInfo.ip_address})
            <div style="margin-top: 4px; font-size: 13px; color: #2e7d32;">
              Click "Fetch Current Instance Logs" to download and archive logs from this running instance.
            </div>
          </div>
        `
            : ""
        }
      </div>
      
      ${logs
        .map(
          (session) => `
        <div class="logs-session">
          <div class="logs-session-header">
            <div class="logs-session-title">${session.session_id}</div>
            <div class="logs-session-date">${new Date(
              Math.max(
                ...session.files.map((f) =>
                  f.modified_iso ? new Date(f.modified_iso).getTime() : f.modified * 1000,
                ),
              ),
            ).toLocaleString()}</div>
            <div class="logs-session-actions">
              <button class="btn btn-sm btn-success" onclick="downloadLogFolder('${
                session.session_id
              }')" title="Download Entire Folder">
                📁 Download Folder
              </button>
            </div>
          </div>
          <div class="logs-files-list">
            ${session.files
              .map(
                (file) => `
              <div class="log-file-item">
                <div class="log-file-info">
                  <div class="log-file-name">${file.filename}</div>
                  <div class="log-file-meta">
                    ${formatFileSize(file.size_bytes)} • ${new Date(
                  file.modified_iso ? new Date(file.modified_iso).getTime() : file.modified * 1000,
                ).toLocaleString()}
                  </div>
                </div>
                <div class="log-file-actions">
                  <button class="btn btn-sm btn-primary" onclick="downloadLogFile('${
                    file.path
                  }')" title="Download">
                    📥 Download
                  </button>
                  <button class="btn btn-sm btn-secondary" onclick="viewLogFile('${
                    file.path
                  }')" title="View">
                    👁️ View
                  </button>
                </div>
              </div>
            `,
              )
              .join("")}
          </div>
        </div>
      `,
        )
        .join("")}
    `
  }

  modal.style.display = "flex"
  console.log("[Logs] Logs viewer displayed successfully")
}

/**
 * Download a specific log file with loading state
 */
async function downloadLogFile(filePath) {
  // Find all download buttons for this file and show loading state
  const downloadButtons = document.querySelectorAll(
    `button[onclick*="downloadLogFile('${filePath}')"]`,
  )
  const originalContents = []

  downloadButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Downloading..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Logs] Downloading log file:", filePath)
    const response = await fetch(`/api/logs/download?path=${encodeURIComponent(filePath)}`)

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = filePath.split("/").pop()
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)

      console.log("[Logs] Log file downloaded successfully")
      showSuccess("Log file downloaded successfully!")
    } else {
      console.error("[Logs] Failed to download log file")
      const errorData = await response.json().catch(() => ({}))
      showError(`Failed to download log file: ${errorData.error || "Unknown error"}`)
    }
  } catch (error) {
    console.error("[Logs] Error downloading log file:", error)
    showError(`Error downloading log file: ${error.message}`)
  } finally {
    // Restore button states
    downloadButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * Download an entire log session folder as ZIP with loading state
 */
async function downloadLogFolder(sessionId) {
  // Find all download folder buttons for this session and show loading state
  const downloadButtons = document.querySelectorAll(
    `button[onclick*="downloadLogFolder('${sessionId}')"]`,
  )
  const originalContents = []

  downloadButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Creating ZIP..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Logs] Downloading log folder:", sessionId)
    const response = await fetch(
      `/api/logs/download_folder?session_id=${encodeURIComponent(sessionId)}`,
    )

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = `${sessionId}_logs.zip`
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)

      console.log("[Logs] Log folder downloaded successfully")
      showSuccess("Log folder downloaded successfully!")
    } else {
      console.error("[Logs] Failed to download log folder")
      const errorData = await response.json().catch(() => ({}))
      showError(`Failed to download log folder: ${errorData.error || "Unknown error"}`)
    }
  } catch (error) {
    console.error("[Logs] Error downloading log folder:", error)
    showError(`Error downloading log folder: ${error.message}`)
  } finally {
    // Restore button states
    downloadButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * View a log file content with loading state
 */
async function viewLogFile(filePath) {
  // Find the view button for this file and show loading state
  const viewButtons = document.querySelectorAll(`button[onclick*="viewLogFile('${filePath}')"]`)
  const originalContents = []

  viewButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Loading..."
    button.style.opacity = "0.7"
  })

  try {
    const response = await fetch(`/api/logs/download?path=${encodeURIComponent(filePath)}`)

    if (response.ok) {
      const content = await response.text()

      // Create a new modal for viewing log content
      const modal = document.createElement("div")
      modal.className = "modal-overlay"
      modal.style.display = "flex"
      modal.innerHTML = `
        <div class="modal-content large-modal">
          <div class="modal-header">
            <h3>📄 ${filePath.split("/").pop()}</h3>
            <button onclick="this.closest('.modal-overlay').remove()" class="btn btn-secondary btn-sm">✕</button>
    </div>
          <div class="modal-body">
            <pre style="background: #f8f9fa; padding: 16px; border-radius: 8px; overflow: auto; max-height: 60vh; font-family: 'Courier New', monospace; font-size: 12px; line-height: 1.4;">${escapeHtml(
              content,
            )}</pre>
    </div>
          <div class="modal-footer">
            <button onclick="downloadLogFile('${filePath}')" class="btn btn-primary">📥 Download</button>
            <button onclick="this.closest('.modal-overlay').remove()" class="btn btn-secondary">✕ Close</button>
    </div>
    </div>
  `

      document.body.appendChild(modal)
    } else {
      console.error("[Logs] Failed to load file content")
      alert("Failed to load log file content")
    }
  } catch (error) {
    console.error("[Logs] Error viewing file:", error)
    alert(`Error viewing log file: ${error.message}`)
  } finally {
    // Restore button states
    viewButtons.forEach((button, index) => {
      button.disabled = false
      button.innerHTML = originalContents[index]
      button.style.opacity = "1"
    })
  }
}

/**
 * Configure auto-termination settings for a repository
 */
async function configureAutoTermination(repoUrl) {
  console.log("[Auto-Termination] Configuring for:", repoUrl)

  try {
    // Get current repository data
    const repos = await api("/api/repos/enriched")
    const repo = repos.repos.find((r) => r.repo_url === repoUrl)

    if (!repo) {
      console.error("[Auto-Termination] Repository not found")
      alert("Repository not found")
      return
    }

    displayAutoTerminationSettings(repo)
  } catch (error) {
    console.error("[Auto-Termination] Error loading settings:", error)
    alert(`Error loading settings: ${error.message}`)
  }
}

/**
 * Display the auto-termination settings modal
 */
function displayAutoTerminationSettings(repo) {
  console.log("[Auto-Termination] Displaying settings for:", repo.repo_url)

  const modal = document.getElementById("autoTerminationModal")
  const content = document.getElementById("autoTerminationContent")

  if (!modal || !content) {
    console.error("[Auto-Termination] Modal elements not found!")
    return
  }

  // Store current repo for saving
  window.currentAutoTermRepo = repo

  const autoTermEnabled = repo.auto_terminate === "true"
  const hasRunningInstance = repo.last_ec2_id && repo.last_ec2_id !== "None"

  content.innerHTML = `
    <div class="auto-termination-setting">
      <div class="auto-termination-info">
        <h4>${repo.repo_url}</h4>
        <p>Configure automatic instance termination when optimization completes</p>
        ${
          hasRunningInstance
            ? `
          <div style="margin-top: 12px; padding: 12px; background: #e3f2fd; border-radius: 6px; border-left: 4px solid #2196f3;">
            <strong>🔄 Currently Running Instance:</strong><br>
            <span style="font-family: monospace; font-size: 13px;">
              Instance ID: ${repo.last_ec2_id}<br>
              IP Address: ${repo.last_ec2_ip}
            </span>
            <div style="margin-top: 8px; font-size: 13px; color: #1976d2;">
              ${
                autoTermEnabled
                  ? "✅ Auto-termination is enabled - this instance will be terminated when optimization completes"
                  : "ℹ️ Auto-termination is disabled - this instance will remain running after optimization completes"
              }
            </div>
          </div>
        `
            : ""
        }
      </div>
      <div class="toggle-switch ${
        autoTermEnabled ? "active" : ""
      }" id="autoTermToggle" onclick="toggleAutoTermination()">
      </div>
    </div>
    
    <div style="margin-top: 20px; padding: 16px; background: #f8f9fa; border-radius: 8px;">
      <h4 style="margin: 0 0 12px 0; color: #374151;">ℹ️ Auto-Termination Information</h4>
      <ul style="margin: 0; padding-left: 20px; color: #6b7280; font-size: 14px; line-height: 1.6;">
        <li><strong>Enabled:</strong> EC2 instances will be automatically terminated when optimization jobs complete</li>
        <li><strong>Disabled:</strong> EC2 instances will remain running and must be manually terminated</li>
        <li><strong>Cost Impact:</strong> Enabling auto-termination helps reduce AWS costs by stopping unused instances</li>
        <li><strong>Manual Override:</strong> You can always manually terminate instances regardless of this setting</li>
        <li><strong>Dynamic Control:</strong> You can enable/disable auto-termination at any time, even while optimization is running</li>
      </ul>
    </div>
  `

  modal.style.display = "flex"
  console.log("[Auto-Termination] Settings displayed successfully")
}

/**
 * Toggle auto-termination setting
 */
function toggleAutoTermination() {
  const toggle = document.getElementById("autoTermToggle")
  toggle.classList.toggle("active")
}

/**
 * Save auto-termination settings
 */
async function saveAutoTerminationSettings() {
  if (!window.currentAutoTermRepo) {
    alert("No repository selected for saving")
    return
  }

  try {
    console.log("[Auto-Termination] Saving settings...")

    const toggle = document.getElementById("autoTermToggle")
    const autoTermEnabled = toggle.classList.contains("active")

    const response = await api(
      `/api/repos/${encodeURIComponent(window.currentAutoTermRepo.repo_url)}/auto_terminate`,
      {
        method: "PUT",
        body: JSON.stringify({ auto_terminate: autoTermEnabled }),
      },
    )

    if (response.ok) {
      console.log("[Auto-Termination] Settings saved successfully:", response)

      // Enhanced success message with running instance information
      let successMessage = `Auto-termination ${
        autoTermEnabled ? "enabled" : "disabled"
      } successfully!`

      if (response.running_instance) {
        const instance = response.running_instance
        if (autoTermEnabled) {
          successMessage += `\n\n✅ Completion watcher started for running instance ${instance.instance_id} (${instance.public_ip})`
          successMessage += `\nThe instance will be automatically terminated when optimization completes.`
        } else {
          successMessage += `\n\nℹ️ Running instance ${instance.instance_id} (${instance.public_ip}) will remain active after optimization completes.`
          successMessage += `\nYou can manually terminate it when needed.`
        }
      }

      alert(successMessage)
      closeAutoTerminationModal()
      refreshRepos()
    } else {
      console.error("[Auto-Termination] Failed to save settings:", response.error)
      alert(`Failed to save settings: ${response.error}`)
    }
  } catch (error) {
    console.error("[Auto-Termination] Error saving settings:", error)
    alert(`Error saving settings: ${error.message}`)
  }
}

/**
 * Close the auto-termination modal
 */
function closeAutoTerminationModal() {
  document.getElementById("autoTerminationModal").style.display = "none"
  window.currentAutoTermRepo = null
}

/**
 * Open SSH Connect modal
 */
async function openSshConnect(repoUrl, ipAddress) {
  const modal = document.getElementById("sshConnectModal")
  const sshCommandEl = document.getElementById("sshCommand")

  if (!modal || !sshCommandEl) {
    console.error("[SSH] Modal elements not found!")
    return
  }

  try {
    // Fetch SSH configuration from server
    const response = await api("/api/ssh-config")

    if (response.ok) {
      // Hardcoded SSH key path for WSL
      const sshKeyPath = "/mnt/c/Users/Ashraf/Downloads/Deployed_Optimization_Factory_key_pair.pem"
      const user = response.user || "ubuntu"

      // Extract org/repo from repository URL
      const match =
        repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+)/) ||
        repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+?)(?:\.git)?$/)
      const repoName = match ? `${match[1]}/${match[2]}` : "Optimization"

      // Create SSH command with terminal title rename for Ubuntu/Linux/WSL
      // Set title locally before SSH connection to ensure it works in WSL
      // Add -o StrictHostKeyChecking=no to skip host verification
      const sshCommand = `echo -en '\\033]0;${repoName}\\007' && sudo ssh -i "${sshKeyPath}" -o StrictHostKeyChecking=no ${user}@${ipAddress}`

      sshCommandEl.textContent = sshCommand
      modal.style.display = "flex"

      console.log(`[SSH] Opening SSH connect modal for ${repoUrl} at ${ipAddress}`)
    } else {
      console.error("[SSH] Failed to get SSH config:", response.error)
      alert("Failed to get SSH configuration")
    }
  } catch (error) {
    console.error("[SSH] Error getting SSH config:", error)
    // Fallback: show generic SSH command with title
    const match = repoUrl.match(/github\.com\/([^\/]+)\/([^\/]+)/)
    const repoName = match ? `${match[1]}/${match[2]}` : "Optimization"
    const sshKeyPath = "/mnt/c/Users/Ashraf/Downloads/Deployed_Optimization_Factory_key_pair.pem"
    const sshCommand = `echo -en '\\033]0;${repoName}\\007' && sudo ssh -i "${sshKeyPath}" -o StrictHostKeyChecking=no ubuntu@${ipAddress}`
    sshCommandEl.textContent = sshCommand
    modal.style.display = "flex"
  }
}

/**
 * Close SSH Connect modal
 */
function closeSshConnectModal() {
  document.getElementById("sshConnectModal").style.display = "none"
}

/**
 * Copy SSH command to clipboard
 */
async function copySshCommand() {
  const sshCommandEl = document.getElementById("sshCommand")
  const copyBtn = document.getElementById("copySshCommand")

  if (!sshCommandEl || !copyBtn) return

  try {
    await navigator.clipboard.writeText(sshCommandEl.textContent)

    const originalText = copyBtn.innerHTML
    copyBtn.innerHTML = "✅ Copied!"
    copyBtn.disabled = true

    setTimeout(() => {
      copyBtn.innerHTML = originalText
      copyBtn.disabled = false
    }, 2000)

    console.log("[SSH] Command copied to clipboard")
  } catch (error) {
    console.error("[SSH] Failed to copy:", error)
    // Fallback for older browsers
    const textArea = document.createElement("textarea")
    textArea.value = sshCommandEl.textContent
    document.body.appendChild(textArea)
    textArea.select()
    document.execCommand("copy")
    document.body.removeChild(textArea)
  }
}

/**
 * Open the instructions modal with comprehensive usage guide
 */
function openInstructionsModal() {
  const modal = document.getElementById("instructionsModal")
  const content = document.getElementById("instructionsContent")

  if (!modal || !content) {
    console.error("[Instructions] Modal elements not found!")
    return
  }

  content.innerHTML = `
    <div class="instruction-step">
      <h4>🔍 Step 1: Analyze Your Repository</h4>
      <p>Before running any optimization, you must first analyze your repository to understand its structure and requirements.</p>
      <ul>
        <li>Click the <strong>🔍 Analyze</strong> button next to your repository</li>
        <li>Wait for the analysis to complete (this may take a few minutes)</li>
        <li>Check the analysis results by clicking the <strong>📊</strong> icon in the repository row</li>
        <li>Review and edit the analysis results if needed</li>
      </ul>
    </div>

    <div class="instruction-step">
      <h4>🚀 Step 2: Run Optimization</h4>
      <p>Once analysis is complete, you can start the optimization process.</p>
      <ul>
        <li>Click the <strong>🚀 Run</strong> button for standard optimization</li>
        <li>Or use <strong>⚙️ Custom Run</strong> for advanced configuration (Beta)</li>
        <li>Wait for the EC2 instance to be created and initialized</li>
        <li>Monitor the <strong>Last EC2 ID</strong> and <strong>IP Address</strong> columns</li>
      </ul>
    </div>

    <div class="instruction-step">
      <h4>☁️ Step 3: Connect to AWS Instance</h4>
      <p>Connect to your running EC2 instance in AWS Ohio (us-east-2) region.</p>
      <p>Look for instances with names starting with your repository name or the EC2 instance ID in aws console.</p>
    </div>

    <div class="instruction-step">
      <h4>📊 Step 4: Monitor the Process</h4>
      <p>Check the current running processes and directory structure.</p>
      <div class="code-block">
        <code>ps -ef</code>
      </div>
      <p>Check the root directory structure:</p>
      <ul>
        <li><strong>Only "app" folder:</strong> Backend is still generating scripts</li>
        <li><strong>"app", "python", and "work" folders:</strong> Ready for optimization</li>
      </ul>
    </div>

    <div class="instruction-step">
      <h4>📁 Step 5: Understanding the Directory Structure</h4>
      <p>Once fully initialized, you'll see these directories:</p>
      <ul>
        <li><strong>app/</strong> - Contains scripts and logs</li>
        <li><strong>work/repo/</strong> - Contains the repository to be optimized</li>
      </ul>
      <div class="info-box">
        <strong>Logs Location:</strong> Check <code>app/logs/</code> for all log files
      </div>
    </div>

    <div class="instruction-step">
      <h4>📋 Step 6: Tracking Optimization Progress</h4>
      <p>Monitor the optimization process through log files:</p>
      <ul>
        <li><strong>stage.jsonl</strong> - Shows current script execution stage</li>
        <li><strong>optimization-$(date +"%Y-%m-%dT%H-%M-%S-00-00").log</strong> - Main optimization logs</li>
        <li><strong>launcher.log</strong> - Launcher script logs</li>
      </ul>
      <div class="code-block">
        <code>tail -f app/logs/optimization-$(date +"%Y-%m-%dT%H-%M-%S-00-00").log</code>
      </div>
    </div>

    <div class="instruction-step">
      <h4>⚠️ Step 7: Handling Common Issues</h4>
      
      <div class="warning-box">
        <strong>Tests Pass but Using Claude CLI Fallback:</strong>
        <p>If tests pass but the script uses Claude CLI instead of Codeflash:</p>
        <ol>
          <li>Kill all related processes: <code>pkill -f "run_job\|optimization\|claude\|tests"</code></li>
          <li>Navigate to work directory: <code>cd work/repo/</code></li>
          <li>Activate virtual environment: <code>source .venv/bin/activate</code></li>
          <li>Set API key: <code>export CODEFLASH_API_KEY="YOUR_KEY_HERE"</code></li>
          <li>Run Codeflash manually: <code>nohup setsid codeflash --all --verbose --async > /app/logs/optimization-$(date +"%Y-%m-%dT%H-%M-%S-00-00").log 2>&1 &</code></li>
        </ol>
      </div>

      <div class="warning-box">
        <strong>Tests Failing:</strong>
        <p>If tests are failing:</p>
        <ul>
          <li>Let Claude CLI fix the failing tests first</li>
          <li>Monitor for "skipping optimization" after two rounds</li>
          <li>If optimization is skipped due to test failures, set up manually as above</li>
        </ul>
      </div>

      <div class="info-box">
        <strong>Missing Modules:</strong>
        <p>Even when tests pass, sometimes modules are missing during optimization. In rare cases, you may need to manually kill the Codeflash process and re-run it after installing missing packages.</p>
      </div>
    </div>

    <div class="instruction-step">
      <h4>✅ Step 8: Success Indicators</h4>
      <p>You'll know everything is working when:</p>
      <ul>
        <li>Tests pass consistently</li>
        <li>Codeflash optimization starts automatically</li>
        <li>Logs show successful optimization progress</li>
        <li>No manual intervention is required</li>
      </ul>
      <div class="info-box">
        <strong>Most Common Scenario:</strong> Everything runs automatically without any manual intervention needed!
      </div>
    </div>
  `

  modal.style.display = "flex"
  console.log("[Instructions] Instructions modal opened")
}

/**
 * Close the instructions modal
 */
function closeInstructionsModal() {
  const modal = document.getElementById("instructionsModal")
  if (modal) {
    modal.style.display = "none"
    console.log("[Instructions] Instructions modal closed")
  }
}

/**
 * Update the fetch logs button state with persistence
 */
function updateFetchLogsButton(hasRunningInstance, isFetching = false) {
  const button = document.getElementById("downloadAllLogs")
  if (!button) return

  // Check if we're currently fetching logs for this repo
  const currentRepo = window.currentLogsRepo
  const fetchKey = `fetching_logs_${currentRepo}`
  const isCurrentlyFetching = localStorage.getItem(fetchKey) === "true"

  if (isFetching || isCurrentlyFetching) {
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Fetching Logs..."
    button.title = "Currently fetching logs from the running EC2 instance"
    button.style.opacity = "0.8"
  } else if (hasRunningInstance) {
    button.disabled = false
    button.innerHTML = "<span>🔄</span> Fetch Current Instance Logs"
    button.title = "Download and archive logs from the running EC2 instance"
    button.style.opacity = "1"
  } else {
    button.disabled = true
    button.innerHTML = "<span>⏸️</span> No Running Instance"
    button.title = "No running EC2 instance found for this repository"
    button.style.opacity = "0.6"
  }
}

/**
 * Set fetching status in localStorage
 */
function setFetchingStatus(repoUrl, isFetching) {
  const fetchKey = `fetching_logs_${repoUrl}`
  if (isFetching) {
    localStorage.setItem(fetchKey, "true")
  } else {
    localStorage.removeItem(fetchKey)
  }
}

/**
 * Check if logs are currently being fetched for a repo
 */
function isCurrentlyFetching(repoUrl) {
  const fetchKey = `fetching_logs_${repoUrl}`
  return localStorage.getItem(fetchKey) === "true"
}

/**
 * Fetch logs from current running instance and archive to S3
 */
async function fetchCurrentInstanceLogs() {
  if (!window.currentLogsRepo) {
    alert("No repository selected")
    return
  }

  const button = document.getElementById("downloadAllLogs")
  if (!button) return

  // Set fetching status
  setFetchingStatus(window.currentLogsRepo, true)
  updateFetchLogsButton(true, true)

  try {
    console.log("[Logs] Fetching logs from current instance...")
    const response = await api(
      `/api/logs/download_all?repo_url=${encodeURIComponent(window.currentLogsRepo)}`,
    )

    if (response.ok) {
      console.log("[Logs] Logs fetched and archived successfully")
      showSuccess(`Logs successfully fetched and archived to S3!`)

      // Refresh the logs viewer to show the new logs
      await refreshLogsViewer()
    } else {
      console.error("[Logs] Failed to fetch logs:", response.error)
      showError(`Failed to fetch logs: ${response.error}`)
    }
  } catch (error) {
    console.error("[Logs] Error fetching logs:", error)
    showError(`Error fetching logs: ${error.message}`)
  } finally {
    // Clear fetching status
    setFetchingStatus(window.currentLogsRepo, false)

    // Check if we still have a running instance
    try {
      const reposResponse = await api("/api/repos/enriched")
      let hasRunningInstance = false
      if (reposResponse.ok) {
        const repo = reposResponse.repos.find((r) => r.repo_url === window.currentLogsRepo)
        hasRunningInstance = repo && repo.last_ec2_id && repo.last_ec2_id !== "None"
      }
      updateFetchLogsButton(hasRunningInstance, false)
    } catch (error) {
      console.error("[Logs] Error checking instance status:", error)
      updateFetchLogsButton(false, false)
    }
  }
}

/**
 * Refresh the logs viewer content
 */
async function refreshLogsViewer() {
  if (!window.currentLogsRepo) return

  try {
    console.log("[Logs] Refreshing logs viewer...")
    const response = await api(`/api/repos/${encodeURIComponent(window.currentLogsRepo)}/logs`)

    if (response.ok) {
      await displayLogsViewer(response.logs, window.currentLogsRepo)
      console.log("[Logs] Logs viewer refreshed successfully")
    } else {
      console.error("[Logs] Failed to refresh logs:", response.error)
    }
  } catch (error) {
    console.error("[Logs] Error refreshing logs viewer:", error)
  }
}

/**
 * Download all logs for the current repository
 */
async function downloadAllLogs() {
  if (!window.currentLogsRepo) {
    alert("No repository selected for download")
    return
  }

  try {
    console.log("[Logs] Downloading all logs...")
    const response = await fetch(
      `/api/logs/download_all?repo_url=${encodeURIComponent(window.currentLogsRepo)}`,
    )

    if (response.ok) {
      const blob = await response.blob()
      const url = window.URL.createObjectURL(blob)
      const a = document.createElement("a")
      a.href = url
      a.download = "all_job_logs.zip"
      document.body.appendChild(a)
      a.click()
      window.URL.revokeObjectURL(url)
      document.body.removeChild(a)

      console.log("[Logs] All logs downloaded successfully")
    } else {
      console.error("[Logs] Failed to download all logs")
      alert("Failed to download all logs")
    }
  } catch (error) {
    console.error("[Logs] Error downloading all logs:", error)
    alert(`Error downloading all logs: ${error.message}`)
  }
}

/**
 * Handle CSV file selection
 */
function handleCsvFile(event) {
  const file = event.target.files[0]
  if (!file) return

  console.log("[CSV] File selected:", file.name)

  const reader = new FileReader()
  reader.onload = function (e) {
    const content = e.target.result
    displayCsvPreview(content)
  }
  reader.readAsText(file)
}

/**
 * Display CSV preview
 */
function displayCsvPreview(content) {
  const preview = document.getElementById("csvPreview")
  const csvContent = document.getElementById("csvContent")

  if (!preview || !csvContent) return

  const lines = content.split("\n").slice(0, 10) // Show first 10 lines
  csvContent.innerHTML = lines
    .map((line) => `<div style="font-family: monospace; padding: 2px 0;">${escapeHtml(line)}</div>`)
    .join("")

  preview.style.display = "block"
  document.getElementById("validateCsv").disabled = false
}

/**
 * Validate CSV content
 */
function validateCsv() {
  const csvFile = document.getElementById("csvFile").files[0]
  if (!csvFile) {
    alert("Please select a CSV file first")
    return
  }

  console.log("[CSV] Validating CSV file...")

  const reader = new FileReader()
  reader.onload = function (e) {
    const content = e.target.result
    const lines = content.split("\n").filter((line) => line.trim())

    if (lines.length < 2) {
      alert("CSV file must have at least a header and one data row")
      return
    }

    const header = lines[0].split(",")
    const expectedHeader = ["repo_url"]

    if (!expectedHeader.every((col) => header.includes(col))) {
      alert(`CSV header must include: ${expectedHeader.join(", ")}`)
      return
    }

    const validationResults = document.getElementById("validationResults")
    const validationSummary = document.getElementById("validationSummary")
    const validationDetails = document.getElementById("validationDetails")

    if (validationResults && validationSummary && validationDetails) {
      validationSummary.innerHTML = `
        <div style="color: #10b981; font-weight: bold;">✅ CSV Validation Passed</div>
        <div>Found ${lines.length - 1} repositories</div>
      `

      validationDetails.innerHTML = lines
        .slice(1, 6)
        .map(
          (line, index) =>
            `<div style="font-family: monospace; padding: 2px 0;">${index + 1}. ${escapeHtml(
              line,
            )}</div>`,
        )
        .join("")

      validationResults.style.display = "block"
      document.getElementById("uploadCsv").disabled = false
    }

    console.log("[CSV] Validation completed successfully")
  }
  reader.readAsText(csvFile)
}

/**
 * Upload CSV repositories
 */
async function uploadCsv() {
  const csvFile = document.getElementById("csvFile").files[0]
  if (!csvFile) {
    alert("Please select a CSV file first")
    return
  }

  try {
    console.log("[CSV] Uploading CSV repositories...")

    const formData = new FormData()
    formData.append("csv_file", csvFile)

    const response = await fetch("/api/repos/bulk", {
      method: "POST",
      body: formData,
    })

    const result = await response.json()

    if (result.ok) {
      console.log("[CSV] CSV uploaded successfully")
      alert(`Successfully uploaded ${result.added_count} repositories!`)
      refreshRepos()

      // Reset form
      document.getElementById("csvFile").value = ""
      document.getElementById("csvPreview").style.display = "none"
      document.getElementById("validationResults").style.display = "none"
      document.getElementById("validateCsv").disabled = true
      document.getElementById("uploadCsv").disabled = true
    } else {
      console.error("[CSV] Failed to upload CSV:", result.error)
      alert(`Failed to upload CSV: ${result.error}`)
    }
  } catch (error) {
    console.error("[CSV] Error uploading CSV:", error)
    alert(`Error uploading CSV: ${error.message}`)
  }
}

/**
 * Download CSV template
 */
function downloadTemplate() {
  const template = "repo_url\nhttps://github.com/example/repo1\nhttps://github.com/example/repo2"

  const blob = new Blob([template], { type: "text/csv" })
  const url = window.URL.createObjectURL(blob)
  const a = document.createElement("a")
  a.href = url
  a.download = "repositories_template.csv"
  document.body.appendChild(a)
  a.click()
  window.URL.revokeObjectURL(url)
  document.body.removeChild(a)

  console.log("[CSV] Template downloaded")
}

/**
 * Close analysis modal
 */
function closeAnalysisModal() {
  document.getElementById("analysisModal").style.display = "none"
}

/**
 * Apply analysis to CSV
 */
function applyAnalysis() {
  console.log("[Analysis] Applying analysis to CSV...")
  // This would typically update the CSV with analysis results
  alert("Analysis applied to CSV successfully!")
  closeAnalysisModal()
}

// =============================================================================
// UTILITY FUNCTIONS
// =============================================================================

/**
 * Format file size in human readable format
 */
function formatFileSize(bytes) {
  if (bytes === 0) return "0 Bytes"

  const k = 1024
  const sizes = ["Bytes", "KB", "MB", "GB"]
  const i = Math.floor(Math.log(bytes) / Math.log(k))

  return parseFloat((bytes / Math.pow(k, i)).toFixed(2)) + " " + sizes[i]
}

/**
 * Escape HTML to prevent XSS
 */
function escapeHtml(text) {
  const div = document.createElement("div")
  div.textContent = text
  return div.innerHTML
}

// =============================================================================
// ANALYSIS GENERATION FUNCTIONALITY
// =============================================================================

/**
 * Analyze a repository to generate analysis results with enhanced UI feedback
 */
async function analyzeRepo(repoUrl) {
  // Find the analyze button for this repo and show loading state
  const analyzeButtons = document.querySelectorAll(`button[onclick*="analyzeRepo('${repoUrl}')"]`)
  const originalContents = []

  analyzeButtons.forEach((button, index) => {
    originalContents[index] = button.innerHTML
    button.disabled = true
    button.innerHTML = "<span>⏳</span> Analyzing..."
    button.style.opacity = "0.7"
  })

  try {
    console.log("[Analysis] Starting analysis for:", repoUrl)
    showLoading("Starting repository analysis...")

    const response = await api("/api/analyze_repo", {
      method: "POST",
      body: JSON.stringify({ repo_url: repoUrl }),
    })

    if (response.ok) {
      console.log("[Analysis] Analysis started successfully:", response.analysis_id)
      showSuccess(`Analysis started for ${repoUrl}! Job ID: ${response.analysis_id}`)

      // Start enhanced polling for analysis status with better UI feedback
      pollAnalysisStatusEnhanced(response.analysis_id, repoUrl, analyzeButtons, originalContents)
    } else {
      console.error("[Analysis] Failed to start analysis:", response.error)
      showError(`Failed to start analysis: ${response.error}`)
    }
  } catch (error) {
    console.error("[Analysis] Error starting analysis:", error)
    showError(`Error starting analysis: ${error.message}`)
  } finally {
    hideLoading()
  }
}

/**
 * Enhanced polling for analysis status with better UI feedback
 */
async function pollAnalysisStatusEnhanced(analysisId, repoUrl, analyzeButtons, originalContents) {
  console.log("[Analysis] Starting enhanced polling for:", analysisId)

  const maxAttempts = 120 // Poll for up to 10 minutes (120 * 5 seconds)
  let attempts = 0
  let lastStatus = ""

  // Show initial status
  showLoading("Analysis in progress...")

  const pollInterval = setInterval(async () => {
    attempts++

    try {
      const response = await api(`/api/analyze_repo/status?analysis_id=${analysisId}`)

      if (response.ok) {
        const status = response.status
        console.log(`[Analysis] Status check ${attempts}:`, status)

        // Update loading message based on status
        if (status !== lastStatus) {
          lastStatus = status
          switch (status) {
            case "running":
              showLoading("Analysis running... Processing repository...")
              break
            case "completed":
              showLoading("Analysis completed! Finalizing results...")
              break
            case "failed":
              showLoading("Analysis failed. Cleaning up...")
              break
            default:
              showLoading(`Analysis status: ${status}`)
          }
        }

        if (status === "completed") {
          clearInterval(pollInterval)
          console.log("[Analysis] Analysis completed successfully!")

          // Restore button states
          analyzeButtons.forEach((button, index) => {
            button.disabled = false
            button.innerHTML = originalContents[index]
            button.style.opacity = "1"
          })

          showSuccess(`Analysis completed for ${repoUrl}! You can now view the results.`)
          hideLoading()

          // Refresh the repository list to show updated analysis status
          await refreshRepos()
        } else if (status === "failed") {
          clearInterval(pollInterval)
          console.error("[Analysis] Analysis failed:", response.message)

          // Restore button states
          analyzeButtons.forEach((button, index) => {
            button.disabled = false
            button.innerHTML = originalContents[index]
            button.style.opacity = "1"
          })

          showError(`Analysis failed: ${response.message}`)
          hideLoading()
        } else if (status === "running") {
          console.log("[Analysis] Analysis is running...")
          // Continue polling
        } else {
          console.log(`[Analysis] Analysis status: ${status}`)
          // Continue polling
        }
      } else {
        console.error("[Analysis] Failed to get status:", response.error)
        if (attempts >= maxAttempts) {
          clearInterval(pollInterval)

          // Restore button states
          analyzeButtons.forEach((button, index) => {
            button.disabled = false
            button.innerHTML = originalContents[index]
            button.style.opacity = "1"
          })

          showError("Analysis status check failed. Please check manually.")
          hideLoading()
        }
      }
    } catch (error) {
      console.error("[Analysis] Error checking status:", error)
      if (attempts >= maxAttempts) {
        clearInterval(pollInterval)

        // Restore button states
        analyzeButtons.forEach((button, index) => {
          button.disabled = false
          button.innerHTML = originalContents[index]
          button.style.opacity = "1"
        })

        showError("Analysis status check failed. Please check manually.")
        hideLoading()
      }
    }

    // Stop polling after max attempts
    if (attempts >= maxAttempts) {
      clearInterval(pollInterval)
      console.log("[Analysis] Stopped polling after max attempts")

      // Restore button states
      analyzeButtons.forEach((button, index) => {
        button.disabled = false
        button.innerHTML = originalContents[index]
        button.style.opacity = "1"
      })

      showError("Analysis is taking longer than expected. Please check manually.")
      hideLoading()
    }
  }, 5000) // Poll every 5 seconds
}

/**
 * Poll analysis status until completion (legacy function for compatibility)
 */
async function pollAnalysisStatus(analysisId, repoUrl) {
  console.log("[Analysis] Polling status for:", analysisId)

  const maxAttempts = 60 // Poll for up to 5 minutes (60 * 5 seconds)
  let attempts = 0

  const pollInterval = setInterval(async () => {
    attempts++

    try {
      const response = await api(`/api/analyze_repo/status?analysis_id=${analysisId}`)

      if (response.ok) {
        const status = response.status
        console.log(`[Analysis] Status check ${attempts}:`, status)

        if (status === "completed") {
          clearInterval(pollInterval)
          console.log("[Analysis] Analysis completed successfully!")
          showSuccess(`Analysis completed for ${repoUrl}! You can now view the results.`)

          // Refresh the repository list to show updated analysis status
          refreshRepos()
        } else if (status === "failed") {
          clearInterval(pollInterval)
          console.error("[Analysis] Analysis failed:", response.message)
          showError(`Analysis failed: ${response.message}`)
        } else if (status === "running") {
          console.log("[Analysis] Analysis is running...")
          // Continue polling
        } else {
          console.log(`[Analysis] Analysis status: ${status}`)
          // Continue polling
        }
      } else {
        console.error("[Analysis] Failed to get status:", response.error)
        if (attempts >= maxAttempts) {
          clearInterval(pollInterval)
          showError("Analysis status check failed. Please check manually.")
        }
      }
    } catch (error) {
      console.error("[Analysis] Error checking status:", error)
      if (attempts >= maxAttempts) {
        clearInterval(pollInterval)
        showError("Analysis status check failed. Please check manually.")
      }
    }

    // Stop polling after max attempts
    if (attempts >= maxAttempts) {
      clearInterval(pollInterval)
      console.log("[Analysis] Stopped polling after max attempts")
    }
  }, 5000) // Poll every 5 seconds
}

/**
 * Show loading state with enhanced styling
 */
function showLoading(message = "Loading...") {
  // Create or update loading indicator
  let loadingDiv = document.getElementById("loadingIndicator")
  if (!loadingDiv) {
    loadingDiv = document.createElement("div")
    loadingDiv.id = "loadingIndicator"
    loadingDiv.className = "loading-indicator"
    document.body.appendChild(loadingDiv)
  }
  loadingDiv.innerHTML = `⏳ ${message}`
  loadingDiv.style.display = "block"
}

/**
 * Hide loading state
 */
function hideLoading() {
  const loadingDiv = document.getElementById("loadingIndicator")
  if (loadingDiv) {
    loadingDiv.style.display = "none"
  }
}

/**
 * Show success message
 */
function showSuccess(message) {
  showNotification(message, "success")
}

/**
 * Show error message
 */
function showError(message) {
  showNotification(message, "error")
}

/**
 * Show notification with enhanced styling
 */
function showNotification(message, type = "info") {
  const notification = document.createElement("div")
  const icon = type === "success" ? "✅" : type === "error" ? "❌" : "ℹ️"

  notification.className = `notification ${type}`
  notification.innerHTML = `${icon} ${message}`

  document.body.appendChild(notification)

  // Auto-remove after 5 seconds
  setTimeout(() => {
    if (notification.parentNode) {
      notification.style.animation = "notification-slide-in 0.3s ease-out reverse"
      setTimeout(() => {
        if (notification.parentNode) {
          notification.parentNode.removeChild(notification)
        }
      }, 300)
    }
  }, 5000)
}

// =============================================================================
// INITIALIZATION
// =============================================================================

// Initialize the security gate system when the page loads
document.addEventListener("DOMContentLoaded", function () {
  // Set up security event listeners immediately
  setupEventListeners()

  // Initialize the security gate system
  if (hasAccessGranted()) {
    showDashboard()
    // Load custom run settings after dashboard is shown
    loadCustomRunSettings()
  } else {
    // Show security gate
    document.getElementById("securityGate").style.display = "flex"
  }
})

// Custom Run Modal Management
let customRunSettings = null
let customRunModal = null

async function loadCustomRunSettings() {
  try {
    console.log("[CustomRun] Loading custom run settings...")
    const response = await api("/api/custom-run/settings")

    if (response.ok) {
      customRunSettings = response.settings
      console.log("[CustomRun] Settings loaded successfully:", customRunSettings)
    } else {
      console.error("[CustomRun] Failed to load settings:", response.error)
      showError(`Failed to load custom run settings: ${response.error}`)
    }
  } catch (error) {
    console.error("[CustomRun] Error loading settings:", error)
    showError(`Error loading custom run settings: ${error.message}`)
  }
}

function createCustomRunModal() {
  if (!customRunSettings) {
    showError("Custom run settings not loaded. Please refresh the page.")
    return
  }

  // Create modal HTML
  const modalHTML = `
    <div id="customRunModal" class="modal-overlay" style="display: none;">
      <div class="modal-content large-modal" style="max-width: 900px; max-height: 90vh; overflow-y: auto;">
        <div class="modal-header">
          <h2>🚀 Custom Codeflash Run</h2>
          <span class="close" onclick="closeCustomRunModal()">&times;</span>
        </div>
        
        <div class="modal-body">
          <!-- Path Information Banner -->
          <div class="path-info-banner">
            <div class="path-info-icon">📁</div>
            <div class="path-info-content">
              <strong>Path Configuration:</strong> All directory paths you enter will be automatically prefixed with <code>/home/ubuntu/work/repo/</code> to ensure Codeflash runs in the correct location on the EC2 instance.
            </div>
          </div>
          
          <form id="customRunForm">
            <!-- Optimization Mode Selection -->
            <div class="form-section">
              <h3>${customRunSettings.ui_sections.optimization_mode.title}</h3>
              <p class="section-description">${
                customRunSettings.ui_sections.optimization_mode.description
              }</p>
              
              <div class="form-group">
                <label for="optimizationMode">Optimization Mode *</label>
                <select id="optimizationMode" required onchange="updateCustomRunForm()">
                  <option value="">Select optimization mode...</option>
                  ${Object.entries(customRunSettings.codeflash_optimization_modes)
                    .map(([key, mode]) => `<option value="${key}">${mode.name}</option>`)
                    .join("")}
                </select>
              </div>
            </div>

            <!-- Basic Settings -->
            <div class="form-section">
              <h3>${customRunSettings.ui_sections.basic_settings.title}</h3>
              <p class="section-description">${
                customRunSettings.ui_sections.basic_settings.description
              }</p>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="moduleRoot">Module Root *</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="moduleRoot" placeholder="e.g., src, my_module" required>
                  </div>
                  <small>Directory containing your Python code to optimize</small>
                </div>
                
                <div class="form-group">
                  <label for="testsRoot">Tests Root *</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="testsRoot" placeholder="e.g., tests, test" required>
                  </div>
                  <small>Directory containing your test files</small>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="testFramework">Test Framework ${
                    customRunSettings.pyproject_toml_settings.test_framework.disabled ? "" : "*"
                  }</label>
                  <select id="testFramework" ${
                    customRunSettings.pyproject_toml_settings.test_framework.disabled
                      ? "disabled"
                      : "required"
                  }>
                    ${customRunSettings.pyproject_toml_settings.test_framework.options
                      .map(
                        (opt) =>
                          `<option value="${opt.value}" ${
                            opt.value ===
                            customRunSettings.pyproject_toml_settings.test_framework.default
                              ? "selected"
                              : ""
                          }>${opt.label}</option>`,
                      )
                      .join("")}
                  </select>
                  ${
                    customRunSettings.pyproject_toml_settings.test_framework.disabled
                      ? `<small class="warning-message">⚠️ ${customRunSettings.pyproject_toml_settings.test_framework.disabled_reason}</small>`
                      : "<small>Test framework for running tests</small>"
                  }
                </div>
                
                <div class="form-group">
                  <label for="benchmarksRoot">Benchmarks Root</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="benchmarksRoot" placeholder="e.g., tests/benchmarks">
                  </div>
                  <small>Required when using --benchmark flag</small>
                </div>
              </div>
              
              <div class="form-group">
                <label for="pytestCmd">Pytest Command</label>
                <input type="text" id="pytestCmd" placeholder="pytest --verbose --cov" value="${
                  customRunSettings.pyproject_toml_settings.pytest_cmd.default
                }">
                <small>Command to run your tests with extra arguments</small>
              </div>
              
              <div class="form-group">
                <label for="formatterCmds">Formatter Commands</label>
                <textarea id="formatterCmds" placeholder="black $file&#10;ruff check --exit-zero --fix $file&#10;ruff format $file" rows="3"></textarea>
                <small>One command per line. Use $file to refer to the current file</small>
              </div>
              
              <div class="form-group">
                <label for="ignorePaths">Ignore Paths</label>
                <div class="path-input-container">
                  <span class="path-prefix">/home/ubuntu/work/repo/</span>
                  <textarea id="ignorePaths" placeholder="build/&#10;__pycache__/&#10;*.pyc" rows="3"></textarea>
                </div>
                <small>Paths to ignore during optimization, one per line</small>
              </div>
            </div>

            <!-- Mode-specific Fields -->
            <div id="modeSpecificFields" class="form-section" style="display: none;">
              <h3>Mode-Specific Configuration</h3>
              <div id="singleFunctionFields" class="mode-fields" style="display: none;">
                <div class="form-row">
                  <div class="form-group">
                    <label for="filePath">File Path *</label>
                    <div class="path-input-container">
                      <span class="path-prefix">/home/ubuntu/work/repo/</span>
                      <input type="text" id="filePath" placeholder="path/to/your/file.py">
                    </div>
                    <small>Path to the Python file containing the function to optimize</small>
                  </div>
                  
                  <div class="form-group">
                    <label for="functionName">Function Name *</label>
                    <input type="text" id="functionName" placeholder="my_function">
                    <small>Name of the function to optimize</small>
                  </div>
                </div>
              </div>
              
              <div id="traceOptimizeFields" class="mode-fields" style="display: none;">
                <div class="form-group">
                  <label for="scriptPath">Script Path *</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="scriptPath" placeholder="path/to/your/script.py">
                  </div>
                  <small>Path to the Python script to trace and optimize</small>
                </div>
              </div>
              
              <div id="optimizeAllFields" class="mode-fields" style="display: none;">
                <div class="form-group">
                  <label for="targetDirectory">Target Directory</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="targetDirectory" placeholder="path/to/directory">
                  </div>
                  <small>Specific directory to optimize (optional, defaults to entire codebase)</small>
                </div>
              </div>
            </div>

            <!-- Optimization Flags -->
            <div class="form-section">
              <h3>${customRunSettings.ui_sections.optimization_flags.title}</h3>
              <p class="section-description">${
                customRunSettings.ui_sections.optimization_flags.description
              }</p>
              
              <div class="form-row">
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="asyncMode" checked>
                    ${customRunSettings.optimization_flags.async.label}
                  </label>
                  <small>${customRunSettings.optimization_flags.async.description}</small>
                </div>
                
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="verbose" checked>
                    ${customRunSettings.optimization_flags.verbose.label}
                  </label>
                  <small>${customRunSettings.optimization_flags.verbose.description}</small>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="noPr">
                    ${customRunSettings.optimization_flags.no_pr.label}
                  </label>
                  <small>${customRunSettings.optimization_flags.no_pr.description}</small>
                </div>
                
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="benchmark">
                    ${customRunSettings.optimization_flags.benchmark.label}
                  </label>
                  <small>${customRunSettings.optimization_flags.benchmark.description}</small>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="traceOnly">
                    ${customRunSettings.optimization_flags.trace_only.label}
                  </label>
                  <small>${customRunSettings.optimization_flags.trace_only.description}</small>
                </div>
                
                <div class="form-group">
                  <label for="tracerTimeout">Tracer Timeout (seconds)</label>
                  <input type="number" id="tracerTimeout" min="1" max="3600" placeholder="300">
                  <small>Maximum time to trace the workflow</small>
                </div>
              </div>
            </div>

            <!-- Advanced Settings -->
            <div class="form-section">
              <h3>${customRunSettings.ui_sections.advanced_settings.title}</h3>
              <p class="section-description">${
                customRunSettings.ui_sections.advanced_settings.description
              }</p>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="pyprojectLocation">PyProject.toml Location</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="pyprojectLocation" placeholder="path/to/pyproject.toml">
                  </div>
                  <small>Custom location for pyproject.toml file</small>
                </div>
                
                <div class="form-group">
                  <label for="traceFile">Trace File Path</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="traceFile" placeholder="custom_trace.trace">
                  </div>
                  <small>Custom location for trace file output</small>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group">
                  <label for="maxFunctionCount">Max Function Count</label>
                  <input type="number" id="maxFunctionCount" min="1" max="1000" value="100">
                  <small>Maximum number of times to trace a single function</small>
                </div>
                
                <div class="form-group">
                  <label for="replayTestPath">Replay Test Path</label>
                  <div class="path-input-container">
                    <span class="path-prefix">/home/ubuntu/work/repo/</span>
                    <input type="text" id="replayTestPath" placeholder="path/to/test_replay_test_0.py">
                  </div>
                  <small>Path to existing replay test file</small>
                </div>
              </div>
              
              <div class="form-row">
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="disableImportsSorting">
                    ${customRunSettings.pyproject_toml_settings.disable_imports_sorting.label}
                  </label>
                  <small>${
                    customRunSettings.pyproject_toml_settings.disable_imports_sorting.description
                  }</small>
                </div>
                
                <div class="form-group checkbox-group">
                  <label>
                    <input type="checkbox" id="disableTelemetry">
                    ${customRunSettings.pyproject_toml_settings.disable_telemetry.label}
                  </label>
                  <small>${
                    customRunSettings.pyproject_toml_settings.disable_telemetry.description
                  }</small>
                </div>
              </div>
            </div>

            <!-- Validation Messages -->
            <div id="customRunValidation" class="validation-messages" style="display: none;">
              <div id="validationErrors" class="error-messages"></div>
              <div id="validationWarnings" class="warning-messages"></div>
            </div>
          </form>
        </div>
        
        <div class="modal-footer">
          <button type="button" class="btn btn-secondary" onclick="closeCustomRunModal()">Cancel</button>
          <button type="button" class="btn btn-primary" onclick="validateCustomRunConfig()">Validate Configuration</button>
          <button type="button" class="btn btn-success" onclick="executeCustomRun()" disabled id="executeCustomRunBtn">Execute Custom Run</button>
        </div>
      </div>
    </div>
  `

  // Add modal to page
  document.body.insertAdjacentHTML("beforeend", modalHTML)
  customRunModal = document.getElementById("customRunModal")
}

function updateCustomRunForm() {
  const mode = document.getElementById("optimizationMode").value
  const modeSpecificFields = document.getElementById("modeSpecificFields")
  const singleFunctionFields = document.getElementById("singleFunctionFields")
  const traceOptimizeFields = document.getElementById("traceOptimizeFields")
  const optimizeAllFields = document.getElementById("optimizeAllFields")

  // Hide all mode-specific fields
  singleFunctionFields.style.display = "none"
  traceOptimizeFields.style.display = "none"
  optimizeAllFields.style.display = "none"
  modeSpecificFields.style.display = "none"

  // Show relevant fields based on mode
  if (mode) {
    modeSpecificFields.style.display = "block"

    switch (mode) {
      case "single_function":
        singleFunctionFields.style.display = "block"
        break
      case "trace_and_optimize":
        traceOptimizeFields.style.display = "block"
        break
      case "optimize_all":
        optimizeAllFields.style.display = "block"
        break
    }
  }
}

async function validateCustomRunConfig() {
  const config = collectCustomRunConfig()

  try {
    console.log("[CustomRun] Validating configuration...", config)
    const response = await api("/api/custom-run/validate", {
      method: "POST",
      body: JSON.stringify(config),
    })

    const validationDiv = document.getElementById("customRunValidation")
    const errorsDiv = document.getElementById("validationErrors")
    const warningsDiv = document.getElementById("validationWarnings")
    const executeBtn = document.getElementById("executeCustomRunBtn")

    validationDiv.style.display = "block"
    errorsDiv.innerHTML = ""
    warningsDiv.innerHTML = ""

    if (response.ok) {
      if (response.valid) {
        console.log("[CustomRun] Configuration is valid")
        showSuccess("Configuration is valid!")
        executeBtn.disabled = false

        if (response.warnings && response.warnings.length > 0) {
          warningsDiv.innerHTML =
            "<h4>⚠️ Warnings:</h4><ul>" +
            response.warnings.map((w) => `<li>${w}</li>`).join("") +
            "</ul>"
        }
      } else {
        console.log("[CustomRun] Configuration has errors:", response.errors)
        errorsDiv.innerHTML =
          "<h4>❌ Errors:</h4><ul>" + response.errors.map((e) => `<li>${e}</li>`).join("") + "</ul>"
        executeBtn.disabled = true
      }
    } else {
      console.error("[CustomRun] Validation failed:", response.error)
      errorsDiv.innerHTML = `<h4>❌ Validation Error:</h4><p>${response.error}</p>`
      executeBtn.disabled = true
    }
  } catch (error) {
    console.error("[CustomRun] Error validating configuration:", error)
    showError(`Error validating configuration: ${error.message}`)
  }
}

function collectCustomRunConfig() {
  const mode = document.getElementById("optimizationMode").value

  // Helper function to get field value, respecting disabled state
  function getFieldValue(fieldId, defaultValue = "") {
    const field = document.getElementById(fieldId)
    if (!field) return defaultValue

    // If field is disabled, it means it has analysis data - use the current value
    if (field.disabled) {
      return field.value || defaultValue
    }

    // Otherwise use the form value
    if (field.type === "checkbox") {
      return field.checked
    } else if (field.tagName === "TEXTAREA") {
      return field.value.split("\n").filter((cmd) => cmd.trim())
    } else {
      return field.value || defaultValue
    }
  }

  // Helper function to normalize paths - ensure they start with /home/ubuntu/work/repo/
  function normalizePath(path, isAbsolute = false) {
    if (!path || path.trim() === "") return path

    const trimmedPath = path.trim()

    // If it's already an absolute path starting with /home/ubuntu/work/repo/, return as-is
    if (trimmedPath.startsWith("/home/ubuntu/work/repo/")) {
      return trimmedPath
    }

    // If it's an absolute path but not in the expected location, prepend the repo path
    if (trimmedPath.startsWith("/")) {
      return `/home/ubuntu/work/repo${trimmedPath}`
    }

    // For relative paths, prepend the repo path
    return `/home/ubuntu/work/repo/${trimmedPath}`
  }

  const config = {
    optimization_mode: mode,
    config: {
      module_root: normalizePath(getFieldValue("moduleRoot")),
      tests_root: normalizePath(getFieldValue("testsRoot")),
      test_framework: getFieldValue("testFramework"),
      benchmarks_root: normalizePath(getFieldValue("benchmarksRoot")),
      pytest_cmd: getFieldValue("pytestCmd"),
      formatter_cmds: getFieldValue("formatterCmds", []),
      ignore_paths: document
        .getElementById("ignorePaths")
        .value.split("\n")
        .filter((path) => path.trim())
        .map((path) => normalizePath(path)),
      disable_imports_sorting: getFieldValue("disableImportsSorting", false),
      disable_telemetry: getFieldValue("disableTelemetry", false),
    },
    flags: {
      async: document.getElementById("asyncMode").checked,
      verbose: document.getElementById("verbose").checked,
      no_pr: document.getElementById("noPr").checked,
      benchmark: document.getElementById("benchmark").checked,
      trace_only: document.getElementById("traceOnly").checked,
      tracer_timeout: document.getElementById("tracerTimeout").value || null,
    },
    advanced: {
      pyproject_location: normalizePath(document.getElementById("pyprojectLocation").value),
      trace_file: normalizePath(document.getElementById("traceFile").value),
      max_function_count: document.getElementById("maxFunctionCount").value || null,
      replay_test_path: normalizePath(document.getElementById("replayTestPath").value),
    },
  }

  // Add mode-specific fields
  switch (mode) {
    case "single_function":
      config.config.file_path = normalizePath(document.getElementById("filePath").value)
      config.config.function_name = document.getElementById("functionName").value
      break
    case "trace_and_optimize":
      config.config.script_path = normalizePath(document.getElementById("scriptPath").value)
      break
    case "optimize_all":
      config.config.target_directory = normalizePath(
        document.getElementById("targetDirectory").value,
      )
      break
  }

  return config
}

async function executeCustomRun() {
  const config = collectCustomRunConfig()
  const repoUrl = window.currentCustomRunRepo

  if (!repoUrl) {
    showError("No repository selected for custom run")
    return
  }

  const executeBtn = document.getElementById("executeCustomRunBtn")
  const originalText = executeBtn.innerHTML

  // Show loading state
  executeBtn.disabled = true
  executeBtn.innerHTML = "<span>⏳</span> Executing..."

  try {
    console.log("[CustomRun] Executing custom run for:", repoUrl, config)

    const response = await api("/api/custom-run/execute", {
      method: "POST",
      body: JSON.stringify({
        repo_url: repoUrl,
        ...config,
      }),
    })

    if (response.ok) {
      console.log("[CustomRun] Custom run started successfully:", response)
      showSuccess(`Custom optimization run started successfully!<br>
        Instance ID: ${response.instance_id}<br>
        Mode: ${response.optimization_mode}<br>
        Module Root: ${response.config_summary.module_root}<br>
        Tests Root: ${response.config_summary.tests_root}`)

      closeCustomRunModal()

      // Refresh the repositories list to show the new job
      await refreshRepos()
    } else {
      console.error("[CustomRun] Failed to execute custom run:", response.error)
      showError(`Failed to execute custom run: ${response.error}`)

      if (response.validation_errors) {
        const errorsDiv = document.getElementById("validationErrors")
        errorsDiv.innerHTML =
          "<h4>❌ Configuration Errors:</h4><ul>" +
          response.validation_errors.map((e) => `<li>${e}</li>`).join("") +
          "</ul>"
        document.getElementById("customRunValidation").style.display = "block"
      }
    }
  } catch (error) {
    console.error("[CustomRun] Error executing custom run:", error)
    showError(`Error executing custom run: ${error.message}`)
  } finally {
    // Restore button state
    executeBtn.disabled = false
    executeBtn.innerHTML = originalText
  }
}

function openCustomRunModal(repoUrl) {
  if (!customRunSettings) {
    showError("Custom run settings not loaded. Please refresh the page.")
    return
  }

  if (!customRunModal) {
    createCustomRunModal()
  }

  window.currentCustomRunRepo = repoUrl

  // Use setTimeout to ensure DOM is fully updated after modal creation
  setTimeout(() => {
    // Reset form
    const form = document.getElementById("customRunForm")
    if (form) {
      form.reset()
    }
    const validationDiv = document.getElementById("customRunValidation")
    if (validationDiv) {
      validationDiv.style.display = "none"
    }
    const executeBtn = document.getElementById("executeCustomRunBtn")
    if (executeBtn) {
      executeBtn.disabled = true
    }

    // Load and apply analysis results
    loadAnalysisResultsForCustomRun(repoUrl)

    // Update form based on current mode
    updateCustomRunForm()

    customRunModal.style.display = "flex"
    console.log("[CustomRun] Modal opened for repository:", repoUrl)
  }, 10) // Small delay to ensure DOM is ready
}

function closeCustomRunModal() {
  if (customRunModal) {
    customRunModal.style.display = "none"
    window.currentCustomRunRepo = null
    console.log("[CustomRun] Modal closed")
  }
}

async function loadAnalysisResultsForCustomRun(repoUrl) {
  try {
    console.log("[CustomRun] Loading analysis results for:", repoUrl)
    const response = await api(`/api/repos/${encodeURIComponent(repoUrl)}/analysis`)

    if (response.ok && response.analysis) {
      const analysis = response.analysis
      console.log("[CustomRun] Analysis results loaded:", analysis)

      // Apply analysis results to form fields
      applyAnalysisToCustomRunForm(analysis)
    } else {
      console.log("[CustomRun] No analysis results found for repository")
    }
  } catch (error) {
    console.error("[CustomRun] Error loading analysis results:", error)
  }
}

function applyAnalysisToCustomRunForm(analysis) {
  // Map analysis fields to custom run form fields
  const fieldMappings = {
    moduleRoot: analysis.codeflash?.module_root,
    testsRoot: analysis.codeflash?.tests_root,
    testFramework: analysis.tests?.test_framework,
    pytestCmd: analysis.tests?.test_command,
    formatterCmds: analysis.codeflash?.formatter_cmds?.join("\n"),
  }

  // Apply values and disable fields that have analysis data
  Object.entries(fieldMappings).forEach(([fieldId, value]) => {
    const field = document.getElementById(fieldId)
    if (field && value) {
      // Set the value from analysis
      if (field.type === "checkbox") {
        field.checked = Boolean(value)
      } else if (field.tagName === "TEXTAREA") {
        field.value = value
      } else if (field.tagName === "SELECT") {
        field.value = value
      } else {
        field.value = value
      }

      // For testFramework, it's already disabled by configuration, so just set the value
      if (fieldId === "testFramework") {
        // testFramework is already disabled by configuration, just set the value
        console.log(`[CustomRun] Applied analysis value to ${fieldId}:`, value)
        return
      }

      // Disable the field and add visual indication for other fields
      field.disabled = true
      field.style.backgroundColor = "#f5f5f5"
      field.style.color = "#666"

      // Add tooltip/help text
      const helpText = field.parentNode.querySelector("small")
      if (helpText) {
        helpText.innerHTML = `⚠️ This value comes from analysis results. Edit it in the Analysis dialog instead.`
        helpText.style.color = "#ff9800"
        helpText.style.fontWeight = "bold"
      }

      console.log(`[CustomRun] Applied analysis value to ${fieldId}:`, value)
    }
  })

  // Show info message about analysis integration
  showAnalysisIntegrationInfo(analysis)
}

function showAnalysisIntegrationInfo(analysis) {
  const infoDiv = document.createElement("div")
  infoDiv.className = "analysis-integration-info"
  infoDiv.style.cssText = `
    background: #e3f2fd;
    border: 1px solid #2196f3;
    border-radius: 8px;
    padding: 12px;
    margin: 16px 0;
    font-size: 14px;
  `

  const confidence = analysis.confidence || 0
  const confidenceColor = confidence >= 0.8 ? "#4caf50" : confidence >= 0.6 ? "#ff9800" : "#f44336"

  infoDiv.innerHTML = `
    <div style="display: flex; align-items: center; margin-bottom: 8px;">
      <span style="font-size: 16px; margin-right: 8px;">📊</span>
      <strong style="color: #1976d2;">Analysis Results Applied</strong>
    </div>
    <div style="color: #666; margin-bottom: 8px;">
      Some fields are pre-filled from repository analysis (confidence: 
      <span style="color: ${confidenceColor}; font-weight: bold;">${Math.round(
    confidence * 100,
  )}%</span>).
    </div>
    <div style="color: #666; font-size: 13px;">
      To modify these values, use the "Analysis" button in the repository table.
    </div>
  `

  // Insert after the optimization mode section
  const modeSection = document.querySelector(".form-section")
  if (modeSection) {
    modeSection.parentNode.insertBefore(infoDiv, modeSection.nextSibling)
  }
}

// Close modal when clicking outside
window.addEventListener("click", function (event) {
  if (event.target === customRunModal) {
    closeCustomRunModal()
  }
})
