'use client';

import { useEffect, useMemo, useRef, useState } from 'react';
import { useRouter } from 'next/navigation';
import { toast } from 'sonner';
import { plansApi } from './plans-api';
import { ChevronDown, Filter, Loader2, PhoneCall, Search, X } from 'lucide-react';
import {
  EXECUTION_OUTCOME_GROUP_META,
  EXECUTION_OUTCOME_META,
  PERSONA_TAG_FILTER_DIMS,
  Permission,
  type ExecutionOutcome,
  type ExecutionOutcomeGroup,
  type PlanListItem,
} from '@pac/types';
import { cn, formatGender } from '@/lib/utils';
import { actionTemplate } from '@/lib/action-url';
import { useHasPermission } from '@/hooks/use-permission';
import { useAuthStore, visibleClinics } from '@/stores/auth-store';
import { PriorityHover, type PriorityBreakdown } from '@/components/priority-hover';
import { Popover, PopoverContent, PopoverTrigger } from '@/components/ui/popover';
import { usePlanSyncStore } from '@/stores/plan-sync-store';
import { usePatientPicker, type PickerFilters } from './use-patient-picker';

/**
 * PatientPickerRail — 详情页固定左栏(第 4 列):一页式工作台的"选患者"列。
 *
 * 吸收列表页核心要素(列表页将弃用):view tab / 搜索 / 排序 / 真实号码 /
 * ⭐画像标签筛选(价值分群 / 生命周期 / 紧迫度 / 潜在治疗,同维 OR 跨维 AND,服务端 SQL)。
 * 不带 KPI 面板(按需求剔除)。点患者 → 路由切详情;本组件挂在 plans/layout(路由段之上),
 * 切患者不重挂、列表状态(筛选/滚动位置/已加载页)全保留。
 */

type View = PickerFilters['view'];
// '全部' tab 已下线(信息过载;召回池 + 我的 足够日常)。view='all' 逻辑保留备用。
const VIEW_TABS: Array<{ v: View; label: string }> = [
  { v: 'pool', label: '召回池' },
  { v: 'mine', label: '我的' },
];

