'use client'

/**
 * Architecture Overview — Interaktiver Service-Graph
 *
 * ReactFlow-Visualisierung der 13 Compliance-Services in 4 Schwimmbahnen:
 * Frontend, Backend APIs, Infrastructure, Data Sovereignty.
 * Analog zum SDK-Flow, aber fuer die Service-Topologie.
 */

import { useCallback, useState, useMemo } from 'react'
import {
  ARCH_SERVICES,
  ARCH_EDGES,
  getAllDbTables,
  getAllRagCollections,
  type ArchService,
} from './architecture-data'
import { type LayerFilter } from './_layout'
import ArchHeader from './_components/ArchHeader'
import Toolbar from './_components/Toolbar'
import ArchCanvas from './_components/ArchCanvas'
import ServiceTable from './_components/ServiceTable'

export default function ArchitecturePage() {
  const [selectedService, setSelectedService] = useState<ArchService | null>(null)
  const [layerFilter, setLayerFilter] = useState<LayerFilter>('alle')
  const [showDb, setShowDb] = useState(false)
  const [showRag, setShowRag] = useState(false)
  const [showApis, setShowApis] = useState(false)
  const [expandedServices, setExpandedServices] = useState<Set<string>>(new Set())

  const toggleExpanded = useCallback((id: string) => {
    setExpandedServices(prev => {
      const next = new Set(prev)
      if (next.has(id)) next.delete(id)
      else next.add(id)
      return next
    })
  }, [])

  const allDbTables = useMemo(() => getAllDbTables(), [])
  const allRagCollections = useMemo(() => getAllRagCollections(), [])

  const stats = useMemo(() => {
    return {
      services: ARCH_SERVICES.length,
      dbTables: allDbTables.length,
      ragCollections: allRagCollections.length,
      edges: ARCH_EDGES.length,
    }
  }, [allDbTables, allRagCollections])

  const handleLayerFilter = useCallback((f: LayerFilter) => {
    setLayerFilter(f)
    setSelectedService(null)
  }, [])

  return (
    <div className="space-y-4">
      <ArchHeader stats={stats} />

      <Toolbar
        layerFilter={layerFilter}
        showDb={showDb}
        showRag={showRag}
        showApis={showApis}
        onLayerFilter={handleLayerFilter}
        onToggleDb={() => setShowDb(v => !v)}
        onToggleRag={() => setShowRag(v => !v)}
        onToggleApis={() => setShowApis(v => !v)}
      />

      <ArchCanvas
        layerFilter={layerFilter}
        showDb={showDb}
        showRag={showRag}
        showApis={showApis}
        selectedService={selectedService}
        setSelectedService={setSelectedService}
      />

      <ServiceTable
        layerFilter={layerFilter}
        expandedServices={expandedServices}
        onToggleExpanded={toggleExpanded}
        onMarkInGraph={setSelectedService}
      />
    </div>
  )
}
