// =============================================================================
// a-history-wallets.jsx — Screens 03 历史成交 · 04 地址管理
// =============================================================================
// AHistory  — paginated order + funding lists (fills grouped by oid).
// AWallets  — tracked address list + bottom-sheet "添加地址" modal.
// =============================================================================

function AHistory({ t, nav, onBack, visible = true }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const LIST_PAGE = 10;
  const state = HL.useStoreWhen(visible, s => ({
    history: s.history || [],
    fundings: s.fundings || [],
    volume: s.volume || { day: 0, allTime: 0 },
    current: s.current,
    historyLoading: s.historyLoading,
    historyExhausted: s.historyExhausted,
    fundingLoading: s.fundingLoading,
    fundingExhausted: s.fundingExhausted,
    netPnlToday: s.netPnlToday,
    netPnlTotal: s.netPnlTotal,
  }));
  const history  = state.history;
  const fundings = state.fundings;
  const vol = state.volume;
  const [tab, setTab] = React.useState('trades'); // 'trades' | 'funding'
  const [statRange, setStatRange] = React.useState('today');
  const [visibleCount, setVisibleCount] = React.useState(LIST_PAGE);
  const scrollRef = React.useRef(null);
  const pendingExpandRef = React.useRef(false);

  const stats = React.useMemo(() => {
    if (window.HL && window.HL.computeHistoryStats) {
      return window.HL.computeHistoryStats(history, fundings, vol);
    }
    return { today: { vol: 0, fee: 0, fund: 0, net: 0 }, yesterday: { vol: 0, fee: 0, fund: 0, net: 0 }, total: { vol: 0, fee: 0, fund: 0, net: 0 } };
  }, [history, fundings, vol]);

  React.useEffect(() => {
    if (!visible || !state.current) return;
    if (window.HL && window.HL.ensureHistoryLoaded) window.HL.ensureHistoryLoaded();
  }, [visible, state.current]);

  const tradeOrders = React.useMemo(() => {
    if (window.HL && window.HL.groupFillsIntoOrders) {
      return window.HL.groupFillsIntoOrders(history);
    }
    return history;
  }, [history]);
  const cur = stats[statRange] || stats.today;
  const colorOf = (v) => v === 0 ? th.ink
    : v > 0 ? (isDark?'#7ee2a8':'#15803d')
    : (isDark?'#fca5a5':'#b91c1c');

  // Flat list per tab — fills are grouped into orders on the trades tab.
  const rows  = tab === 'trades' ? tradeOrders : fundings;
  const total = rows.length;
  const visibleRows = rows.slice(0, visibleCount);
  const loading = tab === 'trades' ? state.historyLoading : state.fundingLoading;
  const exhausted = tab === 'trades' ? state.historyExhausted : state.fundingExhausted;
  const hasMoreLocal = visibleCount < total;
  const hasMoreRemote = !exhausted;

  React.useEffect(() => {
    setVisibleCount(LIST_PAGE);
    pendingExpandRef.current = false;
    if (scrollRef.current) scrollRef.current.scrollTop = 0;
  }, [tab, state.current]);

  React.useEffect(() => {
    if (!pendingExpandRef.current || loading) return;
    pendingExpandRef.current = false;
    setVisibleCount(c => Math.min(c + LIST_PAGE, rows.length));
  }, [loading, rows.length]);

  const onLoadMore = React.useCallback(() => {
    if (hasMoreLocal) {
      setVisibleCount(c => Math.min(c + LIST_PAGE, total));
      return;
    }
    if (loading || exhausted) return;
    pendingExpandRef.current = true;
    if (tab === 'trades') window.HL.loadMoreHistory();
    else window.HL.loadMoreFundings();
  }, [hasMoreLocal, loading, exhausted, tab, total]);

  return (
    <>
      <div style={{ padding:'4px 18px 10px' }}>
        <div style={{ fontSize:12, color:th.dim, letterSpacing:'0.18em' }}>动态</div>
        <div style={{ fontSize:22, fontWeight:600, marginTop:2 }}>历史记录</div>
      </div>

      {/* Tab switcher */}
      <div style={{ padding:'0 18px 8px', display:'flex', gap:6 }}>
        {[
          { id:'trades',  label:'成交' },
          { id:'funding', label:'资金费' },
        ].map(it => {
          const on = tab === it.id;
          return (
            <button key={it.id} onClick={()=>setTab(it.id)} style={{
              ...(on ? th.card : { background:'transparent', border:`1px solid ${th.hair}` }),
              borderRadius:999, padding:'6px 14px', fontSize:13, fontWeight:600,
              color: on ? th.accent : th.dim, cursor:'pointer',
            }}>{it.label}</button>
          );
        })}
      </div>

      <div style={{ padding:'0 14px 12px' }}>
        <ACard t={t} padded={false} style={{ padding:'12px 16px' }}>
          <div style={{
            display:'flex', alignItems:'center', justifyContent:'space-between',
            marginBottom:10,
          }}>
            <div style={{ display:'flex', gap:4 }}>
              {[
                { id:'today',     label:'今日' },
                { id:'yesterday', label:'昨日' },
                { id:'total',     label:'累计' },
              ].map(it => {
                const on = statRange === it.id;
                return (
                  <button key={it.id} onClick={()=>setStatRange(it.id)} style={{
                    background:'transparent', border:0, padding:'4px 10px',
                    fontSize:12.5, fontWeight: on ? 600 : 500,
                    color: on ? th.ink : th.dim,
                    borderBottom: `2px solid ${on ? th.accent : 'transparent'}`,
                    letterSpacing:'0.08em', cursor:'pointer',
                  }}>{it.label}</button>
                );
              })}
            </div>
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
            <Stat3 th={th} k="成交">
              <NumFlow.usd value={cur.vol} d={0}/>
            </Stat3>
            <Stat3 th={th} k="手续费">
              <NumFlow.usd value={cur.fee}/>
            </Stat3>
            <Stat3 th={th} k="资金费">
              <span style={{ color: colorOf(cur.fund) }}>
                <NumFlow value={cur.fund} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v))}/>
              </span>
            </Stat3>
          </div>
          <div style={{
            marginTop:10, paddingTop:12, borderTop:`1px solid ${th.hair}`,
            display:'grid', gridTemplateColumns:'repeat(3, 1fr)', gap:12, alignItems:'center',
          }}>
            <div style={{ fontSize:11, color:th.dim, letterSpacing:'0.1em' }}>净利润</div>
            <div/>
            <div style={{
              fontFamily:th.numFont, fontSize:15, fontWeight:600,
              color:colorOf(cur.net), fontVariantNumeric:'tabular-nums',
            }}>
              <NumFlow value={cur.net} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v), 0)}/>
            </div>
          </div>
          {statRange === 'total' && !state.historyExhausted && (
            <div style={{ fontSize:11, color:th.faint, marginTop:8, textAlign:'center' }}>
              累计同步中，手续费/净利润随后台加载更新
            </div>
          )}
        </ACard>
      </div>

      <LazyListLoader scrollRef={scrollRef} active={visible} onLoadMore={onLoadMore}/>

      <div ref={scrollRef} style={{ flex:1, overflow:'auto', padding:'0 14px' }}>
        {total === 0 ? (
          <div style={{
            margin:'24px 6px', padding:'40px 20px', textAlign:'center',
            color:th.faint, fontSize:13.5, lineHeight:1.7,
            border:`1px dashed ${th.hair}`, borderRadius:14,
          }}>
            {!state.current ? '请先添加 Hyperliquid 地址'
             : tab === 'trades' ? '暂无成交记录' : '暂无资金费结算记录'}
          </div>
        ) : (
          <div style={{ marginBottom: 14 }}>
            <div style={{ display:'flex', justifyContent:'space-between', padding:'4px 8px 8px' }}>
              <span style={{ fontSize:12, color:th.dim, letterSpacing:'0.16em' }}>
                {tab === 'trades' ? '订单' : '资金费'}
              </span>
              <span style={{ fontSize:11.5, color:th.faint, fontFamily:th.numFont }}>
                {visibleRows.length < total ? `${visibleRows.length} / ${total} 笔` : `${total} 笔`}
              </span>
            </div>
            <ACard t={t} padded={false}>
              {visibleRows.map((h, i) => tab === 'trades'
                ? <TradeRow key={h.key || h.hash || i} h={h} t={t} th={th} isDark={isDark} first={i===0}/>
                : <FundingRow key={(h.ms||0)+':'+h.sym+':'+i} f={h} t={t} th={th} isDark={isDark} first={i===0}/>
              )}
            </ACard>
          </div>
        )}
        {total > 0 && (
          <div style={{
            padding:'12px 8px 20px', textAlign:'center',
            fontSize:12, color:th.faint, fontFamily:th.numFont, letterSpacing:'0.06em',
          }}>
            {loading ? '加载更多…'
              : (hasMoreLocal || hasMoreRemote) ? '继续下滑加载更多'
              : '— 已无更多记录 —'}
          </div>
        )}
      </div>

      <ATabBar active="history" onNav={nav || onBack} t={t}/>
    </>
  );
}

