← back to Ken

kalshi-dash/src/pages/Dashboard.jsx

1901 lines

import React, { useState, useEffect } from 'react';
import { api, post } from '../api';
import { Link } from 'react-router-dom';
import {
  AreaChart, Area, BarChart, Bar, Cell, XAxis, YAxis, CartesianGrid,
  Tooltip, ResponsiveContainer, PieChart, Pie, RadialBarChart, RadialBar,
  Legend,
} from 'recharts';
import Sparkline from '../components/Sparkline';
import useAnimatedValue from '../hooks/useAnimatedValue';
import { CHART_COLORS, TOOLTIP_STYLE, AXIS_TICK, GRID_STYLE, fmtDollars, fmtDateShort } from '../utils/chartTheme';

/* ── Seeded random sparkline generator (stable per label) ── */
function genSparkData(seed, count = 8) {
  let s = seed;
  return Array.from({ length: count }, () => {
    s = (s * 1664525 + 1013904223) & 0xffffffff;
    return (Math.abs(s) % 100) + 10;
  });
}

/* Pre-generate stable sparkline datasets for each stat card */
const SPARK_DATA = {
  Balance:        genSparkData(42, 9),
  Positions:      genSparkData(17, 9),
  'Open Markets': genSparkData(93, 9),
  'Today P&L':    genSparkData(55, 9),
  'Markets Tracked': genSparkData(71, 9),
};

/* ── Helper: P&L badge ── */
function PnlBadge({ cents }) {
  const val = Number(cents || 0);
  const dollars = (val / 100).toFixed(2);
  if (val > 0) return <span className="mono" style={{ color: 'var(--green)', fontWeight: 700 }}>+${dollars}</span>;
  if (val < 0) return <span className="mono" style={{ color: 'var(--red)', fontWeight: 700 }}>-${Math.abs(val / 100).toFixed(2)}</span>;
  return <span className="mono" style={{ color: 'var(--text-muted)' }}>$0.00</span>;
}

/* ── Helper: Win/loss ratio ── */
function WinRate({ wins, losses }) {
  const total = wins + losses;
  if (!total) return <span style={{ color: 'var(--text-muted)' }}>—</span>;
  const pct = (wins / total * 100).toFixed(0);
  const color = pct >= 80 ? 'var(--green)' : pct >= 50 ? 'var(--orange)' : 'var(--red)';
  return <span style={{ color }}>{wins}/{total} ({pct}%)</span>;
}

/* ── Helper: Hold indicator badge ── */
function HoldsIndicator({ wins, losses, pnl }) {
  const total = wins + losses;
  const wr = total > 0 ? wins / total : 0;
  const base = { padding: '2px 8px', borderRadius: 4, fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-body)' };
  if (wr >= 0.90 && pnl > 0) return <span style={{ ...base, background: 'var(--green-dim)', color: 'var(--green)', border: '1px solid rgba(0,195,137,0.25)' }}>ADD MORE</span>;
  if (wr >= 0.65 && pnl > 0) return <span style={{ ...base, background: 'var(--orange-dim)', color: 'var(--orange)', border: '1px solid rgba(247,147,26,0.25)' }}>HOLD</span>;
  if (pnl < 0) return <span style={{ ...base, background: 'var(--red-dim)', color: 'var(--red)', border: '1px solid rgba(255,92,92,0.25)' }}>REDUCE</span>;
  return <span style={{ ...base, background: 'rgba(107,114,128,0.15)', color: 'var(--text-muted)', border: '1px solid var(--border)' }}>WATCH</span>;
}

