function FinanceCard({ item, dark, onConfirm }) {
  const th = useTheme(dark);
  return (
    <div style={{ background:th.surface, border:`1px solid ${th.border}`, borderRadius:14, padding:'14px 16px', marginBottom:10 }}>
      <div style={{ display:'flex', alignItems:'center', gap:6 }}>
        <span style={{ fontSize:FS(13), fontWeight:700, color:th.text }}>{item.typeLabel}</span>
        <span style={{ fontFamily:FONTS.mono, fontSize:FS(12), color:th.textMuted }}>#{item.no}</span>
        <StatusPill label={item.status} fg='#0F7A3A' bg='#E6F2EB' style={{ marginLeft:'auto' }} />
        <StatusPill label={item.payment} fg={item.payColor} bg={item.payBg} />
      </div>
      <div style={{ fontFamily:FONTS.mono, fontSize:FS(12), color:th.textSub, marginTop:8 }}>
        {item.date} · {item.time}
      </div>
      <div style={{ background:th.surfaceAlt, borderRadius:10, padding:'12px 14px', marginTop:10, display:'flex', alignItems:'center' }}>
        <div style={{ flex:1 }}>
          <div style={{ fontSize:FS(11), color:th.textMuted }}>行程金額</div>
          <span style={{ fontFamily:FONTS.mono, fontSize:FS(20), fontWeight:900, color:th.danger }}>NT$<span style={{fontWeight:700}}>{item.amount.toLocaleString()}</span></span>
        </div>
        {item.cashBack && (
          <div style={{ textAlign:'right' }}>
            <div style={{ fontSize:FS(11), color:th.textMuted }}>已回金</div>
            <span style={{ fontFamily:FONTS.mono, fontSize:FS(16), fontWeight:800, color:'#B45309' }}>NT${item.cashBack}</span>
          </div>
        )}
      </div>
      {item.payment==='已轉帳' && (
        <button onClick={onConfirm} className="press" style={{
          marginTop:10, width:'100%', padding:'12px', borderRadius:10, background:th.success, color:'#FFF', border:'none', fontSize:FS(14), fontWeight:800, cursor:'pointer', fontFamily:'Noto Sans TC',
        }}>✅ 確認收款</button>
      )}
    </div>
  );
}

