import { lazy, Suspense } from 'react'
import { useTransformedGraph } from './GraphDataProvider'
import type { ApiGraphResponse } from './types'

const BrainGraph3DScene = lazy(() => import('./BrainGraph3DScene'))

function hasWebGL(): boolean {
  try {
    const canvas = document.createElement('canvas')
    return !!(canvas.getContext('webgl2') || canvas.getContext('webgl'))
  } catch {
    return false
  }
}

interface BrainGraph3DProps {
  graphData: ApiGraphResponse | null
}

export default function BrainGraph3D({ graphData }: BrainGraph3DProps) {
  const graph = useTransformedGraph(graphData)

  if (!hasWebGL()) {
    return (
      <div className="flex items-center justify-center h-[480px] text-slate-500 text-sm">
        <div className="text-center">
          <p className="mb-2">WebGL is not available in your browser.</p>
          <p className="text-xs">Try Chrome, Firefox, or Edge for the 3D brain visualization.</p>
        </div>
      </div>
    )
  }

  if (!graph) {
    return (
      <div className="flex items-center justify-center h-[480px] text-slate-500 text-sm">
        No graph data available. Start the API server to load the knowledge graph.
      </div>
    )
  }

  return (
    <div className="w-full h-[600px] bg-slate-900/60 rounded-lg border border-slate-700/50 overflow-hidden relative">
      <Suspense
        fallback={
          <div className="flex items-center justify-center h-full text-slate-500 text-sm">
            <span className="animate-pulse">Loading 3D brain...</span>
          </div>
        }
      >
        <BrainGraph3DScene graph={graph} />
      </Suspense>

      {/* Legend overlay */}
      <div className="absolute bottom-3 left-3 flex flex-wrap gap-x-3 gap-y-1 pointer-events-none max-w-[70%]">
        {Object.entries({
          lesson: '#22c55e', failure: '#ef4444', pattern: '#3b82f6',
          schema: '#a855f7', procedure: '#ec4899', want: '#f59e0b',
          intent: '#06b6d4', anti_pattern: '#d62728', decision: '#8dd3c7', concept: '#64748b',
        }).map(([type, color]) => (
          <span key={type} className="flex items-center gap-1 text-[10px] text-slate-400">
            <span className="w-1.5 h-1.5 rounded-full" style={{ background: color }} />
            {type}
          </span>
        ))}
      </div>

      <div className="absolute top-3 right-3 text-[10px] text-slate-500 pointer-events-none">
        {graph.nodes.length} nodes &middot; {graph.edges.length} edges
      </div>
    </div>
  )
}
