// Claimmee 3 分钟初筛漏斗 — 航段 → 中断 → 结果，平滑过渡。
const F = window.ClaimmeeDesignSystem_e4fda8;
const MktF = window.ClaimmeeMkt;

function FunnelField({ label, children }) {
  return (
    <label style={{ display: 'grid', gap: 8, fontWeight: 750, color: 'var(--slate-700)', fontFamily: 'var(--font-sans)' }}>
      {label}{children}
    </label>
  );
}
function Sel({ value, onChange, children }) {
  return <select value={value} onChange={onChange} style={{ width: '100%', border: '1px solid var(--border-input)', borderRadius: 'var(--radius-md)', padding: '0.85rem 0.9rem', background: '#fff', color: 'var(--slate-900)', fontFamily: 'var(--font-sans)', fontSize: '1rem', minHeight: 'var(--tap-min)' }}>{children}</select>;
}

function StepFade({ stepKey, children }) {
  const [on, setOn] = React.useState(false);
  React.useEffect(() => { setOn(false); const t = setTimeout(() => setOn(true), 20); return () => clearTimeout(t); }, [stepKey]);
  return <div style={{ opacity: on ? 1 : 0, transform: on ? 'none' : 'translateY(14px)', transition: 'opacity .42s var(--ease-out), transform .42s var(--ease-out)' }}>{children}</div>;
}