function dirToZhTag(dir, side) {
  const d = dir ? String(dir).toLowerCase().replace(/\s+/g, ' ') : '';
  if (d === 'open long'  || (d.indexOf('open') >= 0 && d.indexOf('long') >= 0))
    return { label: '开多', kind: 'openLong' };
  if (d === 'open short' || (d.indexOf('open') >= 0 && d.indexOf('short') >= 0))
    return { label: '开空', kind: 'openShort' };
  if (d === 'close long' || (d.indexOf('close') >= 0 && d.indexOf('long') >= 0))
    return { label: '平多', kind: 'closeLong' };
  if (d === 'close short' || (d.indexOf('close') >= 0 && d.indexOf('short') >= 0))
    return { label: '平空', kind: 'closeShort' };
  return side === 'BUY'
    ? { label: '买', kind: 'openLong' }
    : { label: '卖', kind: 'openShort' };
}

function OrderDirTag({ dir, side, t }) {
  const th = aTheme(t);
  const { label, kind } = dirToZhTag(dir, side);
  const isLong = kind === 'openLong' || kind === 'closeLong';
  const p = isLong
    ? { bg: th.isDark ? 'rgba(34,197,94,0.14)' : 'rgba(34,197,94,0.16)', fg: th.isDark ? '#7ee2a8' : '#15803d' }
    : { bg: 'rgba(239,68,68,0.14)', fg: th.isDark ? '#fca5a5' : '#b91c1c' };
  return (
    <span style={{
      display: 'inline-flex', alignItems: 'center',
      fontSize: 10.5, fontWeight: 700, letterSpacing: '0.08em',
      padding: '3px 7px', borderRadius: 5,
      background: p.bg, color: p.fg,
    }}>{label}</span>
  );
}

