;(function () {
/* PortfolioPage — Leveraged Trade sub-app · Portfolio tab.
   Reads positions/balances from the TradeStore via hooks so every
   value ticks live with the engine. Renders an empty-state card when
   no positions are open, or a stack of <PositionCard /> instances
   when there are. Performance and Allocation cards have been moved to
   the Activity page; this surface focuses on the hero plus the open
   positions list. */

/* PLChevron — tiny up/down arrow shown in front of P/L pills. */
const PLChevron = ({ positive }) => (
  <svg width="10" height="10" viewBox="0 0 10 10" fill="none">
    <path
      d={positive ? 'M2 6.5l3-3 3 3' : 'M2 3.5l3 3 3-3'}
      stroke="#fff"
      strokeWidth="1.6"
      strokeLinecap="round"
      strokeLinejoin="round"
    />
  </svg>
);

const PortfolioPage = ({ onOpenTrade }) => {
  const positions = window.usePositions();
  const balances = window.useBalances();
  const { closePosition } = window.useTradeMutators();

  /* Derived numbers — all reactive via the store.
     `notional` per position uses the same lot/contract multiplier as
     computeLivePL so Forex (100,000), commodities (100 / 5000 for silver),
     etc. translate to dollar exposure, not raw size×price. Without this,
     forex 0.10 lots × 1.09 shows as $0.11 — and downstream margin level
     blows up to billions. */
  function notionalFor(p) {
    const sym = window.useSymbol ? null : null;  // can't use hook in helper
    /* Inline the same category-multiplier rules as computeLivePL. */
    const cat = p.cat
      || (window.getSymbol && window.getSymbol(p.sym) && window.getSymbol(p.sym).cat)
      || null;
    let mult = 1;
    if (cat === 'forex') mult = 100000;
    else if (cat === 'commodities' && p.sym === 'XAGUSD') mult = 5000;
    else if (cat === 'commodities') mult = 100;
    return Math.abs(p.size * p.open * mult);
  }
  const openPL = positions.reduce((s, p) => s + p.pl, 0);
  const exposure = positions.reduce((s, p) => s + notionalFor(p), 0);
  const equity = balances.trading + openPL;
  const positiveTotal = openPL >= 0;
  const freeMargin = balances.trading - exposure / 500;
  /* Dollar margin locked up by open exposure (leverage 1:500). The
     small-pill chip up top still shows the percentage version
     (marginUsedPct) for context, but the four-stat row below now
     shows the dollar value the user actually has tied up. */
  const marginUsed = exposure / 500;
  const marginLevel = exposure > 0
    ? Math.round(equity / (exposure / 500) * 100).toLocaleString('en-US') + '%'
    : '—';


  return (
    <div
      style={{
        flex: 1,
        width: '100%',
        height: '100%',
        overflowY: 'auto',
        WebkitOverflowScrolling: 'touch',
        scrollbarWidth: 'none',
        backgroundColor: colors.bg,
      }}
    >
      <div
        style={{
          paddingTop: '16px',
          paddingLeft: '20px',
          paddingRight: '20px',
          paddingBottom: '180px',
          display: 'flex',
          flexDirection: 'column',
          gap: '14px',
        }}
      >
        {/* ===== Hero card ============================================== */}
        <div
          style={{
            background: 'linear-gradient(135deg, #00AFAB 0%, #006B67 100%)',
            borderRadius: '24px',
            padding: '18px 16px',
            display: 'flex',
            flexDirection: 'column',
          }}
        >
          {/* "Equity" label OVER the big number — Equity = Balance + Open P/L. */}
          <div
            style={{
              fontFamily: 'Inter',
              fontSize: '12px',
              color: '#fff',
              opacity: 0.7,
              letterSpacing: '0.04em',
              textTransform: 'uppercase',
              fontWeight: 600,
            }}
          >
            Equity
          </div>

          {/* Big number — equity. Computed as balance + open P/L; with no
             positions this equals the trading balance. */}
          <div
            style={{
              fontFamily: 'Gilroy',
              fontWeight: 700,
              fontSize: '36px',
              color: '#fff',
              fontVariantNumeric: 'tabular-nums',
              lineHeight: 1.1,
              marginTop: '4px',
            }}
          >
            {(function () {
              /* Format with commas + 2 decimal places. */
              const sign = equity < 0 ? '-' : '';
              const abs = Math.abs(equity);
              const fixed = abs.toFixed(2);
              const [whole, frac] = fixed.split('.');
              const withCommas = whole.replace(/\B(?=(\d{3})+(?!\d))/g, ',');
              return sign + '$' + withCommas + '.' + frac;
            })()}
          </div>

          {/* Leverage subtitle BELOW the big number. */}
          <div
            style={{
              fontFamily: 'Inter',
              fontSize: '12px',
              color: '#fff',
              opacity: 0.7,
              marginTop: '4px',
            }}
          >
            {'Leverage ' + window.TRADE_ACCOUNT.leverage}
          </div>

          {/* Open P/L chip — the only chip in the hero now. The dollar
             margin-used value lives in the four-stat row below, which
             made the duplicate %-chip redundant. */}
          <div style={{ display: 'flex', flexDirection: 'row', gap: '8px', marginTop: '12px' }}>
            <div
              style={{
                display: 'inline-flex',
                alignItems: 'center',
                gap: '6px',
                padding: '8px 14px',
                borderRadius: '9999px',
                backgroundColor: 'rgba(255,255,255,0.18)',
                color: '#fff',
                fontFamily: 'Gilroy',
                fontWeight: 600,
                fontSize: '12px',
              }}
            >
              <PLChevron positive={positiveTotal} />
              <span>{'Open P/L: ' + window.formatPL(openPL)}</span>
            </div>
          </div>

          {/* 4 mini stats — order: Balance, Free margin, Margin level, Day P/L. */}
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              justifyContent: 'space-between',
              gap: 0,
              marginTop: '14px',
            }}
          >
            {[
              {
                label: 'Balance',
                /* 2 decimals (min+max) so column widths don't jitter as
                   the value ticks live. */
                value: '$' + balances.trading.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
                opacity: 1,
              },
              {
                label: 'Margin used',
                /* Dollar value, not percent — the chip above already
                   carries the percent. */
                value: '$' + marginUsed.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
                opacity: 1,
              },
              {
                label: 'Free margin',
                value: '$' + freeMargin.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }),
                opacity: 1,
              },
              {
                label: 'Margin level',
                value: marginLevel,
                opacity: 1,
              },
            ].map((s) => (
              <div
                key={s.label}
                style={{ display: 'flex', flexDirection: 'column', gap: '4px' }}
              >
                <span
                  style={{
                    fontFamily: 'Inter',
                    fontSize: '11px',
                    color: 'rgba(255,255,255,0.6)',
                  }}
                >
                  {s.label}
                </span>
                <span
                  style={{
                    fontFamily: 'Gilroy',
                    fontWeight: 600,
                    fontSize: '14px',
                    color: '#fff',
                    opacity: s.opacity,
                    fontVariantNumeric: 'tabular-nums',
                  }}
                >
                  {s.value}
                </span>
              </div>
            ))}
          </div>
        </div>

        {/* ===== Open positions ======================================== */}
        <div>
          <div
            style={{
              display: 'flex',
              flexDirection: 'row',
              alignItems: 'center',
              paddingBottom: '8px',
              paddingLeft: '4px',
              paddingRight: '4px',
            }}
          >
            <span
              style={{
                flex: 1,
                fontFamily: 'Gilroy',
                fontWeight: 600,
                fontSize: '16px',
                color: colors.ink,
              }}
            >
              {'Open positions (' + positions.length + ')'}
            </span>
            {positions.length > 0 && (
              <button
                style={{
                  border: 'none',
                  background: 'transparent',
                  padding: 0,
                  margin: 0,
                  cursor: 'pointer',
                  fontFamily: 'Inter',
                  fontWeight: 500,
                  fontSize: '13px',
                  color: colors.teal2,
                }}
              >
                Manage all
              </button>
            )}
          </div>

          {positions.length === 0 ? (
            <window.EmptyPositions onOpenTrade={onOpenTrade} />
          ) : (
            <div style={{ display: 'flex', flexDirection: 'column', gap: '12px' }}>
              {positions.map((p) => (
                <window.PositionCard key={p.id} position={p} onClose={closePosition} />
              ))}
              <div
                style={{
                  backgroundColor: '#fff',
                  borderRadius: '20px',
                  boxShadow: '0px 24px 28px rgba(14, 20, 32, 0.16)',
                  padding: '14px 16px',
                  display: 'flex',
                  flexDirection: 'row',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                }}
              >
                <button
                  onClick={() => {}}
                  style={{
                    border: 'none',
                    background: 'rgba(240,68,56,0.10)',
                    padding: '8px 14px',
                    margin: 0,
                    cursor: 'pointer',
                    borderRadius: '9999px',
                    color: colors.red,
                    fontFamily: 'Gilroy',
                    fontWeight: 600,
                    fontSize: '12px',
                  }}
                >
                  Close all
                </button>
                <span
                  style={{
                    fontFamily: 'Gilroy',
                    fontWeight: 600,
                    fontSize: '14px',
                    color: positiveTotal ? colors.green : colors.red,
                    fontVariantNumeric: 'tabular-nums',
                  }}
                >
                  {'Total: ' + window.formatPL(openPL)}
                </span>
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

Object.assign(window, { PortfolioPage });
})();