function Funnel() {
  const pre = window.ClaimmeeMkt._prefill || {};
  const [step, setStep] = React.useState(0);
  const [dir, setDir] = React.useState(1);
  const [data, setData] = React.useState({
    from: pre.from || 'PVG', to: pre.to || 'LHR', direct: 'yes',
    disruption: pre.disruption || 'delay', delayMin: pre.delayMin ?? 240, extraordinary: false,
  });
  const set = (k, v) => setData((d) => ({ ...d, [k]: v }));
  const go = (n) => { setDir(n > step ? 1 : -1); setStep(n); };
  const result = React.useMemo(() => MktF.assess(data), [data]);

  const TOTAL = 3;
  const titles = ['航段', '中断详情', '初筛结果'];

  return (
    <div style={{ background: 'var(--bg-page)', minHeight: '100%', paddingBottom: 80 }}>
      {/* 顶部进度 */}
      <div style={{ background: 'var(--grad-hero)', paddingTop: 40, paddingBottom: 30 }}>
        <div style={{ width: 'min(720px, calc(100vw - 32px))', margin: '0 auto' }}>
          <div style={{ color: 'var(--teal-100)', fontWeight: 700, fontSize: '0.82rem', letterSpacing: '0.14em', textTransform: 'uppercase' }}>3 分钟初筛 · 合成演示</div>
          <h1 style={{ margin: '8px 0 22px', color: '#fff', fontSize: 'clamp(1.6rem,3.5vw,2.4rem)', fontWeight: 900, letterSpacing: '-0.03em' }}>{titles[step]}</h1>
          <div style={{ display: 'flex', gap: 8 }}>
            {Array.from({ length: TOTAL }).map((_, i) => (
              <div key={i} style={{ flex: 1, height: 6, borderRadius: 'var(--radius-pill)', background: i <= step ? 'var(--amber-500)' : 'rgba(255,255,255,0.22)', transition: 'background var(--dur-slow) var(--ease-out)' }} />
            ))}
          </div>
        </div>
      </div>

      {/* 步骤卡 */}
      <div style={{ width: 'min(720px, calc(100vw - 32px))', margin: '-18px auto 0', position: 'relative' }}>
        <StepFade stepKey={step}>
          {step === 0 && (
            <F.Panel style={{ display: 'grid', gap: 18 }}>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
                <FunnelField label="出发城市（中国）"><Sel value={data.from} onChange={(e) => set('from', e.target.value)}>{MktF.CN.map((c) => <option key={c} value={c}>{MktF.CITIES[c].city} {c}</option>)}</Sel></FunnelField>
                <FunnelField label="到达城市（欧洲）"><Sel value={data.to} onChange={(e) => set('to', e.target.value)}>{MktF.EU.map((c) => <option key={c} value={c}>{MktF.CITIES[c].city} {c}</option>)}</Sel></FunnelField>
              </div>
              <FunnelField label="是否为直飞航班？">
                <div style={{ display: 'flex', gap: 10 }}>
                  {[['yes', '直飞'], ['no', '中转']].map(([v, l]) => (
                    <button key={v} onClick={() => set('direct', v)} style={{ flex: 1, padding: '0.8rem', borderRadius: 'var(--radius-pill)', border: data.direct === v ? '0' : '1px solid var(--border-input)', background: data.direct === v ? 'var(--teal-700)' : '#fff', color: data.direct === v ? '#fff' : 'var(--slate-700)', fontWeight: 800, fontFamily: 'var(--font-sans)', cursor: 'pointer', minHeight: 'var(--tap-min)' }}>{l}</button>
                  ))}
                </div>
              </FunnelField>
              <div style={{ borderRadius: 'var(--radius-lg)', background: 'var(--surface-tint)', padding: 14, color: 'var(--teal-700)', fontWeight: 700, fontSize: '0.9rem' }}>航程约 {MktF.distanceKm(data.from, data.to).toLocaleString()} km · 预估档位 €{MktF.tier(MktF.distanceKm(data.from, data.to))}</div>
              <F.Button variant="primary" size="lg" fullWidth onClick={() => go(1)}>下一步 · 填写中断情况 →</F.Button>
            </F.Panel>
          )}

          {step === 1 && (
            <F.Panel style={{ display: 'grid', gap: 18 }}>
              <FunnelField label="遇到的问题类型">
                <div style={{ display: 'grid', gap: 10 }}>
                  {MktF.DISRUPTIONS.map((d) => (
                    <button key={d.key} onClick={() => set('disruption', d.key)} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', padding: '14px 18px', borderRadius: 'var(--radius-lg)', border: data.disruption === d.key ? '2px solid var(--teal-700)' : '1px solid var(--border-input)', background: data.disruption === d.key ? 'var(--surface-tint)' : '#fff', cursor: 'pointer', textAlign: 'left', fontFamily: 'var(--font-sans)' }}>
                      <span style={{ fontWeight: 800, color: 'var(--slate-900)' }}>{d.label}</span>
                      <span style={{ color: 'var(--text-muted)', fontSize: '0.88rem' }}>{d.hint}</span>
                    </button>
                  ))}
                </div>
              </FunnelField>
              {data.disruption === 'delay' && (
                <FunnelField label={<span>到达延误时长 · <strong style={{ color: 'var(--teal-700)' }}>{(data.delayMin / 60).toFixed(1)} 小时</strong></span>}>
                  <input type="range" min="0" max="600" step="30" value={data.delayMin} onChange={(e) => set('delayMin', Number(e.target.value))} style={{ width: '100%', accentColor: 'var(--teal-700)' }} />
                </FunnelField>
              )}
              <F.CheckboxRow checked={data.extraordinary} onChange={(e) => set('extraordinary', e.target.checked)}>航司主张特殊情况（恶劣天气 / 罢工等）</F.CheckboxRow>
              <div style={{ display: 'flex', gap: 12 }}>
                <F.Button variant="secondary" onClick={() => go(0)}>← 上一步</F.Button>
                <F.Button variant="primary" fullWidth onClick={() => go(2)}>查看初筛结果 →</F.Button>
              </div>
            </F.Panel>
          )}

          {step === 2 && (
            <div style={{ display: 'grid', gap: 16 }}>
              <F.Panel>
                <F.StatusPill status={result.status} />
                <div style={{ marginTop: 16, borderRadius: 'var(--radius-xl)', padding: 28, background: 'var(--grad-money)' }}>
                  <div style={{ fontSize: '0.9rem', fontWeight: 750, color: 'var(--slate-600)' }}>{result.amount > 0 ? '预计每位乘客可拿回' : '当前规则下未产生赔偿金额'}</div>
                  {result.amount > 0 && <div style={{ fontSize: '3.2rem', fontWeight: 950, color: 'var(--slate-900)', lineHeight: 1.05, fontVariantNumeric: 'tabular-nums' }}>€{result.amount}</div>}
                </div>
                <ul style={{ margin: '18px 0 0', paddingLeft: '1.2rem', color: 'var(--slate-700)', lineHeight: 1.7 }}>
                  {result.reasons.map((r, i) => <li key={i}>{r}</li>)}
                </ul>
              </F.Panel>

              <F.Panel>
                <h3 style={{ margin: '0 0 12px', fontSize: '1.15rem', fontWeight: 800, color: 'var(--slate-900)' }}>下一步：准备材料（无需现在上传）</h3>
                <div style={{ display: 'grid', gap: 10 }}>
                  {['登机牌 / 电子行程单', '航班延误或取消通知', '订单确认 / 预订号'].map((m) => (
                    <div key={m} style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '14px 16px', borderRadius: 'var(--radius-lg)', background: 'var(--slate-50)', border: '1px solid var(--border-subtle)' }}>
                      <span style={{ width: 22, height: 22, borderRadius: '50%', background: 'var(--teal-100)', color: 'var(--teal-700)', display: 'grid', placeItems: 'center', fontWeight: 900, fontSize: '0.8rem' }}>✓</span>
                      <span style={{ fontWeight: 700, color: 'var(--slate-700)' }}>{m}</span>
                    </div>
                  ))}
                </div>
                <div style={{ marginTop: 16 }}><F.Badge tone="gate" dot={false} style={{ fontSize: '0.8rem' }}>身份与银行信息仅在你授权、法务复核后才需要</F.Badge></div>
              </F.Panel>

              <F.Panel variant="hero" style={{ textAlign: 'center' }}>
                <h3 style={{ margin: '0 0 8px', color: '#fff', fontSize: '1.5rem', fontWeight: 900 }}>{result.status === 'eligible' ? '看起来你很可能可以索赔' : result.status === 'needs_review' ? '你的情况需要人工复核' : '换个航段再试试？'}</h3>
                <p style={{ margin: '0 auto 20px', color: 'var(--text-on-teal)', maxWidth: 440, lineHeight: 1.65 }}>正式索赔需你明确授权并经法务复核。本结果仅为一般信息，不构成法律意见。</p>
                <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
                  <button onClick={() => go(0)} style={{ border: '1px solid rgba(255,255,255,0.4)', background: 'rgba(255,255,255,0.1)', color: '#fff', borderRadius: 'var(--radius-pill)', padding: '0.85rem 1.4rem', fontWeight: 800, fontFamily: 'var(--font-sans)', cursor: 'pointer' }}>重新填写</button>
                  <button onClick={() => { window.ClaimmeeMkt._case = MktF.buildCase(data, result); window.ClaimmeeNav && window.ClaimmeeNav('authorize'); }} style={{ border: 0, background: 'var(--amber-500)', color: 'var(--amber-ink)', borderRadius: 'var(--radius-pill)', padding: '0.85rem 1.6rem', fontWeight: 900, fontFamily: 'var(--font-sans)', cursor: 'pointer', boxShadow: 'var(--shadow-amber)' }}>申请授权并提交（演示）</button>
                </div>
              </F.Panel>
            </div>
          )}
        </StepFade>
      </div>
    </div>
  );
}

window.Funnel = Funnel;