function TradeRow({ h, t, th, isDark, first }) {
  const pxFmt = h.price < 10 ? 3 : (h.price < 100 ? 2 : 1);
  const hasPnl = h.closedPnl != null && Math.abs(h.closedPnl) > 1e-9;
  const pnlPos = hasPnl && h.closedPnl >= 0;
  const pnlColor = !hasPnl ? th.faint
    : pnlPos ? (isDark ? '#7ee2a8' : '#15803d')
    : (isDark ? '#fca5a5' : '#b91c1c');
  const timeTxt = h.timeRange && h.timeStart && h.timeStart !== h.time
    ? h.timeStart + ' ~ ' + h.time : h.time;
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:10, padding:'12px 14px',
      borderTop: first ? 'none' : `1px solid ${th.hair}`,
    }}>
      <TokenGlyph sym={h.sym} size={28} radius={8}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:13.5, fontWeight:600, display:'flex', alignItems:'center', gap:6, flexWrap:'wrap' }}>
          {h.sym}
          <OrderDirTag dir={h.dir} side={h.side} t={t}/>
          {h.orderCount > 1 && (
            <span style={{
              fontSize:10, fontWeight:600, color:th.accent, letterSpacing:'0.04em',
              padding:'1px 6px', borderRadius:4, border:`1px solid ${th.accent}44`,
            }}>{h.orderCount}单</span>
          )}
        </div>
        <div style={{ fontSize:11.5, color:th.dim, marginTop:2, fontFamily:th.numFont }}>
          {timeTxt}
        </div>
        <div style={{ fontSize:11.5, color:th.ink, marginTop:3, fontFamily:th.numFont, fontWeight:500 }}>
          {h.size} @ {window.fmt.num(h.price, pxFmt)}
        </div>
      </div>
      <div style={{ textAlign:'right', minWidth:88 }}>
        <div style={{ fontFamily:th.numFont, fontSize:13.5, fontWeight:600 }}>{window.fmt.usd(h.value, 0)}</div>
        {hasPnl && (
          <div style={{ fontFamily:th.numFont, fontSize:11.5, fontWeight:600, color:pnlColor, marginTop:2 }}>
            {(pnlPos ? '+' : '−') + window.fmt.usd(Math.abs(h.closedPnl))}
          </div>
        )}
        <div style={{ fontSize:11, color:th.faint, fontFamily:th.numFont, marginTop:2 }}>
          手续费 {window.fmt.usd(h.fee)}
        </div>
      </div>
    </div>
  );
}

