// =============================================================================
// a-portfolio.jsx — Screen 01 持仓总览
// =============================================================================
// Account equity card + 24h sparkline + position list. Tap a row → detail.
// When no wallets are tracked yet, renders an empty hero with a "use demo
// address" shortcut that calls HL.addWallet(HL.DEMO_ADDR).
// =============================================================================

function APortfolio({ t, nav, onPos }) {
  const th = aTheme(t);
  const isDark = th.isDark;
  const state = HL.useStore();
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const w = state.wallets.find(x => x.id === state.current) || state.wallets[0];

  if (!w) return <APortfolioEmpty t={t} nav={nav}/>;

  const totals    = state.totals;
  const positions = state.positions;
  const equity    = totals.equity || 0;
  const pnl       = totals.pnl || 0;
  const dayPct    = equity ? (pnl / equity) * 100 : 0;
  // 已平仓盈亏 = closedPnl − fee + funding net
  //   closedPnl: HL's per-fill realized PnL (price-only)
  //   −fee: trading fees paid for those fills
  //   +funding: net funding收/付 over the same period (+收 / −付)
  // 今日 / 总 都按这个口径，与「真实进/出 USDC」一致。
  const startOfTodayMs = (() => {
    const n = new Date();
    return new Date(n.getFullYear(), n.getMonth(), n.getDate()).getTime();
  })();
  const history  = state.history  || [];
  const fundings = state.fundings || [];
  const realizedFromFills = (rows) => rows.reduce(
    (s, h) => s + (h.closedPnl || 0) - (h.fee || 0), 0);
  const fundingNet = (rows) => rows.reduce((s, f) => s + (f.amount || 0), 0);
  const realizedPnl = realizedFromFills(history) + fundingNet(fundings);
  const todayPnl    = realizedFromFills(history.filter(h => (h.ms || 0) >= startOfTodayMs))
                    + fundingNet(fundings.filter(f => (f.ms || 0) >= startOfTodayMs));
  const colorFor = (v) => v === 0 ? th.ink
    : v > 0 ? (isDark?'#7ee2a8':'#15803d')
    : (isDark?'#fca5a5':'#b91c1c');
  const realizedColor = colorFor(realizedPnl);
  const todayColor    = colorFor(todayPnl);
  const fmtSignedUsd = (v) => (v>=0?'+':'−') + window.fmt.usd(Math.abs(v), 0);

  return (
    <>
      <div style={{ padding: `4px ${th.L.pagePadX + 2}px 10px`, display:'flex', justifyContent:'space-between', alignItems:'center' }}>
        <button onClick={() => nav?.('wallets')} style={{
          ...th.card, borderRadius: 999, padding:'7px 12px 7px 8px',
          display:'flex', alignItems:'center', gap:8, color: th.ink, cursor:'pointer',
        }}>
          <HLWalletAvatar size={22} radius={6}/>
          <span style={{ fontSize:14, fontWeight:600 }}>{w.name}</span>
          <span style={{ fontFamily: th.numFont, fontSize:12, color: th.dim }}>{w.short}</span>
          {Icon.chev(th.faint, 12)}
        </button>
        <SettingsButton t={t} onClick={()=>setSettingsOpen(true)}/>
      </div>

      <div style={{ padding:'4px 14px 12px' }}>
        <ACard t={t} padded={false} style={{ padding: '18px 18px 14px', position:'relative', overflow:'hidden' }}>
          <div style={{ display:'flex', justifyContent:'space-between', alignItems:'flex-start' }}>
            <div>
              <div style={{ fontSize:12, color:th.dim, letterSpacing:'0.16em', marginBottom:6 }}>账户净值</div>
              <div style={{ fontFamily: th.numFont, fontSize:34, fontWeight:600, letterSpacing:'-0.02em', lineHeight:1 }}>
                <NumFlow.usd value={equity} animate/>
              </div>
              <div style={{ marginTop:8, fontSize:13.5 }}>
                <span style={{ color: window.pnlColor(pnl, th.pnlMode), fontFamily: th.numFont, fontWeight:600 }}>
                  <NumFlow value={pnl} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v))}/>
                  {' '}<span style={{ opacity:.7 }}>(<NumFlow value={dayPct} format={window.fmt.pct}/>)</span>
                </span>
              </div>
            </div>
          </div>
          <div style={{ marginTop:14, marginLeft:-4, marginRight:-4 }}>
            <Spark sym="EQUITY" up w={350} h={48} color={th.accent} strokeW={1.6} />
          </div>
          <div style={{ display:'grid', gridTemplateColumns:'repeat(4, 1fr)', gap:8, marginTop:6, paddingTop:12, borderTop:`1px solid ${th.hair}` }}>
            <Stat th={th} k="持仓价值" align="center"><NumFlow.usd value={totals.notional} d={0}/></Stat>
            <Stat th={th} k="持仓数" align="center"><NumFlow value={positions.length} format={(v)=>String(Math.round(v))}/></Stat>
            <Stat th={th} k="今日盈亏" align="center">
              <span style={{ color: todayColor }}>
                <NumFlow value={todayPnl} format={fmtSignedUsd}/>
              </span>
            </Stat>
            <Stat th={th} k="总盈亏" align="center">
              <span style={{ color: realizedColor }}>
                <NumFlow value={realizedPnl} format={fmtSignedUsd}/>
              </span>
            </Stat>
          </div>
        </ACard>
      </div>

      <div style={{ padding:'4px 22px', display:'flex', justifyContent:'space-between', alignItems:'baseline' }}>
        <div style={{ fontSize:12.5, letterSpacing:'0.18em', color:th.dim }}>当前持仓</div>
        <div style={{ fontSize:12, color:th.faint, fontFamily: th.numFont }}>{positions.length} 个市场</div>
      </div>

      <div style={{ flex:1, overflow:'auto', padding:'8px 14px 0' }}>
        <div style={{ display:'flex', flexDirection:'column', gap:8 }}>
          {positions.length === 0 ? (
            <div style={{
              padding:'40px 20px', textAlign:'center', color:th.faint, fontSize:13.5, lineHeight:1.7,
              border:`1px dashed ${th.hair}`, borderRadius:14,
            }}>
              该地址当前没有持仓<br/>
              <span style={{ fontSize:12 }}>到 Hyperliquid 开仓后将自动出现在这里</span>
            </div>
          ) : positions.map(p => {
            const pColor = window.pnlColor(p.pnl, th.pnlMode);
            return (
              <button key={p.sym} onClick={() => onPos?.(p.sym)} style={{
                ...th.card, borderRadius:14, padding:'12px 14px', textAlign:'left', cursor:'pointer',
                color:th.ink, display:'flex', alignItems:'center', gap:12,
              }}>
                <TokenGlyph sym={p.sym} size={36} />
                <div style={{ flex:1, minWidth:0 }}>
                  <div style={{ display:'flex', alignItems:'center', gap:6 }}>
                    <span style={{ fontWeight:600, fontSize:15 }}>{p.sym}</span>
                    <ATag tone={p.side==='LONG'?'long':'short'} t={t}>{p.side==='LONG'?'Long':'Short'}</ATag>
                    <span style={{ fontSize:11, color:th.faint, fontFamily: th.numFont }}>{p.lev}×</span>
                  </div>
                  <div style={{ fontSize:12, color:th.dim, marginTop:2, fontFamily:th.numFont }}>
                    {p.size} @ <NumFlow value={p.entry} format={(v)=>window.fmt.num(v, p.entry<10?3:1)}/>
                  </div>
                </div>
                <div style={{ flex:'0 0 auto' }}>
                  <Spark sym={p.sym} up={p.pnl>=0} color={pColor} w={56} h={20} strokeW={1.4}/>
                </div>
                <div style={{ textAlign:'right', minWidth:84 }}>
                  <div style={{ fontFamily:th.numFont, fontSize:14, fontWeight:600, color: pColor }}>
                    <NumFlow value={p.pnl} format={(v)=>(v>=0?'+':'−')+window.fmt.usd(Math.abs(v), 0)}/>
                  </div>
                  <div style={{ fontSize:12, fontFamily:th.numFont, color: pColor, opacity:.75, marginTop:2 }}>
                    <NumFlow value={p.pnlPct} format={window.fmt.pct}/>
                  </div>
                </div>
              </button>
            );
          })}
          <div style={{ height: 8 }}/>
        </div>
      </div>

      <ATabBar active="home" onNav={nav} t={t}/>

      <SettingsSheet t={t} open={settingsOpen} onClose={()=>setSettingsOpen(false)}/>
    </>
  );
}

