import { useState, useCallback, useEffect, useRef } from 'react'
import { useNavigate, useParams } from 'react-router-dom'
import { useNodesState, useEdgesState, addEdge } from 'reactflow'
import { api } from '../utils/api'
import { validateWorkflowGraph } from '../utils/workflowValidation'
import { serializeToWorkflowGraph, deserializeFromWorkflowGraph } from '../utils/workflowSerializer'
import { WorkflowCanvas } from '../components/workflow/WorkflowCanvas'
import { StartNode } from '../components/workflow/nodes/StartNode'
import { EndNode } from '../components/workflow/nodes/EndNode'
import { AnalysisNode } from '../components/workflow/nodes/AnalysisNode'
import { LogicNode } from '../components/workflow/nodes/LogicNode'
import { JoinNode } from '../components/workflow/nodes/JoinNode'
import { QuestionAugmentationPanel } from '../components/workflow/panels/QuestionAugmentationPanel'
import { LogicExpressionEditor } from '../components/workflow/panels/LogicExpressionEditor'
import { FallbackConfig } from '../components/workflow/panels/FallbackConfig'
import { JoinConfig } from '../components/workflow/panels/JoinConfig'
import { EndNodeConfig } from '../components/workflow/panels/EndNodeConfig'
import { PlaceholderPicker } from '../components/workflow/panels/PlaceholderPicker'
import { WorkflowExecutePanel } from '../components/workflow/panels/WorkflowExecutePanel'
import { WorkflowResultViewer } from '../components/workflow/panels/WorkflowResultViewer'
import { InlineTemplateEditor } from '../components/workflow/panels/InlineTemplateEditor'
import { ValidationPanel } from '../components/workflow/panels/ValidationPanel'
import { Toast } from '../components/Toast'
import { ConfirmDialog } from '../components/ConfirmDialog'
import '../styles/workflowEditor.css'
import {
  ANALYSIS_CATEGORY_ORDER,
  ANALYSIS_CATEGORY_LABELS,
} from '../config/analysisCategories'

/** Aus Start-Node → Felder für Analyse-UI / ai_prompts (display_name, description, category) */
function getWorkflowAnalysisPublishFields(nodes, fallbackName) {
  const start = nodes.find((n) => n.type === 'start')
  const d = start?.data || {}
  const title =
    String(d.analysis_title ?? '').trim() ||
    String(fallbackName ?? '').trim() ||
    'Workflow'
  const description = String(d.analysis_description ?? '').trim()
  const category =
    String(d.analysis_category ?? 'ganzheitlich').toLowerCase().trim() || 'ganzheitlich'
  return {
    display_name: title,
    description: description || null,
    category,
  }
}

// Node-Type Mapping
const nodeTypes = {
  start: StartNode,
  end: EndNode,
  analysis: AnalysisNode,
  logic: LogicNode,
  join: JoinNode
}

let nodeIdCounter = 1

