import type { Metadata } from 'next'

import { PermissionGate } from '@/components/console/permission-gate'
import { LearningQueue } from '@/components/intelligence/learning-queue'
import { DemoDataBadge, PageHeader } from '@/components/ui/display'
import { getCurrentUser } from '@/lib/auth/current-user'
import { getI18n } from '@/lib/i18n/server'
import { listLearningCandidates, refreshLearningCandidates } from '@/lib/services/memory-service'

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

/**
 * The learning queue (§33).
 *
 * Refreshed on load so the queue reflects the memory as it stands. `refreshLearningCandidates`
 * only writes proposals that do not already exist, so opening the page repeatedly does not
 * produce a wall of duplicates.
 */
export default async function LearningPage() {
  const user = await getCurrentUser()
  const { t } = await getI18n()
  if (!user?.permissions.has('learning.read')) return <PermissionGate />

  await refreshLearningCandidates()
  const candidates = await listLearningCandidates({ limit: 30 })

  return (
    <>
      <PageHeader
        title={t('learning.title')}
        subtitle={t('learning.subtitle')}
        badge={<DemoDataBadge label={t('common.simulated')} title={t('common.simulatedTooltip')} />}
      />
      <LearningQueue
        initial={candidates}
        canReview={user.permissions.has('learning.review')}
      />
    </>
  )
}
