import { lazy, Suspense } from 'react'
import { TreeMetadataForm } from './TreeMetadataForm'
import { NodeList } from './NodeList'
import { TreePreviewPanel } from '@/components/tree-preview/TreePreviewPanel'
import { useTreeEditorStore } from '@/store/treeEditorStore'
import { cn } from '@/lib/utils'

// Lazy load CodeModeEditor (Monaco is ~2MB)
const CodeModeEditor = lazy(() =>
  import('./code-mode/CodeModeEditor').then(m => ({ default: m.CodeModeEditor }))
)

interface TreeEditorLayoutProps {
  isMobile?: boolean
}

export function TreeEditorLayout({ isMobile = false }: TreeEditorLayoutProps) {
  const editorMode = useTreeEditorStore(s => s.editorMode)

  return (
    <div
      className={cn(
        'flex flex-1 overflow-hidden',
        isMobile ? 'flex-col' : 'flex-row'
      )}
    >
      {editorMode === 'code' ? (
        <>
          {/* Code Mode: Monaco editor (60%) + Preview (40%) */}
          <div className={cn(
            'flex flex-col overflow-hidden border-border',
            isMobile ? 'h-full w-full border-b' : 'w-3/5 border-r'
          )}>
            <Suspense fallback={
              <div className="flex h-full items-center justify-center bg-card">
                <div className="h-6 w-6 animate-spin rounded-full border-2 border-border border-t-foreground" />
              </div>
            }>
              <CodeModeEditor />
            </Suspense>
          </div>

          {/* Right Panel - Preview */}
          <div className={cn(
            'flex-1 overflow-hidden bg-accent/50',
            isMobile ? 'hidden' : 'block'
          )}>
            <TreePreviewPanel />
          </div>
        </>
      ) : (
        <>
          {/* Flow Mode: Form editor (60%) + Preview (40%) */}
          <div className={cn(
            'flex flex-col overflow-y-auto border-border',
            isMobile ? 'h-full w-full border-b' : 'w-3/5 border-r'
          )}>
            <div className="space-y-4 p-4">
              <TreeMetadataForm />
              <NodeList />
            </div>
          </div>

          {/* Right Panel - Preview */}
          <div className={cn(
            'flex-1 overflow-hidden bg-accent/50',
            isMobile ? 'hidden' : 'block'
          )}>
            <TreePreviewPanel />
          </div>
        </>
      )}
    </div>
  )
}

export default TreeEditorLayout