function TabFinance({ dark }) {
  const th = useTheme(dark);
  const [filter, setFilter] = useState('earnings');
  const [toast, setToast] = useState(null);
  const [topUpOpen, setTopUpOpen] = useState(false);
  const [topUpAmount, setTopUpAmount] = useState(null);
  const [topUpStep, setTopUpStep] = useState(0);
  const d = DATA.driver;

  const filters = [
    { key:'earnings', label:'我的收入', count: DATA.finance.uncollected.length + DATA.finance.transferred.length },
    { key:'points', label:'點數記錄' },
    { key:'history', label:'歷史行程', count: DATA.finance.history.length },
    { key:'membership', label:'會員及儲值' },
  ];

  function showToast(m) {
    setToast(m);
    setTimeout(() => setToast(null), 2000);
  }

  function handleTopUp(amount) {
    setTopUpAmount(amount);
    setTopUpStep(1);
    setTimeout(() => {
      setTopUpStep(2);
      showToast(`儲值成功 +${amount} 點`);
      setTimeout(() => { setTopUpOpen(false); setTopUpStep(0); }, 1500);
    }, 1200);
  }

  return (
    <div style={{ height:'100%', display:'flex', flexDirection:'column', background:th.bg }}>
      <ScreenHeader title="帳務中心" sub={`可用點數 ${d.points.toLocaleString()} · ${d.tier}`} dark={dark} />

      <div style={{ flex:1, overflowY:'auto', padding:'0 16px 20px' }} className="scroll-hide">
        <button onClick={() => setTopUpOpen(true)} className="press" style={{
          width:'100%', padding:'14px 16px', borderRadius:12, background:th.text, color:th.surface, border:'none',
          display:'flex', alignItems:'center', justifyContent:'space-between', cursor:'pointer', fontSize:FS(15), fontWeight:700, fontFamily:'Noto Sans TC', marginBottom:12,
        }}>
          💳 前往儲值 / 訂閱會員 <span style={{ fontSize:FS(18) }}>›</span>
        </button>

        <FilterChips options={filters} value={filter} onChange={setFilter} dark={dark} />

        {filter==='earnings' && (
          <div style={{ marginTop:12 }}>
            {[...DATA.finance.uncollected, ...DATA.finance.transferred].map(i => (
              <FinanceCard key={i.no} item={i} dark={dark} onConfirm={() => showToast(`訂單 #${i.no} 已確認收款`)} />
            ))}
            {DATA.finance.uncollected.length===0 && <Empty text="尚無待收款行程" dark={dark} />}
          </div>
        )}

        {filter==='points' && (
          <div style={{ marginTop:12 }}>
            {DATA.points.map((p,i) => (
              <div key={i} style={{ background:th.surface, border:`1px solid ${th.border}`, borderRadius:14, padding:'12px 16px', marginBottom:8, display:'flex', alignItems:'center', gap:12 }}>
                <span style={{
                  width:34, height:34, borderRadius:'50%', display:'flex', alignItems:'center', justifyContent:'center', flexShrink:0,
                  background: p.kind==='in'?th.successBg:th.dangerBg, fontSize:FS(15),
                }}>{p.kind==='in'?'▲':'▼'}</span>
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ fontSize:FS(13), fontWeight:700, color:th.text }}>{p.label}</div>
                  <div style={{ fontFamily:FONTS.mono, fontSize:FS(10.5), color:th.textMuted, marginTop:1 }}>{p.fee || `#${p.no}`}</div>
                </div>
                <span style={{ fontFamily:FONTS.mono, fontWeight:800, fontSize:FS(15), color:p.color }}>{p.amount}</span>
              </div>
            ))}
          </div>
        )}

        {filter==='history' && (
          <div style={{ marginTop:12 }}>
            {DATA.finance.history.map(i => (
              <FinanceCard key={i.no} item={i} dark={dark} onConfirm={() => {}} />
            ))}
          </div>
        )}

        {filter==='membership' && (
          <div style={{ marginTop:12 }}>
            <div style={{ background:th.surfaceAlt, borderRadius:14, padding:16, textAlign:'center' }}>
              <div style={{ fontSize:FS(12), color:th.textSub }}>目前會員等級</div>
              <div style={{ fontSize:FS(24), fontWeight:900, color:th.text, marginTop:2 }}>{d.tier}</div>
              <div style={{ fontSize:FS(12), color:th.textSub, marginTop:2 }}>可用點數 <span style={{ fontFamily:FONTS.mono, fontWeight:800, color:th.text }}>{d.points.toLocaleString()}</span></div>
            </div>

            <SectionLabel dark={dark}>快速儲值</SectionLabel>
            <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8 }}>
              {[500,1000,2000,3000,5000].map(n => (
                <button key={n} onClick={() => showToast(`確認儲值 ${n} 點`)} className="press" style={{
                  padding:'14px 0', borderRadius:12, border:`2px solid ${th.border}`, background:th.surface, color:th.text,
                  cursor:'pointer', fontFamily:FONTS.mono, fontSize:FS(16), fontWeight:700, fontFamily:'Noto Sans TC',
                }}>{n.toLocaleString()}</button>
              ))}
              <button onClick={() => showToast('請輸入自訂金額')} className="press" style={{ padding:'14px 0', borderRadius:12, border:`2px dashed ${th.border}`, background:th.surface, color:th.textSub, cursor:'pointer', fontSize:FS(14), fontFamily:'Noto Sans TC' }}>自訂金額</button>
            </div>

            <SectionLabel dark={dark}>功能模組</SectionLabel>
            <Card dark={dark}>
              <div style={{ display:'flex', alignItems:'center', gap:10 }}>
                <span style={{ width:38, height:38, borderRadius:10, background:th.surfaceAlt, display:'flex', alignItems:'center', justifyContent:'center' }}>🚕</span>
                <div style={{ flex:1 }}>
                  <div style={{ fontSize:FS(14), fontWeight:700, color:th.text }}>小車頭模組</div>
                  <div style={{ fontSize:FS(11), color:th.textMuted, marginTop:2 }}>月繳 NT$300 / 季繳 NT$800</div>
                </div>
                <Pill fg='#B45309' bg='#FBEFD9'>未開通</Pill>
              </div>
            </Card>

            <SectionLabel dark={dark}>會員訂閱方案</SectionLabel>
            {DATA.membership.plans.map(p => (
              <Card key={p.name} dark={dark} style={{ marginBottom:10 }}>
                <div style={{ display:'flex', alignItems:'center' }}>
                  <div style={{ flex:1 }}>
                    <div style={{ fontSize:FS(15), fontWeight:800, color:th.text }}>{p.name}</div>
                    <div style={{ fontSize:FS(11), color:th.textSub, marginTop:3 }}>含 {p.features} · 贈送 {p.points} 點儲值點數</div>
                  </div>
                  <Pill fg='#0F7A3A' bg='#E6F2EB'>立即訂閱</Pill>
                </div>
                <div style={{ display:'flex', gap:8, marginTop:12 }}>
                  <button onClick={() => showToast(`訂閱 ${p.name}（月繳 ${p.monthly}）`)} className="press" style={{ flex:1, padding:'11px', borderRadius:10, background:th.text, color:th.surface, border:'none', fontSize:FS(13), fontWeight:800, cursor:'pointer', fontFamily:'Noto Sans TC' }}>月繳 NT${p.monthly}</button>
                  <button onClick={() => showToast(`訂閱 ${p.name}（季繳 ${p.quarterly}）`)} className="press" style={{ flex:1, padding:'11px', borderRadius:10, background:th.surfaceAlt, color:th.text, border:'none', fontSize:FS(13), fontWeight:800, cursor:'pointer', fontFamily:'Noto Sans TC' }}>季繳 NT${p.quarterly}</button>
                </div>
              </Card>
            ))}
          </div>
        )}
      </div>

      {topUpOpen && (
        <div className="modal-overlay fade-in" onClick={() => setTopUpOpen(false)}>
          <div className="modal-card" onClick={e => e.stopPropagation()} style={{ background:th.surface, width:340, padding:18 }}>
            {topUpStep === 0 && (
              <>
                <div style={{ fontSize:FS(18), fontWeight:900, color:th.text, textAlign:'center' }}>儲值點數</div>
                <div style={{ fontSize:FS(12), color:th.textSub, marginTop:6, textAlign:'center' }}>目前點數 <span style={{ fontFamily:FONTS.mono, fontWeight:800, color:th.text }}>{d.points.toLocaleString()}</span></div>
                <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:8, marginTop:14 }}>
                  {[500,1000,2000,3000,5000].map(n => (
                    <button key={n} onClick={() => handleTopUp(n)} className="press" style={{
                      padding:'14px 0', borderRadius:12, border:`2px solid ${th.border}`, background:th.surface, color:th.text,
                      cursor:'pointer', fontSize:FS(16), fontWeight:700, fontFamily:FONTS.mono,
                    }}>{n.toLocaleString()}</button>
                  ))}
                  <button onClick={() => handleTopUp(800)} className="press" style={{ padding:'14px 0', borderRadius:12, border:`2px dashed ${th.border}`, background:th.surface, color:th.textSub, cursor:'pointer', fontSize:FS(14), fontFamily:'Noto Sans TC' }}>自訂</button>
                </div>
                <button onClick={() => setTopUpOpen(false)} className="press" style={{ marginTop:14, width:'100%', padding:'12px', borderRadius:10, background:th.surfaceAlt, color:th.text, border:'none', fontSize:FS(14), fontWeight:700, cursor:'pointer', fontFamily:'Noto Sans TC' }}>取消</button>
              </>
            )}
            {topUpStep === 1 && (
              <div style={{ textAlign:'center', padding:'10px 0' }}>
                <div style={{ width:48, height:48, borderRadius:'50%', border:`3px solid ${th.border}`, borderTopColor:th.text, margin:'0 auto', animation:'spin .8s linear infinite' }} />
                <div style={{ fontSize:FS(14), fontWeight:700, color:th.text, marginTop:14 }}>處理中...</div>
                <div style={{ fontSize:FS(12), color:th.textSub, marginTop:4 }}>正在儲值 NT${topUpAmount}</div>
              </div>
            )}
            {topUpStep === 2 && (
              <div style={{ textAlign:'center', padding:'10px 0' }}>
                <div style={{ width:52, height:52, borderRadius:'50%', background:th.successBg, display:'flex', alignItems:'center', justifyContent:'center', margin:'0 auto' }}>
                  <Icon.Check size={26} color={th.success} />
                </div>
                <div style={{ fontSize:FS(16), fontWeight:900, color:th.text, marginTop:12 }}>儲值成功</div>
                <div style={{ fontSize:FS(13), color:th.textSub, marginTop:4 }}>
                  <span style={{ fontFamily:FONTS.mono, fontWeight:700, color:th.text }}>+{topUpAmount} 點</span> 已加入您的帳戶
                </div>
              </div>
            )}
          </div>
        </div>
      )}

      {toast && <Toast msg={toast} dark={dark} />}
    </div>
  );
}

function Empty({ text, dark }) {
  const th = useTheme(dark);
  return <div style={{ textAlign:'center', paddingTop:50, color:th.textMuted }}><div style={{ fontSize:FS(40) }}>—</div><div style={{ fontSize:FS(14), marginTop:8 }}>{text}</div></div>;
}