export default function WorkflowEditorPage() {
  const navigate = useNavigate()
  const { id } = useParams() // prompt_id wenn vorhanden

  // State
  const [nodes, setNodes, onNodesChange] = useNodesState([])
  const [edges, setEdges, onEdgesChange] = useEdgesState([])
  const [selectedNodeId, setSelectedNodeId] = useState(null)
  const selectedNode = selectedNodeId ? nodes.find(n => n.id === selectedNodeId) : null
  const [currentPrompt, setCurrentPrompt] = useState(null)
  const [workflowName, setWorkflowName] = useState('Neuer Workflow')
  const [validationErrors, setValidationErrors] = useState([])
  const [validationWarnings, setValidationWarnings] = useState([])
  const [loading, setLoading] = useState(false)
  const [error, setError] = useState(null)
  const [availablePrompts, setAvailablePrompts] = useState([])
  const [executionResult, setExecutionResult] = useState(null)
  const [showPlaceholderPicker, setShowPlaceholderPicker] = useState(false)
  const [placeholderPickerTarget, setPlaceholderPickerTarget] = useState('end') // 'end' | 'inline'
  const endNodeTextareaRef = useRef(null)
  const inlineTemplateTextareaRef = useRef(null)
  const [hasUnsavedChanges, setHasUnsavedChanges] = useState(false)
  const [showValidationPanel, setShowValidationPanel] = useState(true)

  // Toast & Confirm Dialog
  const [toast, setToast] = useState(null)
  const [confirmDialog, setConfirmDialog] = useState(null)

  // Wrapped handlers to track unsaved changes
  const handleNodesChange = useCallback((changes) => {
    onNodesChange(changes)
    setHasUnsavedChanges(true)
  }, [onNodesChange])

  const handleEdgesChange = useCallback((changes) => {
    onEdgesChange(changes)
    setHasUnsavedChanges(true)
  }, [onEdgesChange])

  // Load available basis prompts for Analysis nodes
  useEffect(() => {
    async function loadPrompts() {
      try {
        const prompts = await api.listAdminPrompts()
        // Filter nur type='base' Prompts
        const basisPrompts = prompts.filter(p => p.type === 'base')
        setAvailablePrompts(basisPrompts)
      } catch (e) {
        console.error('Failed to load prompts:', e)
      }
    }
    loadPrompts()
  }, [])

  // Load workflow wenn ID vorhanden
  useEffect(() => {
    if (id && id !== 'new') {
      console.log('🔍 useEffect: Loading workflow with ID:', id)
      loadWorkflow(id)  // UUID as string, no parseInt!
    }
  }, [id])

  // Auto-Validation
  useEffect(() => {
    const { errors, warnings } = validateWorkflowGraph(nodes, edges)
    setValidationErrors(errors)
    setValidationWarnings(warnings)

    // Re-show validation panel if there are new errors/warnings
    if (errors.length > 0 || warnings.length > 0) {
      setShowValidationPanel(true)
    }
  }, [nodes, edges])

  // Warn on browser back/refresh if unsaved changes
  useEffect(() => {
    const handleBeforeUnload = (e) => {
      if (hasUnsavedChanges) {
        e.preventDefault()
        e.returnValue = '' // Chrome requires returnValue to be set
      }
    }

    window.addEventListener('beforeunload', handleBeforeUnload)
    return () => window.removeEventListener('beforeunload', handleBeforeUnload)
  }, [hasUnsavedChanges])

  // ── Handlers ──────────────────────────────────────────────────────────────

  const onConnect = useCallback(
    (params) => {
      setEdges((eds) => addEdge(params, eds))
      setHasUnsavedChanges(true)
    },
    [setEdges]
  )

  const onNodeClick = useCallback((event, node) => {
    setSelectedNodeId(node.id)
  }, [])

  const handleAddNode = (nodeType) => {
    const base = {
      id: `node_${nodeIdCounter++}`,
      type: nodeType,
      position: { x: 250, y: 100 + nodes.length * 100 },
      data: {
        label: `${nodeType.charAt(0).toUpperCase() + nodeType.slice(1)} ${nodeIdCounter - 1}`,
      },
    }
    if (nodeType === 'start') {
      base.data = {
        label: 'Start',
        analysis_title:
          workflowName && workflowName !== 'Neuer Workflow'
            ? workflowName
            : '',
        analysis_description: '',
        analysis_category: 'ganzheitlich',
      }
    }
    setNodes((nds) => [...nds, base])
    setHasUnsavedChanges(true)
  }

  const handleNodeUpdate = (nodeId, updates) => {
    console.log('🔧 handleNodeUpdate:', { nodeId, updates })
    setNodes((nds) => {
      const updated = nds.map((n) => (n.id === nodeId ? { ...n, data: { ...n.data, ...updates } } : n))
      console.log('📝 Nodes after update:', updated.find(n => n.id === nodeId))
      return updated
    })
    setHasUnsavedChanges(true)
  }

  const handleDeleteNode = () => {
    if (!selectedNode) return

    setNodes((nds) => nds.filter((n) => n.id !== selectedNode.id))
    setEdges((eds) => eds.filter((e) => e.source !== selectedNode.id && e.target !== selectedNode.id))
    setSelectedNodeId(null)
    setHasUnsavedChanges(true)
  }

  const handleSave = async () => {
    console.log('💾 handleSave called')
    try {
      setLoading(true)
      setError(null)

      // Validierung
      const { errors, isValid } = validateWorkflowGraph(nodes, edges)
      if (!isValid) {
        setError(`Validierung fehlgeschlagen: ${errors.length} Fehler gefunden`)
        return
      }

      // Serialisieren
      const graph_data = serializeToWorkflowGraph(nodes, edges, {
        created_at: currentPrompt?.created_at,
        version: '1.0'
      })
      console.log('📊 Serialized graph_data:', graph_data)

      const { display_name, description, category } = getWorkflowAnalysisPublishFields(
        nodes,
        workflowName
      )

      if (currentPrompt) {
        // Update existing
        console.log('📝 Updating existing workflow:', currentPrompt.id)
        await api.updateUnifiedPrompt(currentPrompt.id, {
          type: 'workflow',
          name: workflowName,
          display_name,
          description: description ?? undefined,
          category,
          graph_data
        })
        setToast({ message: '✅ Workflow gespeichert!', type: 'success' })
      } else {
        // Create new
        console.log('✨ Creating new workflow')
        const result = await api.createUnifiedPrompt({
          type: 'workflow',
          name: workflowName,
          display_name,
          description: description ?? undefined,
          category,
          graph_data
        })
        console.log('✅ Workflow created:', result)
        setCurrentPrompt({ id: result.id, slug: result.slug, name: workflowName })
        setToast({ message: '✅ Workflow erstellt!', type: 'success' })
        console.log('🚀 Navigating to:', `/workflow-editor/${result.id}`)
        navigate(`/workflow-editor/${result.id}`)
      }

      // Clear unsaved changes flag after successful save
      setHasUnsavedChanges(false)
    } catch (e) {
      console.error('❌ handleSave error:', e)
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  const loadWorkflow = async (promptId) => {
    console.log('📦 loadWorkflow called with:', promptId)
    try {
      setLoading(true)
      setError(null)

      const prompt = await api.getPrompt(promptId)
      console.log('✅ Prompt loaded:', prompt)
      console.log('📊 graph_data:', prompt.graph_data)

      if (prompt.type !== 'workflow') {
        throw new Error('Nicht ein Workflow')
      }

      // Deserialisieren
      const { nodes: loadedNodes, edges: loadedEdges } = deserializeFromWorkflowGraph(prompt.graph_data)
      console.log('🎯 Deserialized:', { nodes: loadedNodes, edges: loadedEdges })

      const mergedNodes = loadedNodes.map((n) => {
        if (n.type !== 'start') return n
        const hasStoredTitle = Object.prototype.hasOwnProperty.call(n.data || {}, 'analysis_title')
        return {
          ...n,
          data: {
            label: n.data?.label || 'Start',
            ...n.data,
            analysis_title: hasStoredTitle
              ? n.data.analysis_title
              : (prompt.display_name || prompt.name || ''),
            analysis_description: Object.prototype.hasOwnProperty.call(n.data || {}, 'analysis_description')
              ? n.data.analysis_description
              : (prompt.description || ''),
            analysis_category:
              (n.data?.analysis_category || prompt.category || 'ganzheitlich').toLowerCase(),
          },
        }
      })

      setNodes(mergedNodes)
      setEdges(loadedEdges)
      setCurrentPrompt(prompt)
      setWorkflowName(prompt.name)

      // nodeIdCounter aktualisieren
      const maxId = Math.max(
        ...loadedNodes.map((n) => parseInt(n.id.replace('node_', '')) || 0),
        0
      )
      nodeIdCounter = maxId + 1
      console.log('✅ Workflow loaded successfully, nodes:', loadedNodes.length, 'edges:', loadedEdges.length)

      // Clear unsaved changes flag after successful load
      setHasUnsavedChanges(false)
    } catch (e) {
      console.error('❌ loadWorkflow error:', e)
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  const handleValidate = () => {
    const { errors, warnings } = validateWorkflowGraph(nodes, edges)
    setValidationErrors(errors)
    setValidationWarnings(warnings)

    if (errors.length === 0) {
      alert(`✅ Workflow ist valide!\n\n${warnings.length} Warnungen`)
    } else {
      alert(`❌ Validierung fehlgeschlagen!\n\n${errors.length} Fehler, ${warnings.length} Warnungen`)
    }
  }

  const handleNew = () => {
    if (hasUnsavedChanges) {
      if (!confirm('Neuen Workflow erstellen? Ungespeicherte Änderungen gehen verloren.')) {
        return
      }
    }
    setNodes([])
    setEdges([])
    setCurrentPrompt(null)
    setWorkflowName('Neuer Workflow')
    setSelectedNodeId(null)
    setHasUnsavedChanges(false)
    navigate('/workflow-editor/new')
  }

  const handleDelete = async () => {
    if (!currentPrompt) return

    if (!confirm(`Workflow "${workflowName}" wirklich löschen?`)) return

    try {
      setLoading(true)
      await api.deletePrompt(currentPrompt.id)
      alert('Workflow gelöscht')
      navigate('/admin/prompts')
    } catch (e) {
      setError(e.message)
    } finally {
      setLoading(false)
    }
  }

  const handleExecutionComplete = (result) => {
    console.log('🎯 Execution completed:', result)
    setExecutionResult(result)
  }

  const handleBack = () => {
    if (hasUnsavedChanges) {
      const confirm = window.confirm(
        'Du hast ungespeicherte Änderungen.\n\n' +
        'Möchtest du wirklich zurück gehen? Alle Änderungen gehen verloren.'
      )
      if (!confirm) return
    }
    navigate('/admin/prompts')
  }

  const handleValidationNodeClick = (nodeId) => {
    // Select the node to show its config panel
    setSelectedNodeId(nodeId)

    // TODO: Optional - scroll to node in canvas
    // ReactFlow doesn't expose a direct scrollTo API, but we could use fitView
    // or manual DOM manipulation if needed
  }

  const handlePlaceholderSelect = (placeholderString) => {
    if (!selectedNode) return

    // Target bestimmen: End Node oder Inline Template
    if (placeholderPickerTarget === 'end' && selectedNode.type === 'end') {
      const textarea = endNodeTextareaRef.current
      const currentTemplate = selectedNode.data.template || ''

      // Wenn Textarea Ref verfügbar, an Cursor-Position einfügen
      if (textarea) {
        const cursorPos = textarea.selectionStart || currentTemplate.length
        const before = currentTemplate.substring(0, cursorPos)
        const after = currentTemplate.substring(cursorPos)
        const newTemplate = before + placeholderString + after

        handleNodeUpdate(selectedNode.id, { template: newTemplate })

        // Cursor nach eingefügtem Platzhalter positionieren
        setTimeout(() => {
          const newPos = cursorPos + placeholderString.length
          textarea.setSelectionRange(newPos, newPos)
          textarea.focus()
        }, 0)
      } else {
        // Fallback: Am Ende einfügen
        const newTemplate = currentTemplate + placeholderString
        handleNodeUpdate(selectedNode.id, { template: newTemplate })
      }
    }

    // Inline Template (Analysis Node)
    else if (placeholderPickerTarget === 'inline' && selectedNode.type === 'analysis') {
      const textarea = inlineTemplateTextareaRef.current
      const currentTemplate = selectedNode.data.inline_template || ''

      // Wenn Textarea Ref verfügbar, an Cursor-Position einfügen
      if (textarea) {
        const cursorPos = textarea.selectionStart || currentTemplate.length
        const before = currentTemplate.substring(0, cursorPos)
        const after = currentTemplate.substring(cursorPos)
        const newTemplate = before + placeholderString + after

        handleNodeUpdate(selectedNode.id, { inline_template: newTemplate })

        // Cursor nach eingefügtem Platzhalter positionieren
        setTimeout(() => {
          const newPos = cursorPos + placeholderString.length
          textarea.setSelectionRange(newPos, newPos)
          textarea.focus()
        }, 0)
      } else {
        // Fallback: Am Ende einfügen
        const newTemplate = currentTemplate + placeholderString
        handleNodeUpdate(selectedNode.id, { inline_template: newTemplate })
      }
    }
  }

  // ── Render ────────────────────────────────────────────────────────────────

  return (
    <div className="workflow-editor">
      {/* Toolbar */}
      <div className="workflow-toolbar">
        <button className="btn-secondary" onClick={handleBack}>
          ← Zurück
        </button>

        <input
          type="text"
          value={workflowName}
          onChange={(e) => {
            setWorkflowName(e.target.value)
            setHasUnsavedChanges(true)
          }}
          placeholder="Interner Workflow-Name (Slug-Basis)"
          title="Technischer Name in der Datenbank. Den sichtbaren Titel für die KI-Analyse setzt du in der Start-Node."
          style={{ flex: 1, padding: '8px', borderRadius: '4px', border: '1px solid var(--border)' }}
        />

        <button className="btn-secondary" onClick={handleNew}>
          Neu
        </button>
        <button className="btn-secondary" onClick={handleValidate}>
          Validieren {validationErrors.length > 0 ? `(${validationErrors.length} ⚠️)` : ''}
        </button>

        {/* Execute Panel */}
        <WorkflowExecutePanel
          currentPrompt={currentPrompt}
          onExecutionComplete={handleExecutionComplete}
          disabled={validationErrors.length > 0}
        />

        <button
          className="btn-primary"
          onClick={handleSave}
          disabled={loading}
          title={validationErrors.length > 0
            ? `Speichern blockiert: ${validationErrors.length} Validierungsfehler`
            : 'Workflow in Datenbank speichern'}
        >
          {loading ? 'Speichern...' : validationErrors.length > 0 ? '🔒 Speichern' : '💾 Speichern'}
        </button>
        {currentPrompt && (
          <button className="btn-secondary" onClick={handleDelete} disabled={loading}>
            Löschen
          </button>
        )}
      </div>

      {error && (
        <div style={{ padding: '12px', background: 'var(--danger)', color: 'white', borderRadius: '4px', marginBottom: '8px' }}>
          ❌ {error}
          {validationErrors.length > 0 && (
            <div style={{ marginTop: 8, fontSize: 12 }}>
              Tipp: Behebe die Validierungsfehler unten, um speichern zu können.
            </div>
          )}
        </div>
      )}

      {/* Main Content */}
      <div className="workflow-content">
        {/* Sidebar */}
        <div className="workflow-sidebar" style={{ display: selectedNode ? 'none' : 'block' }}>
          <div className="sidebar-section">
            <h3>Workflow-Knoten</h3>
            <div className="node-palette">
              <button className="node-palette-button" onClick={() => handleAddNode('start')}>
                <span className="icon">🚀</span> Start
              </button>
              <button className="node-palette-button" onClick={() => handleAddNode('analysis')}>
                <span className="icon">🤖</span> Analyse
              </button>
              <button className="node-palette-button" onClick={() => handleAddNode('logic')}>
                <span className="icon">⚡</span> Logik
              </button>
              <button className="node-palette-button" onClick={() => handleAddNode('join')}>
                <span className="icon">🔀</span> Join
              </button>
              <button className="node-palette-button" onClick={() => handleAddNode('end')}>
                <span className="icon">🏁</span> Ende
              </button>
            </div>
          </div>

          {selectedNode && (
            <div className="sidebar-section">
              <h3>Aktionen</h3>
              <button className="btn-secondary btn-full" onClick={handleDeleteNode}>
                🗑️ Node löschen
              </button>
            </div>
          )}

          <div className="sidebar-section">
            <h3>Info</h3>
            <div style={{ fontSize: '12px', color: 'var(--text3)' }}>
              <div>Nodes: {nodes.length}</div>
              <div>Edges: {edges.length}</div>
              <div>Errors: {validationErrors.length}</div>
              <div>Warnings: {validationWarnings.length}</div>
            </div>
          </div>
        </div>

        {/* Canvas */}
        <div className="workflow-canvas-container">
          <WorkflowCanvas
            nodes={nodes}
            edges={edges}
            nodeTypes={nodeTypes}
            onNodesChange={handleNodesChange}
            onEdgesChange={handleEdgesChange}
            onConnect={onConnect}
            onNodeClick={onNodeClick}
          />
        </div>

        {/* Config Panel */}
        {selectedNode && (
          <div className="workflow-config-panel">
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 16 }}>
              <h2 style={{ margin: 0 }}>Node-Konfiguration</h2>
              <button
                onClick={() => setSelectedNodeId(null)}
                style={{
                  background: 'none',
                  border: 'none',
                  fontSize: 24,
                  cursor: 'pointer',
                  color: 'var(--text3)',
                  padding: 4,
                  lineHeight: 1
                }}
                title="Schließen"
              >
                ×
              </button>
            </div>

            {/* Inline Validation Display */}
            {(validationErrors.length > 0 || validationWarnings.length > 0) && (
              <div style={{
                background: validationErrors.length > 0 ? '#ffebee' : '#fff3cd',
                border: `1px solid ${validationErrors.length > 0 ? 'var(--danger)' : '#FFC107'}`,
                borderRadius: '8px',
                padding: '12px',
                marginBottom: '16px'
              }}>
                <div style={{ fontWeight: 600, marginBottom: '8px', color: validationErrors.length > 0 ? 'var(--danger)' : '#856404' }}>
                  {validationErrors.length > 0 ? `❌ ${validationErrors.length} Fehler` : `⚠️ ${validationWarnings.length} Warnungen`}
                </div>
                {validationErrors.map((err, i) => (
                  <div key={`err-${i}`} style={{ fontSize: '13px', marginBottom: '4px', color: 'var(--danger)', cursor: err.nodeId ? 'pointer' : 'default' }}
                    onClick={() => err.nodeId && setSelectedNodeId(err.nodeId)}>
                    • {err.message}
                  </div>
                ))}
                {validationWarnings.map((warn, i) => (
                  <div key={`warn-${i}`} style={{ fontSize: '13px', marginBottom: '4px', color: '#856404', cursor: warn.nodeId ? 'pointer' : 'default' }}
                    onClick={() => warn.nodeId && setSelectedNodeId(warn.nodeId)}>
                    • {warn.message}
                  </div>
                ))}
              </div>
            )}

            {/* Start-Node: Metadaten für KI-Analyse (wie Pipeline: display_name, description, category) */}
            {selectedNode.type === 'start' && (
              <div className="config-section" style={{ marginBottom: 20 }}>
                <h3 style={{ margin: '0 0 10px', fontSize: 15 }}>Anzeige in KI-Analyse</h3>
                <p style={{ fontSize: 12, color: 'var(--text3)', lineHeight: 1.5, marginBottom: 12 }}>
                  Titel, Kurzbeschreibung und Kategorie erscheinen auf der Analyse-Seite, im Verlauf und in der
                  Kategorie-Navigation – analog zu Pipeline-Prompts im Admin.
                </p>
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
                  Titel (sichtbar für Nutzer)
                </label>
                <input
                  type="text"
                  value={selectedNode.data.analysis_title ?? ''}
                  onChange={(e) =>
                    handleNodeUpdate(selectedNode.id, { analysis_title: e.target.value })
                  }
                  placeholder="z. B. Ganzheitliche Auswertung"
                  style={{
                    width: '100%',
                    padding: '8px',
                    borderRadius: '4px',
                    border: '1px solid var(--border)',
                    background: 'var(--surface)',
                    color: 'var(--text1)',
                    fontSize: '14px',
                    marginBottom: 12,
                  }}
                />
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
                  Kurzbeschreibung (optional)
                </label>
                <textarea
                  value={selectedNode.data.analysis_description ?? ''}
                  onChange={(e) =>
                    handleNodeUpdate(selectedNode.id, { analysis_description: e.target.value })
                  }
                  placeholder="Ein Satz, worum es bei dieser Auswertung geht …"
                  rows={4}
                  style={{
                    width: '100%',
                    padding: '8px',
                    borderRadius: '4px',
                    border: '1px solid var(--border)',
                    background: 'var(--surface)',
                    color: 'var(--text1)',
                    fontSize: '13px',
                    lineHeight: 1.5,
                    marginBottom: 12,
                    resize: 'vertical',
                  }}
                />
                <label style={{ display: 'block', marginBottom: 6, fontWeight: 600, fontSize: 13 }}>
                  Kategorie
                </label>
                <select
                  value={selectedNode.data.analysis_category || 'ganzheitlich'}
                  onChange={(e) =>
                    handleNodeUpdate(selectedNode.id, { analysis_category: e.target.value })
                  }
                  style={{
                    width: '100%',
                    padding: '8px',
                    borderRadius: '4px',
                    border: '1px solid var(--border)',
                    background: 'var(--surface)',
                    color: 'var(--text1)',
                    fontSize: '14px',
                  }}
                >
                  {ANALYSIS_CATEGORY_ORDER.map((key) => (
                    <option key={key} value={key}>
                      {ANALYSIS_CATEGORY_LABELS[key] || key}
                    </option>
                  ))}
                </select>
              </div>
            )}

            {/* Basis-Konfiguration */}
            <div className="config-section">
              <label>Node-Name {selectedNode.type === 'start' && '(auf dem Canvas)'}</label>
              <input
                type="text"
                value={selectedNode.data.label || ''}
                onChange={(e) => handleNodeUpdate(selectedNode.id, { label: e.target.value })}
                placeholder="z.B. Gewichtsanalyse"
                style={{
                  width: '100%',
                  padding: '8px',
                  borderRadius: '4px',
                  border: '1px solid var(--border)',
                  background: 'var(--surface)',
                  color: 'var(--text1)',
                  fontSize: '14px'
                }}
              />
              <div style={{ marginTop: 4, fontSize: 11, color: 'var(--text3)' }}>
                Änderungen werden automatisch übernommen
              </div>
            </div>

            {/* Type-spezifische Konfiguration */}
            {selectedNode.type === 'analysis' && (() => {
              // Helper: Bestimme aktuellen Mode basierend auf node.data
              const isInlineMode = selectedNode.data.inline_template !== null && selectedNode.data.inline_template !== undefined
              const isReferenceMode = !isInlineMode

              return (
                <>
                  {/* Prompt Source Selector */}
                  <div className="config-section">
                    <label className="form-label">Prompt-Quelle</label>
                    <div style={{ display: 'flex', flexDirection: 'column', gap: '8px' }}>
                      <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                        <input
                          type="radio"
                          name={`promptSource-${selectedNode.id}`}
                          checked={isReferenceMode}
                          onChange={() => {
                            // Wechsel zu Reference Mode
                            handleNodeUpdate(selectedNode.id, {
                              inline_template: null,  // Inline löschen
                              prompt_slug: selectedNode.data.prompt_slug || ''  // Behalte existierenden slug
                            })
                          }}
                          style={{ marginRight: '8px' }}
                        />
                        <span style={{ fontSize: '14px' }}>📚 Basis-Prompt referenzieren</span>
                      </label>
                      <label style={{ display: 'flex', alignItems: 'center', cursor: 'pointer' }}>
                        <input
                          type="radio"
                          name={`promptSource-${selectedNode.id}`}
                          checked={isInlineMode}
                          onChange={() => {
                            // Wechsel zu Inline Mode
                            // WICHTIG: prompt_slug NICHT löschen, damit er beim Zurückwechseln noch da ist
                            handleNodeUpdate(selectedNode.id, {
                              inline_template: selectedNode.data.inline_template || ''  // Aktiviere Inline Mode
                            })
                          }}
                          style={{ marginRight: '8px' }}
                        />
                        <span style={{ fontSize: '14px' }}>✏️ Inline-Template erstellen</span>
                      </label>
                    </div>
                  </div>

                  {/* Conditional Rendering: Reference Mode */}
                  {isReferenceMode && (
                    <div className="config-section">
                      <label>Basis-Prompt auswählen</label>
                      <select
                        value={selectedNode.data.prompt_slug || ''}
                        onChange={(e) => {
                          const promptSlug = e.target.value
                          const selectedPrompt = availablePrompts.find(p => p.slug === promptSlug)
                          handleNodeUpdate(selectedNode.id, {
                            prompt_slug: promptSlug,
                            prompt_name: selectedPrompt?.name || null,
                            inline_template: null
                          })
                        }}
                        style={{
                          width: '100%',
                          padding: '8px',
                          borderRadius: '4px',
                          border: '1px solid var(--border)',
                          background: 'var(--surface)',
                          color: 'var(--text1)'
                        }}
                      >
                        <option value="">-- Basis-Prompt wählen --</option>
                        {availablePrompts.map(prompt => (
                          <option key={prompt.id} value={prompt.slug}>
                            {prompt.name}
                          </option>
                        ))}
                      </select>
                      {selectedNode.data.prompt_slug && (
                        <div style={{ marginTop: 8, fontSize: 12, color: 'var(--text3)' }}>
                          Prompt: {selectedNode.data.prompt_slug} ({selectedNode.data.prompt_name || 'unbekannt'})
                        </div>
                      )}
                    </div>
                  )}

                  {/* Conditional Rendering: Inline Mode */}
                  {isInlineMode && (
                    <InlineTemplateEditor
                      value={selectedNode.data.inline_template || ''}
                      onChange={(template) => handleNodeUpdate(selectedNode.id, {
                        inline_template: template,
                        prompt_slug: null
                      })}
                      onPlaceholderPick={() => {
                        setPlaceholderPickerTarget('inline')
                        setShowPlaceholderPicker(true)
                      }}
                      textareaRef={inlineTemplateTextareaRef}
                    />
                  )}

                  <QuestionAugmentationPanel node={selectedNode} onChange={handleNodeUpdate} />
                  <FallbackConfig node={selectedNode} edges={edges} nodes={nodes} onChange={handleNodeUpdate} />
                </>
              )
            })()}

            {selectedNode.type === 'logic' && (
              <>
                <LogicExpressionEditor
                  node={selectedNode}
                  nodes={nodes}
                  edges={edges}
                  onChange={handleNodeUpdate}
                />
                <FallbackConfig node={selectedNode} edges={edges} nodes={nodes} onChange={handleNodeUpdate} />
              </>
            )}

            {selectedNode.type === 'join' && (
              <JoinConfig node={selectedNode} onChange={handleNodeUpdate} />
            )}

            {selectedNode.type === 'end' && (
              <EndNodeConfig
                node={selectedNode}
                onChange={handleNodeUpdate}
                onOpenPlaceholderPicker={() => {
                  setPlaceholderPickerTarget('end')
                  setShowPlaceholderPicker(true)
                }}
                textareaRef={endNodeTextareaRef}
              />
            )}
          </div>
        )}
      </div>

      {/* Validation Panel - REMOVED (moved to config panel header) */}

      {/* Execution Result Viewer */}
      {executionResult && (
        <WorkflowResultViewer
          result={executionResult}
          onClose={() => setExecutionResult(null)}
        />
      )}

      {/* Placeholder Picker Modal */}
      {showPlaceholderPicker && (
        <PlaceholderPicker
          nodes={nodes}
          currentNodeId={selectedNode?.id}
          onSelect={handlePlaceholderSelect}
          onClose={() => setShowPlaceholderPicker(false)}
        />
      )}

      {/* Validation Panel */}
      {showValidationPanel && (validationErrors.length > 0 || validationWarnings.length > 0) && (
        <ValidationPanel
          errors={validationErrors}
          warnings={validationWarnings}
          onNodeClick={handleValidationNodeClick}
          onClose={() => setShowValidationPanel(false)}
        />
      )}

      {/* Toast Notification */}
      {toast && (
        <Toast
          message={toast.message}
          type={toast.type}
          duration={toast.duration || 3000}
          onClose={() => setToast(null)}
        />
      )}

      {/* Confirm Dialog */}
      {confirmDialog && (
        <ConfirmDialog
          message={confirmDialog.message}
          onConfirm={confirmDialog.onConfirm}
          onCancel={() => setConfirmDialog(null)}
          confirmText={confirmDialog.confirmText}
          cancelText={confirmDialog.cancelText}
          type={confirmDialog.type}
        />
      )}
    </div>
  )
}
