'use client';

import {
  subLabelZh,
  triggerTypeLabelZh,
  diagnosisCodeNameZh,
  treatmentCategoryNameZh,
} from '@pac/types';
import { formatToothPosition, formatDaysReadable } from '@/lib/utils';

/**
 * ReasonLine — 召回理由富文本渲染。
 *
 * 数据契约:后端只回原始 enum / canonical code(reason.signals JSON),
 * 前端用 @pac/types 字典翻译 + 富文本组合(加粗 + 玫红高亮,色彩克制)。
 *
 * 同源:列表页 PatientPlanCard + 详情页 WhyCard 共用。
 *
 * 老数据/异常兜底:signals 缺失时落回 reason 文本。
 */
export interface ReasonLineInput {
  scenario: string;
  reason: string;
  signals?: {
    subKey: string;
    triggers: Array<{ type: string; code?: string | null }>;
    toothPosition?: string | null;
    daysSince: number;
    expectedCategories: string[];
  } | null;
}

export function ReasonLine({ reason }: { reason: ReasonLineInput }) {
  if (!reason.signals) return <span>{reason.reason}</span>;
  const s = reason.signals;
  const trig = s.triggers[0]; // 当前单源;多源 W5+ 再调
  const subLabel = subLabelZh(reason.scenario, s.subKey);
  const cats = s.expectedCategories.map(treatmentCategoryNameZh).join(' / ');
  return (
    <span>
      <strong className="text-slate-900">{subLabel}</strong>
      {s.toothPosition && ` · 牙位 ${formatToothPosition(s.toothPosition)}`}
      {trig?.code && ` — ${diagnosisCodeNameZh(trig.code)}`}
      {trig && `(${triggerTypeLabelZh(trig.type)})`}{' '}
      <strong className="text-rose-600 tabular-nums">{formatDaysReadable(s.daysSince)}前</strong>
      {cats && `,未启动 ${cats}`}
    </span>
  );
}
