;(function () {
/* PerformanceScreen — Portfolio tab. Returns card + Allocation + 2x2 stats grid. */

const perfStyles = {
  // Returns card
  returnsCard: {
    marginLeft: '16px',
    marginRight: '16px',
    marginTop: '16px',
    marginBottom: '16px',
    backgroundColor: '#fff',
    borderRadius: '20px',
    padding: '20px',
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
  },
  returnsHeader: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
  },
  totalReturnLabel: {
    fontFamily: 'Inter',
    fontWeight: 400,
    fontSize: '13px',
    color: colors.muted,
  },
  allTimeLabel: {
    fontFamily: 'Inter',
    fontWeight: 400,
    fontSize: '12px',
    color: '#079455',
    textAlign: 'right',
  },
  bigValue: {
    fontFamily: 'Gilroy',
    fontWeight: 700,
    fontSize: '32px',
    color: colors.ink,
    marginBottom: '8px',
    fontVariantNumeric: 'tabular-nums',
    letterSpacing: '-0.5px',
  },

  // Allocation card
  allocationCard: {
    marginLeft: '16px',
    marginRight: '16px',
    backgroundColor: '#fff',
    borderRadius: '20px',
    padding: '20px',
    display: 'flex',
    flexDirection: 'column',
    gap: '16px',
    marginBottom: '16px',
  },
  allocationTitle: {
    fontFamily: 'Gilroy',
    fontWeight: 600,
    fontSize: '16px',
    color: colors.ink,
  },
  allocationBody: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    gap: '20px',
  },
  legend: {
    flex: 1,
    display: 'flex',
    flexDirection: 'column',
    /* No `gap` here — dividers come from per-row borderBottom so the
       hairline aligns with the row's vertical centre, not floats in
       a `gap` band. */
  },
  legendRow: {
    display: 'flex',
    flexDirection: 'row',
    alignItems: 'center',
    gap: '8px',
    paddingTop: '8px',
    paddingBottom: '8px',
  },
  legendRowBordered: {
    borderBottom: '1px solid #F2F4F7',
  },
  dot: {
    width: '8px',
    height: '8px',
    borderRadius: '4px',
    flexShrink: 0,
  },
  legendLabel: {
    flex: 1,
    fontFamily: 'Gilroy',
    fontWeight: 500,
    fontSize: '13px',
    color: colors.ink2,
  },
  legendPct: {
    fontFamily: 'Gilroy',
    fontWeight: 700,
    fontSize: '13px',
    color: colors.ink,
    fontVariantNumeric: 'tabular-nums',
    textAlign: 'right',
  },

  // Stats grid — true 2×2 via CSS grid. The previous flex+48% layout
  // collapsed to content-width because `flex: 0` set the flex-basis to
  // 0%, so cards intrinsically sized to their text and 3 fit on row 1.
  statsGrid: {
    paddingLeft: '16px',
    paddingRight: '16px',
    marginBottom: '16px',
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '12px',
  },
};

const PerformanceScreen = () => {
  const [range, setRange] = React.useState('1M');
  /* Live equity-aware slices — Trading slice value = balance + open
     P/L, others stay at static balances. Mirrors the home Summary
     widget so both screens stay in lock-step. */
  const live = window.useTradingNumbers ? window.useTradingNumbers() : null;
  const total = live ? live.total : getTotal();
  const slices = getSlices().map((s) => {
    const value = s.id === 'trading' && live ? live.equity : s.value;
    const pct = total > 0 ? value / total : 0;
    return { ...s, value, pct };
  });

  return (
    <div
      // ScrollView bg = grey for BOTTOM overscroll; TOP overscroll uses the
      // absolute white cushion below to match the PageHeader.
      style={{ backgroundColor: colors.bg, overflowY: 'auto', WebkitOverflowScrolling: 'touch', height: '100%', position: 'relative' }}
    >
      <div style={{ paddingBottom: '200px', backgroundColor: colors.bg, position: 'relative' }}>
        <div
          style={{ position: 'absolute', top: '-1000px', left: 0, right: 0, height: '1000px', backgroundColor: '#fff', pointerEvents: 'none' }}
        />
        <PageHeader title="Performance" />

        {/* A. Returns card — live "Total return" reflects realised P/L
           on closed positions. Open positions don't count yet (no
           realised gain). The big number stays as the demo's headline
           figure but the percentage shifts as you close positions. */}
        <div style={perfStyles.returnsCard}>
          <div style={perfStyles.returnsHeader}>
            <span style={perfStyles.totalReturnLabel}>Total return</span>
            <span style={{ ...perfStyles.allTimeLabel, color: live && live.openPL >= 0 ? '#079455' : '#F04438' }}>
              {(live && live.openPL >= 0 ? '+' : '−') + (live ? '$' + Math.abs(live.openPL).toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '$0.00') + ' open'}
            </span>
          </div>
          <div style={perfStyles.bigValue}>{live ? '$' + live.equity.toLocaleString('en-US', { minimumFractionDigits: 2, maximumFractionDigits: 2 }) : '$0.00'}</div>
          <div style={{ height: '140px', width: '100%' }}>
            <AreaChart />
          </div>
          <RangeTabs value={range} onChange={setRange} />
        </div>

        {/* B. Allocation card */}
        <div style={perfStyles.allocationCard}>
          <div style={perfStyles.allocationTitle}>Allocation</div>
          <div style={perfStyles.allocationBody}>
            <AllocationDonut slices={slices} />
            <div style={perfStyles.legend}>
              {slices.map((s, i) => {
                const isLast = i === slices.length - 1;
                return (
                  <div
                    key={s.id}
                    style={{
                      ...perfStyles.legendRow,
                      ...(!isLast ? perfStyles.legendRowBordered : null),
                    }}
                  >
                    <div style={{ ...perfStyles.dot, backgroundColor: s.color }} />
                    <span style={perfStyles.legendLabel}>{s.label}</span>
                    <span style={perfStyles.legendPct}>{`${Math.round(s.pct * 100)}%`}</span>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* C. Stats grid — true 2×2 via CSS grid (the wrapper handles
           the columns; each cell renders directly). Top row: Best day /
           Worst day. Bottom row: Win rate / Avg trade P/L. */}
        <div style={perfStyles.statsGrid}>
          <StatCard
            label="Best day"
            value="+$420.10"
            sub="Apr 18"
            valueColor={colors.green}
          />
          <StatCard
            label="Worst day"
            value="-$215.40"
            sub="Mar 22"
            valueColor={colors.red}
          />
          <StatCard
            label="Win rate"
            value="62%"
            sub="Last 30 days"
            valueColor={colors.ink}
          />
          <StatCard
            label="Avg trade P/L"
            value="$148.20"
            sub="Last 30 days"
            valueColor={colors.ink}
          />
        </div>
      </div>
    </div>
  );
};

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