function Stat({ th, k, align='left', children }) {
  return (
    <div style={{ textAlign: align, minWidth: 0 }}>
      <div style={{ fontSize:10.5, color:th.dim, letterSpacing:'0.08em', whiteSpace:'nowrap' }}>{k}</div>
      <div style={{
        fontFamily: th.numFont, fontSize:13, marginTop:3,
        whiteSpace:'nowrap', overflow:'hidden', textOverflow:'ellipsis',
      }}>{children}</div>
    </div>
  );
}

function APortfolioEmpty({ t, nav }) {
  const th = aTheme(t);
  const isDark = th.isDark;
  const [busy, setBusy] = React.useState(false);
  const [settingsOpen, setSettingsOpen] = React.useState(false);
  const useDemo = () => {
    if (busy) return; setBusy(true);
    HL.addWallet(HL.DEMO_ADDR, '示例账户').finally(() => setBusy(false));
  };
  return (
    <>
      <div style={{ padding:`4px ${th.L.pagePadX + 2}px 8px`, display:'flex', justifyContent:'space-between', alignItems:'flex-end' }}>
        <div>
          <div style={{ fontSize:12, color:th.dim, letterSpacing:'0.18em' }}>持仓</div>
          <div style={{ fontSize:22, fontWeight:600, marginTop:2 }}>开始追踪</div>
        </div>
        <SettingsButton t={t} onClick={()=>setSettingsOpen(true)}/>
      </div>

      <div style={{ flex:1, overflow:'auto', padding:'12px 16px' }}>
        <ACard t={t} padded={false} style={{ padding:'24px 22px', position:'relative', overflow:'hidden' }}>
          <div style={{
            width:48, height:48, borderRadius:14,
            background: isDark?'rgba(92,220,201,0.12)':'rgba(13,138,122,0.10)',
            color: th.accent, display:'flex', alignItems:'center', justifyContent:'center',
            fontSize:24, fontWeight:300, marginBottom:14,
          }}>+</div>
          <div style={{ fontSize:17, fontWeight:600, marginBottom:6 }}>添加你的第一个 Hyperliquid 地址</div>
          <div style={{ fontSize:13.5, color:th.dim, lineHeight:1.6 }}>
            只读模式 · 永远不会请求私钥。粘贴任意 Hyperliquid 地址即可追踪其仓位、行情与历史成交。
          </div>
          <div style={{ marginTop:18, display:'flex', flexDirection:'column', gap:10 }}>
            <button onClick={() => nav?.('wallets')} style={{
              padding:'12px 0', background: th.accent, color: isDark?'#04130f':'#fff',
              border:0, borderRadius:12, fontWeight:600, fontSize:15, cursor:'pointer',
            }}>添加地址</button>
            <button onClick={useDemo} disabled={busy} style={{
              padding:'12px 0', background:'transparent', color: th.ink,
              border:`1px solid ${th.hair}`, borderRadius:12, fontWeight:500, fontSize:14, cursor: busy?'wait':'pointer',
              fontFamily: th.numFont,
            }}>{busy ? '加载中…' : '使用示例地址查看效果'}</button>
          </div>
          <div style={{ marginTop:14, fontSize:11.5, color:th.faint, fontFamily:th.numFont, letterSpacing:'0.04em', wordBreak:'break-all' }}>
            示例 · {window.fmt.addr(HL.DEMO_ADDR)}
          </div>
        </ACard>

        <div style={{ marginTop:18, fontSize:12, color:th.faint, lineHeight:1.7, padding:'0 4px' }}>
          数据来源：<span style={{ color:th.dim }}>api.hyperliquid.xyz</span><br/>
          · 行情、持仓、历史成交均通过 WebSocket 实时推送<br/>
          · 钱包地址保存在你本地（localStorage）
        </div>
      </div>

      <ATabBar active="home" onNav={nav} t={t}/>

      <SettingsSheet t={t} open={settingsOpen} onClose={()=>setSettingsOpen(false)}/>
    </>
  );
}

window.APortfolio = APortfolio;
