// components/Editor/monaco-diff-editor-github.tsx
"use client"

import React, { type JSX, useState, useEffect, useRef, useCallback } from "react"
import { Editor, DiffEditor } from "@monaco-editor/react"
import type { editor } from "monaco-editor"
import ReactMarkdown from "react-markdown"
import remarkGfm from "remark-gfm"
import { createPatch } from "diff"
import {
  ChevronRight,
  FileText,
  FolderOpen,
  Folder,
  Eye,
  Edit,
  PanelLeftClose,
  PanelLeft,
  PanelBottomClose,
  PanelBottom,
  Zap,
  Clock,
  Percent,
  IterationCw,
  TestTube2,
  Info,
  Copy,
  Check,
  GitPullRequest,
  Loader2,
  Undo,
  Redo,
  Save,
  ExternalLink,
  Download,
  FileCode2,
  CheckCircle2,
  Terminal,
  X,
  Star,
} from "lucide-react"
import { ReviewQualityBadge } from "../ui/quality_badge"
import { getMonacoLanguage } from "@/lib/utils"

interface DiffContent {
  newContent: string
  oldContent: string
}

interface DiffContents {
  [filePath: string]: DiffContent
}

interface TestResults {
  passed: number
  failed: number
}

interface ReportTable {
  [key: string]: TestResults
}

interface PRCommentFields {
  original_runtime?: string
  best_runtime?: string
  loop_count?: number
  optimization_explanation?: string
  report_table?: ReportTable
}

interface OptimizationInfo {
  speedup_x?: number
  speedup_pct?: number
  prCommentFields?: PRCommentFields
  generatedTests?: string
  coverage_message?: string
  review_quality?: string | null
  review_explanation?: string | null
}

interface MonacoDiffEditorGithubProps {
  diffContents: DiffContents
  onContentChange?: (filePath: string, newContent: string) => void
  onEdit?: (filePath: string, newContent: string) => void
  optimizationInfo?: OptimizationInfo
  functionName?: string
  filePath?: string
  onCreatePR?: () => void | Promise<void>
  onViewPR?: () => void
  prNumber?: string
  repositoryFullName?: string
  isCreatingPR?: boolean
  showGitDiffDownload?: boolean
  disableAutoSave?: boolean
  isPrivacyModeNoDiff?: boolean
}

interface FileNode {
  name: string
  path: string
  type: "file" | "folder"
  children?: FileNode[]
  isTest?: boolean
}

interface TestFile {
  path: string
  content: string
}

// Enhanced debounce hook with cleanup
function useDebounce<T extends (...args: Parameters<T>) => ReturnType<T>>(
  callback: T,
  delay: number,
): (...args: Parameters<T>) => void {
  const timeoutRef = useRef<NodeJS.Timeout | null>(null)
  const callbackRef = useRef(callback)

  useEffect(() => {
    callbackRef.current = callback
  }, [callback])

  useEffect(() => {
    return () => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
    }
  }, [])

  const debouncedCallback = useCallback(
    (...args: Parameters<T>) => {
      if (timeoutRef.current) {
        clearTimeout(timeoutRef.current)
      }
      timeoutRef.current = setTimeout(() => {
        callbackRef.current(...args)
      }, delay)
    },
    [delay],
  )

  return debouncedCallback
}

//Function to parse multiple code blocks from test content
function parseTestCodeBlocks(testContent: string): TestFile[] {
  const codeBlockRegex = /```python\n([\s\S]*?)```/g
  const matches = Array.from(testContent.matchAll(codeBlockRegex))

  if (matches.length === 0) {
    // No code blocks found, return the entire content as a single test file
    return [
      {
        path: "tests/test_suite.py",
        content: testContent,
      },
    ]
  }

  if (matches.length === 1) {
    // Single code block, use default path
    return [
      {
        path: "tests/test_suite.py",
        content: matches[0][1].trim(),
      },
    ]
  }

  // Multiple code blocks, create separate files
  return matches.map((match, index) => ({
    path: `tests/test_suite_${index + 1}.py`,
    content: match[1].trim(),
  }))
}

