// =============================================================================
// a-history-wallets.jsx — Screens 03 历史成交 · 04 地址管理
// =============================================================================
// AHistory  — daily-grouped trade list + 24h aggregate strip (HL userFills).
// AWallets  — tracked address list + bottom-sheet "添加地址" modal.
// =============================================================================

function AHistory({ t, nav, onBack }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const state = HL.useStore();
  const history  = state.history  || [];
  const fundings = state.fundings || [];
  const [tab, setTab] = React.useState('trades'); // 'trades' | 'funding'
  const scrollRef = React.useRef(null);

  // Aggregates. Volume uses HL's canonical day/allTime numbers from
  // /info portfolio. Fees / funding aggregate from records in store
  // (REST userFillsByTime + WS deltas).
  const vol = state.volume || { day: 0, allTime: 0 };
  const startOfTodayMs = (() => {
    const n = new Date();
    return new Date(n.getFullYear(), n.getMonth(), n.getDate()).getTime();
  })();
  const isToday = (rec) => (rec.ms || 0) >= startOfTodayMs;
  const todayFills    = history.filter(isToday);
  const todayFundings = fundings.filter(isToday);
  const todayVol      = vol.day || todayFills.reduce((s, h) => s + h.value, 0);
  const todayFee      = todayFills.reduce((s, h) => s + h.fee, 0);
  const todayFunding  = todayFundings.reduce((s, f) => s + f.amount, 0);
  const totalVol      = vol.allTime || history.reduce((s, h) => s + h.value, 0);
  const totalFee      = history.reduce((s, h) => s + h.fee, 0);
  const totalFunding  = fundings.reduce((s, f) => s + f.amount, 0);
  const colorOf = (v) => v === 0 ? th.ink
    : v > 0 ? (isDark?'#7ee2a8':'#15803d')
    : (isDark?'#fca5a5':'#b91c1c');

  // Flat list per tab — no day grouping. Time labels include MM-DD HH:MM
  // so each row is self-explanatory.
  const rows  = tab === 'trades' ? history : fundings;
  const total = rows.length;

  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={{
            fontSize:11, color:th.dim, letterSpacing:'0.16em',
            marginBottom:8, fontWeight:500,
          }}>今日</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
            <Stat3 th={th} k="成交">
              <NumFlow.usd value={todayVol} d={0}/>
            </Stat3>
            <Stat3 th={th} k="手续费">
              <NumFlow.usd value={todayFee}/>
            </Stat3>
            <Stat3 th={th} k="资金费">
              <span style={{ color: colorOf(todayFunding) }}>
                <NumFlow value={todayFunding} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v))}/>
              </span>
            </Stat3>
          </div>
          <div style={{
            fontSize:11, color:th.dim, letterSpacing:'0.16em',
            margin:'14px 0 8px', fontWeight:500,
            paddingTop:12, borderTop:`1px solid ${th.hair}`,
          }}>累计</div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(3,1fr)', gap:12 }}>
            <Stat3 th={th} k="成交">
              <NumFlow.usd value={totalVol} d={0}/>
            </Stat3>
            <Stat3 th={th} k="手续费">
              <NumFlow.usd value={totalFee}/>
            </Stat3>
            <Stat3 th={th} k="资金费">
              <span style={{ color: colorOf(totalFunding) }}>
                <NumFlow value={totalFunding} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v))}/>
              </span>
            </Stat3>
          </div>
        </ACard>
      </div>

      <ScrollLoader scrollRef={scrollRef}/>

      <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 }}>{total} 笔</span>
            </div>
            <ACard t={t} padded={false} style={{ overflow:'hidden' }}>
              {rows.map((h, i)=> tab === 'trades'
                ? <TradeRow key={h.hash || i} h={h} t={t} th={th} first={i===0}/>
                : <FundingRow key={(h.ms||0)+':'+h.sym+':'+i} f={h} t={t} th={th} isDark={isDark} first={i===0}/>
              )}
            </ACard>
          </div>
        )}
        {tab === 'trades' && total > 0 && (
          <div style={{
            padding:'12px 8px 20px', textAlign:'center',
            fontSize:12, color:th.faint, fontFamily:th.numFont, letterSpacing:'0.06em',
          }}>
            {state.historyLoading ? '加载更多…' : state.historyExhausted ? '— 已无更多记录 —' : ''}
          </div>
        )}
      </div>

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

function TradeRow({ h, t, th, first }) {
  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 }}>
          {h.sym}
          <ATag tone={h.side==='BUY'?'long':'short'} t={t}>{h.side==='BUY'?'Buy':'Sell'}</ATag>
        </div>
        <div style={{ fontSize:11.5, color:th.dim, marginTop:2, fontFamily:th.numFont }}>
          {h.time} · {h.size} @ {window.fmt.num(h.price, h.price<10?3:1)}
        </div>
      </div>
      <div style={{ textAlign:'right' }}>
        <div style={{ fontFamily:th.numFont, fontSize:13.5, fontWeight:500 }}>{window.fmt.usd(h.value, 0)}</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>
  );
}

// Watches the history scroll container; when the user is within ~200px of
// the bottom, kicks HL.loadMoreHistory(). Throttled by historyLoading flag
// in the store so we don't fire concurrent requests.
function ScrollLoader({ scrollRef }) {
  React.useEffect(() => {
    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 { window.HL && window.HL.loadMoreHistory && window.HL.loadMoreHistory(); } catch (e) {}
        }
      });
    };
    el.addEventListener('scroll', onScroll, { passive: true });
    onScroll();
    return () => { el.removeEventListener('scroll', onScroll); cancelAnimationFrame(raf); };
  }, [scrollRef]);
  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 }) {
  const th = aTheme(t);
  const isDark = th.mode === 'dark';
  const state = HL.useStore();
  const wallets = state.wallets || [];
  const current = state.current;
  // 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;
              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={w.balance}/> : window.fmt.usd(w.balance)}
                        </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(w.pnl24h, th.pnlMode) }}>
                          {isCurrent
                            ? <NumFlow value={w.pnl24h} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v), 0)}/>
                            : ((w.pnl24h>=0?'+':'−') + window.fmt.usd(Math.abs(w.pnl24h), 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;
