/**
 * 闭环健康度条组件
 *
 * 展示"信号→决策→任务→验收→知识"5 阶段转化率。
 * 数据来源：/tasks/loop-health API。
 */
import { ChevronRight } from 'lucide-react'
import { cn } from '@/lib/utils'

interface LoopHealthBarProps {
  /** 闭环健康度数据 */
  data: {
    task_generation_rate?: number
    store_execution_rate?: number
    weekly_check_rate?: number
    monthly_review_rate?: number
    practice_promotion_rate?: number
  } | null
  /** 各阶段数量（可选） */
  counts?: {
    signals?: number
    decisions?: number
    tasks?: number
    checks?: number
    reviews?: number
    practices?: number
  }
}

/** 5 阶段定义 */
const STAGES = [
  { key: 'task_generation_rate', label: '经营信号', countKey: 'signals', placeholder: '1,284' },
  { key: 'store_execution_rate', label: '有效决策', countKey: 'decisions', placeholder: '46' },
  { key: 'store_execution_rate', label: '执行任务', countKey: 'tasks', placeholder: '38' },
  { key: 'weekly_check_rate', label: '完成验收', countKey: 'reviews', placeholder: '28' },
  { key: 'practice_promotion_rate', label: '沉淀案例', countKey: 'practices', placeholder: '14' },
]

export function LoopHealthBar({ data, counts }: LoopHealthBarProps) {
  const stages = STAGES.map((s) => {
    const rate = data ? (data as any)[s.key] : null
    const count = counts ? (counts as any)[s.countKey] : null
    return {
      ...s,
      rate: rate != null ? Math.round(Number(rate) * 100) / 100 : null,
      count: count != null ? String(count) : s.placeholder,
    }
  })

  return (
    <div className="flex flex-wrap items-center gap-1 rounded-lg border bg-card p-3">
      {stages.map((s, i) => (
        <div key={s.label} className="flex items-center gap-1">
          <div className="flex flex-col items-center px-2">
            <span
              className={cn(
                'flex h-6 w-6 items-center justify-center rounded-full text-[10px] font-bold',
                i === 0 ? 'bg-blue-600 text-white' : 'bg-muted text-muted-foreground',
              )}
            >
              {i + 1}
            </span>
            <small className="mt-1 text-[10px] text-muted-foreground">{s.label}</small>
            <b className="text-sm font-bold">{s.count}</b>
            {s.rate != null && (
              <em className="text-[10px] text-green-600">{s.rate}% 转化</em>
            )}
          </div>
          {i < stages.length - 1 && <ChevronRight className="h-4 w-4 text-muted-foreground" />}
        </div>
      ))}
    </div>
  )
}