export function PatientPickerRail({
  currentPlanId,
  onNavigated,
}: {
  currentPlanId: string;
  /** 行点击跳转后回调(小屏抽屉模式用来收起) */
  onNavigated?: () => void;
}) {
  const router = useRouter();
  const canViewAll = useHasPermission(Permission.PLAN_VIEW_ALL);
  const canRecycle = useHasPermission(Permission.PLAN_RECYCLE); // 「返池」按钮门控(leader/admin)

  // 默认进「我的」;加载后若「我的」为空,自动回落「召回池」(见下方 effect)。
  // 与落地页选默认患者同策略(mine 优先,空则 pool)。
  const [view, setView] = useState<View>('mine');
  const autoFellBackRef = useRef(false); // 只自动回落一次,之后尊重用户手动切换
  const [search, setSearch] = useState('');
  const [keyword, setKeyword] = useState(''); // 防抖后的值(真正上服务端)
  const composingRef = useRef(false); // 中文输入法组字中(true 时别拿拼音中间态"李石ming"去搜)
  // 排序固定优先级高→低(去掉可切换的排序控件后,顺序仍按优先级)
  const [sort] = useState<PickerFilters['sort']>('priority_desc');
  const [realPhoneOnly, setRealPhoneOnly] = useState(false);
  // 配了原始档案(宿主 VIEW_PATIENT)时,手机号在宿主档案页看 → 与身份卡手机号行同条件,
  // 隐藏"真手机号"筛选(PAC 侧为造数假号,按真伪筛选无意义)。
  const hasPatientArchive = !!actionTemplate('VIEW_PATIENT');
  const [clinics, setClinics] = useState<string[]>([]);
  const [tags, setTags] = useState<Set<string>>(new Set()); // "key:value"

  const user = useAuthStore((st) => st.user);
  const clinicDict = user?.dictionary?.clinics; // 显示 plan 诊所名用(字典查表,非 scope)
  const clinicOptions = useMemo(() => visibleClinics(user), [user]);

  // 关键词防抖:手动排定,**不依赖 search 状态变化触发**。
  //   (若靠 useEffect([search]):组字结束时最终值"李石明"可能与组字中最后一次 onChange 同值 →
  //    React 不重渲染 → effect 不重跑 → 搜索永不发。这正是"中文搜不发请求"的坑。)
  //   规则:组字中(composingRef)onChange 不排;组字结束由 onCompositionEnd 直接排一次。
  const debounceRef = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);
  const scheduleKeyword = (value: string) => {
    if (debounceRef.current) clearTimeout(debounceRef.current);
    debounceRef.current = setTimeout(() => setKeyword(value.trim()), 300);
  };
  useEffect(
    () => () => {
      if (debounceRef.current) clearTimeout(debounceRef.current);
    },
    [],
  );

  const filters: PickerFilters = useMemo(
    () => ({
      view,
      keyword: keyword || undefined,
      sort,
      phoneVerified: realPhoneOnly ? true : undefined,
      targetClinicIds: clinics.length ? clinics : undefined,
      personaTags: tags.size ? [...tags].join(',') : undefined,
    }),
    [view, keyword, sort, realPhoneOnly, clinics, tags],
  );
  const { items, total, loading, hasMore, error, loadMore, patchItem, removeItem } = usePatientPicker(filters);

  // 默认「我的」加载完成后若为空 → 自动回落「召回池」(只一次)。
  // 与落地页 mine 优先、空则 pool 的默认患者策略一致,避免左栏 tab 与所选患者来源不符。
  // ⚠️ 必须等「一次真实加载完成」(loading true→false)再判空:usePatientPicker 的 loading
  //    初值是 false、total 初值 0,若不卡这个转变,首帧就会误判空而抢切 pool(且并发守卫会
  //    跳过 pool 的 fetch → 出现 tab=召回池 但数据仍是我的 的错位)。
  const prevLoadingRef = useRef(false);
  useEffect(() => {
    const justFinished = prevLoadingRef.current && !loading; // 刚从加载中变为完成
    prevLoadingRef.current = loading;
    if (autoFellBackRef.current) return;
    if (view === 'mine' && justFinished && total === 0) {
      autoFellBackRef.current = true;
      setView('pool');
    }
  }, [view, loading, total]);

  // 右侧详情动作(提交归档等)→ 同步左栏对应行状态(不重拉)。
  //   终态(completed/abandoned)行已不属于 pool/mine 视图(服务端过滤口径)→ 原地剔除,
  //   与认领/返池同款处理;all 视图仍显示全部 → 只改状态角标。
  const sync = usePlanSyncStore();
  useEffect(() => {
    if (!sync.planId) return;
    const terminal = sync.status === 'completed' || sync.status === 'abandoned';
    if (terminal && view !== 'all') {
      removeItem(sync.planId);
      return;
    }
    const patch: Partial<PlanListItem> = {};
    if (sync.status) patch.status = sync.status as PlanListItem['status'];
    if (sync.outcome) patch.lastOutcome = sync.outcome as ExecutionOutcome;
    if (Object.keys(patch).length) patchItem(sync.planId, patch);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [sync.seq]);

  // 认领:assign 给自己。认领后该 plan 归「我的」、离开「召回池」:
  //   在召回池 tab → 原地移除该行(它已不属于本 tab);其它 tab(all)→ 仅改状态。
  //   不重拉,保滚动/筛选。
  const claim = async (planId: string, name: string) => {
    const sub = user?.sub;
    if (!sub) return;
    try {
      await plansApi.assign(planId, sub);
      if (view === 'pool') removeItem(planId);
      else patchItem(planId, { status: 'assigned', assigneeUserId: sub });
      // 反向通知详情页:认领入口只在本列表,详情页的操作闸要靠这条即时解锁
      usePlanSyncStore.getState().notifyClaim(planId, sub);
      toast.success(`已认领 ${name}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '认领失败');
    }
  };

  // 返池:回收已认领的 plan → 回到召回池可被再次认领(plan 仍 active)。需 PLAN_RECYCLE 权限。
  //   返池后该 plan 离开「我的」:在我的 tab → 原地移除该行;其它 tab → 仅改状态。
  //   不重拉,保滚动/筛选。
  const recycle = async (planId: string, name: string) => {
    try {
      await plansApi.recycle(planId);
      if (view === 'mine') removeItem(planId);
      else patchItem(planId, { status: 'active', assigneeUserId: null });
      // 反向通知详情页:返池后要把闸重新上锁,否则还停在详情页的人仍能操作已交还的单
      usePlanSyncStore.getState().notifyClaim(planId, null);
      toast.success(`已返池 ${name}`);
    } catch (err) {
      toast.error(err instanceof Error ? err.message : '返池失败');
    }
  };

  // 触底加载
  const listRef = useRef<HTMLDivElement>(null);
  const onScroll = () => {
    const el = listRef.current;
    if (!el || loading || !hasMore) return;
    if (el.scrollHeight - el.scrollTop - el.clientHeight < 120) loadMore();
  };

  const toggleTag = (k: string) =>
    setTags((prev) => {
      const next = new Set(prev);
      if (next.has(k)) next.delete(k);
      else next.add(k);
      return next;
    });

  return (
    <aside className="flex h-full w-[300px] flex-none flex-col border-r border-slate-100 bg-white">
      {/* view tabs */}
      <div className="flex flex-none gap-1 border-b border-slate-100 px-2 pt-2">
        {VIEW_TABS.filter((t) => t.v !== 'all' || canViewAll).map((t) => (
          <button
            key={t.v}
            type="button"
            onClick={() => setView(t.v)}
            className={cn(
              'rounded-t-md px-3 py-1.5 text-[12.5px] transition-colors',
              view === t.v
                ? 'border-b-2 border-teal-600 font-semibold text-teal-700'
                : 'text-slate-500 hover:text-slate-800',
            )}
          >
            {t.label}
          </button>
        ))}
        <span className="ml-auto self-center pr-1 text-[10.5px] tabular-nums text-slate-400">
          {total} 人
        </span>
      </div>

      {/* 搜索 + 工具行 */}
      <div className="flex-none space-y-1.5 border-b border-slate-100 p-2">
        <div className="relative">
          <Search className="absolute left-2 top-1/2 h-3.5 w-3.5 -translate-y-1/2 text-slate-400" />
          <input
            type="search"
            value={search}
            onChange={(e) => {
              const v = e.target.value;
              setSearch(v);
              // 组字中(拼音中间态)不搜;非组字(英文/数字/粘贴/原生清空)正常排定
              if (!composingRef.current) scheduleKeyword(v);
            }}
            onCompositionStart={() => {
              composingRef.current = true;
            }}
            onCompositionEnd={(e) => {
              // 组字完成(拼音→汉字上屏)→ 解锁,并用最终中文直接排一次搜索
              // (直接调 scheduleKeyword,不依赖 setSearch 是否引起重渲染)
              composingRef.current = false;
              const v = e.currentTarget.value;
              setSearch(v);
              scheduleKeyword(v);
            }}
            placeholder="姓名 / 手机 / 病历号"
            className="h-7 w-full rounded-md border border-slate-100 bg-slate-50 pl-7 pr-2 text-[12px] outline-none placeholder:text-slate-400 focus:border-teal-300 focus:bg-white"
          />
        </div>
        <div className="flex items-center gap-1.5">
          {!hasPatientArchive && (
            <button
              type="button"
              onClick={() => setRealPhoneOnly((v) => !v)}
              title="只看已核实的真实手机号"
              className={cn(
                'inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-[11px] transition-colors',
                realPhoneOnly
                  ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
                  : 'border-slate-100 bg-white text-slate-500 hover:bg-slate-50',
              )}
            >
              <PhoneCall className="h-3 w-3" />真
            </button>
          )}
          <PersonaTagFilter selected={tags} onToggle={toggleTag} onClear={() => setTags(new Set())} />
        </div>
        {clinicOptions.length > 1 && (
          <RailClinicFilter options={clinicOptions} selected={clinics} onChange={setClinics} />
        )}
        {/* 已选标签 chips */}
        {tags.size > 0 && (
          <div className="flex flex-wrap gap-1">
            {[...tags].map((kv) => {
              const [k, v] = kv.split(':');
              const dim = PERSONA_TAG_FILTER_DIMS.find((d) => d.key === k);
              const opt = dim?.options.find((o) => o.value === v);
              return (
                <button
                  key={kv}
                  type="button"
                  onClick={() => toggleTag(kv)}
                  className="inline-flex items-center gap-0.5 rounded-full bg-teal-50 px-1.5 py-0.5 text-[10.5px] text-teal-700 ring-1 ring-inset ring-teal-200 hover:bg-teal-100"
                  title={`${dim?.nameZh}:${opt?.zh}(点击移除)`}
                >
                  {opt?.zh ?? v}
                  <X className="h-2.5 w-2.5" />
                </button>
              );
            })}
          </div>
        )}
      </div>

      {/* 患者列表 */}
      <div ref={listRef} onScroll={onScroll} className="min-h-0 flex-1 overflow-y-auto">
        {error && <div className="p-3 text-center text-[11.5px] text-rose-500">{error}</div>}
        {items.map((p) => (
          <PatientRow
            key={p.id}
            plan={p}
            active={p.id === currentPlanId}
            clinicName={p.targetClinicId ? String(clinicDict?.[p.targetClinicId] ?? '') : ''}
            hidePhone={hasPatientArchive}
            onClick={() => {
              router.push(`/plans/${p.id}`);
              onNavigated?.();
            }}
            onClaim={
              p.status === 'active' && !p.assigneeUserId
                ? () => void claim(p.id, p.patient.name ?? '')
                : undefined
            }
            onRecycle={
              // 被认领(有 assignee)且非终态 → 可返池。不再只认 status='assigned':
              //   无自动回收后 plan 可能停在 active 但仍挂人名下,也要能退回池。
              canRecycle &&
              !!p.assigneeUserId &&
              p.status !== 'completed' &&
              p.status !== 'abandoned' &&
              p.status !== 'superseded'
                ? () => void recycle(p.id, p.patient.name ?? '')
                : undefined
            }
          />
        ))}
        {loading && (
          <div className="flex justify-center py-3">
            <Loader2 className="h-4 w-4 animate-spin text-slate-300" />
          </div>
        )}
        {!loading && items.length === 0 && !error && (
          <div className="p-6 text-center text-[11.5px] text-slate-400">没有匹配的患者</div>
        )}
        {/* data-pet-perch:助手宠物的栖息点(滚到列表底时它会跳上来蹲;按钮被压住也无妨,滚动加载兜底) */}
        {!loading && hasMore && (
          <button
            type="button"
            data-pet-perch
            onClick={loadMore}
            className="block w-full py-2 text-center text-[11px] text-teal-700 hover:bg-teal-50/50"
          >
            加载更多({items.length}/{total})
          </button>
        )}
      </div>
    </aside>
  );
}

// ── 画像标签筛选 popover(多维度分组多选)────────────────────
function PersonaTagFilter({
  selected,
  onToggle,
  onClear,
}: {
  selected: Set<string>;
  onToggle: (kv: string) => void;
  onClear: () => void;
}) {
  /// 当前悬停选项的说明,渲染在面板底部固定行(见下方注释:为什么不用浮层)
  const [hint, setHint] = useState<string | null>(null);
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            'inline-flex h-6 items-center gap-1 rounded-md border px-1.5 text-[11px] transition-colors',
            selected.size > 0
              ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
              : 'border-slate-100 bg-white text-slate-500 hover:bg-slate-50',
          )}
        >
          <Filter className="h-3 w-3" />
          画像标签{selected.size > 0 ? ` ${selected.size}` : ''}
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" className="w-64 p-2">
        <div className="mb-1 flex items-center justify-between px-1">
          <span className="text-[11px] font-medium text-slate-500">按画像圈人</span>
          {selected.size > 0 && (
            <button type="button" onClick={onClear} className="text-[10.5px] text-teal-700 hover:underline">
              清空
            </button>
          )}
        </div>
        {/* 悬停某个选项时在底部解释它。「重要保持」「待激活」这类名字是算法口径的产物,
            光看名字猜不出边界(重要保持 vs 重要挽留差在哪?待激活 vs 沉睡客几个月分界?),
            客服只能凭感觉勾。说明文案在 persona-tag-filters.ts 的 hint 字段。 */}
        <div className="max-h-80 space-y-2 overflow-y-auto">
          {PERSONA_TAG_FILTER_DIMS.map((dim) => (
            <div key={dim.key}>
              <div className="px-1 py-0.5 text-[10.5px] font-medium uppercase tracking-wide text-slate-400">
                {dim.nameZh}
              </div>
              <div className="flex flex-wrap gap-1 px-1 pb-1">
                {dim.options.map((o) => {
                  const kv = `${dim.key}:${o.value}`;
                  const on = selected.has(kv);
                  return (
                    <button
                      key={kv}
                      type="button"
                      onClick={() => onToggle(kv)}
                      // 说明走面板底部的固定行,不用浮层:这些选项是用来**横向比较**的
                      // (重要保持 vs 重要挽留差在哪),浮层会盖住正要比的那几个。
                      onMouseEnter={() => o.hint && setHint(`${o.zh} · ${o.hint}`)}
                      onMouseLeave={() => setHint(null)}
                      onFocus={() => o.hint && setHint(`${o.zh} · ${o.hint}`)}
                      onBlur={() => setHint(null)}
                      className={cn(
                        'rounded-full border px-2 py-0.5 text-[11px] transition-colors',
                        on
                          ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
                          : 'border-slate-100 bg-white text-slate-600 hover:border-teal-200 hover:bg-teal-50/40',
                      )}
                    >
                      {o.zh}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}
        </div>
        {/* 定高:hover 进出不抖动 */}
        <div className="mt-1 min-h-[30px] border-t border-slate-100 px-1 pt-1.5 text-[10.5px] leading-relaxed">
          {hint ? (
            <span className="text-slate-600">{hint}</span>
          ) : (
            <span className="text-slate-300">悬停任一标签看它的含义</span>
          )}
        </div>
      </PopoverContent>
    </Popover>
  );
}

// ── 诊所筛选(popover 多选,样式与列表页 ClinicFilter 同源紧凑版)──────
function RailClinicFilter({
  options,
  selected,
  onChange,
}: {
  options: Array<{ id: string; name: string }>;
  selected: string[];
  onChange: (ids: string[]) => void;
}) {
  const sel = new Set(selected);
  const toggle = (id: string) => {
    const next = new Set(sel);
    if (next.has(id)) next.delete(id);
    else next.add(id);
    onChange([...next]);
  };
  return (
    <Popover>
      <PopoverTrigger asChild>
        <button
          type="button"
          className={cn(
            'inline-flex h-6 w-full items-center justify-between rounded-md border px-1.5 text-[11px] transition-colors',
            selected.length
              ? 'border-teal-300 bg-teal-50 font-medium text-teal-700'
              : 'border-slate-100 bg-white text-slate-500 hover:bg-slate-50',
          )}
        >
          <span className="truncate">
            {selected.length === 0
              ? '全部诊所'
              : selected.map((id) => options.find((o) => o.id === id)?.name ?? id).join('、')}
          </span>
          <ChevronDown className="h-3 w-3 flex-none text-slate-400" />
        </button>
      </PopoverTrigger>
      <PopoverContent align="start" className="max-h-72 w-56 overflow-y-auto p-1.5">
        <div className="mb-1 flex items-center justify-between border-b border-slate-100 px-1.5 py-1">
          <span className="text-[10.5px] text-slate-400">按诊所筛选(可多选)</span>
          {selected.length > 0 && (
            <button type="button" onClick={() => onChange([])} className="text-[10.5px] text-teal-600 hover:underline">
              清空
            </button>
          )}
        </div>
        {options.map((o) => (
          <label key={o.id} className="flex cursor-pointer items-center gap-2 rounded px-1.5 py-1.5 hover:bg-slate-50">
            <input
              type="checkbox"
              className="h-3.5 w-3.5 accent-teal-600"
              checked={sel.has(o.id)}
              onChange={() => toggle(o.id)}
            />
            <span className="truncate text-[12px] text-slate-700">{o.name}</span>
          </label>
        ))}
      </PopoverContent>
    </Popover>
  );
}

// ── 状态 pill(与列表页 STATUS_META 同款)─────────────────────
const STATUS_META: Record<string, { label: string; tone: string }> = {
  active: { label: '待认领', tone: 'bg-sky-100 text-sky-700' },
  assigned: { label: '进行中', tone: 'bg-amber-100 text-amber-700' },
  completed: { label: '已完成', tone: 'bg-emerald-100 text-emerald-700' },
  abandoned: { label: '已放弃', tone: 'bg-rose-100 text-rose-700' },
  superseded: { label: '已替代', tone: 'bg-slate-100 text-slate-600' },
};

function StatusPill({ status }: { status: string }) {
  const m = STATUS_META[status] ?? { label: status, tone: 'bg-slate-100 text-slate-700' };
  return <span className={cn('inline-block flex-none whitespace-nowrap rounded px-1.5 py-0.5 text-[10px] font-medium', m.tone)}>{m.label}</span>;
}

// ── 回访结果角标(最近一次执行的分组:成功 / 不成功 / 保持)────────
// 分组 / 文案 / 色板全部取自 @pac/types 单一真理源(EXECUTION_OUTCOME_META)。
const OUTCOME_GROUP_TONE: Record<ExecutionOutcomeGroup, string> = {
  close: 'bg-emerald-100 text-emerald-700 ring-emerald-200', // 成功
  give_up: 'bg-rose-100 text-rose-700 ring-rose-200', // 不成功
  keep: 'bg-amber-100 text-amber-700 ring-amber-200', // 保持
};

function OutcomeTag({ outcome }: { outcome: string }) {
  const meta = EXECUTION_OUTCOME_META[outcome as ExecutionOutcome];
  if (!meta) return null;
  const group = EXECUTION_OUTCOME_GROUP_META[meta.group];
  return (
    <span
      title={`回访结果:${group.labelZh} · ${meta.labelZh}`}
      className={cn(
        'flex-none rounded px-1 text-[9.5px] font-medium leading-4 ring-1 ring-inset',
        OUTCOME_GROUP_TONE[meta.group],
      )}
    >
      {group.labelZh}
    </span>
  );
}

// ── 优先级(与列表页 PriorityBar 同款:五格条 + 10 分制)────────
function PriorityBar({ score, raw }: { score: number; raw?: number }) {
  const pct = Math.max(0, Math.min(1, score / 100));
  const filled = Math.max(1, Math.round(pct * 5));
  const colors = ['bg-emerald-400', 'bg-emerald-500', 'bg-amber-400', 'bg-amber-500', 'bg-rose-500'];
  const labelTone =
    pct >= 0.6 ? (pct >= 0.8 ? 'text-rose-700' : 'text-amber-700') : pct >= 0.2 ? 'text-emerald-700' : 'text-slate-500';
  const disp = (raw ?? score / 10).toFixed(2);
  return (
    <span className="inline-flex flex-none items-center gap-1" title={`优先级 ${disp} / 10`}>
      <span className="inline-flex items-center gap-0.5">
        {Array.from({ length: 5 }).map((_, i) => (
          <span key={i} className={cn('h-1.5 w-[6px] rounded-sm', i < filled ? colors[i] : 'bg-slate-200')} />
        ))}
      </span>
      <span className={cn('text-[10.5px] font-semibold tabular-nums', labelTone)}>{disp}</span>
    </span>
  );
}

// ── 患者行(紧凑单列卡)────────────────────────────────────
function PatientRow({
  plan: p,
  active,
  clinicName,
  hidePhone,
  onClick,
  onClaim,
  onRecycle,
}: {
  plan: PlanListItem;
  active: boolean;
  clinicName: string;
  /** 宿主配了原始档案(VIEW_PATIENT)时隐藏手机号 —— 真号在宿主档案页,PAC 侧为造数假号。与详情页同条件。 */
  hidePhone: boolean;
  onClick: () => void;
  onClaim?: () => void;
  /** 已认领 plan 的「返池」回收动作(仅 PLAN_RECYCLE 权限 + status=assigned 时传入) */
  onRecycle?: () => void;
}) {
  const breakdown = (p.reasons[0]?.breakdown as { priority?: PriorityBreakdown } | null | undefined)?.priority;
  return (
    <div
      role="button"
      tabIndex={0}
      onClick={onClick}
      onKeyDown={(e) => e.key === 'Enter' && onClick()}
      className={cn(
        'group block w-full cursor-pointer border-b border-slate-100 px-3 py-2 text-left transition-colors',
        active ? 'bg-teal-50/70 ring-1 ring-inset ring-teal-200' : 'hover:bg-slate-50',
      )}
    >
      <div className="flex items-center gap-1.5">
        {p.lastOutcome && <OutcomeTag outcome={p.lastOutcome} />}
        <span className={cn('truncate text-[13px] font-semibold', active ? 'text-teal-800' : 'text-slate-900')}>
          {p.patient.name ?? p.patient.nameMasked ?? '—'}
        </span>
        <span className="flex-none text-[10.5px] tabular-nums text-slate-500">
          {formatGender(p.patient.gender)} · {p.patient.age ?? '?'} 岁
        </span>
        {p.patient.phoneVerified && (
          <span className="flex-none rounded bg-teal-50 px-1 text-[9.5px] font-medium leading-4 text-teal-700 ring-1 ring-inset ring-teal-200">
            真
          </span>
        )}
        <span className="ml-auto flex-none">
          <PriorityHover
            score={p.priorityScore}
            breakdown={breakdown}
            percentile={p.priorityPercentile}
            signals={p.reasons[0]?.signals}
          >
            <span className="cursor-help">
              <PriorityBar score={p.priorityScore} raw={breakdown?.raw} />
            </span>
          </PriorityHover>
        </span>
      </div>
      <div className="mt-0.5 flex items-center gap-1.5">
        {!hidePhone && (
          <span className="flex-none font-mono text-[10.5px] tabular-nums text-slate-400">
            {p.patient.phoneMasked ?? ''}
          </span>
        )}
        {clinicName && (
          <span className="min-w-0 flex-1 truncate text-[10px] text-slate-400" title={clinicName}>
            {hidePhone ? '' : '· '}
            {clinicName}
          </span>
        )}
        <span className="ml-auto flex-none" />
        {(() => {
          // 动作按钮:待认领→「认领」(teal),已认领→「返池」(amber)。二者与状态药丸叠同 grid 格,
          // 槽位宽/高恒为较大值,hover 只切 visibility(非 display)→ 悬停整行不重排、不位移。
          const act = onClaim
            ? { label: '认领', tone: 'bg-teal-600 hover:bg-teal-700', fn: onClaim }
            : onRecycle
              ? { label: '返池', tone: 'bg-amber-500 hover:bg-amber-600', fn: onRecycle }
              : null;
          if (!act) return <StatusPill status={p.status} />;
          return (
            <span className="grid flex-none items-center justify-items-end">
              <span className="col-start-1 row-start-1 group-hover:invisible">
                <StatusPill status={p.status} />
              </span>
              <button
                type="button"
                onClick={(e) => {
                  e.stopPropagation();
                  act.fn();
                }}
                className={cn(
                  'invisible col-start-1 row-start-1 whitespace-nowrap rounded-md px-2 py-0.5 text-[10.5px] font-medium text-white group-hover:visible',
                  act.tone,
                )}
              >
                {act.label}
              </button>
            </span>
          );
        })()}
      </div>
    </div>
  );
}