function FundingRow({ f, t, th, isDark, first }) {
  const positive = f.amount >= 0;
  const color = positive ? (isDark?'#7ee2a8':'#15803d') : (isDark?'#fca5a5':'#b91c1c');
  return (
    <div style={{
      display:'flex', alignItems:'center', gap:10, padding:'12px 14px',
      borderTop: first ? 'none' : `1px solid ${th.hair}`,
    }}>
      <TokenGlyph sym={f.sym} size={28} radius={8}/>
      <div style={{ flex:1, minWidth:0 }}>
        <div style={{ fontSize:13.5, fontWeight:600, display:'flex', alignItems:'center', gap:6 }}>
          {f.sym}
          <ATag tone={f.side==='LONG'?'long':'short'} t={t}>{f.side==='LONG'?'Long':'Short'}</ATag>
        </div>
        <div style={{ fontSize:11.5, color:th.dim, marginTop:2, fontFamily:th.numFont }}>
          {f.time} · 费率 {(f.rate*100).toFixed(4)}%
        </div>
      </div>
      <div style={{ textAlign:'right' }}>
        <div style={{ fontFamily:th.numFont, fontSize:13.5, fontWeight:600, color }}>
          {(positive?'+':'−')}{window.fmt.usd(Math.abs(f.amount))}
        </div>
        <div style={{ fontSize:11, color:th.faint, fontFamily:th.numFont, marginTop:2 }}>
          {positive ? '收到' : '支付'}
        </div>
      </div>
    </div>
  );
}