const MonacoDiffEditorGithub: React.FC<MonacoDiffEditorGithubProps> = ({
  diffContents,
  onContentChange,
  onEdit,
  optimizationInfo,
  functionName,
  onCreatePR,
  onViewPR,
  prNumber,
  isCreatingPR = false,
  showGitDiffDownload = false,
  disableAutoSave = false,
  isPrivacyModeNoDiff = false,
}) => {
  const [isDarkMode, setIsDarkMode] = useState<boolean>(false)
  const [mounted, setMounted] = useState(false)
  const [selectedFile, setSelectedFile] = useState<string>("")
  const [expandedFolders, setExpandedFolders] = useState<Set<string>>(new Set())
  const [fileTree, setFileTree] = useState<FileNode[]>([])
  const [modifiedContents, setModifiedContents] = useState<DiffContents>(diffContents)
  const [viewMode, setViewMode] = useState<"diff" | "edit">("diff")
  const [isFilesPanelOpen, setIsFilesPanelOpen] = useState(true)
  const [isBottomPanelOpen, setIsBottomPanelOpen] = useState(true)
  const [activeBottomTab, setActiveBottomTab] = useState<
    "metrics" | "explanation" | "test-results" | "review"
  >("metrics")
  const [copiedTests, setCopiedTests] = useState(false)
  const [isSaving, setIsSaving] = useState(false)
  const [lastSaved, setLastSaved] = useState<Date | null>(null)
  const [, setIsEditorReady] = useState(false)
  const [isContentLoaded, setIsContentLoaded] = useState(false)
  const [isTransitioning, setIsTransitioning] = useState(false)
  const [isDownloadingDiff, setIsDownloadingDiff] = useState(false)
  const [showApplyModal, setShowApplyModal] = useState(false)
  const [copiedCommand2, setCopiedCommand2] = useState(false)
  const [testFiles, setTestFiles] = useState<TestFile[]>([]) // NEW: Store parsed test files

  const editorRef = useRef<editor.IStandaloneCodeEditor | null>(null)
  const diffEditorRef = useRef<editor.IStandaloneDiffEditor | null>(null)
  const testEditorRef = useRef<editor.IStandaloneCodeEditor | null>(null)

  // Check if any operation is in progress
  const isAnyOperationInProgress = isCreatingPR || isDownloadingDiff || isSaving || isTransitioning

  // NEW: Parse test files when optimization info changes
  useEffect(() => {
    if (optimizationInfo?.generatedTests) {
      const parsedTests = parseTestCodeBlocks(optimizationInfo.generatedTests)
      setTestFiles(parsedTests)
    } else {
      setTestFiles([])
    }
  }, [optimizationInfo?.generatedTests])

  // Check if content is fully loaded (or if there's simply no diff content)
  useEffect(() => {
    const hasContent = Object.keys(diffContents).length > 0
    const isLoaded =
      !hasContent ||
      Object.values(diffContents).every(
        content => content.oldContent !== undefined && content.newContent !== undefined,
      )
    setIsContentLoaded(isLoaded)
  }, [diffContents])

  // Set up a theme listener that will update in real-time
  useEffect(() => {
    setMounted(true)
    checkTheme()

    const observer = new MutationObserver(mutations => {
      mutations.forEach(mutation => {
        if (mutation.attributeName === "class") {
          checkTheme()
        }
      })
    })

    observer.observe(document.documentElement, { attributes: true })

    return () => observer.disconnect()
  }, [])

  const checkTheme = () => {
    const isDark = document.documentElement.classList.contains("dark")
    setIsDarkMode(isDark)
  }

  // UPDATED: Build file tree with multiple test files
  useEffect(() => {
    const buildFileTree = () => {
      const root: FileNode[] = []
      const folderPaths = new Set<string>()

      // Add main diff contents
      Object.keys(diffContents).forEach(filePath => {
        const parts = filePath.split("/")
        let currentLevel = root
        let currentPath = ""

        parts.forEach((part, index) => {
          currentPath = currentPath ? `${currentPath}/${part}` : part
          const isFile = index === parts.length - 1

          if (!isFile) {
            folderPaths.add(currentPath)
          }

          let existingNode = currentLevel.find(node => node.name === part)

          if (!existingNode) {
            existingNode = {
              name: part,
              path: currentPath,
              type: isFile ? "file" : "folder",
              children: isFile ? undefined : [],
            }
            currentLevel.push(existingNode)
          }

          if (!isFile && existingNode.children) {
            currentLevel = existingNode.children
          }
        })
      })

      // Add test files
      testFiles.forEach(testFile => {
        const testParts = testFile.path.split("/")
        let currentLevel = root
        let currentPath = ""

        testParts.forEach((part, index) => {
          currentPath = currentPath ? `${currentPath}/${part}` : part
          const isFile = index === testParts.length - 1

          if (!isFile) {
            folderPaths.add(currentPath)
          }

          let existingNode = currentLevel.find(node => node.name === part)

          if (!existingNode) {
            existingNode = {
              name: part,
              path: currentPath,
              type: isFile ? "file" : "folder",
              children: isFile ? undefined : [],
              isTest: isFile,
            }
            currentLevel.push(existingNode)
          }

          if (!isFile && existingNode.children) {
            currentLevel = existingNode.children
          }
        })
      })

      setExpandedFolders(folderPaths)

      return root
    }

    setFileTree(buildFileTree())
    const firstDiffFile = Object.keys(diffContents)[0]
    const firstTestFile = testFiles[0]?.path
    // Prefer diff files, but fall back to test files in privacy mode
    const firstFile = firstDiffFile || firstTestFile
    if (firstFile && !selectedFile) {
      setSelectedFile(firstFile)
    }
  }, [diffContents, testFiles, selectedFile])

  // UPDATED: Check if file is a test file
  const isTestFile = useCallback(
    (path: string) => testFiles.some(tf => tf.path === path),
    [testFiles],
  )

  // UPDATED: Get test file content
  const getTestFileContent = (path: string): string => {
    const testFile = testFiles.find(tf => tf.path === path)
    return testFile?.content || ""
  }

  const toggleFolder = (path: string) => {
    setExpandedFolders(prev => {
      const newSet = new Set(prev)
      if (newSet.has(path)) {
        newSet.delete(path)
      } else {
        newSet.add(path)
      }
      return newSet
    })
  }

  // Generate unified diff format using the diff library
  const generateGitDiff = useCallback(() => {
    let diff = ""
    diff += `# Generated by Codeflash\n`
    if (functionName) {
      diff += `# Function: ${functionName}\n`
    }
    diff += `\n`

    Object.entries(modifiedContents).forEach(([filePath, content]) => {
      const patch = createPatch(
        filePath,
        content.oldContent,
        content.newContent,
        "original",
        "optimized",
      )
      diff += patch + "\n"
    })
    return diff
  }, [modifiedContents, functionName])

  const handleDownloadGitDiff = useCallback(async () => {
    if (isAnyOperationInProgress) {
      return
    }

    setIsDownloadingDiff(true)

    try {
      await new Promise(resolve => setTimeout(resolve, 500))

      const diffContent = generateGitDiff()
      const blob = new Blob([diffContent], { type: "text/plain;charset=utf-8" })
      const url = URL.createObjectURL(blob)
      const link = document.createElement("a")

      const timestamp = new Date().toISOString().replace(/[:.]/g, "-").split("T")[0]
      const filename = functionName
        ? `${functionName.replace(/[^a-zA-Z0-9_-]/g, "_")}-optimization-${timestamp}.patch`
        : `optimization-${timestamp}.patch`

      link.href = url
      link.download = filename
      document.body.appendChild(link)
      link.click()
      document.body.removeChild(link)
      URL.revokeObjectURL(url)

      setShowApplyModal(true)
    } catch (error) {
      console.error("Failed to download git diff:", error)
    } finally {
      setIsDownloadingDiff(false)
    }
  }, [generateGitDiff, functionName, isAnyOperationInProgress])

  const copyCommandToClipboard = async (command: string) => {
    try {
      await navigator.clipboard.writeText(command)
      setCopiedCommand2(true)
      setTimeout(() => setCopiedCommand2(false), 2000)
    } catch (err) {
      console.error("Failed to copy command:", err)
    }
  }

  // Autosave logic
  const performAutosave = useCallback(
    (filePath: string, content: string) => {
      setIsSaving(true)

      if (onEdit) {
        onEdit(filePath, content)
      }

      setTimeout(() => {
        setIsSaving(false)
        setLastSaved(new Date())
      }, 500)
    },
    [onEdit],
  )

  const debouncedAutosave = useDebounce(performAutosave, 1000)

  const handleEditorChange = useCallback(
    (value: string | undefined) => {
      if (!selectedFile || isTestFile(selectedFile)) return

      const newValue = value || ""

      setModifiedContents(prev => ({
        ...prev,
        [selectedFile]: {
          ...prev[selectedFile],
          newContent: newValue,
        },
      }))

      if (onContentChange) {
        onContentChange(selectedFile, newValue)
      }

      // Skip autosave if disabled (e.g., for git_branch storage)
      if (!disableAutoSave) {
        debouncedAutosave(selectedFile, newValue)
      }
    },
    [selectedFile, onContentChange, debouncedAutosave, isTestFile, disableAutoSave],
  )

  const handleManualSave = useCallback(() => {
    if (!selectedFile || isTestFile(selectedFile) || !editorRef.current) return

    const content = editorRef.current.getValue()
    performAutosave(selectedFile, content)
  }, [selectedFile, performAutosave, isTestFile])

  const handleUndo = useCallback(() => {
    if (editorRef.current && viewMode === "edit" && !isTestFile(selectedFile)) {
      editorRef.current.trigger("keyboard", "undo", null)
      editorRef.current.focus()
    }
  }, [selectedFile, viewMode, isTestFile])

  const handleRedo = useCallback(() => {
    if (editorRef.current && viewMode === "edit" && !isTestFile(selectedFile)) {
      editorRef.current.trigger("keyboard", "redo", null)
      editorRef.current.focus()
    }
  }, [selectedFile, viewMode, isTestFile])

  const handleEditorDidMount = useCallback(
    (editor: editor.IStandaloneCodeEditor) => {
      editorRef.current = editor
      setIsEditorReady(true)

      if (!isTestFile(selectedFile)) {
        editor.focus()
      }

      editor.addCommand(2048 /* CtrlCmd */ | 49 /* KeyS */, () => {
        handleManualSave()
      })
    },
    [selectedFile, handleManualSave, isTestFile],
  )

  const handleTestEditorDidMount = useCallback((editor: editor.IStandaloneCodeEditor) => {
    testEditorRef.current = editor
    setIsEditorReady(true)
  }, [])

  const handleDiffEditorDidMount = useCallback((diffEditor: editor.IStandaloneDiffEditor) => {
    diffEditorRef.current = diffEditor
    setIsEditorReady(true)

    const disposable = diffEditor.onDidUpdateDiff(() => {
      const lineChanges = diffEditor.getLineChanges()
      if (lineChanges && lineChanges.length > 0) {
        const firstChange = lineChanges[0]
        const targetLine =
          firstChange.modifiedStartLineNumber || firstChange.originalStartLineNumber || 1
        const modifiedEditor = diffEditor.getModifiedEditor()
        modifiedEditor.revealLineInCenter(targetLine)
      }
      disposable.dispose()
    })
  }, [])

  const handleFileSelect = useCallback(
    (filePath: string) => {
      if (isAnyOperationInProgress) return

      setIsTransitioning(true)

      if (editorRef.current) {
        editorRef.current = null
      }
      if (diffEditorRef.current) {
        diffEditorRef.current = null
      }
      if (testEditorRef.current) {
        testEditorRef.current = null
      }

      setTimeout(() => {
        setSelectedFile(filePath)
        setIsEditorReady(false)
        setIsTransitioning(false)
      }, 100)
    },
    [isAnyOperationInProgress],
  )

  const handleViewModeChange = useCallback(
    (mode: "diff" | "edit") => {
      if (isAnyOperationInProgress) return

      setIsTransitioning(true)

      if (editorRef.current) {
        editorRef.current = null
      }
      if (diffEditorRef.current) {
        diffEditorRef.current = null
      }

      setTimeout(() => {
        setViewMode(mode)
        setIsEditorReady(false)
        setIsTransitioning(false)
      }, 100)
    },
    [isAnyOperationInProgress],
  )

  // UPDATED: Copy test file content to clipboard
  const copyToClipboard = async (text: string) => {
    try {
      await navigator.clipboard.writeText(text)
      setCopiedTests(true)
      setTimeout(() => setCopiedTests(false), 2000)
    } catch (err) {
      console.error("Failed to copy:", err)
    }
  }

  const handleCreatePR = async () => {
    if (!onCreatePR || isAnyOperationInProgress) return
    await onCreatePR()
  }

  const handleViewPRClick = () => {
    if (!onViewPR) return
    onViewPR()
  }

  const handleReviewBadgeClick = () => {
    setActiveBottomTab("review")
    if (!isBottomPanelOpen) {
      setIsBottomPanelOpen(true)
    }
  }

  const renderFileTree = (nodes: FileNode[], level = 0): JSX.Element[] => {
    return nodes.map(node => {
      const isExpanded = expandedFolders.has(node.path)
      const isSelected = node.path === selectedFile

      if (node.type === "folder") {
        return (
          <div key={node.path}>
            <div
              className={`flex items-center gap-1 px-2 py-1 hover:bg-accent cursor-pointer select-none transition-colors`}
              style={{ paddingLeft: `${level * 12 + 8}px` }}
              onClick={() => toggleFolder(node.path)}
            >
              <ChevronRight
                className={`w-4 h-4 text-muted-foreground transition-transform duration-200 ${isExpanded ? "rotate-90" : ""}`}
              />
              {isExpanded ? (
                <FolderOpen className="w-4 h-4 text-muted-foreground" />
              ) : (
                <Folder className="w-4 h-4 text-muted-foreground" />
              )}
              <span className="text-sm text-foreground">{node.name}</span>
            </div>
            <div
              className={`overflow-hidden transition-all duration-200 ${
                isExpanded ? "max-h-[1000px] opacity-100" : "max-h-0 opacity-0"
              }`}
            >
              {node.children && renderFileTree(node.children, level + 1)}
            </div>
          </div>
        )
      }

      return (
        <div
          key={node.path}
          className={`flex items-center gap-1 px-2 py-1 cursor-pointer select-none transition-colors ${
            isSelected
              ? "bg-secondary text-secondary-foreground"
              : "hover:bg-accent hover:text-accent-foreground"
          }`}
          style={{ paddingLeft: `${level * 12 + 24}px` }}
          onClick={() => handleFileSelect(node.path)}
        >
          {node.isTest ? (
            <TestTube2 className={`w-4 h-4 ${isSelected ? "text-green-600" : "text-green-500"}`} />
          ) : (
            <FileText className="w-4 h-4 text-muted-foreground" />
          )}
          <span className={`text-sm ${isSelected ? "font-medium" : ""}`}>{node.name}</span>
        </div>
      )
    })
  }

  const parseTestType = (testType: string) => {
    const emojiMatch = testType.match(
      /^([\u{1F300}-\u{1F9FF}]|[\u{2600}-\u{26FF}]|⚙️|⏪|🔎|🌀|🎨)/u,
    )
    const emoji = emojiMatch ? emojiMatch[0] : ""
    const label = testType.replace(emoji, "").trim()
    return { emoji, label }
  }

  if (!mounted || !isContentLoaded) {
    return (
      <div className="flex h-full w-full bg-card border border-border rounded-lg overflow-hidden shadow-sm">
        <div className="w-64 bg-muted/30 border-r border-border flex flex-col">
          <div className="p-3 border-b border-border">
            <h3 className="text-sm font-medium text-foreground">Files</h3>
          </div>
          <div className="flex-1 flex items-center justify-center">
            <Loader2 className="w-6 h-6 animate-spin text-muted-foreground" />
          </div>
        </div>
        <div className="flex-1 bg-background flex items-center justify-center">
          <div className="text-center">
            <Loader2 className="w-8 h-8 animate-spin text-muted-foreground mx-auto mb-2" />
            <p className="text-sm text-muted-foreground">Loading editor...</p>
          </div>
        </div>
      </div>
    )
  }

  // Show empty state when there's no diff content AND no test files AND not privacy mode
  const hasNoDiffContent = Object.keys(diffContents).length === 0 && testFiles.length === 0
  if (hasNoDiffContent && !isPrivacyModeNoDiff) {
    return (
      <div className="flex h-full w-full bg-card border border-border rounded-lg overflow-hidden shadow-sm">
        <div className="flex-1 bg-background flex items-center justify-center">
          <div className="text-center p-8">
            <FileText className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
            <h3 className="text-lg font-medium text-foreground mb-2">No Changes Available</h3>
            <p className="text-sm text-muted-foreground max-w-md">
              There are no code changes to display. The staging branch may have been merged or
              deleted.
            </p>
          </div>
        </div>
      </div>
    )
  }

  // Check if we're in privacy mode with no diff (but might have test files/optimization info)
  const showPrivacyModeMessage = isPrivacyModeNoDiff && Object.keys(diffContents).length === 0

  const prCommentFields = optimizationInfo?.prCommentFields || {}
  const reportTable = prCommentFields.report_table || {}

  const totalPassed = Object.values(reportTable).reduce(
    (acc: number, curr: TestResults) => acc + curr.passed,
    0,
  )

  const bottomTabs = [
    { id: "metrics", label: "Performance", icon: Zap },
    { id: "explanation", label: "Explanation", icon: Info },
    {
      id: "test-results",
      label: `Results ${totalPassed > 0 ? `(${totalPassed})` : ""}`,
      icon: TestTube2,
    },
    { id: "review", label: "Review Details", icon: Star },
  ]

  type BottomTabId = "metrics" | "explanation" | "test-results" | "review"

  // UPDATED: Get editor content based on file type
  const editorContent = isTestFile(selectedFile)
    ? getTestFileContent(selectedFile)
    : modifiedContents[selectedFile]?.newContent || ""

  const originalContent = !isTestFile(selectedFile)
    ? modifiedContents[selectedFile]?.oldContent || ""
    : ""

  const editorKey = `${selectedFile}-${viewMode}-edit`
  const diffEditorKey = `${selectedFile}-${viewMode}-diff`
  const testEditorKey = `${selectedFile}-test`

  return (
    <div className="flex flex-col h-full w-full bg-card border border-border rounded-lg overflow-hidden shadow-sm relative">
      {/* Apply Diff Modal */}
      {showApplyModal && (
        <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/50 backdrop-blur-sm p-4">
          <div className="bg-popover text-popover-foreground rounded-lg shadow-2xl border border-border max-w-2xl w-full animate-in fade-in zoom-in duration-200">
            <div className="flex items-center justify-between p-5 border-b border-border bg-gradient-to-r from-primary/5 to-primary/10">
              <div className="flex items-center gap-3">
                <div className="p-2 bg-primary/10 rounded-lg">
                  <Terminal className="w-5 h-5 text-primary" />
                </div>
                <div>
                  <h2 className="text-lg font-semibold">Apply Your Optimization</h2>
                </div>
              </div>
              <button
                onClick={() => setShowApplyModal(false)}
                className="p-1.5 hover:bg-accent rounded-md transition-colors"
                aria-label="Close dialog"
              >
                <X className="w-5 h-5" />
              </button>
            </div>
            <div className="p-6 space-y-5">
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-bold">
                    1
                  </div>
                  <h3 className="font-semibold text-sm">Navigate to your module directory</h3>
                </div>
              </div>
              <div className="space-y-3">
                <div className="flex items-center gap-2">
                  <div className="flex items-center justify-center w-6 h-6 rounded-full bg-primary text-primary-foreground text-xs font-bold">
                    2
                  </div>
                  <h3 className="font-semibold text-sm">Apply the patch file</h3>
                </div>
                <div className="ml-8 bg-muted rounded-lg p-4">
                  <div className="flex items-center justify-between gap-2">
                    <code className="text-sm font-mono text-foreground flex-1">
                      git apply your-downloaded-file.patch
                    </code>
                    <button
                      onClick={() => copyCommandToClipboard("git apply your-downloaded-file.patch")}
                      className="p-1.5 hover:bg-accent rounded-md transition-colors flex-shrink-0"
                      title="Copy command"
                    >
                      {copiedCommand2 ? (
                        <Check className="w-3.5 h-3.5 text-green-500" />
                      ) : (
                        <Copy className="w-3.5 h-3.5 text-muted-foreground hover:text-foreground" />
                      )}
                    </button>
                  </div>
                  <p className="text-xs text-muted-foreground mt-2">
                    Replace{" "}
                    <code className="font-mono bg-muted-foreground/10 px-1.5 py-0.5 rounded">
                      your-downloaded-file.patch
                    </code>{" "}
                    with the actual filename from your Downloads folder
                  </p>
                </div>
              </div>
            </div>
            <div className="flex items-center justify-between gap-3 p-4 border-t border-border bg-muted/30">
              <a
                href="https://git-scm.com/docs/git-apply"
                target="_blank"
                rel="noopener noreferrer"
                className="text-xs text-muted-foreground hover:text-foreground transition-colors flex items-center gap-1"
              >
                <ExternalLink className="w-3 h-3" />
                Learn more about git apply
              </a>
              <button
                onClick={() => setShowApplyModal(false)}
                className="px-4 py-2 bg-primary text-primary-foreground rounded-md hover:bg-primary/90 transition-colors text-sm font-medium shadow-sm hover:shadow-md"
              >
                Got it, thanks!
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Header Bar */}
      <div className="flex items-center justify-between w-full px-4 py-2.5 bg-gradient-to-r from-muted/50 to-muted/30 border-b border-border backdrop-blur-sm">
        <div className="flex items-center gap-4">
          <button
            onClick={() => setIsFilesPanelOpen(!isFilesPanelOpen)}
            disabled={isAnyOperationInProgress}
            className="p-1.5 hover:bg-accent rounded-md transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed hover:scale-105 active:scale-95"
            title={isFilesPanelOpen ? "Hide files panel" : "Show files panel"}
          >
            {isFilesPanelOpen ? (
              <PanelLeftClose className="w-5 h-5 text-muted-foreground" />
            ) : (
              <PanelLeft className="w-5 h-5 text-muted-foreground" />
            )}
          </button>

          {functionName && (
            <div className="flex items-center gap-2 text-sm bg-yellow-500/10 px-3 py-1.5 rounded-md border border-yellow-500/20">
              <Zap className="w-4 h-4 text-yellow-600 dark:text-yellow-500" />
              <span className="font-medium text-foreground">
                Optimized{" "}
                <code className="font-mono text-yellow-700 dark:text-yellow-400">
                  {functionName}()
                </code>
              </span>
            </div>
          )}

          {optimizationInfo?.review_quality && (
            <ReviewQualityBadge
              quality={optimizationInfo.review_quality}
              asButton
              onClick={handleReviewBadgeClick}
            />
          )}

          {viewMode === "edit" && !isTestFile(selectedFile) && !disableAutoSave && (
            <div className="flex items-center gap-2 text-xs">
              {isSaving ? (
                <div className="flex items-center gap-1.5 px-2.5 py-1 bg-blue-500/10 text-blue-600 dark:text-blue-400 rounded-md border border-blue-500/20">
                  <Loader2 className="w-3 h-3 animate-spin" />
                  <span className="font-medium">Saving...</span>
                </div>
              ) : lastSaved ? (
                <div className="flex items-center gap-1.5 px-2.5 py-1 bg-green-500/10 text-green-600 dark:text-green-400 rounded-md border border-green-500/20">
                  <CheckCircle2 className="w-3 h-3" />
                  <span className="font-medium">Saved</span>
                </div>
              ) : null}
            </div>
          )}
        </div>

        <div className="flex items-center gap-2">
          {showGitDiffDownload && (
            <button
              onClick={handleDownloadGitDiff}
              disabled={isAnyOperationInProgress}
              className={`group px-4 py-2 rounded-md transition-all duration-200 flex items-center gap-2 text-sm font-medium shadow-sm
                bg-primary hover:bg-primary/90 text-primary-foreground border border-primary
                disabled:opacity-50 disabled:cursor-not-allowed
                hover:shadow-md hover:scale-[1.02] active:scale-[0.98]`}
              title="Download changes as .patch file"
            >
              {isDownloadingDiff ? (
                <>
                  <Loader2 className="w-4 h-4 animate-spin" />
                  <span>Downloading...</span>
                </>
              ) : (
                <>
                  <FileCode2 className="w-4 h-4 group-hover:rotate-6 transition-transform" />
                  <span className="hidden sm:inline">Download Diff</span>
                  <span className="sm:hidden">Diff</span>
                  <Download className="w-3.5 h-3.5 group-hover:translate-y-0.5 transition-transform" />
                </>
              )}
            </button>
          )}

          {prNumber ? (
            <button
              onClick={handleViewPRClick}
              disabled={isAnyOperationInProgress}
              className="px-4 py-2 bg-gradient-to-r from-green-600 to-emerald-600 hover:from-green-700 hover:to-emerald-700 text-white rounded-md transition-all duration-200 flex items-center gap-2 text-sm font-medium shadow-sm hover:shadow-md hover:scale-[1.02] active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed"
              title={`View PR #${prNumber} on GitHub`}
            >
              <ExternalLink className="w-4 h-4" />
              <span className="hidden sm:inline">View PR</span> #{prNumber}
            </button>
          ) : (
            onCreatePR && (
              <button
                onClick={handleCreatePR}
                disabled={isAnyOperationInProgress}
                className="px-4 py-2 bg-gradient-to-r from-blue-600 to-cyan-600 hover:from-blue-700 hover:to-cyan-700 text-white rounded-md transition-all duration-200 flex items-center gap-2 text-sm font-medium shadow-sm hover:shadow-md hover:scale-[1.02] active:scale-[0.98] disabled:opacity-50 disabled:cursor-not-allowed border border-blue-700"
              >
                {isCreatingPR ? (
                  <>
                    <Loader2 className="w-4 h-4 animate-spin" />
                    Creating PR...
                  </>
                ) : (
                  <>
                    <GitPullRequest className="w-4 h-4" />
                    Create PR
                  </>
                )}
              </button>
            )
          )}

          <button
            onClick={() => setIsBottomPanelOpen(!isBottomPanelOpen)}
            disabled={isAnyOperationInProgress}
            className="p-1.5 hover:bg-accent rounded-md transition-all duration-200 disabled:opacity-50 disabled:cursor-not-allowed hover:scale-105 active:scale-95"
            title={isBottomPanelOpen ? "Hide bottom panel" : "Show bottom panel"}
          >
            {isBottomPanelOpen ? (
              <PanelBottomClose className="w-5 h-5 text-muted-foreground" />
            ) : (
              <PanelBottom className="w-5 h-5 text-muted-foreground" />
            )}
          </button>
        </div>
      </div>

      {/* Main Layout Container */}
      <div className="flex-1 flex flex-col w-full overflow-hidden">
        <div className={`flex w-full overflow-hidden ${isBottomPanelOpen ? "flex-1" : "h-full"}`}>
          {/* File Explorer */}
          <div
            className={`bg-background border-r border-border flex flex-col transition-all duration-300 ${
              isFilesPanelOpen ? "w-64" : "w-0"
            }`}
          >
            <div
              className={`h-full transition-opacity duration-300 ${isFilesPanelOpen ? "opacity-100" : "opacity-0"}`}
            >
              <div className="p-3 border-b border-border bg-muted/20">
                <h3 className="text-sm font-semibold text-foreground">Files</h3>
              </div>
              <div className="flex-1 overflow-y-auto overflow-x-hidden">
                {renderFileTree(fileTree)}
              </div>
            </div>
          </div>

          {/* Editor Area */}
          <div className="flex-1 flex flex-col bg-background overflow-hidden">
            {/* Privacy mode banner - always visible when in privacy mode with no diff */}
            {showPrivacyModeMessage && (
              <div className="px-4 py-2.5 bg-amber-500/10 border-b border-amber-500/20 flex items-center justify-between">
                <div className="flex items-center gap-2">
                  <Info className="w-4 h-4 text-amber-600 dark:text-amber-500 flex-shrink-0" />
                  <p className="text-sm text-amber-700 dark:text-amber-400">
                    <span className="font-medium">Code diff not available.</span> The PR has been
                    merged and the staging branch was deleted.
                  </p>
                </div>
              </div>
            )}
            {/* Show centered message when no file selected in privacy mode */}
            {showPrivacyModeMessage && !selectedFile ? (
              <div className="flex-1 flex items-center justify-center">
                <div className="text-center p-8 max-w-md">
                  <TestTube2 className="w-10 h-10 text-muted-foreground mx-auto mb-3" />
                  <p className="text-sm text-muted-foreground">
                    Select a test file from the sidebar to view
                  </p>
                </div>
              </div>
            ) : selectedFile ? (
              <>
                <div className="px-4 py-2 bg-muted/30 border-b border-border flex items-center justify-between w-full">
                  <h3 className="text-sm font-medium text-foreground flex items-center gap-2">
                    {isTestFile(selectedFile) ? (
                      <TestTube2 className="w-4 h-4 text-green-500" />
                    ) : (
                      <FileText className="w-4 h-4 text-primary" />
                    )}
                    {selectedFile}
                  </h3>
                  <div className="flex items-center gap-2">
                    {isTestFile(selectedFile) ? (
                      <button
                        onClick={() => copyToClipboard(getTestFileContent(selectedFile))}
                        disabled={isAnyOperationInProgress}
                        className="px-3 py-1.5 text-xs font-medium rounded-md transition-all duration-200 bg-muted text-foreground hover:bg-accent flex items-center gap-1.5 hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed shadow-sm"
                        title="Copy test code"
                      >
                        {copiedTests ? (
                          <>
                            <Check className="w-3.5 h-3.5 text-green-500" />
                            Copied!
                          </>
                        ) : (
                          <>
                            <Copy className="w-3.5 h-3.5" />
                            Copy
                          </>
                        )}
                      </button>
                    ) : (
                      <>
                        {viewMode === "edit" && (
                          <>
                            <button
                              onClick={handleUndo}
                              disabled={isAnyOperationInProgress}
                              className="p-1.5 text-xs font-medium rounded-md transition-all duration-200 bg-muted text-foreground hover:bg-accent hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Undo (Ctrl/Cmd+Z)"
                            >
                              <Undo className="w-3.5 h-3.5" />
                            </button>
                            <button
                              onClick={handleRedo}
                              disabled={isAnyOperationInProgress}
                              className="p-1.5 text-xs font-medium rounded-md transition-all duration-200 bg-muted text-foreground hover:bg-accent hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
                              title="Redo (Ctrl/Cmd+Shift+Z)"
                            >
                              <Redo className="w-3.5 h-3.5" />
                            </button>
                            {!disableAutoSave && (
                              <button
                                onClick={handleManualSave}
                                disabled={isAnyOperationInProgress || isSaving}
                                className="p-1.5 text-xs font-medium rounded-md transition-all duration-200 bg-muted text-foreground hover:bg-accent hover:scale-105 active:scale-95 disabled:opacity-50 disabled:cursor-not-allowed"
                                title="Save (Ctrl/Cmd+S)"
                              >
                                <Save className="w-3.5 h-3.5" />
                              </button>
                            )}
                            <div className="w-px h-4 bg-border mx-1" />
                          </>
                        )}
                        <button
                          onClick={() => handleViewModeChange("edit")}
                          disabled={isTransitioning}
                          className={`px-3 py-1.5 text-xs font-medium rounded-md transition-all duration-200 flex items-center gap-1.5 shadow-sm hover:scale-105 active:scale-95 ${
                            viewMode === "edit"
                              ? "bg-primary text-primary-foreground"
                              : "bg-muted text-muted-foreground hover:bg-accent"
                          } disabled:opacity-50 disabled:cursor-not-allowed`}
                        >
                          <Edit className="w-3.5 h-3.5" />
                          Edit
                        </button>
                        <button
                          onClick={() => handleViewModeChange("diff")}
                          disabled={isTransitioning}
                          className={`px-3 py-1.5 text-xs font-medium rounded-md transition-all duration-200 flex items-center gap-1.5 shadow-sm hover:scale-105 active:scale-95 ${
                            viewMode === "diff"
                              ? "bg-primary text-primary-foreground"
                              : "bg-muted text-muted-foreground hover:bg-accent"
                          } disabled:opacity-50 disabled:cursor-not-allowed`}
                        >
                          <Eye className="w-3.5 h-3.5" />
                          Diff
                        </button>
                      </>
                    )}
                  </div>
                </div>
                <div className="flex-1 relative w-full overflow-hidden">
                  {isTransitioning ? (
                    <div className="absolute inset-0 flex items-center justify-center bg-background">
                      <div className="text-center">
                        <Loader2 className="w-8 h-8 animate-spin text-primary mx-auto mb-2" />
                        <p className="text-sm text-muted-foreground">Loading...</p>
                      </div>
                    </div>
                  ) : (
                    <>
                      {isTestFile(selectedFile) ? (
                        <div className="absolute inset-0 w-full h-full">
                          <Editor
                            key={testEditorKey}
                            value={editorContent}
                            language={getMonacoLanguage(selectedFile)}
                            theme={isDarkMode ? "vs-dark" : "light"}
                            onMount={handleTestEditorDidMount}
                            options={{
                              readOnly: true,
                              automaticLayout: true,
                              fontSize: 14,
                              minimap: { enabled: false },
                              scrollBeyondLastLine: false,
                              wordWrap: "on",
                              lineNumbers: "on",
                              renderLineHighlight: "none",
                              scrollbar: {
                                vertical: "visible",
                                horizontal: "visible",
                                useShadows: false,
                                verticalHasArrows: false,
                                horizontalHasArrows: false,
                                verticalScrollbarSize: 10,
                                horizontalScrollbarSize: 10,
                              },
                            }}
                          />
                        </div>
                      ) : viewMode === "diff" &&
                        originalContent === editorContent &&
                        originalContent.trim() === "" ? (
                        <div className="absolute inset-0 w-full h-full flex items-center justify-center bg-background">
                          <div className="text-center p-8">
                            <FileText className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                            <h3 className="text-lg font-medium text-foreground mb-2">
                              No Changes to Display
                            </h3>
                            <p className="text-sm text-muted-foreground max-w-md">
                              The file content is empty. The staging branch may have been merged or
                              the changes have been reverted.
                            </p>
                          </div>
                        </div>
                      ) : viewMode === "diff" && originalContent === editorContent ? (
                        <div className="absolute inset-0 w-full h-full flex items-center justify-center bg-background">
                          <div className="text-center p-8">
                            <FileText className="w-12 h-12 text-muted-foreground mx-auto mb-4" />
                            <h3 className="text-lg font-medium text-foreground mb-2">
                              No Differences Found
                            </h3>
                            <p className="text-sm text-muted-foreground max-w-md">
                              The original and optimized code are identical. The changes may have
                              already been applied or reverted.
                            </p>
                          </div>
                        </div>
                      ) : (
                        <>
                          {viewMode === "edit" ? (
                            <div className="absolute inset-0 w-full h-full">
                              <Editor
                                key={editorKey}
                                value={editorContent}
                                language={getMonacoLanguage(selectedFile)}
                                theme={isDarkMode ? "vs-dark" : "light"}
                                onChange={handleEditorChange}
                                onMount={handleEditorDidMount}
                                options={{
                                  automaticLayout: true,
                                  fontSize: 14,
                                  minimap: { enabled: false },
                                  scrollBeyondLastLine: false,
                                  wordWrap: "on",
                                  lineNumbers: "on",
                                  renderLineHighlight: "all",
                                  scrollbar: {
                                    vertical: "visible",
                                    horizontal: "visible",
                                    useShadows: false,
                                    verticalHasArrows: false,
                                    horizontalHasArrows: false,
                                    verticalScrollbarSize: 10,
                                    horizontalScrollbarSize: 10,
                                  },
                                }}
                              />
                            </div>
                          ) : (
                            <div className="absolute inset-0 w-full h-full">
                              <DiffEditor
                                key={diffEditorKey}
                                original={originalContent}
                                modified={editorContent}
                                language={getMonacoLanguage(selectedFile)}
                                theme={isDarkMode ? "vs-dark" : "light"}
                                onMount={handleDiffEditorDidMount}
                                keepCurrentOriginalModel={true}
                                keepCurrentModifiedModel={true}
                                options={{
                                  renderSideBySide: true,
                                  automaticLayout: true,
                                  fontSize: 14,
                                  minimap: { enabled: false },
                                  scrollBeyondLastLine: false,
                                  wordWrap: "on",
                                  diffWordWrap: "on",
                                  readOnly: true,
                                  renderValidationDecorations: "off",
                                  originalEditable: false,
                                  scrollbar: {
                                    vertical: "visible",
                                    horizontal: "visible",
                                    useShadows: false,
                                    verticalHasArrows: false,
                                    horizontalHasArrows: false,
                                    verticalScrollbarSize: 10,
                                    horizontalScrollbarSize: 10,
                                  },
                                }}
                              />
                            </div>
                          )}
                        </>
                      )}
                    </>
                  )}
                </div>
              </>
            ) : null}
          </div>
        </div>

        {/* Bottom Panel */}
        {optimizationInfo && (
          <div
            className={`bg-muted/30 border-t border-border transition-all duration-300 w-full ${
              isBottomPanelOpen ? "h-80" : "h-0"
            } overflow-hidden`}
          >
            <div
              className={`h-full flex flex-col transition-opacity duration-300 ${isBottomPanelOpen ? "opacity-100" : "opacity-0"}`}
            >
              <div className="px-4 py-2 bg-muted/30 border-b border-border flex items-center gap-2 w-full">
                {bottomTabs.map(tab => {
                  const Icon = tab.icon
                  return (
                    <button
                      key={tab.id}
                      onClick={() => setActiveBottomTab(tab.id as BottomTabId)}
                      className={`px-3 py-1.5 text-xs font-medium rounded-md transition-all duration-200 flex items-center gap-1.5 shadow-sm hover:scale-105 active:scale-95 ${
                        activeBottomTab === tab.id
                          ? "bg-primary text-primary-foreground"
                          : "bg-muted text-muted-foreground hover:bg-accent"
                      }`}
                    >
                      <Icon className="w-3.5 h-3.5" />
                      {tab.label}
                    </button>
                  )
                })}
              </div>

              <div className="flex-1 overflow-y-auto p-4 w-full">
                {activeBottomTab === "metrics" && (
                  <div className="grid grid-cols-2 lg:grid-cols-4 gap-3 w-full">
                    <div className="border rounded-lg p-4 bg-gradient-to-br from-background to-muted/20 shadow-sm hover:shadow-md transition-shadow">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
                        <Clock className="w-3.5 h-3.5" />
                        Original Runtime
                      </div>
                      <div className="text-xl font-mono font-semibold">
                        {prCommentFields.original_runtime || "N/A"}
                      </div>
                    </div>
                    <div className="border rounded-lg p-4 bg-gradient-to-br from-green-500/5 to-emerald-500/5 shadow-sm hover:shadow-md transition-shadow border-green-500/20">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
                        <Zap className="w-3.5 h-3.5 text-green-600" />
                        Optimized Runtime
                      </div>
                      <div className="text-xl font-mono font-semibold text-green-600 dark:text-green-500">
                        {prCommentFields.best_runtime || "N/A"}
                      </div>
                    </div>
                    <div className="border rounded-lg p-4 bg-gradient-to-br from-background to-muted/20 shadow-sm hover:shadow-md transition-shadow">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
                        <IterationCw className="w-3.5 h-3.5" />
                        Benchmarking loops
                      </div>
                      <div className="text-xl font-mono font-semibold">
                        {prCommentFields.loop_count || 0}
                      </div>
                    </div>
                    <div className="border rounded-lg p-4 bg-gradient-to-br from-yellow-500/5 to-amber-500/5 shadow-sm hover:shadow-md transition-shadow border-yellow-500/20">
                      <div className="flex items-center gap-2 text-xs text-muted-foreground mb-2">
                        <Percent className="w-3.5 h-3.5 text-yellow-600" />
                        Improvement
                      </div>
                      <div className="text-xl font-mono font-semibold text-green-600 dark:text-green-500">
                        {optimizationInfo.speedup_x && `${optimizationInfo.speedup_x.toFixed(2)}x`}
                      </div>
                    </div>
                  </div>
                )}

                {activeBottomTab === "explanation" && (
                  <div
                    className={`prose prose-sm max-w-none w-full ${isDarkMode ? "prose-invert" : ""}
                    [&_code]:font-mono [&_code]:text-xs [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:rounded
                    [&_code]:bg-muted [&_code]:text-foreground
                    [&_pre]:bg-muted [&_pre]:text-sm [&_pre]:p-4 [&_pre]:rounded [&_pre]:overflow-x-auto
                    [&_pre_code]:bg-transparent [&_pre_code]:p-0
                    [&_table]:w-full [&_table]:border-collapse
                    [&_th]:border [&_td]:border [&_th]:border-border [&_td]:border-border
                    [&_th]:bg-muted [&_th]:px-4 [&_th]:py-2 [&_td]:px-4 [&_td]:py-2
                    [&_blockquote]:border-l-4 [&_blockquote]:border-primary [&_blockquote]:pl-4
                    [&_ul]:list-disc [&_ul]:pl-6 [&_ul]:space-y-1
                    [&_ol]:list-decimal [&_ol]:pl-6 [&_ol]:space-y-1
                    [&_li]:text-sm
                    [&_p]:text-sm [&_p]:leading-relaxed`}
                  >
                    {prCommentFields.optimization_explanation ? (
                      <ReactMarkdown remarkPlugins={[remarkGfm]}>
                        {prCommentFields.optimization_explanation}
                      </ReactMarkdown>
                    ) : (
                      <p className="text-sm text-muted-foreground">No explanation available</p>
                    )}
                  </div>
                )}

                {activeBottomTab === "test-results" && (
                  <div className="space-y-3 w-full">
                    <div className="grid grid-cols-1 md:grid-cols-2 lg:grid-cols-3 gap-3">
                      {Object.entries(reportTable)
                        .filter(([testType]) => !testType.includes("🎨"))
                        .map(([testType, results]) => {
                          const { emoji, label } = parseTestType(testType)
                          const hasTests = results.passed > 0 || results.failed > 0

                          return (
                            <div
                              key={testType}
                              className="flex items-center justify-between p-3 rounded-lg bg-background border transition-all duration-200 hover:shadow-md hover:scale-[1.02]"
                            >
                              <div className="flex items-center gap-2">
                                <span className="text-lg">{emoji}</span>
                                <span className="text-sm font-medium">{label}</span>
                              </div>
                              <div className="text-sm">
                                {!hasTests ? (
                                  <span className="text-muted-foreground">None</span>
                                ) : (
                                  <span className="font-semibold text-green-600 dark:text-green-500">
                                    {results.passed} ✓
                                  </span>
                                )}
                              </div>
                            </div>
                          )
                        })}
                    </div>
                    <div className="mt-6 pt-4 border-t">
                      <div className="grid grid-cols-2 gap-6">
                        <div className="text-center p-4 rounded-lg bg-green-500/10 border border-green-500/20">
                          <div className="text-3xl font-bold text-green-600 dark:text-green-500">
                            {totalPassed}
                          </div>
                          <div className="text-sm text-muted-foreground mt-1">Tests Passed</div>
                        </div>
                        <div className="text-center p-4 rounded-lg bg-blue-500/10 border border-blue-500/20">
                          <div
                            className={`text-3xl font-bold ${
                              parseFloat(
                                (optimizationInfo.coverage_message || "").replace("%", ""),
                              ) >= 80
                                ? "text-green-600 dark:text-green-500"
                                : parseFloat(
                                      (optimizationInfo.coverage_message || "").replace("%", ""),
                                    ) >= 60
                                  ? "text-yellow-600 dark:text-yellow-500"
                                  : "text-red-600 dark:text-red-500"
                            }`}
                          >
                            {optimizationInfo.coverage_message}
                          </div>
                          <div className="text-sm text-muted-foreground mt-1">Coverage</div>
                        </div>
                      </div>
                    </div>
                  </div>
                )}

                {activeBottomTab === "review" && (
                  <div
                    className={`prose prose-sm max-w-none w-full ${isDarkMode ? "prose-invert" : ""}
                    [&_code]:font-mono [&_code]:text-xs [&_code]:px-1.5 [&_code]:py-0.5 [&_code]:rounded
                    [&_code]:bg-muted [&_code]:text-foreground
                    [&_pre]:bg-muted [&_pre]:text-sm [&_pre]:p-4 [&_pre]:rounded [&_pre]:overflow-x-auto
                    [&_pre_code]:bg-transparent [&_pre_code]:p-0
                    [&_table]:w-full [&_table]:border-collapse
                    [&_th]:border [&_td]:border [&_th]:border-border [&_td]:border-border
                    [&_th]:bg-muted [&_th]:px-4 [&_th]:py-2 [&_td]:px-4 [&_td]:py-2
                    [&_blockquote]:border-l-4 [&_blockquote]:border-primary [&_blockquote]:pl-4
                    [&_ul]:list-disc [&_ul]:pl-6 [&_ul]:space-y-1
                    [&_ol]:list-decimal [&_ol]:pl-6 [&_ol]:space-y-1
                    [&_li]:text-sm
                    [&_p]:text-sm [&_p]:leading-relaxed`}
                  >
                    {optimizationInfo.review_explanation ? (
                      <ReactMarkdown remarkPlugins={[remarkGfm]}>
                        {optimizationInfo.review_explanation}
                      </ReactMarkdown>
                    ) : (
                      <p className="text-sm text-muted-foreground">
                        No review explanation available for this optimization.
                      </p>
                    )}
                  </div>
                )}
              </div>
            </div>
          </div>
        )}
      </div>
    </div>
  )
}

export default MonacoDiffEditorGithub
