import { Panel, PanelBody, PanelHeader } from '@/components/ui/display'
import { getI18n } from '@/lib/i18n/server'
import { formatNumber } from '@/lib/i18n/translate'
import { cn } from '@/lib/cn'
import type { OrchestrationFlowStep } from '@/lib/engine/orchestrator'

/**
 * Agent collaboration (§4).
 *
 * One rail, one step per agent, in the order the pass ran, ending in the orchestrator's
 * decision. The rail sits on the start edge so it reads correctly in both directions.
 */

const STATUS_DOT: Record<string, string> = {
  clear: 'bg-normal',
  observing: 'bg-info',
  flagged: 'bg-watch',
  alarming: 'bg-critical',
  decided: 'bg-brand',
}

export async function AgentFlow({
  flow,
  className,
}: {
  flow: OrchestrationFlowStep[]
  className?: string
}) {
  const { t, locale } = await getI18n()
  const ar = locale === 'ar'

  return (
    <Panel className={className}>
      <PanelHeader title={t('aiOps.collaboration')} subtitle={t('aiOps.collaborationHint')} />
      <PanelBody className="pt-0">
        <ol className="relative space-y-3.5 pt-3">
          <span
            aria-hidden
            className="absolute inset-y-2 w-px bg-border"
            style={{ insetInlineStart: '0.3125rem' }}
          />
          {flow.map((step, index) => (
            <li key={`${step.agentKey}-${index}`} className="relative ps-6">
              <span
                aria-hidden
                className={cn(
                  'absolute top-1.5 size-2.5 rounded-full ring-4 ring-surface',
                  STATUS_DOT[step.status] ?? 'bg-text-faint',
                  step.agentKey === 'orchestrator' && 'nabdh-pulse',
                )}
                style={{ insetInlineStart: 0 }}
              />
              <div className="flex flex-wrap items-baseline justify-between gap-x-3 gap-y-1">
                <p
                  className={cn(
                    'text-xs font-semibold',
                    step.agentKey === 'orchestrator' ? 'text-brand' : 'text-text',
                  )}
                >
                  {t(`agents.key.${step.agentKey}`)}
                </p>
                <p className="tnum text-[10px] text-text-faint">
                  {t('agents.confidence')} {formatNumber(locale, step.confidence, { maximumFractionDigits: 0 })}%
                </p>
              </div>
              <p className="mt-1 text-[11px] leading-relaxed text-text-muted">
                {ar ? step.headlineAr : step.headline}
              </p>
            </li>
          ))}
        </ol>
      </PanelBody>
    </Panel>
  )
}
