// =============================================================================
// 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, visible = true }) {
  const th = aTheme(t);
  const isDark = th.isDark;
  const state = HL.useStoreWhen(visible, s => ({
    wallets: s.wallets,
    current: s.current,
    totals: s.totals,
    positions: s.positions,
    equityHistory: s.equityHistory || [],
    netPnlToday: s.netPnlToday,
    netPnlTotal: s.netPnlTotal,
    historyExhausted: s.historyExhausted,
    historyLoading: s.historyLoading,
    openOrders: s.openOrders || [],
    mids: s.mids || {},
  }));
  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;
  // 今日/总净利润 = sum(closedPnl) − |fee| + funding（store 统一去重 tid）
  const todayPnl  = state.netPnlToday || 0;
  const realizedPnl = state.netPnlTotal || 0;
  const equityHist = state.equityHistory;

  React.useEffect(() => {
    if (!visible || !state.current) return;
    if (window.HL && window.HL.ensureHistoryLoaded) window.HL.ensureHistoryLoaded();
  }, [visible, state.current]);
  const pendingGroups = React.useMemo(() => {
    const group = window.HL && window.HL.groupOpenOrdersForUI;
    if (!group) return [];
    return group(state.openOrders || [], positions);
  }, [state.openOrders, positions]);
  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 }}>
            {equityHist && equityHist.length >= 2
              ? <LiveSpark points={equityHist} w={350} h={48} color={th.accent} strokeW={1.6}/>
              : <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 }} title="已实现盈亏 − 手续费 + 资金费">
                <NumFlow value={realizedPnl} format={fmtSignedUsd}/>
              </span>
            </Stat>
          </div>
        </ACard>
      </div>

      <div style={{ flex:1, overflow:'auto', padding: positions.length > 0 ? '8px 14px 0' : '4px 14px 0' }}>
        {positions.length > 0 && (
          <>
            <div style={{
              padding:'0 8px 8px', 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={{ display:'flex', flexDirection:'column', gap:8, marginBottom: pendingGroups.length > 0 ? 4 : 8 }}>
              {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 }}>{(() => {
                          const split = window.HL.splitCoin && window.HL.splitCoin(p.sym);
                          return split ? (split.ticker + '·' + split.dex) : 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>
          </>
        )}

        {pendingGroups.length > 0 && (
          <PendingOrdersSection
            t={t}
            th={th}
            title="待成交挂单"
            groups={pendingGroups}
            onSymClick={onPos}
            getPosition={(sym, side) => (positions || []).find(
              p => String(p.sym) === String(sym) && p.side === side
            )}
            style={{ padding: positions.length > 0 ? '4px 0 12px' : '0 0 12px' }}
          />
        )}
      </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;