// Near-bottom scroll hook — reveals the next UI page or fetches older rows.
function LazyListLoader({ scrollRef, active, onLoadMore }) {
  const onLoadMoreRef = React.useRef(onLoadMore);
  onLoadMoreRef.current = onLoadMore;
  React.useEffect(() => {
    if (!active) return;
    const el = scrollRef.current;
    if (!el) return;
    let raf = 0;
    const onScroll = () => {
      cancelAnimationFrame(raf);
      raf = requestAnimationFrame(() => {
        const remaining = el.scrollHeight - el.scrollTop - el.clientHeight;
        if (remaining < 240) {
          try { onLoadMoreRef.current && onLoadMoreRef.current(); } catch (e) {}
        }
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { el.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, [scrollRef, active]);
  return null;
}

function Stat3({ th, k, children }) {
  return (
    <div>
      <div style={{ fontSize:11, color:th.dim, letterSpacing:'0.1em' }}>{k}</div>
      <div style={{ fontFamily:th.numFont, fontSize:14.5, marginTop:4, color:th.ink, fontWeight:500 }}>{children}</div>
    </div>
  );
}

const ADDR_RE = /^0x[0-9a-fA-F]{40}$/;

function AWallets({ t, nav, onBack, addOpen=false, onToggleAdd, visible = true }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const state = HL.useStoreWhen(visible, s => ({
    wallets: s.wallets || [],
    current: s.current,
    totals: s.totals || { equity: 0, pnl: 0 },
  }));
  const wallets = state.wallets;
  const current = state.current;
  const liveTotals = state.totals;
  // Spacing handled below via list padding so the first card doesn't touch the header.

  const [confirmDel, setConfirmDel] = React.useState(null);

  const copyAddr = (addr) => {
    try { navigator.clipboard?.writeText(addr); } catch (e) {}
  };

  return (
    <>
      <div style={{ padding:'4px 18px 12px', display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <div>
          <div style={{ fontSize:12, color:th.dim, letterSpacing:'0.18em' }}>已追踪</div>
          <div style={{ fontSize:22, fontWeight:600, marginTop:2 }}>钱包地址</div>
        </div>
        <button onClick={onToggleAdd} style={{
          background: th.accent, color: isDark?'#04130f':'#ffffff', border:0,
          borderRadius:999, padding:'8px 14px', display:'flex', alignItems:'center', gap:5,
          fontSize:13.5, fontWeight:600, cursor:'pointer', boxShadow:`0 8px 24px ${th.accent}33`,
        }}>{Icon.plus('currentColor', 14)}<span>添加</span></button>
      </div>

      <div style={{ flex:1, overflow:'auto', padding:'8px 14px 0' }}>
        {wallets.length === 0 ? (
          <div style={{
            margin:'8px 6px', padding:'48px 22px', textAlign:'center',
            border:`1px dashed ${th.hair}`, borderRadius:16, color:th.faint, fontSize:13.5, lineHeight:1.7,
          }}>
            还没有追踪任何地址<br/>
            <button onClick={onToggleAdd} style={{
              marginTop:14, padding:'8px 16px', background: th.accent, color: isDark?'#04130f':'#fff',
              border:0, borderRadius:10, fontWeight:600, fontSize:13.5, cursor:'pointer',
            }}>添加第一个地址</button>
            <div style={{ marginTop:12 }}>
              <button onClick={()=>HL.addWallet(HL.DEMO_ADDR, '示例账户')} style={{
                background:'transparent', border:0, color: th.dim, fontSize:12.5,
                fontFamily: th.numFont, cursor:'pointer', textDecoration:'underline',
              }}>使用示例地址</button>
            </div>
          </div>
        ) : (
          <div style={{ display:'flex', flexDirection:'column', gap:10 }}>
            {wallets.map(w => {
              const isCurrent = w.id === current;
              const equity = isCurrent ? liveTotals.equity : w.balance;
              const upnl = isCurrent ? liveTotals.pnl : w.pnl24h;
              return (
                <ACard key={w.id} t={t} padded={false} style={{
                  padding:'14px 16px', position:'relative', overflow:'hidden', cursor:'pointer',
                  outline: isCurrent ? `1.5px solid ${th.accent}` : 'none',
                }} >
                  <div onClick={()=>HL.setCurrent(w.id)}>
                    <div style={{ display:'flex', alignItems:'center', gap:12, marginBottom:10 }}>
                      <HLWalletAvatar size={36} radius={10}/>
                      <div style={{ flex:1, minWidth:0 }}>
                        <div style={{ fontWeight:600, fontSize:15, display:'flex', alignItems:'center', gap:6 }}>
                          {w.name}
                          {isCurrent && <span style={{
                            fontSize:10.5, fontWeight:700, letterSpacing:'0.08em',
                            color: isDark?'#04130f':'#fff', background: th.accent,
                            padding:'2px 6px', borderRadius:4,
                          }}>当前</span>}
                        </div>
                        <div onClick={(e)=>{ e.stopPropagation(); copyAddr(w.addr); }}
                             style={{ fontSize:12, color:th.dim, fontFamily:th.numFont, marginTop:2, display:'flex', alignItems:'center', gap:5, cursor:'copy' }}>
                          {w.short}{Icon.copy(th.faint, 11)}
                        </div>
                      </div>
                      <button onClick={(e)=>{ e.stopPropagation(); setConfirmDel(w.id); }}
                              style={{ background:'transparent', border:0, color:th.faint, cursor:'pointer', padding:6 }}
                              aria-label="删除">
                        {Icon.trash('currentColor', 14)}
                      </button>
                    </div>
                    <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-end', paddingTop:10, borderTop:`1px solid ${th.hair}` }}>
                      <div>
                        <div style={{ fontSize:11, color:th.dim, letterSpacing:'0.12em' }}>账户净值</div>
                        <div style={{ fontFamily:th.numFont, fontSize:18, fontWeight:600, marginTop:3 }}>
                          {isCurrent ? <NumFlow.usd value={equity}/> : window.fmt.usd(equity)}
                        </div>
                      </div>
                      <div style={{ textAlign:'right' }}>
                        <div style={{ fontSize:11, color:th.dim, letterSpacing:'0.12em' }}>未实现</div>
                        <div style={{ fontFamily:th.numFont, fontSize:14, marginTop:3, color: window.pnlColor(upnl, th.pnlMode) }}>
                          {isCurrent
                            ? <NumFlow value={upnl} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v), 0)}/>
                            : ((upnl>=0?'+':'−') + window.fmt.usd(Math.abs(upnl), 0))}
                        </div>
                      </div>
                    </div>
                  </div>

                  {confirmDel === w.id && (
                    <div onClick={(e)=>e.stopPropagation()} style={{
                      position:'absolute', inset:0, background: isDark?'rgba(11,14,17,0.94)':'rgba(255,255,255,0.94)',
                      display:'flex', flexDirection:'column', justifyContent:'center', alignItems:'center', gap:10, padding:14,
                    }}>
                      <div style={{ fontSize:14, fontWeight:600 }}>移除地址？</div>
                      <div style={{ fontSize:12, color:th.dim, textAlign:'center' }}>仅从本地列表移除，不会影响链上数据</div>
                      <div style={{ display:'flex', gap:8, marginTop:6 }}>
                        <button onClick={()=>setConfirmDel(null)} style={{
                          padding:'7px 14px', background:'transparent', color:th.dim,
                          border:`1px solid ${th.hair}`, borderRadius:8, fontSize:13, cursor:'pointer',
                        }}>取消</button>
                        <button onClick={()=>{ HL.removeWallet(w.id); setConfirmDel(null); }} style={{
                          padding:'7px 14px', background: isDark?'#ef4444':'#dc2626', color:'#fff',
                          border:0, borderRadius:8, fontSize:13, fontWeight:600, cursor:'pointer',
                        }}>移除</button>
                      </div>
                    </div>
                  )}
                </ACard>
              );
            })}
          </div>
        )}
      </div>

      <ATabBar active="wallets" onNav={nav || onBack} t={t}/>

      {addOpen && <AddWalletSheet t={t} onClose={onToggleAdd}/>}
    </>
  );
}

function AddWalletSheet({ t, onClose }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const [addr, setAddr] = React.useState('');
  const [name, setName] = React.useState('');
  const [busy, setBusy] = React.useState(false);
  const valid = ADDR_RE.test(addr.trim());
  const submit = () => {
    if (!valid || busy) return;
    setBusy(true);
    HL.addWallet(addr.trim(), name.trim() || null)
      .then(() => onClose?.())
      .finally(() => setBusy(false));
  };
  const paste = async () => {
    try {
      const v = await navigator.clipboard?.readText();
      if (v) setAddr(v.trim());
    } catch (e) {}
  };
  return (
    <div style={{
      position:'absolute', inset:0, background: isDark?'rgba(0,0,0,0.55)':'rgba(0,0,0,0.35)', backdropFilter:'blur(6px)',
      display:'flex', alignItems:'flex-end', zIndex:80,
    }} onClick={onClose}>
      <div onClick={e=>e.stopPropagation()} style={{
        width:'100%', background: th.tk.sheetBg, backdropFilter:'blur(30px)',
        borderTop: th.tk.sheetBorder,
        borderRadius:'24px 24px 0 0', padding:'14px 18px 26px',
      }}>
        <div style={{ width:36, height:4, borderRadius:2, background: isDark?'rgba(255,255,255,0.18)':'rgba(0,0,0,0.18)', margin:'0 auto 12px' }}/>
        <div style={{ display:'flex', justifyContent:'space-between', alignItems:'center', marginBottom:14 }}>
          <div style={{ fontSize:16, fontWeight:600 }}>添加地址</div>
          <button onClick={onClose} style={{ background:'transparent', border:0, color:th.dim, cursor:'pointer' }}>
            {Icon.close('currentColor', 18)}
          </button>
        </div>
        <div style={{ fontSize:13, color:th.dim, marginBottom:10 }}>粘贴任意 Hyperliquid 钱包地址（0x… 40 位 hex）</div>
        <div style={{
          ...th.card, borderRadius:12, padding:'10px 12px',
          fontFamily:th.numFont, fontSize:13, color: th.ink,
          display:'flex', alignItems:'center', gap:8,
          border: addr && !valid ? `1px solid ${isDark?'#ef4444':'#dc2626'}` : (th.card.border || `1px solid ${th.hair}`),
        }}>
          <span style={{ color:th.faint }}>›</span>
          <input
            type="text"
            inputMode="text"
            autoComplete="off"
            spellCheck={false}
            placeholder="0x…"
            value={addr}
            onChange={(e)=>setAddr(e.target.value)}
            style={{
              flex:1, background:'transparent', border:0, outline:'none',
              // 16px keeps iOS from auto-zooming when the input gains focus.
              fontFamily: th.numFont, fontSize:16, color: th.ink, padding:'4px 0', minWidth:0,
            }}
          />
          <button onClick={paste} style={{ background:'transparent', color: th.accent, border:0, fontSize:12, fontWeight:600, cursor:'pointer' }}>粘贴</button>
        </div>
        {addr && !valid && (
          <div style={{ marginTop:6, fontSize:12, color: isDark?'#fca5a5':'#b91c1c' }}>
            地址格式不正确（应为 0x 开头的 40 位 hex）
          </div>
        )}
        <div style={{ marginTop:14, marginBottom:6, display:'flex', alignItems:'baseline', gap:8 }}>
          <span style={{ fontSize:12, color:th.dim, letterSpacing:'0.14em', fontWeight:500 }}>备注</span>
          <span style={{ fontSize:11.5, color:th.faint }}>选填</span>
        </div>
        <div style={{
          ...th.card, borderRadius:12, padding:'10px 12px',
          display:'flex', alignItems:'center', gap:8,
        }}>
          <input
            type="text"
            placeholder=""
            value={name}
            onChange={(e)=>setName(e.target.value)}
            maxLength={24}
            style={{
              flex:1, background:'transparent', border:0, outline:'none',
              fontSize:16, color: th.ink, padding:'4px 0', minWidth:0,
            }}
          />
        </div>
        <button onClick={submit} disabled={!valid || busy} style={{
          width:'100%', marginTop:16, padding:'14px 0',
          background: valid ? th.accent : (isDark?'rgba(255,255,255,0.06)':'rgba(0,0,0,0.06)'),
          color: valid ? (isDark?'#04130f':'#ffffff') : th.faint,
          border:0, borderRadius:14, fontWeight:600, fontSize:15,
          cursor: valid && !busy ? 'pointer' : 'not-allowed',
          transition:'all 200ms ease-out',
        }}>{busy ? '添加中…' : '添加'}</button>
        <button onClick={()=>{ setAddr(HL.DEMO_ADDR); }} style={{
          width:'100%', marginTop:8, padding:'10px 0',
          background:'transparent', color: th.dim,
          border:`1px solid ${th.hair}`, borderRadius:12, fontSize:13, cursor:'pointer',
          fontFamily: th.numFont,
        }}>填入示例地址</button>
      </div>
    </div>
  );
}

window.AHistory = AHistory;
window.AWallets = AWallets;