/* ── Top 3 Best Opportunities ── */
function TopOpportunities({ opportunities }) {
  const ops = opportunities || [];

  if (!ops.length) {
    return (
      <div className="card">
        <div className="section-title" style={{ marginBottom: 8 }}>
          <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
          </svg>
          Best Opportunities Right Now
        </div>
        <p style={{ color: 'var(--text-muted)', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>
          No fresh signals — waiting for next pipeline cycle...
        </p>
      </div>
    );
  }

  const rankStyles = [
    { borderColor: 'rgba(247,147,26,0.35)', background: 'rgba(247,147,26,0.06)', rankColor: 'var(--orange)', rankLabel: '#1' },
    { borderColor: 'rgba(160,160,160,0.25)', background: 'rgba(160,160,160,0.04)', rankColor: 'var(--text-dim)', rankLabel: '#2' },
    { borderColor: 'rgba(180,100,50,0.25)', background: 'rgba(180,100,50,0.04)', rankColor: '#CD7F32', rankLabel: '#3' },
  ];

  return (
    <div className="card" style={{ border: '1px solid rgba(0,240,255,0.15)', background: 'linear-gradient(135deg, rgba(0,240,255,0.03), var(--surface), rgba(0,195,137,0.03))' }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 16 }}>
        <div className="section-title">
          <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
          </svg>
          Best Opportunities Right Now
        </div>
        <span style={{ marginLeft: 'auto', fontSize: 10, color: 'var(--text-muted)', textTransform: 'uppercase', fontWeight: 600, letterSpacing: '0.08em' }}>Live Signals</span>
      </div>

      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {ops.map((o, i) => {
          const rs = rankStyles[i] || rankStyles[2];
          const hasHistory = o.hist_trades > 0;
          const histColor = parseFloat(o.hist_wr) >= 80 ? 'var(--green)' : parseFloat(o.hist_wr) >= 50 ? 'var(--orange)' : 'var(--red)';

          return (
            <div
              key={o.ticker}
              className={i === 0 ? 'breathe-neon' : ''}
              style={{
                borderRadius: 10,
                padding: '14px 16px',
                background: rs.background,
                border: `1px solid ${rs.borderColor}`,
                display: 'flex',
                gap: 14,
                alignItems: 'flex-start',
              }}
            >
              {/* Rank */}
              <div
                style={{
                  width: 28,
                  height: 28,
                  borderRadius: 7,
                  background: `${rs.rankColor}22`,
                  border: `1px solid ${rs.borderColor}`,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                  marginTop: 2,
                }}
              >
                <span style={{ fontSize: 11, fontWeight: 800, color: rs.rankColor, fontFamily: 'var(--font-mono)' }}>{rs.rankLabel}</span>
              </div>

              <div style={{ flex: 1, minWidth: 0 }}>
                <a
                  href={o.url}
                  target="_blank"
                  rel="noopener noreferrer"
                  style={{
                    fontSize: 13,
                    fontWeight: 600,
                    color: 'var(--text)',
                    textDecoration: 'none',
                    display: 'block',
                    marginBottom: 8,
                    overflow: 'hidden',
                    textOverflow: 'ellipsis',
                    whiteSpace: 'nowrap',
                  }}
                  onMouseEnter={e => { e.currentTarget.style.color = 'var(--cyan)'; }}
                  onMouseLeave={e => { e.currentTarget.style.color = 'var(--text)'; }}
                >
                  {o.title}
                </a>

                <div style={{ display: 'flex', flexWrap: 'wrap', alignItems: 'center', gap: 8, marginBottom: 8 }}>
                  <span
                    className="badge"
                    style={o.direction === 'NO'
                      ? { background: 'var(--red-dim)', color: 'var(--red)', border: '1px solid rgba(255,92,92,0.25)' }
                      : { background: 'var(--green-dim)', color: 'var(--green)', border: '1px solid rgba(0,195,137,0.25)' }
                    }
                  >
                    BUY {o.direction}
                  </span>

                  <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
                    Edge: <span className="mono" style={{ color: 'var(--cyan)', fontWeight: 700 }}>{o.edge_pct}%</span>
                  </span>
                  <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
                    Conf: <span style={{ color: 'var(--blue)', fontWeight: 700 }}>{o.confidence}%</span>
                  </span>
                  {o.price_cents > 0 && (
                    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
                      Price: <span className="mono" style={{ color: 'var(--text)' }}>{o.price_cents}c</span>
                    </span>
                  )}
                  {hasHistory && (
                    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>
                      History: <span style={{ fontWeight: 700, color: histColor }}>{o.hist_wr}% WR</span>
                      <span style={{ color: 'var(--text-muted)', marginLeft: 4 }}>({o.hist_trades} trades, {(o.hist_pnl / 100) >= 0 ? '+' : ''}${(o.hist_pnl / 100).toFixed(0)})</span>
                    </span>
                  )}
                  {!hasHistory && <span style={{ fontSize: 11, color: 'var(--text-muted)', fontStyle: 'italic' }}>New market</span>}
                </div>

                <p style={{ fontSize: 11, color: 'var(--text-dim)', lineHeight: 1.5 }}>{o.why}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Strategy Flow Diagram ── */
function StrategyFlowDiagram({ topMarkets, seedMoney, balance }) {
  const best = (topMarkets || []).slice(0, 3);
  if (!best.length) return null;

  const avgWinRate = best.reduce((s, m) => s + m.wins / (m.wins + m.losses), 0) / best.length * 100;
  const avgEntry = best.length > 0 ? Math.round(best.reduce((s, m) => {
    const wr = m.wins / (m.wins + m.losses || 1);
    return s + (wr >= 0.9 ? 95 : 80);
  }, 0) / best.length) : 95;
  const seedDollars = seedMoney ? (seedMoney / 100) : 50000;
  const balDollars = balance ? (balance / 100) : seedDollars;
  const pnlPct = seedDollars > 0 ? ((balDollars - seedDollars) / seedDollars * 100) : 0;

  const steps = [
    {
      icon: (
        <svg style={{ width: 20, height: 20 }} fill="none" stroke="var(--cyan)" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z" />
        </svg>
      ),
      label: `Start: $${seedDollars.toLocaleString()}`,
      sub: `$${balDollars.toLocaleString()} (${pnlPct >= 0 ? '+' : ''}${pnlPct.toFixed(1)}%)`,
      borderColor: 'rgba(0,240,255,0.25)',
      subColor: pnlPct >= 0 ? 'var(--green)' : 'var(--red)',
    },
    {
      icon: (
        <svg style={{ width: 20, height: 20 }} fill="none" stroke="var(--blue)" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M8.111 16.404a5.5 5.5 0 017.778 0M12 20h.01m-7.08-7.071c3.904-3.905 10.236-3.905 14.141 0M1.394 9.393c5.857-5.857 15.355-5.857 21.213 0" />
        </svg>
      ),
      label: 'Signal Found',
      sub: 'AI scans 135 markets',
      borderColor: 'rgba(59,130,246,0.25)',
      subColor: 'var(--text-muted)',
    },
    {
      icon: (
        <svg style={{ width: 20, height: 20 }} fill="none" stroke="var(--orange)" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      label: `Buy NO at ${avgEntry}c`,
      sub: 'High-prob event',
      borderColor: 'rgba(247,147,26,0.25)',
      subColor: 'var(--text-muted)',
    },
    {
      icon: (
        <svg style={{ width: 20, height: 20 }} fill="none" stroke="var(--purple)" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      label: 'Hold 5min-2hr',
      sub: 'TP +3c / SL -5c',
      borderColor: 'rgba(168,85,247,0.25)',
      subColor: 'var(--text-muted)',
    },
    {
      icon: (
        <svg style={{ width: 20, height: 20 }} fill="none" stroke="var(--green)" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
        </svg>
      ),
      label: `Collect ${100 - avgEntry}c`,
      sub: `${avgWinRate.toFixed(0)}% of the time`,
      borderColor: 'rgba(0,195,137,0.25)',
      subColor: 'var(--text-muted)',
    },
  ];

  return (
    <div className="card" style={{ border: '1px solid rgba(0,195,137,0.12)', background: 'linear-gradient(135deg, rgba(0,195,137,0.04), var(--surface), rgba(247,147,26,0.04))' }}>
      <div className="section-title" style={{ marginBottom: 16 }}>
        <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 10V3L4 14h7v7l9-11h-7z" />
        </svg>
        Winning Strategy — Live Flow
      </div>

      <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 18 }}>
        {steps.map((step, i) => (
          <React.Fragment key={i}>
            <div
              style={{
                flex: 1,
                borderRadius: 10,
                padding: '12px 10px',
                background: 'rgba(255,255,255,0.02)',
                border: `1px solid ${step.borderColor}`,
                textAlign: 'center',
              }}
            >
              <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 6 }}>{step.icon}</div>
              <p style={{ fontSize: 11, fontWeight: 600, color: 'var(--text)', marginBottom: 2 }}>{step.label}</p>
              <p style={{ fontSize: 10, color: step.subColor }}>{step.sub}</p>
            </div>
            {i < steps.length - 1 && (
              <svg style={{ width: 14, height: 14, color: 'var(--border-light)', flexShrink: 0 }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
              </svg>
            )}
          </React.Fragment>
        ))}
      </div>

      <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3,1fr)', gap: 10 }}>
        {[
          { label: 'Cost Per Trade', value: `${avgEntry}c`, sub: 'buying NO side', color: 'var(--orange)' },
          { label: 'Profit on Win', value: `${100 - avgEntry}c`, sub: 'per contract', color: 'var(--green)' },
          { label: 'Return Multiple', value: `${((100 - avgEntry) / avgEntry * 100).toFixed(0)}%`, sub: 'per winning trade', color: 'var(--green)' },
        ].map(stat => (
          <div
            key={stat.label}
            style={{
              borderRadius: 8,
              padding: '12px',
              background: 'var(--surface-el)',
              border: '1px solid var(--border)',
              textAlign: 'center',
            }}
          >
            <p className="stat-label" style={{ marginBottom: 4 }}>{stat.label}</p>
            <p className="mono" style={{ fontSize: 20, fontWeight: 700, color: stat.color }}>{stat.value}</p>
            <p style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }}>{stat.sub}</p>
          </div>
        ))}
      </div>
    </div>
  );
}

/* ── Next Actions Panel ── */
function NextActions({ topMarkets, worstMarkets, strategies }) {
  const addMore = (topMarkets || []).filter(m => m.wins / (m.wins + m.losses || 1) >= 0.90 && m.pnl > 0);
  const cutLosses = (worstMarkets || []).filter(m => m.pnl < -5000);
  const disableStrats = (strategies || []).filter(s => s.pnl < -10000 && s.win_rate < 20).slice(0, 3);

  const actions = [];
  if (addMore.length > 0) {
    actions.push({ priority: 'HIGH', color: 'green', iconPath: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6', title: `Double down on ${addMore.length} near-certain markets`, detail: addMore.slice(0, 2).map(m => m.title?.split('?')[0] || m.ticker).join(', '), reason: `${addMore.length} markets have 90%+ win rate — the edge is proven` });
  }
  if (cutLosses.length > 0) {
    actions.push({ priority: 'HIGH', color: 'red', iconPath: 'M18.364 18.364A9 9 0 005.636 5.636m12.728 12.728A9 9 0 015.636 5.636m12.728 12.728L5.636 5.636', title: `Exit ${cutLosses.length} bleeding market(s)`, detail: cutLosses.slice(0, 2).map(m => m.title?.split('?')[0] || m.ticker).join(', '), reason: `0% win rate, losing $${Math.abs(cutLosses.reduce((s, m) => s + m.pnl, 0) / 100).toFixed(0)} total` });
  }
  if (disableStrats.length > 0) {
    actions.push({ priority: 'MED', color: 'orange', iconPath: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z', title: `Consider disabling ${disableStrats.length} strategy(ies)`, detail: disableStrats.map(s => s.name).join(', '), reason: 'Sub-20% win rate — these are coin flips minus fees' });
  }
  actions.push({ priority: 'INFO', color: 'cyan', iconPath: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z', title: 'Keep hyper-trading high-prob NO markets', detail: 'The 95c+ NO strategy is the #1 edge — scale it up', reason: 'Compounding small spreads at 99%+ win rate = consistent returns' });

  const colorMap = {
    green: { bg: 'var(--green-dim)', border: 'rgba(0,195,137,0.2)', text: 'var(--green)', badge: 'rgba(0,195,137,0.2)' },
    red: { bg: 'var(--red-dim)', border: 'rgba(255,92,92,0.2)', text: 'var(--red)', badge: 'rgba(255,92,92,0.2)' },
    orange: { bg: 'var(--orange-dim)', border: 'rgba(247,147,26,0.2)', text: 'var(--orange)', badge: 'rgba(247,147,26,0.2)' },
    cyan: { bg: 'var(--cyan-dim)', border: 'rgba(0,240,255,0.2)', text: 'var(--cyan)', badge: 'rgba(0,240,255,0.2)' },
  };

  return (
    <div className="card" style={{ border: '1px solid rgba(247,147,26,0.12)' }}>
      <div className="section-title" style={{ marginBottom: 14 }}>
        <svg style={{ width: 18, height: 18, color: 'var(--orange)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 12l2 2 4-4M7.835 4.697a3.42 3.42 0 001.946-.806 3.42 3.42 0 014.438 0 3.42 3.42 0 001.946.806 3.42 3.42 0 013.138 3.138 3.42 3.42 0 00.806 1.946 3.42 3.42 0 010 4.438 3.42 3.42 0 00-.806 1.946 3.42 3.42 0 01-3.138 3.138 3.42 3.42 0 00-1.946.806 3.42 3.42 0 01-4.438 0 3.42 3.42 0 00-1.946-.806 3.42 3.42 0 01-3.138-3.138 3.42 3.42 0 00-.806-1.946 3.42 3.42 0 010-4.438 3.42 3.42 0 00.806-1.946 3.42 3.42 0 013.138-3.138z" />
        </svg>
        What To Do Next
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {actions.map((a, i) => {
          const c = colorMap[a.color];
          return (
            <div
              key={i}
              style={{
                borderRadius: 10,
                padding: '12px 14px',
                background: c.bg,
                border: `1px solid ${c.border}`,
                display: 'flex',
                gap: 12,
                alignItems: 'flex-start',
              }}
            >
              <div
                style={{
                  width: 30,
                  height: 30,
                  borderRadius: 8,
                  background: c.badge,
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'center',
                  flexShrink: 0,
                  marginTop: 1,
                }}
              >
                <svg style={{ width: 15, height: 15, color: c.text }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                  <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d={a.iconPath} />
                </svg>
              </div>
              <div style={{ flex: 1 }}>
                <div style={{ display: 'flex', alignItems: 'center', gap: 8, marginBottom: 3 }}>
                  <span
                    className="badge"
                    style={{ background: c.badge, color: c.text, fontSize: 9, padding: '2px 6px' }}
                  >
                    {a.priority}
                  </span>
                  <span style={{ fontSize: 13, fontWeight: 600, color: c.text }}>{a.title}</span>
                </div>
                <p style={{ fontSize: 12, color: 'var(--text-dim)', marginBottom: 2 }}>{a.detail}</p>
                <p style={{ fontSize: 11, color: 'var(--text-muted)' }}>{a.reason}</p>
              </div>
            </div>
          );
        })}
      </div>
    </div>
  );
}

/* ── Strategy P&L Bar Chart ── */
function StrategyBars({ strategies }) {
  const sorted = [...(strategies || [])].sort((a, b) => b.pnl - a.pnl).slice(0, 10);
  if (!sorted.length) return null;
  const barData = sorted.map(s => ({
    name: s.name,
    pnl: s.pnl / 100,
    fill: s.pnl >= 0 ? '#00C389' : '#FF5C5C',
  }));

  return (
    <div className="card">
      <div className="section-title" style={{ marginBottom: 14 }}>
        <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
        </svg>
        Strategy P&L — Top 10
      </div>
      <ResponsiveContainer width="100%" height={250}>
        <BarChart data={barData} layout="vertical" margin={{ left: 70, right: 20 }}>
          <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" horizontal={false} />
          <XAxis type="number" stroke="var(--text-muted)" tick={{ fill: 'var(--text-muted)', fontSize: 11 }} tickFormatter={v => `$${v}`} />
          <YAxis type="category" dataKey="name" stroke="var(--text-muted)" tick={{ fill: 'var(--text-muted)', fontSize: 11 }} width={65} />
          <Tooltip
            contentStyle={{ background: 'var(--surface-el)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text)' }}
            formatter={v => [`$${v.toFixed(2)}`, 'P&L']}
          />
          <Bar dataKey="pnl" radius={[0, 4, 4, 0]}>
            {barData.map((entry, i) => <Cell key={i} fill={entry.fill} />)}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

/* ── Win Rate Donut ── */
function WinRateDonut({ todayWins, todayLosses }) {
  const total = (todayWins || 0) + (todayLosses || 0);
  if (!total) return null;
  const wr = ((todayWins / total) * 100).toFixed(1);
  const data = [
    { name: 'Wins', value: todayWins, fill: '#00C389' },
    { name: 'Losses', value: todayLosses, fill: '#FF5C5C' },
  ];

  return (
    <div className="card" style={{ display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
      <p className="stat-label" style={{ marginBottom: 12 }}>Today's Win Rate</p>
      <div style={{ position: 'relative', width: 140, height: 140 }}>
        <ResponsiveContainer width="100%" height="100%">
          <PieChart>
            <Pie data={data} innerRadius={45} outerRadius={65} paddingAngle={2} dataKey="value" startAngle={90} endAngle={-270}>
              {data.map((entry, i) => <Cell key={i} fill={entry.fill} />)}
            </Pie>
          </PieChart>
        </ResponsiveContainer>
        <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' }}>
          <span className="mono" style={{ fontSize: 22, fontWeight: 700, color: Number(wr) >= 50 ? 'var(--green)' : 'var(--red)' }}>{wr}%</span>
          <span style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 2 }}>{total.toLocaleString()} trades</span>
        </div>
      </div>
      <div style={{ display: 'flex', gap: 16, marginTop: 10 }}>
        <span style={{ fontSize: 12, color: 'var(--green)', fontWeight: 600 }}>{todayWins?.toLocaleString()} W</span>
        <span style={{ fontSize: 12, color: 'var(--red)', fontWeight: 600 }}>{todayLosses?.toLocaleString()} L</span>
      </div>
    </div>
  );
}

/* ── Custom Tooltip: Daily P&L ── */
function DailyPnlTooltip({ active, payload, label }) {
  if (!active || !payload || !payload.length) return null;
  const d = payload[0]?.payload || {};
  return (
    <div style={{
      background: '#1C1C24',
      border: '1px solid #2A2A35',
      borderRadius: 8,
      padding: '10px 14px',
      fontFamily: "'Inter', sans-serif",
      fontSize: 12,
      minWidth: 160,
    }}>
      <p style={{ color: '#6B7280', fontWeight: 600, marginBottom: 6, fontSize: 11 }}>{label}</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
          <span style={{ color: '#6B7280' }}>Daily P&L</span>
          <span className="mono" style={{ color: (d.pnl || 0) >= 0 ? '#00C389' : '#FF5C5C', fontWeight: 700 }}>
            {(d.pnl || 0) >= 0 ? '+' : ''}${((d.pnl || 0) / 100).toFixed(2)}
          </span>
        </div>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
          <span style={{ color: '#6B7280' }}>Cumulative</span>
          <span className="mono" style={{ color: '#00F0FF', fontWeight: 700 }}>
            {(d.cumulative_pnl || 0) >= 0 ? '+' : ''}${((d.cumulative_pnl || 0) / 100).toFixed(2)}
          </span>
        </div>
        {d.trades != null && (
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
            <span style={{ color: '#6B7280' }}>Trades</span>
            <span className="mono" style={{ color: '#E0E0E0' }}>
              {d.wins || 0}W / {(d.trades || 0) - (d.wins || 0)}L
            </span>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Chart 1: Daily P&L Area Chart ── */
function DailyPnlChart({ dailyPnl }) {
  const data = dailyPnl || [];

  if (!data.length) {
    return (
      <div className="card" style={{ borderLeft: '3px solid #00F0FF', paddingLeft: 16 }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 12 }}>
          <h2 className="section-title section-accent-cyan" style={{ borderLeft: 'none', paddingLeft: 0 }}>Portfolio Performance</h2>
        </div>
        <p style={{ color: '#6B7280', fontSize: 13, textAlign: 'center', padding: '48px 0' }}>
          No daily P&L data yet — will appear after trading activity is recorded
        </p>
      </div>
    );
  }

  /* Compute stat pills */
  const bestDay = data.reduce((best, d) => d.pnl > (best?.pnl || -Infinity) ? d : best, data[0]);
  const worstDay = data.reduce((worst, d) => d.pnl < (worst?.pnl || Infinity) ? d : worst, data[0]);
  const latestCumulative = data[data.length - 1]?.cumulative_pnl || 0;
  const firstCumulative = data[0]?.cumulative_pnl || 0;
  const totalReturn = latestCumulative - firstCumulative;
  const isPositive = totalReturn >= 0;

  /* Determine if overall trend is up or down for gradient color */
  const gradientColor = isPositive ? '#00C389' : '#FF5C5C';

  /* Format data for chart */
  const chartData = data.map(d => ({
    ...d,
    label: fmtDateShort(d.date),
    cumDisplay: d.cumulative_pnl / 100,
  }));

  return (
    <div className="card" style={{ borderLeft: '3px solid #00F0FF', paddingLeft: 20 }}>
      {/* Header */}
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
        <h2 className="section-title" style={{ fontSize: '1.1rem' }}>Portfolio Performance</h2>
        {/* Stat pills */}
        <div style={{ display: 'flex', gap: 10 }}>
          <div style={{
            padding: '4px 12px', borderRadius: 20,
            background: isPositive ? 'rgba(0,195,137,0.12)' : 'rgba(255,92,92,0.12)',
            border: `1px solid ${isPositive ? 'rgba(0,195,137,0.3)' : 'rgba(255,92,92,0.3)'}`,
          }}>
            <span style={{ fontSize: 10, color: '#6B7280', marginRight: 6, fontWeight: 600 }}>30d RETURN</span>
            <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: isPositive ? '#00C389' : '#FF5C5C' }}>
              {isPositive ? '+' : ''}${(totalReturn / 100).toFixed(2)}
            </span>
          </div>
          <div style={{
            padding: '4px 12px', borderRadius: 20,
            background: 'rgba(0,195,137,0.08)',
            border: '1px solid rgba(0,195,137,0.2)',
          }}>
            <span style={{ fontSize: 10, color: '#6B7280', marginRight: 6, fontWeight: 600 }}>BEST DAY</span>
            <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: '#00C389' }}>
              +${((bestDay?.pnl || 0) / 100).toFixed(2)}
            </span>
          </div>
          <div style={{
            padding: '4px 12px', borderRadius: 20,
            background: 'rgba(255,92,92,0.08)',
            border: '1px solid rgba(255,92,92,0.2)',
          }}>
            <span style={{ fontSize: 10, color: '#6B7280', marginRight: 6, fontWeight: 600 }}>WORST DAY</span>
            <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: '#FF5C5C' }}>
              ${((worstDay?.pnl || 0) / 100).toFixed(2)}
            </span>
          </div>
        </div>
      </div>

      <ResponsiveContainer width="100%" height={280}>
        <AreaChart data={chartData} margin={{ top: 8, right: 12, left: 0, bottom: 0 }}>
          <defs>
            <linearGradient id="dailyPnlGradPos" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%"  stopColor="#00C389" stopOpacity={0.25} />
              <stop offset="95%" stopColor="#00C389" stopOpacity={0.01} />
            </linearGradient>
            <linearGradient id="dailyPnlGradNeg" x1="0" y1="0" x2="0" y2="1">
              <stop offset="5%"  stopColor="#FF5C5C" stopOpacity={0.22} />
              <stop offset="95%" stopColor="#FF5C5C" stopOpacity={0.01} />
            </linearGradient>
          </defs>
          <CartesianGrid
            strokeDasharray="3 3"
            stroke="#2A2A35"
            strokeOpacity={0.6}
            horizontal={true}
            vertical={false}
          />
          <XAxis
            dataKey="label"
            stroke="#2A2A35"
            tick={{ fill: '#6B7280', fontSize: 11, fontFamily: "'Inter', sans-serif" }}
            tickLine={false}
            axisLine={{ stroke: '#2A2A35' }}
          />
          <YAxis
            stroke="#2A2A35"
            tick={{ fill: '#6B7280', fontSize: 11, fontFamily: "'Inter', sans-serif" }}
            tickLine={false}
            axisLine={false}
            tickFormatter={v => `$${v >= 0 ? '' : ''}${v.toFixed(0)}`}
            width={55}
          />
          <Tooltip content={<DailyPnlTooltip />} />
          <Area
            type="monotone"
            dataKey="cumDisplay"
            name="Cumulative P&L"
            stroke={gradientColor}
            strokeWidth={2}
            fill={`url(#${isPositive ? 'dailyPnlGradPos' : 'dailyPnlGradNeg'})`}
            dot={false}
            activeDot={{
              r: 5,
              fill: '#00F0FF',
              stroke: '#1C1C24',
              strokeWidth: 2,
              filter: 'drop-shadow(0 0 6px rgba(0,240,255,0.8))',
            }}
          />
        </AreaChart>
      </ResponsiveContainer>
    </div>
  );
}

/* ── Custom Tooltip: Strategy Breakdown ── */
function StrategyTooltip({ active, payload, label }) {
  if (!active || !payload || !payload.length) return null;
  const d = payload[0]?.payload || {};
  return (
    <div style={{
      background: '#1C1C24',
      border: '1px solid #2A2A35',
      borderRadius: 8,
      padding: '10px 14px',
      fontFamily: "'Inter', sans-serif",
      fontSize: 12,
      minWidth: 180,
    }}>
      <p style={{ color: '#E0E0E0', fontWeight: 600, marginBottom: 6, fontSize: 12 }}>{d.name}</p>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
          <span style={{ color: '#6B7280' }}>P&L</span>
          <span className="mono" style={{ color: d.pnlRaw >= 0 ? '#00C389' : '#FF5C5C', fontWeight: 700 }}>
            {d.pnlRaw >= 0 ? '+' : ''}${Math.abs(d.pnlRaw).toFixed(2)}
          </span>
        </div>
        {d.trades != null && (
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
            <span style={{ color: '#6B7280' }}>Trades</span>
            <span className="mono" style={{ color: '#E0E0E0' }}>{d.trades}</span>
          </div>
        )}
        {d.win_rate != null && (
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
            <span style={{ color: '#6B7280' }}>Win Rate</span>
            <span className="mono" style={{ color: d.win_rate >= 50 ? '#00C389' : '#FF5C5C' }}>{d.win_rate}%</span>
          </div>
        )}
        {d.avg_edge != null && (
          <div style={{ display: 'flex', justifyContent: 'space-between', gap: 16 }}>
            <span style={{ color: '#6B7280' }}>Avg Edge</span>
            <span className="mono" style={{ color: '#00F0FF' }}>{d.avg_edge}%</span>
          </div>
        )}
      </div>
    </div>
  );
}

/* ── Chart 2: Strategy Performance Horizontal Bar Chart ── */
function StrategyBreakdownChart({ strategies }) {
  const sorted = [...(strategies || [])].sort((a, b) => b.pnl - a.pnl).slice(0, 10);

  if (!sorted.length) {
    return (
      <div className="card">
        <h2 className="section-title" style={{ marginBottom: 12, fontSize: '1.1rem' }}>Strategy Breakdown</h2>
        <p style={{ color: '#6B7280', fontSize: 13, textAlign: 'center', padding: '32px 0' }}>
          No strategy data yet
        </p>
      </div>
    );
  }

  const barData = sorted.map(s => ({
    name: (s.name || s.strategy || 'Unknown').slice(0, 22),
    pnl: Math.abs(s.pnl / 100),
    pnlRaw: s.pnl / 100,
    fill: s.pnl >= 0 ? '#00C389' : '#FF5C5C',
    trades: s.trades,
    win_rate: s.win_rate,
    avg_edge: s.avg_edge,
  }));

  const dynamicHeight = Math.max(220, barData.length * 36);

  return (
    <div className="card">
      <h2 className="section-title" style={{ marginBottom: 16, fontSize: '1.1rem' }}>Strategy Breakdown</h2>
      <ResponsiveContainer width="100%" height={dynamicHeight}>
        <BarChart
          data={barData}
          layout="vertical"
          margin={{ left: 10, right: 24, top: 4, bottom: 4 }}
        >
          <CartesianGrid
            strokeDasharray="3 3"
            stroke="#2A2A35"
            strokeOpacity={0.6}
            horizontal={false}
          />
          <XAxis
            type="number"
            stroke="#2A2A35"
            tick={{ fill: '#6B7280', fontSize: 11, fontFamily: "'Inter', sans-serif" }}
            tickLine={false}
            axisLine={{ stroke: '#2A2A35' }}
            tickFormatter={v => `$${v.toFixed(0)}`}
          />
          <YAxis
            type="category"
            dataKey="name"
            stroke="#2A2A35"
            tick={{ fill: '#A8A8A8', fontSize: 11, fontFamily: "'Inter', sans-serif" }}
            tickLine={false}
            axisLine={false}
            width={130}
          />
          <Tooltip content={<StrategyTooltip />} cursor={{ fill: 'rgba(0,240,255,0.04)' }} />
          <Bar dataKey="pnl" radius={[0, 4, 4, 0]} maxBarSize={22}>
            {barData.map((entry, i) => (
              <Cell key={i} fill={entry.fill} fillOpacity={0.85} />
            ))}
          </Bar>
        </BarChart>
      </ResponsiveContainer>
    </div>
  );
}

/* ── Chart 3: Win Rate Radial Widget ── */
function WinRateRadial({ winRate }) {
  const pct = Math.round((winRate || 0) * 100);
  const color = pct >= 80 ? '#00C389' : pct >= 50 ? '#F7931A' : '#FF5C5C';

  const radialData = [
    { name: 'Win Rate', value: pct, fill: color },
  ];

  return (
    <div className="card" style={{
      display: 'flex',
      flexDirection: 'column',
      alignItems: 'center',
      justifyContent: 'center',
      minHeight: 200,
    }}>
      <p className="stat-label" style={{ marginBottom: 8 }}>Overall Win Rate</p>
      <div style={{ position: 'relative', width: 160, height: 160 }}>
        <ResponsiveContainer width="100%" height="100%">
          <RadialBarChart
            cx="50%"
            cy="50%"
            innerRadius="60%"
            outerRadius="85%"
            startAngle={90}
            endAngle={-270}
            data={radialData}
          >
            {/* Background track */}
            <RadialBar
              background={{ fill: '#2A2A35' }}
              dataKey="value"
              cornerRadius={6}
              fill={color}
            />
          </RadialBarChart>
        </ResponsiveContainer>
        {/* Center text overlay */}
        <div style={{
          position: 'absolute',
          inset: 0,
          display: 'flex',
          flexDirection: 'column',
          alignItems: 'center',
          justifyContent: 'center',
          pointerEvents: 'none',
        }}>
          <span
            className="mono"
            style={{
              fontSize: 28,
              fontWeight: 700,
              color,
              textShadow: `0 0 12px ${color}60`,
              lineHeight: 1,
            }}
          >
            {pct}%
          </span>
          <span style={{ fontSize: 10, color: '#6B7280', marginTop: 4, fontFamily: "'Inter', sans-serif" }}>
            win rate
          </span>
        </div>
      </div>
    </div>
  );
}

/* ══ Strategy Deep Dive Section ══ */
function StrategyDeepDive() {
  const exampleTrades = [
    { id: 1, market: 'NVDA closes above $50 on Mar 2', direction: 'NO @ 95c', entry: '95c', exit: '$1.00', contracts: 200, cost: 190.00, profit: 10.00, roi: '5.26%', holdTime: '47min' },
    { id: 2, market: 'S&P 500 above 4000 on Mar 2', direction: 'NO @ 96c', entry: '96c', exit: '$1.00', contracts: 150, cost: 144.00, profit: 6.00, roi: '4.17%', holdTime: '1h 12min' },
    { id: 3, market: 'BTC above $10K on Mar 2', direction: 'NO @ 97c', entry: '97c', exit: '$1.00', contracts: 300, cost: 291.00, profit: 9.00, roi: '3.09%', holdTime: '23min' },
    { id: 4, market: 'Fed rate cut Mar 2', direction: 'NO @ 94c', entry: '94c', exit: '$1.00', contracts: 250, cost: 235.00, profit: 15.00, roi: '6.38%', holdTime: '1h 45min' },
    { id: 5, market: 'Tesla below $50 on Mar 2', direction: 'NO @ 93c', entry: '93c', exit: '$1.00', contracts: 100, cost: 93.00, profit: 7.00, roi: '7.53%', holdTime: '55min' },
  ];

  const insights = [
    {
      title: 'Mathematical Edge',
      icon: 'M9 7h6m0 10v-3m-3 3h.01M9 17h.01M9 14h.01M12 14h.01M15 11h.01M12 11h.01M9 11h.01M7 21h10a2 2 0 002-2V5a2 2 0 00-2-2H7a2 2 0 00-2 2v14a2 2 0 002 2z',
      color: 'var(--cyan)',
      borderColor: 'rgba(0,240,255,0.2)',
      bgColor: 'rgba(0,240,255,0.05)',
      text: 'Even with occasional losses, a 95% win rate with 5% gains per trade generates massive compound returns. One loss costs 5c, but 19 consecutive wins cover that loss and then some.',
    },
    {
      title: 'Market Inefficiency',
      icon: 'M13 10V3L4 14h7v7l9-11h-7z',
      color: 'var(--orange)',
      borderColor: 'rgba(247,147,26,0.2)',
      bgColor: 'rgba(247,147,26,0.05)',
      text: 'Prediction markets still underprice certainty. Events priced at 95% probability should often be 99%+. This gap between market price and true probability is our edge.',
    },
    {
      title: 'AI Advantage',
      icon: 'M9.75 17L9 20l-1 1h8l-1-1-.75-3M3 13h18M5 17h14a2 2 0 002-2V5a2 2 0 00-2-2H5a2 2 0 00-2 2v10a2 2 0 002 2z',
      color: 'var(--green)',
      borderColor: 'rgba(0,195,137,0.2)',
      bgColor: 'rgba(0,195,137,0.05)',
      text: 'Our AI scans 135+ markets in real-time, finding opportunities humans miss. It evaluates probability, liquidity, and time-to-expiry simultaneously across every active contract.',
    },
    {
      title: 'Time Decay Works For Us',
      icon: 'M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z',
      color: 'var(--purple)',
      borderColor: 'rgba(168,85,247,0.2)',
      bgColor: 'rgba(168,85,247,0.05)',
      text: 'As events approach expiry, NO contracts on events that will not happen converge toward $1.00. Time is our ally. The closer to expiry, the more certain the outcome, the safer the trade.',
    },
    {
      title: 'Scalability',
      icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6',
      color: 'var(--blue)',
      borderColor: 'rgba(59,130,246,0.2)',
      bgColor: 'rgba(59,130,246,0.05)',
      text: 'Strategy works whether trading $100 or $100,000. Kalshi liquidity is sufficient for large positions on high-volume markets. Scale capital, not complexity.',
    },
  ];

  const flowSteps = [
    { label: 'AI Scans 135 Markets', color: 'var(--cyan)', bgColor: 'rgba(0,240,255,0.08)' },
    { label: 'Finds High-Prob NO', color: 'var(--orange)', bgColor: 'rgba(247,147,26,0.08)' },
    { label: 'Buy at 95c', color: 'var(--green)', bgColor: 'rgba(0,195,137,0.08)' },
    { label: 'Hold 5min-2hr', color: 'var(--purple)', bgColor: 'rgba(168,85,247,0.08)' },
    { label: 'Collect 5c Profit', color: 'var(--green)', bgColor: 'rgba(0,195,137,0.12)' },
  ];

  return (
    <div className="strategy-deep-dive">
      {/* Section Header */}
      <div className="sdd-header">
        <div className="sdd-header-line" />
        <div className="sdd-header-content">
          <svg style={{ width: 22, height: 22, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
          </svg>
          <h2 className="heading" style={{ fontSize: 22, fontWeight: 800, color: 'var(--text)' }}>Strategy Deep Dive</h2>
          <svg style={{ width: 22, height: 22, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9.663 17h4.673M12 3v1m6.364 1.636l-.707.707M21 12h-1M4 12H3m3.343-5.657l-.707-.707m2.828 9.9a5 5 0 117.072 0l-.548.547A3.374 3.374 0 0014 18.469V19a2 2 0 11-4 0v-.531c0-.895-.356-1.754-.988-2.386l-.548-.547z" />
          </svg>
        </div>
        <div className="sdd-header-line" />
      </div>

      {/* Section 1: How It Works */}
      <div className="card sdd-section-card" style={{ border: '1px solid rgba(0,240,255,0.15)', background: 'linear-gradient(135deg, rgba(0,240,255,0.03), var(--surface), rgba(0,195,137,0.03))' }}>
        <div className="section-title" style={{ marginBottom: 20 }}>
          <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 10V3L4 14h7v7l9-11h-7z" />
          </svg>
          Winning Strategy — How It Works
        </div>

        {/* Key Points Grid */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 12, marginBottom: 24 }}>
          {[
            { label: 'The Edge', value: 'Buy NO at 95c', sub: 'on near-certain events', color: 'var(--cyan)', glow: true },
            { label: 'The Math', value: '95c in, $1 out', sub: '= 5c profit per contract', color: 'var(--green)', glow: false },
            { label: 'Per-Trade Return', value: '5.26%', sub: 'per winning trade', color: 'var(--green)', glow: true },
            { label: 'Risk Mgmt', value: 'TP +3c / SL -5c', sub: 'early exit if favorable', color: 'var(--orange)', glow: false },
            { label: 'Win Rate', value: '95%+', sub: 'on high-prob events', color: 'var(--cyan)', glow: true },
          ].map(stat => (
            <div
              key={stat.label}
              className={stat.glow ? 'sdd-stat-glow' : ''}
              style={{
                borderRadius: 10,
                padding: '16px 12px',
                background: 'var(--surface-el)',
                border: `1px solid ${stat.color}33`,
                textAlign: 'center',
              }}
            >
              <p className="stat-label" style={{ marginBottom: 6 }}>{stat.label}</p>
              <p className="mono" style={{ fontSize: 16, fontWeight: 700, color: stat.color, lineHeight: 1.2 }}>{stat.value}</p>
              <p style={{ fontSize: 10, color: 'var(--text-muted)', marginTop: 4 }}>{stat.sub}</p>
            </div>
          ))}
        </div>

        {/* Flow Diagram */}
        <div style={{ marginBottom: 16 }}>
          <p className="stat-label" style={{ marginBottom: 12, textAlign: 'center' }}>Trade Flow</p>
          <div className="sdd-flow-row">
            {flowSteps.map((step, i) => (
              <React.Fragment key={i}>
                <div
                  className="sdd-flow-step"
                  style={{
                    background: step.bgColor,
                    border: `1px solid ${step.color}33`,
                  }}
                >
                  <span className="mono" style={{ fontSize: 12, fontWeight: 700, color: step.color, textAlign: 'center' }}>
                    {step.label}
                  </span>
                </div>
                {i < flowSteps.length - 1 && (
                  <div className="sdd-flow-arrow">
                    <svg style={{ width: 16, height: 16, color: 'var(--border-light)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                      <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2.5" d="M9 5l7 7-7 7" />
                    </svg>
                  </div>
                )}
              </React.Fragment>
            ))}
          </div>
        </div>

        {/* Compound Effect Callout */}
        <div
          style={{
            borderRadius: 10,
            padding: '14px 18px',
            background: 'linear-gradient(90deg, rgba(0,195,137,0.08), rgba(0,240,255,0.06))',
            border: '1px solid rgba(0,195,137,0.18)',
            display: 'flex',
            alignItems: 'center',
            gap: 14,
          }}
        >
          <div style={{
            width: 36, height: 36, borderRadius: 10,
            background: 'rgba(0,195,137,0.15)',
            display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
          }}>
            <svg style={{ width: 18, height: 18, color: 'var(--green)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 7h8m0 0v8m0-8l-8 8-4-4-6 6" />
            </svg>
          </div>
          <div>
            <p style={{ fontSize: 13, fontWeight: 600, color: 'var(--green)', marginBottom: 2 }}>Compound Effect</p>
            <p style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.5 }}>
              5% per trade x multiple trades per day = exponential growth. At just 3 trades/day with 95% win rate,
              capital compounds at roughly 14% per week. This is how $60K becomes $221K.
            </p>
          </div>
        </div>
      </div>

      {/* Section 2: Example Trades */}
      <div className="card sdd-section-card" style={{ border: '1px solid rgba(247,147,26,0.15)', background: 'linear-gradient(135deg, rgba(247,147,26,0.03), var(--surface))' }}>
        <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', marginBottom: 16 }}>
          <div className="section-title">
            <svg style={{ width: 18, height: 18, color: 'var(--orange)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            Example Trades
          </div>
          <span className="badge" style={{ background: 'var(--orange-dim)', color: 'var(--orange)', fontSize: 10 }}>ILLUSTRATIVE</span>
        </div>

        <div style={{ overflowX: 'auto' }}>
          <table className="sdd-trades-table">
            <thead>
              <tr>
                <th style={{ width: 32 }}>#</th>
                <th style={{ textAlign: 'left' }}>Market</th>
                <th>Direction</th>
                <th style={{ textAlign: 'right' }}>Entry</th>
                <th style={{ textAlign: 'right' }}>Exit</th>
                <th style={{ textAlign: 'right' }}>Contracts</th>
                <th style={{ textAlign: 'right' }}>Cost</th>
                <th style={{ textAlign: 'right' }}>Profit</th>
                <th style={{ textAlign: 'right' }}>ROI</th>
                <th style={{ textAlign: 'right' }}>Hold Time</th>
              </tr>
            </thead>
            <tbody>
              {exampleTrades.map(t => (
                <tr key={t.id}>
                  <td style={{ textAlign: 'center' }}>
                    <span className="mono" style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t.id}</span>
                  </td>
                  <td style={{ textAlign: 'left', maxWidth: 240 }}>
                    <span style={{ fontSize: 13, color: 'var(--text)', fontWeight: 500 }}>{t.market}</span>
                  </td>
                  <td style={{ textAlign: 'center' }}>
                    <span className="badge" style={{ background: 'var(--red-dim)', color: 'var(--red)', fontSize: 10, border: '1px solid rgba(255,92,92,0.25)' }}>
                      {t.direction}
                    </span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--text-dim)' }}>{t.entry}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--green)' }}>{t.exit}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--text)' }}>{t.contracts}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, color: 'var(--orange)' }}>${t.cost.toFixed(2)}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 13, fontWeight: 700, color: 'var(--green)' }}>+${t.profit.toFixed(2)}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span className="mono" style={{ fontSize: 12, color: 'var(--cyan)', fontWeight: 600 }}>{t.roi}</span>
                  </td>
                  <td style={{ textAlign: 'right' }}>
                    <span style={{ fontSize: 12, color: 'var(--text-muted)' }}>{t.holdTime}</span>
                  </td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>

        {/* Summary Row */}
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 12, marginTop: 16, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
          {[
            { label: 'Total Cost', value: '$953.00', color: 'var(--orange)' },
            { label: 'Total Profit', value: '+$47.00', color: 'var(--green)' },
            { label: 'Avg ROI', value: '5.29%', color: 'var(--cyan)' },
            { label: 'Avg Hold', value: '52min', color: 'var(--purple)' },
          ].map(s => (
            <div key={s.label} style={{ textAlign: 'center' }}>
              <p className="stat-label" style={{ marginBottom: 4 }}>{s.label}</p>
              <p className="mono" style={{ fontSize: 18, fontWeight: 700, color: s.color }}>{s.value}</p>
            </div>
          ))}
        </div>
      </div>

      {/* Section 3: Why This Works Long-Term */}
      <div className="card sdd-section-card" style={{ border: '1px solid rgba(0,195,137,0.15)', background: 'linear-gradient(135deg, rgba(0,195,137,0.03), var(--surface), rgba(168,85,247,0.03))' }}>
        <div className="section-title" style={{ marginBottom: 20 }}>
          <svg style={{ width: 18, height: 18, color: 'var(--green)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 12l2 2 4-4m5.618-4.016A11.955 11.955 0 0112 2.944a11.955 11.955 0 01-8.618 3.04A12.02 12.02 0 003 9c0 5.591 3.824 10.29 9 11.622 5.176-1.332 9-6.03 9-11.622 0-1.042-.133-2.052-.382-3.016z" />
          </svg>
          Why This Works Long-Term
        </div>

        <div className="sdd-insights-grid">
          {insights.map((ins, i) => (
            <div
              key={i}
              className="sdd-insight-card"
              style={{
                border: `1px solid ${ins.borderColor}`,
                background: ins.bgColor,
              }}
            >
              <div style={{ display: 'flex', alignItems: 'center', gap: 10, marginBottom: 10 }}>
                <div style={{
                  width: 32, height: 32, borderRadius: 8,
                  background: `${ins.color}1A`,
                  display: 'flex', alignItems: 'center', justifyContent: 'center', flexShrink: 0,
                }}>
                  <svg style={{ width: 16, height: 16, color: ins.color }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d={ins.icon} />
                  </svg>
                </div>
                <h4 style={{ fontSize: 14, fontWeight: 700, color: ins.color, fontFamily: 'var(--font-heading)' }}>{ins.title}</h4>
              </div>
              <p style={{ fontSize: 12, color: 'var(--text-dim)', lineHeight: 1.6 }}>{ins.text}</p>
            </div>
          ))}
        </div>

        {/* Bottom CTA */}
        <div
          style={{
            marginTop: 20,
            borderRadius: 10,
            padding: '16px 20px',
            background: 'linear-gradient(90deg, rgba(0,240,255,0.06), rgba(247,147,26,0.06))',
            border: '1px solid rgba(0,240,255,0.12)',
            textAlign: 'center',
          }}
        >
          <p style={{ fontSize: 14, fontWeight: 600, color: 'var(--text)', marginBottom: 4 }}>
            The Bottom Line
          </p>
          <p style={{ fontSize: 13, color: 'var(--text-dim)', lineHeight: 1.6, maxWidth: 700, margin: '0 auto' }}>
            This is not gambling. It is systematic, AI-driven arbitrage on prediction market inefficiencies.
            Small, consistent profits compounded over hundreds of trades per week create exponential portfolio growth.
            The math is on our side, and the AI never sleeps.
          </p>
        </div>
      </div>
    </div>
  );
}

/* ══ Animated stat card inner component (uses hooks at top level) ══ */
function AnimatedStatCard({ label, rawValue, displayValue, color, accent, icon, sparkColor, hero }) {
  const animated = useAnimatedValue(typeof rawValue === 'number' ? rawValue : 0);
  const sparkData = SPARK_DATA[label] || SPARK_DATA['Balance'];

  // For numeric stat cards, show animated value; for formatted strings fall back to displayValue
  const shownValue = typeof rawValue === 'number' && rawValue !== 0
    ? (label === 'Balance' || label === 'Today P&L'
        ? `$${(animated / 100).toLocaleString(undefined, { minimumFractionDigits: 2, maximumFractionDigits: 2 })}`
        : Math.round(animated).toLocaleString())
    : displayValue;

  return (
    <div className={`card ${accent}${hero ? ' border-neon-animated' : ''}`} style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
        <span className="stat-label">{label}</span>
        <div
          style={{
            width: 28,
            height: 28,
            borderRadius: 7,
            background: `${color}1A`,
            display: 'flex',
            alignItems: 'center',
            justifyContent: 'center',
          }}
        >
          <svg style={{ width: 14, height: 14, color }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d={icon} />
          </svg>
        </div>
      </div>
      <div style={{ display: 'flex', alignItems: 'flex-end', justifyContent: 'space-between', gap: 8 }}>
        <p className="stat-v mono" style={{ color }}>{shownValue}</p>
        <Sparkline
          data={sparkData}
          color={sparkColor || color}
          width={60}
          height={22}
          id={label.replace(/\s+/g, '-').toLowerCase()}
        />
      </div>
    </div>
  );
}

/* ══ Main Dashboard ══ */
/* ── Collapsible Section Wrapper ── */
function CollapsibleSection({ title, defaultOpen = true, children }) {
  const key = `ken-sec-${title.toLowerCase().replace(/[^a-z0-9]/g, '-')}`;
  const [open, setOpen] = useState(() => {
    try { return localStorage.getItem(key) !== 'false'; } catch { return defaultOpen; }
  });
  const toggle = () => setOpen(v => {
    const next = !v;
    try { localStorage.setItem(key, String(next)); } catch {}
    return next;
  });
  return (
    <div>
      <button
        onClick={toggle}
        style={{
          display: 'flex', alignItems: 'center', gap: 8,
          padding: '2px 0 8px', width: '100%',
          background: 'transparent', border: 'none', cursor: 'pointer',
        }}
        onMouseEnter={e => { e.currentTarget.style.opacity = '0.7'; }}
        onMouseLeave={e => { e.currentTarget.style.opacity = '1'; }}
      >
        <svg
          style={{
            width: 12, height: 12, color: 'var(--text-muted)', flexShrink: 0,
            transition: 'transform 220ms ease',
            transform: open ? 'rotate(0deg)' : 'rotate(-90deg)',
          }}
          fill="none" stroke="currentColor" viewBox="0 0 24 24"
        >
          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 9l-7 7-7-7" />
        </svg>
        <span style={{
          fontSize: 10, fontWeight: 700, fontFamily: 'var(--font-body)',
          color: 'var(--text-muted)', textTransform: 'uppercase', letterSpacing: '0.1em',
        }}>
          {title}
        </span>
      </button>
      <div style={{
        maxHeight: open ? '3500px' : 0,
        overflow: 'hidden',
        opacity: open ? 1 : 0,
        transition: 'max-height 0.4s cubic-bezier(0.4,0,0.2,1), opacity 0.3s ease',
      }}>
        {children}
      </div>
    </div>
  );
}

export default function Dashboard() {
  const [data, setData] = useState(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    loadDashboard();
    const i = setInterval(loadDashboard, 30000);
    return () => clearInterval(i);
  }, []);

  async function loadDashboard() {
    try {
      const r = await api('/dashboard');
      setData(r);
    } catch {}
    setLoading(false);
  }

  if (loading) {
    return (
      <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', height: 256 }}>
        <div
          className="w-8 h-8 rounded-full border-2 border-t-transparent animate-spin"
          style={{ borderColor: 'var(--cyan)', borderTopColor: 'transparent' }}
        />
      </div>
    );
  }

  const d = data || {};
  const pnlData = (d.pnl_history || []).map((p, i) => ({ day: i + 1, pnl: p }));
  const todayWinRate = d.today_trades > 0 ? (d.today_wins / d.today_trades * 100).toFixed(1) : '0';
  const topStrats = (d.strategies || []).filter(s => s.pnl > 0).slice(0, 5);
  const worstStrats = (d.strategies || []).filter(s => s.pnl < 0).slice(-5).reverse();

  const statCards = [
    {
      label: 'Balance',
      rawValue: d.balance || 0,
      displayValue: d.balance ? `$${(d.balance / 100).toLocaleString(undefined, { minimumFractionDigits: 2 })}` : '—',
      color: 'var(--green)',
      sparkColor: 'var(--green)',
      accent: 'card-accent-green',
      icon: 'M3 10h18M7 15h1m4 0h1m-7 4h12a3 3 0 003-3V8a3 3 0 00-3-3H6a3 3 0 00-3 3v8a3 3 0 003 3z',
    },
    {
      label: 'Positions',
      rawValue: d.position_count || 0,
      displayValue: d.position_count ?? '—',
      color: 'var(--orange)',
      sparkColor: 'var(--orange)',
      accent: 'card-accent-orange',
      icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z',
    },
    {
      label: 'Open Markets',
      rawValue: d.open_orders || 0,
      displayValue: d.open_orders ?? '—',
      color: 'var(--blue)',
      sparkColor: 'var(--cyan)',
      accent: 'card-accent-blue',
      icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6',
    },
    {
      label: 'Today P&L',
      rawValue: d.daily_pnl || 0,
      displayValue: d.daily_pnl ? `$${(d.daily_pnl / 100).toLocaleString(undefined, { minimumFractionDigits: 2 })}` : '$0.00',
      color: (d.daily_pnl || 0) >= 0 ? 'var(--green)' : 'var(--red)',
      sparkColor: (d.daily_pnl || 0) >= 0 ? 'var(--green)' : 'var(--red)',
      accent: (d.daily_pnl || 0) >= 0 ? 'card-accent-green' : 'card-accent-red',
      icon: 'M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z',
    },
    {
      label: 'Markets Tracked',
      rawValue: d.markets_tracked || 0,
      displayValue: d.markets_tracked ?? '—',
      color: 'var(--purple)',
      sparkColor: 'var(--purple)',
      accent: 'card-accent-purple',
      icon: 'M21 12a9 9 0 01-9 9m9-9a9 9 0 00-9-9m9 9H3m9 9a9 9 0 01-9-9m9 9c1.657 0 3-4.03 3-9s-1.343-9-3-9m0 18c-1.657 0-3-4.03-3-9s1.343-9 3-9m-9 9a9 9 0 019-9',
    },
  ];

  return (
    <div className="fade-in" style={{ display: 'flex', flexDirection: 'column', gap: 24 }}>

      {/* ── Page Header ── */}
      <div style={{ display: 'flex', alignItems: 'flex-start', justifyContent: 'space-between' }}>
        <div>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 4 }}>
            <h1 className="heading" style={{ fontSize: 26, fontWeight: 800, color: 'var(--text)', letterSpacing: '-0.025em' }}>
              Dashboard
            </h1>
            <span className="live-indicator">
              <span className="live-dot" />
              LIVE
            </span>
          </div>
          <p className="section-subtitle">Ken event contracts overview</p>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span
            className="badge"
            style={d.env === 'prod'
              ? { background: 'var(--green-dim)', color: 'var(--green)' }
              : { background: 'var(--orange-dim)', color: 'var(--orange)' }
            }
          >
            {(d.env || 'DEMO').toUpperCase()}
          </span>
          {d.safe_mode && (
            <span className="badge" style={{ background: 'var(--orange-dim)', color: 'var(--orange)' }}>
              SAFE MODE
            </span>
          )}
        </div>
      </div>

      {/* ── 5 Stat Cards with Sparklines + Animated Values ── */}
      <CollapsibleSection title="Overview">
        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(5,1fr)', gap: 14 }}>
          {statCards.map((s, i) => (
            <AnimatedStatCard key={s.label} {...s} hero={i === 0} />
          ))}
        </div>
      </CollapsibleSection>

      {/* ── Chart 1: Daily P&L Area Chart (Portfolio Performance) ── */}
      <CollapsibleSection title="Portfolio Performance">
        <DailyPnlChart dailyPnl={d.daily_pnl_history || d.dailyPnl || []} />
      </CollapsibleSection>

      {/* ── Charts 2+3: Strategy Breakdown + Win Rate Radial ── */}
      <CollapsibleSection title="Strategy Breakdown">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
          <StrategyBreakdownChart strategies={d.strategies} />
          <WinRateRadial winRate={d.win_rate || (d.today_trades > 0 ? d.today_wins / d.today_trades : 0)} />
        </div>
      </CollapsibleSection>

      {/* ── Capital & Economics ── */}
      {d.seed_money > 0 && (
        <CollapsibleSection title="Capital & Economics">
        <div
          className="card"
          style={{
            border: '1px solid rgba(59,130,246,0.18)',
            background: 'linear-gradient(135deg, rgba(59,130,246,0.04), var(--surface), rgba(0,195,137,0.04))',
          }}
        >
          <div className="section-title" style={{ marginBottom: 16 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M12 8c-1.657 0-3 .895-3 2s1.343 2 3 2 3 .895 3 2-1.343 2-3 2m0-8c1.11 0 2.08.402 2.599 1M12 8V7m0 1v8m0 0v1m0-1c-1.11 0-2.08-.402-2.599-1M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
            </svg>
            Capital & Economics
          </div>

          <div style={{ display: 'grid', gridTemplateColumns: 'repeat(6,1fr)', gap: 12, textAlign: 'center' }}>
            {[
              { label: 'Seed Money', value: `$${(d.seed_money / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: `${d.num_portfolios} portfolios`, color: 'var(--blue)' },
              { label: 'Current Balance', value: `$${(d.balance / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: 'all portfolios', color: 'var(--green)' },
              { label: 'Net P&L', value: `${d.net_pnl_from_seed >= 0 ? '+' : ''}$${(d.net_pnl_from_seed / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: `${d.roi_pct >= 0 ? '+' : ''}${d.roi_pct}% ROI`, color: d.net_pnl_from_seed >= 0 ? 'var(--green)' : 'var(--red)', subColor: d.roi_pct >= 0 ? 'var(--green)' : 'var(--red)' },
              { label: 'Capital Deployed', value: `$${(d.total_invested / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: 'total traded', color: 'var(--orange)' },
              { label: 'Capital at Risk', value: `$${(d.capital_at_risk / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: 'open positions', color: 'var(--red)' },
              { label: 'Daily Budget', value: `$${(d.daily_budget / 100).toLocaleString(undefined, { minimumFractionDigits: 0 })}`, sub: 'across strategies', color: 'var(--purple)' },
            ].map(stat => (
              <div key={stat.label}>
                <p className="stat-label" style={{ marginBottom: 6 }}>{stat.label}</p>
                <p className="mono" style={{ fontSize: 18, fontWeight: 700, color: stat.color }}>{stat.value}</p>
                <p style={{ fontSize: 10, color: stat.subColor || 'var(--text-muted)', marginTop: 2 }}>{stat.sub}</p>
              </div>
            ))}
          </div>

          {/* Daily Breakdown — 7-day grid */}
          {d.daily_economics?.length > 0 && (
            <div style={{ marginTop: 18, paddingTop: 14, borderTop: '1px solid var(--border)' }}>
              <p className="stat-label" style={{ marginBottom: 10 }}>Daily Breakdown (Last 7 Days)</p>
              <div style={{ display: 'grid', gridTemplateColumns: 'repeat(7,1fr)', gap: 8 }}>
                {(d.daily_economics || []).slice(0, 7).reverse().map((e, i) => {
                  const dayLabel = new Date(e.day).toLocaleDateString('en-US', { weekday: 'short', month: 'numeric', day: 'numeric', timeZone: 'America/Los_Angeles' });
                  const isPositive = e.net_pnl >= 0;
                  return (
                    <div
                      key={i}
                      style={{
                        borderRadius: 8,
                        padding: '10px 8px',
                        background: isPositive ? 'rgba(0,195,137,0.06)' : 'rgba(255,92,92,0.06)',
                        border: `1px solid ${isPositive ? 'rgba(0,195,137,0.18)' : 'rgba(255,92,92,0.18)'}`,
                        textAlign: 'center',
                      }}
                    >
                      <p style={{ fontSize: 10, color: 'var(--text-muted)', fontWeight: 600, marginBottom: 4 }}>{dayLabel}</p>
                      <p className="mono" style={{ fontSize: 13, fontWeight: 700, color: isPositive ? 'var(--green)' : 'var(--red)', marginBottom: 3 }}>
                        {isPositive ? '+' : ''}${(e.net_pnl / 100).toFixed(0)}
                      </p>
                      <p style={{ fontSize: 10, color: 'var(--text-muted)', marginBottom: 2 }}>{e.trades} trades</p>
                      <p style={{ fontSize: 10, color: 'var(--text-muted)' }}>
                        <span style={{ color: 'var(--green)' }}>{e.wins}W</span>
                        {' / '}
                        <span style={{ color: 'var(--red)' }}>{e.losses}L</span>
                      </p>
                    </div>
                  );
                })}
              </div>
            </div>
          )}
        </div>
        </CollapsibleSection>
      )}

      {/* ── Best Opportunities ── */}
      <CollapsibleSection title="Best Opportunities">
        <TopOpportunities opportunities={d.top_opportunities} />
      </CollapsibleSection>

      {/* ── Today's Lessons ── */}
      <CollapsibleSection title="Today's Performance">
      <div
        className="card"
        style={{
          border: '1px solid rgba(247,147,26,0.18)',
          background: 'linear-gradient(135deg, rgba(247,147,26,0.04), var(--surface))',
        }}
      >
        <div style={{ display: 'flex', alignItems: 'center', marginBottom: 14 }}>
          <div className="section-title">
            <svg style={{ width: 18, height: 18, color: 'var(--orange)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z" />
            </svg>
            Today's Lessons
          </div>
          <span style={{ marginLeft: 'auto', fontSize: 12, color: 'var(--text-muted)' }}>
            {new Date().toLocaleDateString('en-US', { weekday: 'long', month: 'short', day: 'numeric' })}
          </span>
        </div>

        <div style={{ display: 'grid', gridTemplateColumns: 'repeat(4,1fr)', gap: 16, textAlign: 'center' }}>
          {[
            { label: 'Trades Resolved', value: (d.today_trades || 0).toLocaleString(), color: 'var(--orange)' },
            {
              label: 'Wins / Losses',
              value: (
                <span>
                  <span style={{ color: 'var(--green)' }}>{d.today_wins || 0}</span>
                  <span style={{ color: 'var(--border-light)', margin: '0 4px' }}>/</span>
                  <span style={{ color: 'var(--red)' }}>{d.today_losses || 0}</span>
                </span>
              ),
              color: null,
            },
            { label: 'Win Rate', value: `${todayWinRate}%`, color: Number(todayWinRate) >= 50 ? 'var(--green)' : 'var(--red)' },
            {
              label: 'Day P&L',
              value: `${(d.daily_pnl || 0) >= 0 ? '+' : ''}$${((d.daily_pnl || 0) / 100).toLocaleString(undefined, { minimumFractionDigits: 2 })}`,
              color: (d.daily_pnl || 0) >= 0 ? 'var(--green)' : 'var(--red)',
            },
          ].map((s, i) => (
            <div key={i}>
              <p className="stat-label" style={{ marginBottom: 6 }}>{s.label}</p>
              {typeof s.value === 'string' ? (
                <p className="mono" style={{ fontSize: 22, fontWeight: 700, color: s.color }}>{s.value}</p>
              ) : (
                <p className="mono" style={{ fontSize: 22, fontWeight: 700 }}>{s.value}</p>
              )}
            </div>
          ))}
        </div>
      </div>
      </CollapsibleSection>

      {/* ── Strategy Flow + Win Rate Donut ── */}
      <CollapsibleSection title="Strategy Flow">
        <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 16 }}>
          <StrategyFlowDiagram topMarkets={d.top_markets} seedMoney={d.seed_money} balance={d.balance} />
          <WinRateDonut todayWins={d.today_wins} todayLosses={d.today_losses} />
        </div>
      </CollapsibleSection>

      {/* ── What To Do Next ── */}
      <CollapsibleSection title="Action Plan">
        <NextActions topMarkets={d.top_markets} worstMarkets={d.worst_markets} strategies={d.strategies} />
      </CollapsibleSection>

      {/* ── Top Markets Table ── */}
      {(d.top_markets || []).length > 0 && (
        <CollapsibleSection title="Top Markets">
        <div className="card">
          <div className="section-title" style={{ marginBottom: 14 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--green)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M5 3l14 9-14 9V3z" />
            </svg>
            Top Markets — Money Makers
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table>
              <thead>
                <tr>
                  <th style={{ textAlign: 'left' }}>Market</th>
                  <th style={{ textAlign: 'right' }}>Trades</th>
                  <th style={{ textAlign: 'right' }}>Wins</th>
                  <th style={{ textAlign: 'right' }}>P&L</th>
                  <th>Edge</th>
                  <th>Signal</th>
                </tr>
              </thead>
              <tbody>
                {(d.top_markets || []).map((m, i) => (
                  <tr key={i}>
                    <td style={{ maxWidth: 300 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <Link
                          to={`/positions?market=${encodeURIComponent(m.ticker)}`}
                          style={{
                            fontSize: 13,
                            color: 'var(--text)',
                            textDecoration: 'none',
                            display: 'block',
                            overflow: 'hidden',
                            textOverflow: 'ellipsis',
                            whiteSpace: 'nowrap',
                            transition: 'color 150ms',
                          }}
                          onMouseEnter={e => { e.currentTarget.style.color = 'var(--cyan)'; }}
                          onMouseLeave={e => { e.currentTarget.style.color = 'var(--text)'; }}
                        >
                          {m.title}
                        </Link>
                        <a
                          href={`https://kalshi.com/search?query=${encodeURIComponent(m.title?.split('?')[0] || m.ticker)}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{ color: 'var(--text-muted)', flexShrink: 0, textDecoration: 'none', fontSize: 13 }}
                          onMouseEnter={e => { e.currentTarget.style.color = 'var(--cyan)'; }}
                          onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-muted)'; }}
                          title="View on Kalshi"
                        >
                          ↗
                        </a>
                      </div>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{m.ticker}</span>
                    </td>
                    <td style={{ textAlign: 'right' }} className="mono"><span style={{ fontSize: 13, color: 'var(--text-dim)' }}>{m.trades}</span></td>
                    <td style={{ textAlign: 'right', fontSize: 13 }}><WinRate wins={m.wins} losses={m.losses} /></td>
                    <td style={{ textAlign: 'right', fontSize: 13 }}><PnlBadge cents={m.pnl} /></td>
                    <td style={{ fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{m.edge}</td>
                    <td style={{ textAlign: 'center' }}><HoldsIndicator wins={m.wins} losses={m.losses} pnl={m.pnl} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        </CollapsibleSection>
      )}

      {/* ── Worst Markets Table ── */}
      {(d.worst_markets || []).length > 0 && (
        <CollapsibleSection title="Bleeding Markets">
        <div className="card" style={{ border: '1px solid rgba(255,92,92,0.12)' }}>
          <div className="section-title" style={{ marginBottom: 14, color: 'var(--red)' }}>
            <svg style={{ width: 18, height: 18 }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M12 9v2m0 4h.01m-6.938 4h13.856c1.54 0 2.502-1.667 1.732-3L13.732 4c-.77-1.333-2.694-1.333-3.464 0L3.34 16c-.77 1.333.192 3 1.732 3z" />
            </svg>
            Bleeding Markets — Consider Exiting
          </div>
          <div style={{ overflowX: 'auto' }}>
            <table>
              <thead>
                <tr>
                  <th style={{ textAlign: 'left' }}>Market</th>
                  <th style={{ textAlign: 'right' }}>Trades</th>
                  <th style={{ textAlign: 'right' }}>Wins</th>
                  <th style={{ textAlign: 'right' }}>P&L</th>
                  <th>Edge</th>
                  <th>Signal</th>
                </tr>
              </thead>
              <tbody>
                {(d.worst_markets || []).map((m, i) => (
                  <tr key={i}>
                    <td style={{ maxWidth: 300 }}>
                      <div style={{ display: 'flex', alignItems: 'center', gap: 4 }}>
                        <Link
                          to={`/positions?market=${encodeURIComponent(m.ticker)}`}
                          style={{ fontSize: 13, color: 'var(--text)', textDecoration: 'none', display: 'block', overflow: 'hidden', textOverflow: 'ellipsis', whiteSpace: 'nowrap', transition: 'color 150ms' }}
                          onMouseEnter={e => { e.currentTarget.style.color = 'var(--red)'; }}
                          onMouseLeave={e => { e.currentTarget.style.color = 'var(--text)'; }}
                        >
                          {m.title}
                        </Link>
                        <a
                          href={`https://kalshi.com/search?query=${encodeURIComponent(m.title?.split('?')[0] || m.ticker)}`}
                          target="_blank"
                          rel="noopener noreferrer"
                          style={{ color: 'var(--text-muted)', flexShrink: 0, textDecoration: 'none', fontSize: 13 }}
                          onMouseEnter={e => { e.currentTarget.style.color = 'var(--red)'; }}
                          onMouseLeave={e => { e.currentTarget.style.color = 'var(--text-muted)'; }}
                          title="View on Kalshi"
                        >
                          ↗
                        </a>
                      </div>
                      <span className="mono" style={{ fontSize: 10, color: 'var(--text-muted)' }}>{m.ticker}</span>
                    </td>
                    <td style={{ textAlign: 'right' }} className="mono"><span style={{ fontSize: 13, color: 'var(--text-dim)' }}>{m.trades}</span></td>
                    <td style={{ textAlign: 'right', fontSize: 13 }}><WinRate wins={m.wins} losses={m.losses} /></td>
                    <td style={{ textAlign: 'right', fontSize: 13 }}><PnlBadge cents={m.pnl} /></td>
                    <td style={{ fontSize: 12, color: 'var(--text-muted)', whiteSpace: 'nowrap' }}>{m.edge}</td>
                    <td style={{ textAlign: 'center' }}><HoldsIndicator wins={m.wins} losses={m.losses} pnl={m.pnl} /></td>
                  </tr>
                ))}
              </tbody>
            </table>
          </div>
        </div>
        </CollapsibleSection>
      )}

      {/* ── P&L History Chart ── */}
      {pnlData.length > 0 && (
        <CollapsibleSection title="P&L History">
        <div className="card">
          <div className="section-title" style={{ marginBottom: 14 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M7 12l3-3 3 3 4-4M8 21l4-4 4 4M3 4h18M4 4h16v12a1 1 0 01-1 1H5a1 1 0 01-1-1V4z" />
            </svg>
            P&L History (Daily)
          </div>
          <ResponsiveContainer width="100%" height={200}>
            <AreaChart data={pnlData}>
              <defs>
                <linearGradient id="pnlGrad" x1="0" y1="0" x2="0" y2="1">
                  <stop offset="5%" stopColor="#00F0FF" stopOpacity={0.2} />
                  <stop offset="95%" stopColor="#00F0FF" stopOpacity={0} />
                </linearGradient>
              </defs>
              <CartesianGrid strokeDasharray="3 3" stroke="var(--border)" />
              <XAxis dataKey="day" stroke="var(--text-muted)" tick={{ fill: 'var(--text-muted)', fontSize: 11 }} />
              <YAxis stroke="var(--text-muted)" tick={{ fill: 'var(--text-muted)', fontSize: 11 }} tickFormatter={v => `$${v}`} />
              <Tooltip
                contentStyle={{ background: 'var(--surface-el)', border: '1px solid var(--border)', borderRadius: 8, color: 'var(--text)' }}
              />
              <Area type="monotone" dataKey="pnl" stroke="var(--cyan)" strokeWidth={2} fill="url(#pnlGrad)" />
            </AreaChart>
          </ResponsiveContainer>
        </div>
        </CollapsibleSection>
      )}

      {/* ── Strategy P&L Bar Chart ── */}
      <CollapsibleSection title="Strategy P&L">
        <StrategyBars strategies={d.strategies} />
      </CollapsibleSection>

      {/* ── Strategy Leaderboard ── */}
      <CollapsibleSection title="Strategy Leaderboard">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Top Strategies */}
        <div className="card">
          <div className="section-title" style={{ marginBottom: 12 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--green)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M5 3l14 9-14 9V3z" />
            </svg>
            Top Strategies
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {topStrats.map((s, i) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '8px 0',
                  borderBottom: i < topStrats.length - 1 ? '1px solid var(--border)' : 'none',
                }}
              >
                <div>
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)' }}>{s.name}</span>
                  <span style={{ marginLeft: 8, fontSize: 10, color: 'var(--text-muted)' }}>{s.strategy}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{s.win_rate}% WR</span>
                  <PnlBadge cents={s.pnl} />
                </div>
              </div>
            ))}
            {topStrats.length === 0 && (
              <p style={{ color: 'var(--text-muted)', fontSize: 13, textAlign: 'center', padding: '16px 0' }}>No profitable strategies yet</p>
            )}
          </div>
        </div>

        {/* Worst Strategies */}
        <div className="card">
          <div className="section-title" style={{ marginBottom: 12 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--red)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 17h8m0 0V9m0 8l-8-8-4 4-6-6" />
            </svg>
            Losing Strategies
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 4 }}>
            {worstStrats.map((s, i) => (
              <div
                key={i}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  justifyContent: 'space-between',
                  padding: '8px 0',
                  borderBottom: i < worstStrats.length - 1 ? '1px solid var(--border)' : 'none',
                }}
              >
                <div>
                  <span style={{ fontSize: 13, fontWeight: 500, color: 'var(--text-dim)' }}>{s.name}</span>
                  <span style={{ marginLeft: 8, fontSize: 10, color: 'var(--text-muted)' }}>{s.strategy}</span>
                </div>
                <div style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ fontSize: 11, color: 'var(--text-muted)' }}>{s.win_rate}% WR</span>
                  <PnlBadge cents={s.pnl} />
                </div>
              </div>
            ))}
            {worstStrats.length === 0 && (
              <p style={{ color: 'var(--text-muted)', fontSize: 13, textAlign: 'center', padding: '16px 0' }}>No losing strategies</p>
            )}
          </div>
        </div>
      </div>
      </CollapsibleSection>

      {/* ── Strategy Deep Dive ── */}
      <CollapsibleSection title="Strategy Deep Dive" defaultOpen={false}>
        <StrategyDeepDive />
      </CollapsibleSection>

      {/* ── Recent Fills + Quick Actions ── */}
      <CollapsibleSection title="Recent Activity">
      <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
        {/* Recent Fills */}
        <div className="card">
          <div className="section-title" style={{ marginBottom: 12 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
            </svg>
            Recent Fills
          </div>
          {(d.recent_fills || []).length > 0 ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
              {(d.recent_fills || []).slice(0, 5).map((f, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', justifyContent: 'space-between', fontSize: 13 }}>
                  <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
                    <span className="mono" style={{ fontSize: 11, color: 'var(--text-muted)' }}>{f.ticker}</span>
                    <span
                      className="badge"
                      style={f.side === 'yes'
                        ? { background: 'var(--green-dim)', color: 'var(--green)' }
                        : { background: 'var(--red-dim)', color: 'var(--red)' }
                      }
                    >
                      {f.side?.toUpperCase()}
                    </span>
                  </div>
                  <span className="mono" style={{ color: 'var(--text-dim)', fontSize: 12 }}>{f.count}@{f.yes_price}c</span>
                </div>
              ))}
            </div>
          ) : (
            <p style={{ color: 'var(--text-muted)', fontSize: 13, textAlign: 'center', padding: '24px 0' }}>No recent fills</p>
          )}
        </div>

        {/* Quick Actions */}
        <div className="card">
          <div className="section-title" style={{ marginBottom: 12 }}>
            <svg style={{ width: 18, height: 18, color: 'var(--cyan)' }} fill="none" stroke="currentColor" viewBox="0 0 24 24">
              <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="1.8" d="M13 10V3L4 14h7v7l9-11h-7z" />
            </svg>
            Quick Actions
          </div>
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {[
              { to: '/markets', icon: 'M13 7h8m0 0v8m0-8l-8 8-4-4-6 6', iconColor: 'var(--orange)', label: 'Browse Markets', sub: 'Find weather contracts' },
              { to: '/positions', icon: 'M9 19v-6a2 2 0 00-2-2H5a2 2 0 00-2 2v6a2 2 0 002 2h2a2 2 0 002-2zm0 0V9a2 2 0 012-2h2a2 2 0 012 2v10m-6 0a2 2 0 002 2h2a2 2 0 002-2m0 0V5a2 2 0 012-2h2a2 2 0 012 2v14a2 2 0 01-2 2h-2a2 2 0 01-2-2z', iconColor: 'var(--green)', label: 'View Positions', sub: 'Current portfolio' },
              { to: '/settings', icon: 'M10.325 4.317c.426-1.756 2.924-1.756 3.35 0a1.724 1.724 0 002.573 1.066c1.543-.94 3.31.826 2.37 2.37a1.724 1.724 0 001.066 2.573c1.756.426 1.756 2.924 0 3.35a1.724 1.724 0 00-1.066 2.573c.94 1.543-.826 3.31-2.37 2.37a1.724 1.724 0 00-2.573 1.066c-.426 1.756-2.924 1.756-3.35 0a1.724 1.724 0 00-2.573-1.066c-1.543.94-3.31-.826-2.37-2.37a1.724 1.724 0 00-1.066-2.573c-1.756-.426-1.756-2.924 0-3.35a1.724 1.724 0 001.066-2.573c-.94-1.543.826-3.31 2.37-2.37.996.608 2.296.07 2.572-1.065z M15 12a3 3 0 11-6 0 3 3 0 016 0z', iconColor: 'var(--blue)', label: 'Scan Config', sub: 'Intervals & risk params' },
            ].map(action => (
              <Link
                key={action.to}
                to={action.to}
                style={{
                  display: 'flex',
                  alignItems: 'center',
                  gap: 12,
                  padding: '10px 12px',
                  borderRadius: 8,
                  background: 'var(--surface-el)',
                  border: '1px solid var(--border)',
                  textDecoration: 'none',
                  transition: 'all 150ms ease',
                }}
                onMouseEnter={e => { e.currentTarget.style.borderColor = 'var(--cyan)'; e.currentTarget.style.background = 'rgba(0,240,255,0.04)'; }}
                onMouseLeave={e => { e.currentTarget.style.borderColor = 'var(--border)'; e.currentTarget.style.background = 'var(--surface-el)'; }}
              >
                <div
                  style={{
                    width: 32,
                    height: 32,
                    borderRadius: 8,
                    background: `${action.iconColor}1A`,
                    display: 'flex',
                    alignItems: 'center',
                    justifyContent: 'center',
                    flexShrink: 0,
                  }}
                >
                  <svg style={{ width: 15, height: 15, color: action.iconColor }} fill="none" stroke="currentColor" strokeWidth="1.8" viewBox="0 0 24 24">
                    <path strokeLinecap="round" strokeLinejoin="round" d={action.icon} />
                  </svg>
                </div>
                <div>
                  <p style={{ fontSize: 13, fontWeight: 500, color: 'var(--text)', marginBottom: 1 }}>{action.label}</p>
                  <p style={{ fontSize: 11, color: 'var(--text-muted)' }}>{action.sub}</p>
                </div>
              </Link>
            ))}
          </div>
        </div>
      </div>
      </CollapsibleSection>
    </div>
  );
}