import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { KnowledgeExplorer } from '@/components/intelligence/knowledge-explorer'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { getNeighbourhood } from '@/lib/services/knowledge-service'

export const metadata: Metadata = { title: 'Knowledge Graph' }
export const dynamic = 'force-dynamic'

/**
 * Graph Explorer (§17).
 *
 * Opens on failure risk, which is the concept most edges pass through — the fastest way
 * for a reader to understand what kind of structure they are looking at.
 */
export default async function KnowledgeGraphPage({
  searchParams,
}: {
  searchParams: Promise<{ focus?: string }>
}) {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('knowledge.read')) return <PermissionGate />

  const { focus } = await searchParams
  const neighbourhood = await getNeighbourhood(focus?.trim() || 'C-RISK', 1)

  return (
    <>
      <PageHeader
        title={t('knowledge.title')}
        subtitle={t('knowledge.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />
      <KnowledgeExplorer
        initialFocus={neighbourhood.focus}
        initialNodes={neighbourhood.nodes}
        initialEdges={neighbourhood.edges}
      />
    </>
  )
}
