"use client"

import React, { useState, useEffect, useMemo, useCallback, useRef } from "react"
import { DiffEditor, useMonaco, DiffOnMount } from "@monaco-editor/react"
import {
  AlertTriangle,
  BarChart3,
  CheckCircle2,
  ChevronDown,
  ChevronUp,
  Edit3,
  ExternalLink,
  FileCode,
  FileText,
  GitPullRequest,
  Loader2,
  Lock,
  Monitor,
  Save,
  Smartphone,
  TestTube,
  X,
  XCircle,
  Zap,
} from "lucide-react"
import type { ExperimentMetadata, DiffContents } from "@/lib/types" // Adjust path if needed
import { getMonacoLanguage } from "@/lib/utils"
import dynamic from "next/dynamic"

const GeneratedTestsContent = dynamic(
  () => import("./generated-tests-content").then(mod => ({ default: mod.GeneratedTestsContent })),
  {
    loading: () => <div className="text-xs text-slate-400 p-3 animate-pulse">Loading tests...</div>,
    ssr: false,
  },
)

interface MonacoDiffViewerProps {
  metadata: ExperimentMetadata | null // Full metadata object
  repoFullName: string // Formatted as "owner/repo"
  traceId: string
  review_quality: string
  review_explanation: string
}

const MonacoDiffViewer: React.FC<MonacoDiffViewerProps> = ({
  metadata,
  repoFullName,
  traceId,
  review_quality,
  review_explanation,
}) => {
  const monaco = useMonaco()
  const [activeFileKey, setActiveFileKey] = useState<string | null>(null)
  const [showTestDetails, setShowTestDetails] = useState(false)
  const [showGeneratedTests, setShowGeneratedTests] = useState(false)
  const [showOptimizationQuality, setShowOptimizationQuality] = useState(false)
  const [showOptimizationExplanation, setShowOptimizationExplanation] = useState(false)
  const [isEditing, setIsEditing] = useState(false)
  const [editSecret, setEditSecret] = useState("")
  const [showSecretPrompt, setShowSecretPrompt] = useState(false)
  const [currentEdit, setCurrentEdit] = useState<{ [key: string]: string }>({})
  const [saveStatus, setSaveStatus] = useState<"idle" | "saving" | "saved" | "error">("idle")
  const [savedChanges, setSavedChanges] = useState<{ [key: string]: string }>({})
  const [isMobile, setIsMobile] = useState(false)
  const [useInlineView, setUseInlineView] = useState(false)

  const isEditingRef = useRef(isEditing)
  const activeFileKeyRef = useRef(activeFileKey)

  useEffect(() => {
    isEditingRef.current = isEditing
  }, [isEditing])

  useEffect(() => {
    activeFileKeyRef.current = activeFileKey
  }, [activeFileKey])

  const handleEditorOnMount: DiffOnMount = useCallback(editor => {
    // Always set up the change listener, but only update state when editing
    const modifiedEditor = editor.getModifiedEditor()
    modifiedEditor.onDidChangeModelContent(() => {
      if (isEditingRef.current) {
        const value = modifiedEditor.getValue()
        if (activeFileKeyRef.current && value !== undefined) {
          setCurrentEdit(prev => ({
            ...prev,
            [activeFileKeyRef.current!]: value,
          }))
        }
      }
    })
  }, [])

  // Merge metadata with saved changes for display
  const diffContents: DiffContents | null = useMemo(() => {
    if (!metadata?.diffContents) return null

    const updatedContents = { ...metadata.diffContents }
    Object.entries(savedChanges).forEach(([fileKey, newContent]) => {
      if (updatedContents[fileKey]) {
        updatedContents[fileKey] = {
          ...updatedContents[fileKey],
          newContent,
        }
      }
    })
    return updatedContents
  }, [metadata?.diffContents, savedChanges])
  const prCommentFields = metadata?.prCommentFields
  const fileKeys = useMemo(() => {
    return diffContents ? Object.keys(diffContents) : []
  }, [diffContents])

  // Calculate test statistics
  const testStats = useMemo(() => {
    const stats = {
      totalPassed: 0,
      totalFailed: 0,
      categories: [] as { name: string; passed: number; failed: number; icon: string }[],
    }

    if (prCommentFields?.report_table) {
      Object.entries(prCommentFields.report_table).forEach(([category, results]) => {
        stats.totalPassed += results.passed
        stats.totalFailed += results.failed

        // Map category names to icons
        let icon = "🧪"
        if (category.includes("Replay")) icon = "⏪"
        else if (category.includes("Unit")) icon = "⚙️"
        else if (category.includes("Coverage")) icon = "🔎"
        else if (category.includes("Regression")) icon = "🌀"
        else if (category.includes("Inspired")) icon = "🎨"

        stats.categories.push({
          name: category,
          passed: results.passed,
          failed: results.failed,
          icon,
        })
      })
    }

    return stats
  }, [prCommentFields])

  const handleEditClick = () => {
    setShowSecretPrompt(true)
  }

  const handleSecretSubmit = () => {
    if (editSecret === "codeflash-edit-2025") {
      setIsEditing(true)
      setShowSecretPrompt(false)
      // Initialize current edit with current content if not already set
      if (activeFileKey && diffContents?.[activeFileKey] && !currentEdit[activeFileKey]) {
        setCurrentEdit(prev => ({
          ...prev,
          [activeFileKey]:
            diffContents[activeFileKey].newContent || diffContents[activeFileKey].oldContent || "",
        }))
      }
    } else {
      alert("Invalid secret!")
    }
  }

  const handleSaveCode = async () => {
    if (!activeFileKey || !currentEdit[activeFileKey]) return

    setSaveStatus("saving")
    try {
      const response = await fetch(`/api/traces/${traceId}/save-modified-code`, {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          fileKey: activeFileKey,
          modifiedCode: currentEdit[activeFileKey],
          secret: editSecret,
        }),
      })

      if (response.ok) {
        setSaveStatus("saved")

        // Update local saved changes state to show the changes immediately
        setSavedChanges(prev => ({
          ...prev,
          [activeFileKey]: currentEdit[activeFileKey],
        }))

        // Clear current edit and auto-return to diff view after successful save
        setTimeout(() => {
          setSaveStatus("idle")
          setIsEditing(false)
          setCurrentEdit(prev => {
            const newEdit = { ...prev }
            delete newEdit[activeFileKey!]
            return newEdit
          })
        }, 1500)
      } else {
        setSaveStatus("error")
        setTimeout(() => setSaveStatus("idle"), 3000)
      }
    } catch (error) {
      console.error("Failed to save modified code:", error)
      setSaveStatus("error")
      setTimeout(() => setSaveStatus("idle"), 3000)
    }
  }

  const handleCancelEdit = () => {
    setIsEditing(false)
    setEditSecret("")
    // Revert changes for current file
    if (activeFileKey) {
      setCurrentEdit(prev => {
        const newEdit = { ...prev }
        delete newEdit[activeFileKey]
        return newEdit
      })
    }
  }

  useEffect(() => {
    if (fileKeys.length > 0 && !activeFileKey) {
      setActiveFileKey(fileKeys[0])
    }
  }, [fileKeys, activeFileKey])

  // Mobile detection and responsive handler
  useEffect(() => {
    const checkMobile = () => {
      const mobile = window.innerWidth < 768
      setIsMobile(mobile)
      setUseInlineView(mobile)
    }

    checkMobile()
    window.addEventListener("resize", checkMobile)
    return () => window.removeEventListener("resize", checkMobile)
  }, [])

  useEffect(() => {
    if (monaco) {
      // Define your custom dark theme for Monaco Editor
      monaco.editor.defineTheme("codeflash-python-dark", {
        base: "vs-dark",
        inherit: true,
        rules: [
          { token: "comment.python", foreground: "6A9955" }, // Python comments
          { token: "keyword.python", foreground: "569CD6" }, // Python keywords
          { token: "string.python", foreground: "CE9178" }, // Python strings
          { token: "number.python", foreground: "B5CEA8" }, // Python numbers
          { token: "identifier.python", foreground: "9CDCFE" },
          { token: "type.identifier.python", foreground: "4EC9B0" }, // class names, etc.
        ],
        colors: {
          "editor.background": "#0A0E14",
          "editor.foreground": "#F8F8F2",
          "editorLineNumber.foreground": "#6272A4",
          "editor.selectionBackground": "#44475A",
          "editor.lineHighlightBackground": "#1A1F29",
          "diffEditor.insertedTextBackground": "#50FA7B33",
          "diffEditor.removedTextBackground": "#FF555533",
          "diffEditor.insertedLineBackground": "#50FA7B22",
          "diffEditor.removedLineBackground": "#FF555522",
          "diffEditorGutter.insertedLineBackground": "#50FA7B",
          "diffEditorGutter.removedLineBackground": "#FF5555",
        },
      })
    }
  }, [monaco])

  // Loading or error states - NOW AFTER ALL HOOKS
  if (!metadata) {
    return (
      <div className="flex flex-col items-center justify-center h-screen bg-[#0f0f0f] text-slate-400">
        <Loader2 className="h-12 w-12 animate-spin text-sky-500 mb-4" />
        <p className="text-lg">
          Loading trace details for <span className="font-mono">{traceId}</span>...
        </p>
      </div>
    )
  }

  if (!diffContents || fileKeys.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-screen bg-[#0f0f0f] text-slate-400">
        <AlertTriangle className="h-12 w-12 text-amber-500 mb-4" />
        <p className="text-lg">No diff content available for this trace.</p>
        <p className="text-sm font-mono mt-2">Trace ID: {traceId}</p>
      </div>
    )
  }

  const currentDiff = activeFileKey && diffContents ? diffContents[activeFileKey] : null
  const functionName = prCommentFields?.function_name || "N/A"
  const speedup = prCommentFields?.speedup_pct || prCommentFields?.speedup_x || "N/A"
  const explanation = prCommentFields?.optimization_explanation

  return (
    <div className="flex flex-col h-screen bg-gradient-to-br from-slate-900 via-slate-800 to-slate-900 text-slate-200">
      {/* Header Section - Mobile Optimized. flex-shrink-0 prevents this section
          from collapsing during flex layout, which would cause the editor below to
          shift (CLS). The max-h constraint still limits overflow on mobile. */}
      <div className="px-3 sm:px-4 md:px-6 py-2 sm:py-3 md:py-4 border-b border-slate-700/50 overflow-y-auto max-h-[40vh] md:max-h-none flex-shrink-0">
        <div className="flex flex-col gap-3 sm:gap-4 md:gap-6">
          {/* Top Row - Title with PR Link and Observability Link */}
          <div className="flex items-center justify-between gap-2">
            <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1">
              <h1 className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold bg-gradient-to-r from-cyan-400 via-blue-500 to-purple-600 text-transparent bg-clip-text truncate">
                CodeFlash Optimization
              </h1>
              {metadata.pullNumber && (
                <a
                  href={`https://github.com/${metadata.owner || repoFullName.split("/")[0]}/${metadata.repo || repoFullName.split("/")[1]}/pull/${metadata.pullNumber}`}
                  target="_blank"
                  rel="noopener noreferrer"
                  className="flex items-center gap-1 text-cyan-400 hover:text-cyan-300 transition-colors bg-slate-800/50 px-2 py-1 rounded-md text-xs sm:text-sm flex-shrink-0"
                >
                  <GitPullRequest className="h-3 w-3 sm:h-4 sm:w-4" />
                  <span className="hidden sm:inline">PR #{metadata.pullNumber}</span>
                  <span className="sm:hidden">#{metadata.pullNumber}</span>
                  <ExternalLink className="h-2.5 w-2.5 sm:h-3 sm:w-3" />
                </a>
              )}
            </div>
            {/* Observability Link */}
            <a
              href={`/observability/trace/${traceId}`}
              target="_blank"
              rel="noopener noreferrer"
              className="flex items-center gap-1 text-cyan-400 hover:text-cyan-300 transition-colors bg-slate-800/50 px-2 py-1 rounded-md text-xs sm:text-sm flex-shrink-0"
            >
              <BarChart3 className="h-3 w-3 sm:h-4 sm:w-4" />
              <span className="hidden sm:inline">Observability</span>
              <span className="sm:hidden">Obs</span>
              <ExternalLink className="h-2.5 w-2.5 sm:h-3 sm:w-3" />
            </a>
          </div>

          {/* Info Row - Repository and Function (Compact on Mobile) */}
          <div className="flex flex-col sm:flex-row sm:items-center gap-2 sm:gap-4 text-xs sm:text-sm">
            <div className="flex items-center gap-2 min-w-0">
              <FileCode className="h-3 w-3 sm:h-4 sm:w-4 text-cyan-400 flex-shrink-0" />
              <span className="text-slate-400 flex-shrink-0">Repo:</span>
              <span className="text-slate-200 font-medium truncate">{repoFullName}</span>
            </div>
            <div className="flex items-center gap-2 min-w-0">
              <span className="text-slate-400 flex-shrink-0">Function:</span>
              <code className="text-purple-400 bg-slate-800/50 px-1.5 sm:px-2 py-0.5 sm:py-1 rounded font-mono text-xs sm:text-sm truncate">
                {functionName}
              </code>
            </div>
          </div>

          {/* Performance Metrics Row - Compact on Mobile */}
          <div className="flex flex-wrap items-center gap-2 sm:gap-4">
            {/* Performance Boost - Smaller on Mobile */}
            <div className="bg-slate-800/30 rounded-lg p-2 sm:p-3 md:p-4 border border-slate-700/30 flex items-center gap-1.5 sm:gap-2">
              <Zap className="h-4 w-4 sm:h-5 sm:w-5 md:h-6 md:w-6 text-yellow-400 flex-shrink-0" />
              <div>
                <div className="text-[10px] sm:text-xs text-slate-400 uppercase tracking-wider">
                  Boost
                </div>
                <span className="text-lg sm:text-xl md:text-2xl lg:text-3xl font-bold bg-gradient-to-r from-green-400 to-emerald-500 text-transparent bg-clip-text block leading-tight">
                  {speedup}
                </span>
              </div>
            </div>

            {/* Additional Metrics - Hidden on very small screens */}
            {prCommentFields?.loop_count && (
              <div className="hidden sm:block text-center">
                <div className="text-[10px] sm:text-xs text-slate-400 uppercase tracking-wider mb-1">
                  Loops
                </div>
                <div className="text-sm sm:text-base md:text-lg font-semibold text-blue-400">
                  {prCommentFields.loop_count.toLocaleString()}
                </div>
              </div>
            )}
            {prCommentFields?.original_runtime && prCommentFields?.best_runtime && (
              <div className="hidden md:block text-center">
                <div className="text-[10px] sm:text-xs text-slate-400 uppercase tracking-wider mb-1">
                  Runtime
                </div>
                <div className="text-xs sm:text-sm">
                  <span className="text-red-400 line-through">
                    {prCommentFields.original_runtime}
                  </span>
                  <span className="mx-1 sm:mx-2 text-slate-500">→</span>
                  <span className="text-green-400">{prCommentFields.best_runtime}</span>
                </div>
              </div>
            )}

            {/* Edit Button - Compact on Mobile */}
            <div className="ml-auto flex items-center gap-1.5 sm:gap-2">
              {!isEditing ? (
                <button
                  onClick={handleEditClick}
                  className="flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors text-xs sm:text-sm font-medium"
                >
                  <Edit3 className="h-3 w-3 sm:h-4 sm:w-4" />
                  <span className="hidden sm:inline">Edit Code</span>
                  <span className="sm:hidden">Edit</span>
                </button>
              ) : (
                <div className="flex items-center gap-1.5 sm:gap-2">
                  <button
                    onClick={handleSaveCode}
                    disabled={saveStatus === "saving"}
                    className="flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 bg-green-600 hover:bg-green-700 disabled:bg-green-800 text-white rounded-lg transition-colors text-xs sm:text-sm font-medium"
                  >
                    <Save className="h-3 w-3 sm:h-4 sm:w-4" />
                    <span className="hidden sm:inline">
                      {saveStatus === "saving"
                        ? "Saving..."
                        : saveStatus === "saved"
                          ? "Saved!"
                          : "Save"}
                    </span>
                    <span className="sm:hidden">
                      {saveStatus === "saving" ? "..." : saveStatus === "saved" ? "✓" : "Save"}
                    </span>
                  </button>
                  <button
                    onClick={handleCancelEdit}
                    className="flex items-center gap-1 sm:gap-2 px-2 sm:px-3 py-1.5 sm:py-2 bg-red-600 hover:bg-red-700 text-white rounded-lg transition-colors text-xs sm:text-sm font-medium"
                  >
                    <X className="h-3 w-3 sm:h-4 sm:w-4" />
                    <span className="hidden sm:inline">Cancel</span>
                  </button>
                </div>
              )}
            </div>
          </div>

          {/* Test Results Summary - Collapsed by default on mobile */}
          {testStats.totalPassed > 0 || testStats.totalFailed > 0 ? (
            <div className="bg-slate-800/30 rounded-lg p-2 sm:p-3 md:p-4 border border-slate-700/30">
              <div
                className="flex items-center justify-between cursor-pointer gap-2"
                onClick={() => setShowTestDetails(!showTestDetails)}
              >
                <div className="flex items-center gap-2 sm:gap-3 min-w-0 flex-1">
                  <TestTube className="h-4 w-4 sm:h-5 sm:w-5 text-blue-400 flex-shrink-0" />
                  <span className="font-semibold text-xs sm:text-sm md:text-base truncate">
                    Test Results
                  </span>
                  <div className="flex items-center gap-2 sm:gap-4 flex-shrink-0">
                    <div className="flex items-center gap-1">
                      <CheckCircle2 className="h-3 w-3 sm:h-4 sm:w-4 text-green-400" />
                      <span className="text-green-400 font-medium text-xs sm:text-sm">
                        {testStats.totalPassed}
                      </span>
                    </div>
                    {testStats.totalFailed > 0 && (
                      <div className="flex items-center gap-1">
                        <XCircle className="h-3 w-3 sm:h-4 sm:w-4 text-red-400" />
                        <span className="text-red-400 font-medium text-xs sm:text-sm">
                          {testStats.totalFailed}
                        </span>
                      </div>
                    )}
                  </div>
                </div>
                {showTestDetails ? (
                  <ChevronUp className="h-4 w-4 flex-shrink-0" />
                ) : (
                  <ChevronDown className="h-4 w-4 flex-shrink-0" />
                )}
              </div>

              {showTestDetails && (
                <div className="mt-3 sm:mt-4 grid grid-cols-1 sm:grid-cols-2 lg:grid-cols-3 gap-2 sm:gap-3">
                  {testStats.categories.map((category, idx) => (
                    <div
                      key={idx}
                      className="bg-slate-700/50 rounded-lg p-2 sm:p-3 flex items-center justify-between gap-2"
                    >
                      <div className="flex items-center gap-2 min-w-0 flex-1">
                        <span className="text-xs sm:text-sm text-slate-300 truncate">
                          {category.name}
                        </span>
                      </div>
                      <div className="flex items-center gap-2 text-xs sm:text-sm flex-shrink-0">
                        {category.passed > 0 && (
                          <span className="text-green-400">{category.passed}✓</span>
                        )}
                        {category.failed > 0 && (
                          <span className="text-red-400">{category.failed}✗</span>
                        )}
                      </div>
                    </div>
                  ))}
                </div>
              )}
            </div>
          ) : null}
        </div>
      </div>

      {/* File Path/Tabs - Mobile Optimized. flex-shrink-0 prevents CLS from
          this section collapsing during initial layout. */}
      {fileKeys.length === 1 ? (
        // Single file - show full path with view toggle
        <div className="bg-[rgba(15,15,15,0.95)] border-b border-[rgba(255,255,255,0.05)] px-3 sm:px-4 md:px-5 py-2 sm:py-2.5 md:py-3 flex items-center justify-between gap-2 flex-shrink-0">
          <div className="flex items-center gap-1.5 sm:gap-2 min-w-0 flex-1">
            <FileText size={12} className="text-sky-400 flex-shrink-0 sm:w-3.5 sm:h-3.5" />
            <span className="text-xs sm:text-sm text-slate-300 font-mono truncate">
              {fileKeys[0]}
            </span>
          </div>
          {/* View Toggle for mobile compatibility */}
          <div className="flex items-center gap-1.5 sm:gap-2 flex-shrink-0">
            <button
              onClick={() => setUseInlineView(!useInlineView)}
              className={`flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1 rounded-md text-[10px] sm:text-xs transition-colors ${
                useInlineView
                  ? "bg-blue-600/20 text-blue-400 border border-blue-600/30"
                  : "bg-slate-700/50 text-slate-400 hover:text-slate-300"
              }`}
              title={useInlineView ? "Switch to side-by-side view" : "Switch to inline view"}
            >
              {useInlineView ? (
                <Smartphone size={10} className="sm:w-3 sm:h-3" />
              ) : (
                <Monitor size={10} className="sm:w-3 sm:h-3" />
              )}
              <span className="hidden sm:inline">{useInlineView ? "Inline" : "Side-by-side"}</span>
            </button>
          </div>
        </div>
      ) : (
        // Multiple files - show tabs with full path on hover
        <div className="bg-[rgba(15,15,15,0.95)] border-b border-[rgba(255,255,255,0.05)] flex-shrink-0">
          <div className="flex items-center justify-between gap-2">
            <div className="flex overflow-x-auto whitespace-nowrap scrollbar-thin scrollbar-thumb-slate-700 scrollbar-track-slate-800 flex-1 min-w-0">
              {fileKeys.map(fileKey => (
                <button
                  key={fileKey}
                  onClick={() => setActiveFileKey(fileKey)}
                  title={fileKey}
                  className={`px-3 sm:px-4 md:px-5 py-2 sm:py-2.5 md:py-3 text-xs sm:text-sm transition-all duration-200 ease-in-out focus:outline-none flex items-center gap-1.5 sm:gap-2 flex-shrink-0
                    ${
                      activeFileKey === fileKey
                        ? "text-white bg-[rgba(255,255,255,0.05)] border-b-2 border-sky-400"
                        : "text-slate-400 hover:text-slate-200 hover:bg-[rgba(255,255,255,0.03)] border-b-2 border-transparent"
                    }`}
                >
                  <FileText
                    size={12}
                    className={`${activeFileKey === fileKey ? "text-sky-400" : "text-slate-500"} flex-shrink-0 sm:w-3.5 sm:h-3.5`}
                  />
                  <span className="truncate max-w-[120px] sm:max-w-none">
                    {fileKey.split("/").pop()}
                  </span>
                </button>
              ))}
            </div>
            {/* View Toggle for mobile compatibility */}
            <div className="flex items-center gap-1.5 sm:gap-2 px-2 sm:px-3 md:px-5 flex-shrink-0">
              <button
                onClick={() => setUseInlineView(!useInlineView)}
                className={`flex items-center gap-1 sm:gap-1.5 px-2 sm:px-3 py-1 rounded-md text-[10px] sm:text-xs transition-colors ${
                  useInlineView
                    ? "bg-blue-600/20 text-blue-400 border border-blue-600/30"
                    : "bg-slate-700/50 text-slate-400 hover:text-slate-300"
                }`}
                title={useInlineView ? "Switch to side-by-side view" : "Switch to inline view"}
              >
                {useInlineView ? (
                  <Smartphone size={10} className="sm:w-3 sm:h-3" />
                ) : (
                  <Monitor size={10} className="sm:w-3 sm:h-3" />
                )}
                <span className="hidden sm:inline">
                  {useInlineView ? "Inline" : "Side-by-side"}
                </span>
              </button>
            </div>
          </div>
        </div>
      )}

      {/* Monaco Editor Container */}
      <div className="flex-grow relative min-h-0">
        {activeFileKey && currentDiff && monaco ? (
          // Check for empty diff scenarios first (only in non-editing mode)
          !isEditing &&
          (currentDiff.oldContent || "") === (currentDiff.newContent || "") &&
          (currentDiff.oldContent || "").trim() === "" ? (
            // Both contents are empty
            <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#0A0A0A] text-slate-400">
              <FileText className="h-12 w-12 text-slate-500 mb-4" />
              <h3 className="text-lg font-medium text-slate-200 mb-2">No Changes to Display</h3>
              <p className="text-sm text-slate-400 max-w-md text-center px-4">
                The file content is empty. The staging branch may have been merged or the changes
                have been reverted.
              </p>
            </div>
          ) : !isEditing && (currentDiff.oldContent || "") === (currentDiff.newContent || "") ? (
            // Contents are identical (no diff)
            <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#0A0A0A] text-slate-400">
              <FileText className="h-12 w-12 text-slate-500 mb-4" />
              <h3 className="text-lg font-medium text-slate-200 mb-2">No Differences Found</h3>
              <p className="text-sm text-slate-400 max-w-md text-center px-4">
                The original and optimized code are identical. The changes may have already been
                applied or reverted.
              </p>
            </div>
          ) : isEditing ? (
            // Edit Mode with Diff View - Like VS Code changes view
            <DiffEditor
              height="100%"
              original={currentDiff.oldContent || ""}
              modified={currentEdit[activeFileKey] || currentDiff.newContent || ""}
              language={activeFileKey ? getMonacoLanguage(activeFileKey) : "python"}
              theme="codeflash-python-dark"
              onMount={handleEditorOnMount}
              options={{
                automaticLayout: true,
                renderSideBySide: !useInlineView,
                readOnly: false, // Allow editing on the modified side
                scrollBeyondLastLine: false,
                minimap: { enabled: !isMobile, scale: isMobile ? 0.5 : 1, size: "proportional" },
                diffCodeLens: true,
                renderIndicators: true,
                ignoreTrimWhitespace: false,
                renderWhitespace: "boundary",
                fontSize: isMobile ? 12 : 13,
                fontFamily: "'Fira Code', 'Cascadia Code', Consolas, 'Courier New', monospace",
                fontLigatures: !isMobile, // Disable font ligatures on mobile for better performance
                wordWrap: isMobile ? "on" : "off", // Enable word wrap on mobile
                scrollbar: {
                  verticalScrollbarSize: isMobile ? 14 : 10,
                  horizontalScrollbarSize: isMobile ? 14 : 10,
                  useShadows: false,
                },
                originalEditable: false, // Original side stays read-only
                enableSplitViewResizing: !isMobile,
                // Enable diff review mode for better editing experience
                diffWordWrap: isMobile ? "on" : "off",
                // Mobile-specific optimizations
                mouseWheelZoom: !isMobile,
                contextmenu: !isMobile,
                quickSuggestions: !isMobile,
                parameterHints: { enabled: !isMobile },
                suggest: !isMobile ? {} : undefined,
                hover: { enabled: !isMobile },
              }}
              loading={
                <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#0A0A0A] text-slate-400">
                  <Loader2 className="h-10 w-10 animate-spin text-sky-500 mb-3" />
                  <p>Loading Diff Editor...</p>
                </div>
              }
            />
          ) : (
            // Diff View Mode
            <DiffEditor
              height="100%"
              original={currentDiff.oldContent || ""}
              modified={currentDiff.newContent || ""}
              language={activeFileKey ? getMonacoLanguage(activeFileKey) : "python"}
              theme="codeflash-python-dark"
              onMount={handleEditorOnMount}
              options={{
                automaticLayout: true,
                renderSideBySide: !useInlineView,
                readOnly: true,
                scrollBeyondLastLine: false,
                minimap: { enabled: !isMobile, scale: isMobile ? 0.5 : 1, size: "proportional" },
                diffCodeLens: true,
                renderIndicators: true,
                ignoreTrimWhitespace: false,
                renderWhitespace: "boundary",
                fontSize: isMobile ? 12 : 13,
                fontFamily: "'Fira Code', 'Cascadia Code', Consolas, 'Courier New', monospace",
                fontLigatures: !isMobile, // Disable font ligatures on mobile for better performance
                wordWrap: isMobile ? "on" : "off", // Enable word wrap on mobile
                scrollbar: {
                  verticalScrollbarSize: isMobile ? 14 : 10,
                  horizontalScrollbarSize: isMobile ? 14 : 10,
                  useShadows: false,
                },
                originalEditable: false,
                enableSplitViewResizing: !isMobile,
                // Mobile-specific optimizations
                mouseWheelZoom: !isMobile,
                contextmenu: !isMobile,
                quickSuggestions: false,
                parameterHints: { enabled: false },
                suggest: undefined,
                hover: { enabled: !isMobile },
              }}
              loading={
                <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#0A0A0A] text-slate-400">
                  <Loader2 className="h-10 w-10 animate-spin text-sky-500 mb-3" />
                  <p>Loading Diff Editor...</p>
                </div>
              }
            />
          )
        ) : (
          <div className="absolute inset-0 flex flex-col items-center justify-center bg-[#0A0A0A] text-slate-500">
            <Loader2 className="h-10 w-10 animate-spin text-sky-500 mb-3" />
            <p>{!monaco ? "Initializing Editor Subsystem..." : "Preparing View..."}</p>
          </div>
        )}
      </div>
      {/* Bottom Section with Explanation and Generated Tests - Mobile Optimized */}
      <div className="bg-gradient-to-t from-slate-900 to-slate-800/50 border-t border-slate-700/50 max-h-[30vh] sm:max-h-[35vh] md:max-h-none overflow-y-auto">
        {/* Optimization review details */}
        {review_quality && (
          <div className="p-2 sm:p-3 md:p-4 border-b border-slate-700/30">
            <div
              className="flex items-center justify-between cursor-pointer gap-2"
              onClick={() => setShowOptimizationQuality(!showOptimizationQuality)}
            >
              <h3 className="text-xs sm:text-sm font-semibold text-cyan-400 flex items-center gap-1.5 sm:gap-2 min-w-0 flex-1">
                <Zap className="h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
                <span className="truncate">🎯 Quality: {review_quality}</span>
              </h3>
              {showOptimizationQuality ? (
                <ChevronUp className="h-3 w-3 sm:h-4 sm:w-4 text-slate-400 flex-shrink-0" />
              ) : (
                <ChevronDown className="h-3 w-3 sm:h-4 sm:w-4 text-slate-400 flex-shrink-0" />
              )}
            </div>
            {showOptimizationQuality && (
              <div className="mt-2 text-xs sm:text-sm text-slate-300 whitespace-pre-wrap bg-slate-800/50 rounded-lg p-2 sm:p-3 max-h-24 sm:max-h-32 overflow-y-auto scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-slate-800">
                {review_explanation}
              </div>
            )}
          </div>
        )}
        {/* Optimization Explanation */}
        {explanation && (
          <div className="p-2 sm:p-3 md:p-4 border-b border-slate-700/30">
            <div
              className="flex items-center justify-between cursor-pointer gap-2"
              onClick={() => setShowOptimizationExplanation(!showOptimizationExplanation)}
            >
              <h3 className="text-xs sm:text-sm font-semibold text-cyan-400 flex items-center gap-1.5 sm:gap-2">
                <Zap className="h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
                <span className="hidden sm:inline">Optimization Explanation</span>
                <span className="sm:hidden">Explanation</span>
              </h3>
              {showOptimizationExplanation ? (
                <ChevronUp className="h-3 w-3 sm:h-4 sm:w-4 text-slate-400 flex-shrink-0" />
              ) : (
                <ChevronDown className="h-3 w-3 sm:h-4 sm:w-4 text-slate-400 flex-shrink-0" />
              )}
            </div>
            {showOptimizationExplanation && (
              <div className="mt-2 text-xs sm:text-sm text-slate-300 whitespace-pre-wrap bg-slate-800/50 rounded-lg p-2 sm:p-3 max-h-24 sm:max-h-32 overflow-y-auto scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-slate-800">
                {explanation}
              </div>
            )}
          </div>
        )}

        {/* Generated Tests Toggle */}
        {metadata.generatedTests && (
          <div className="p-2 sm:p-3 md:p-4">
            <button
              onClick={() => setShowGeneratedTests(!showGeneratedTests)}
              className="flex items-center gap-1.5 sm:gap-2 text-xs sm:text-sm font-semibold text-purple-400 hover:text-purple-300 transition-colors w-full"
            >
              <TestTube className="h-3 w-3 sm:h-4 sm:w-4 flex-shrink-0" />
              <span className="hidden sm:inline">Generated Tests</span>
              <span className="sm:hidden">Tests</span>
              {showGeneratedTests ? (
                <ChevronUp className="h-3 w-3 sm:h-4 sm:w-4 ml-auto flex-shrink-0" />
              ) : (
                <ChevronDown className="h-3 w-3 sm:h-4 sm:w-4 ml-auto flex-shrink-0" />
              )}
            </button>
            {showGeneratedTests && (
              <div className="mt-2 sm:mt-3 bg-slate-800/50 rounded-lg p-2 sm:p-3 max-h-48 sm:max-h-64 overflow-y-auto scrollbar-thin scrollbar-thumb-slate-600 scrollbar-track-slate-800">
                <GeneratedTestsContent generatedTests={metadata.generatedTests} />
              </div>
            )}
          </div>
        )}
      </div>

      {/* Secret Prompt Modal - Mobile Optimized */}
      {showSecretPrompt && (
        <div className="fixed inset-0 bg-black bg-opacity-50 flex items-center justify-center z-50 p-4">
          <div className="bg-slate-800 rounded-lg p-4 sm:p-6 max-w-md w-full mx-4">
            <div className="flex items-center gap-2 sm:gap-3 mb-3 sm:mb-4">
              <Lock className="h-4 w-4 sm:h-5 sm:w-5 text-amber-400 flex-shrink-0" />
              <h3 className="text-base sm:text-lg font-semibold text-white">Enter Edit Secret</h3>
            </div>
            <p className="text-slate-300 text-xs sm:text-sm mb-3 sm:mb-4">
              Please enter the secret key to enable code editing.
            </p>
            <input
              type="password"
              placeholder="Enter secret..."
              value={editSecret}
              onChange={e => setEditSecret(e.target.value)}
              onKeyDown={e => e.key === "Enter" && handleSecretSubmit()}
              className="w-full px-3 py-2 bg-slate-700 border border-slate-600 rounded-lg text-white placeholder-slate-400 focus:outline-none focus:ring-2 focus:ring-purple-500 focus:border-transparent mb-3 sm:mb-4 text-sm sm:text-base"
              autoFocus
            />
            <div className="flex gap-2 sm:gap-3 justify-end">
              <button
                onClick={() => {
                  setShowSecretPrompt(false)
                  setEditSecret("")
                }}
                className="px-3 sm:px-4 py-1.5 sm:py-2 text-slate-300 hover:text-white transition-colors text-sm sm:text-base"
              >
                Cancel
              </button>
              <button
                onClick={handleSecretSubmit}
                className="px-3 sm:px-4 py-1.5 sm:py-2 bg-purple-600 hover:bg-purple-700 text-white rounded-lg transition-colors text-sm sm:text-base"
              >
                Unlock
              </button>
            </div>
          </div>
        </div>
      )}
    </div>
  )
}

export default MonacoDiffViewer
