// ─── 屏 5：成交漏斗 / 7 阶段状态机 ───
function parseAmt(a) { const m = (a || '').match(/([\d.]+)/); return m ? parseFloat(m[1]) : 0; }
function PipelineScreen({ aiLevel = '标准' }) {
  const T = useT();
  const { go, openSheet } = useApp();
  const stageColor = (i) => {
    if (i <= 1) return T.faint;
    if (i <= 3) return T.accent;
    if (i === 4) return T.warn;
    return T.good;
  };
  // 各阶段加权金额（金额 × 胜率）
  const stageVal = STAGES.map((_, i) => Math.round(DEALS.filter(d => d.stage === i).reduce((s, d) => s + parseAmt(d.amount) * d.winRate / 100, 0)));
  const maxVal = Math.max(...stageVal, 1);
  const sorted = [...DEALS].sort((a, b) => (b.hot ? 1 : 0) - (a.hot ? 1 : 0) || b.winRate - a.winRate);

  return (
    <div style={{ padding: '4px 16px 24px' }}>
      <div style={{ padding: '6px 2px 14px' }}>
        <div style={{ fontSize: 23, fontWeight: 800, color: T.text, letterSpacing: -0.5 }}>成交漏斗</div>
        <div style={{ fontSize: 12.5, color: T.sub, marginTop: 3 }}>{DEALS.length} 个机会 · 加权预期 ¥312 万</div>
      </div>

      {/* AI 聚焦 */}
      {aiLevel !== '克制' && (
        <div style={{ marginBottom: 18 }}>
          <AICard tag="今日聚焦" tone="accent"
            title="3 个机会在等你推一把"
            body="恒升刚跃迁至「谈判」前夜；上海凌动的条款会签今天到期；苏州科锐已 14 天无互动——再不触达就要凉。" />
        </div>
      )}

      {/* 加权金额漏斗 */}
      <SectionLabel right={<Tag tone="plain" style={{ fontSize: 10 }}>加权金额</Tag>}>阶段漏斗</SectionLabel>
      <Card style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
          {STAGES.map((s, i) => {
            const w = 18 + (stageVal[i] / maxVal) * 82; // 百分比宽度
            return (
              <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 10 }}>
                <span style={{ fontSize: 11, color: T.sub, width: 56, flexShrink: 0, textAlign: 'right' }}>{s}</span>
                <div style={{ flex: 1, display: 'flex', justifyContent: 'center' }}>
                  <div style={{ width: `${w}%`, minWidth: 36, height: 26, borderRadius: 6, background: `linear-gradient(90deg,${hexA(stageColor(i), 0.35)},${hexA(stageColor(i), 0.7)})`, border: `1px solid ${hexA(stageColor(i), 0.5)}`, display: 'flex', alignItems: 'center', justifyContent: 'center', transition: 'width .6s cubic-bezier(.4,0,.2,1)' }}>
                    <span style={{ fontSize: 10.5, fontWeight: 700, color: T.dark ? '#fff' : T.text, whiteSpace: 'nowrap' }}>{STAGE_COUNTS[i]} 个{stageVal[i] ? ` · ¥${stageVal[i]}万` : ''}</span>
                  </div>
                </div>
              </div>
            );
          })}
        </div>
        <div style={{ fontSize: 10.5, color: T.faint, marginTop: 11, paddingTop: 11, borderTop: `1px solid ${T.line}`, lineHeight: 1.5 }}>条宽 = 该阶段加权预期金额（金额 × 胜率），不是机会数——真实管道并非越往下越窄。</div>
      </Card>

      {/* Stage 1 · AI 拓客雷达 */}
      <SectionLabel right={<Tag tone="plain" style={{ fontSize: 10 }}>漏斗顶部</Tag>}>拓客雷达 · AI 正在补线索</SectionLabel>
      <Card style={{ marginBottom: 18 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginBottom: 11, paddingBottom: 11, borderBottom: `1px solid ${T.line}` }}>
          <Icon name="target" size={15} color={T.accent} />
          <span style={{ fontSize: 11.5, color: T.sub }}>匹配你的理想客户画像</span>
          <span style={{ marginLeft: 'auto', fontSize: 11, color: T.text, fontWeight: 600 }}>{PROSPECT.icp}</span>
        </div>
        <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
          {PROSPECT.leads.map((l, i) => (
            <div key={i} onClick={() => openSheet('pitch', { name: l.name })} style={{ display: 'flex', alignItems: 'center', gap: 11, cursor: 'pointer' }}>
              <div style={{ width: 38, height: 38, borderRadius: 11, background: T.accSoft, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', flexShrink: 0 }}>
                <span style={{ fontFamily: NUMF, fontSize: 13, fontWeight: 800, color: T.accent, lineHeight: 1 }}>{l.match}</span>
                <span style={{ fontSize: 7, color: T.accent, opacity: 0.8 }}>匹配</span>
              </div>
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
                  <span style={{ fontSize: 13.5, fontWeight: 700, color: T.text }}>{l.name}</span>
                  <Tag tone="good" style={{ fontSize: 9.5 }}>{l.kind}</Tag>
                </div>
                <div style={{ fontSize: 11.5, color: T.sub, marginTop: 3, display: 'flex', alignItems: 'center', gap: 5 }}>
                  <Sparkle size={10} color={T.good} /><span style={{ whiteSpace: 'nowrap' }}>触发：{l.trigger}</span>
                </div>
              </div>
              <button onClick={(e) => { e.stopPropagation(); openSheet('pitch', { name: l.name }); }} style={{ border: `1px solid ${T.accLine}`, background: T.accSoft, color: T.accent, fontSize: 11.5, fontWeight: 700, fontFamily: FONT, padding: '7px 10px', borderRadius: 10, cursor: 'pointer', flexShrink: 0, whiteSpace: 'nowrap' }}>话术</button>
            </div>
          ))}
        </div>
      </Card>

      {/* 机会列表 */}
      <SectionLabel right={<span style={{ fontSize: 11, color: T.faint }}>按优先级</span>}>全部机会</SectionLabel>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {sorted.map((d, i) => (
          <Card key={i} pad={14} glow={d.hot} onClick={d.hot ? () => go('presence') : undefined}
            style={{ position: 'relative' }}>
            {d.hot && <div style={{ position: 'absolute', top: 12, right: 14 }}><Tag tone="accent" style={{ fontSize: 10 }}><Sparkle size={10} />刚跃迁</Tag></div>}
            <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
              <Ring value={d.winRate} size={44} stroke={3.5} />
              <div style={{ flex: 1, minWidth: 0 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
                  <span style={{ fontSize: 14.5, fontWeight: 700, color: T.text }}>{d.name}</span>
                  {d.amount !== '—' && <span style={{ fontSize: 13, fontWeight: 700, color: T.accent, fontFamily: NUMF }}>{d.amount}</span>}
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 7, marginTop: 5 }}>
                  <span style={{ display: 'inline-flex', alignItems: 'center', gap: 5, fontSize: 11, color: stageColor(d.stage), fontWeight: 600 }}>
                    <span style={{ width: 6, height: 6, borderRadius: '50%', background: stageColor(d.stage) }} />{STAGES[d.stage]}
                  </span>
                  {d.days > 0 && <span style={{ fontSize: 10.5, color: T.faint }}>· {d.days} 天</span>}
                  {d.delta && <Tag tone="good" style={{ fontSize: 9.5, padding: '1px 6px' }}>{d.delta}</Tag>}
                  {d.stage === 6 && <Tag tone={d.next.includes('增购') ? 'accent' : 'good'} style={{ fontSize: 9.5, padding: '1px 6px' }}>{d.next.includes('增购') ? '增购机会' : '续约健康'}</Tag>}
                </div>
              </div>
            </div>
            <div style={{ marginTop: 11, paddingTop: 11, borderTop: `1px solid ${T.line}`, display: 'flex', alignItems: 'flex-start', gap: 7 }}>
              {d.risk
                ? <Icon name="alert" size={15} color={T.warn} style={{ flexShrink: 0, marginTop: 1 }} />
                : <Icon name="arrowRight" size={15} color={T.faint} style={{ flexShrink: 0, marginTop: 1 }} />}
              <span style={{ fontSize: 12, color: d.risk ? T.warn : T.sub, lineHeight: 1.45, fontWeight: d.risk ? 600 : 400 }}>
                {d.risk ? `${d.risk} · ` : ''}{d.next}
              </span>
            </div>
          </Card>
        ))}
      </div>
    </div>
  );
}
window.PipelineScreen = PipelineScreen;
