// Tempo — pro dashboard widgets (replacements for Tempo Score)
// Focus: actionable charts that drive decisions

// ─── R-multiple distribution histogram ────────────────────────────
function RDistribution() {
  // Bucketed R-multiples from sample trades
  const buckets = [
    { r: '< -2R',   n: 3,  pnl: -480 },
    { r: '-2 / -1', n: 11, pnl: -820 },
    { r: '-1 / 0',  n: 22, pnl: -360 },
    { r: '0 / 1',   n: 38, pnl: 1240 },
    { r: '1 / 2',   n: 41, pnl: 2680 },
    { r: '2 / 3',   n: 18, pnl: 1980 },
    { r: '> 3R',    n: 9,  pnl: 1640 },
  ];
  const max = Math.max(...buckets.map(b => b.n));
  const [hover, setHover] = React.useState(4);
  const tone = (i) => i < 3 ? 'red' : 'green';
  const sel = buckets[hover];
  return (
    <div className="card lift" style={{ padding: '18px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-.01em' }}>Distribution R-multiple</span>
        <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>142 trades · R moyen <span className="pos" style={{ fontWeight: 600 }}>+0,84</span></span>
      </div>
      <p style={{ fontSize: 11, color: 'var(--fg-3)', margin: '4px 0 14px' }}>Combien de fois tu gagnes/perds chaque multiple de risque</p>

      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 4, height: 130 }}>
        {buckets.map((b, i) => {
          const isHov = hover === i;
          const h = (b.n / max) * 100;
          const color = tone(i) === 'red' ? 'var(--red)' : 'var(--green)';
          return (
            <button key={b.r}
              onMouseEnter={() => setHover(i)}
              className="tap"
              style={{
                flex: 1, height: '100%',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end',
                background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit',
              }}>
              <span className="mono" style={{ fontSize: 10, color: isHov ? color : 'var(--fg-3)', marginBottom: 4, fontWeight: 600 }}>{b.n}</span>
              <div style={{
                width: '100%', height: `${h}%`,
                background: color,
                opacity: isHov ? 1 : .72,
                borderRadius: 5,
                animation: `bar-grow .55s var(--ease) ${.15 + i * .04}s backwards`,
                transformOrigin: `bottom`, transition: 'opacity .15s var(--ease)',
              }}></div>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 4, marginTop: 8 }}>
        {buckets.map((b, i) => (
          <span key={b.r} className="mono" style={{ flex: 1, fontSize: 10, textAlign: 'center', color: hover === i ? 'var(--fg)' : 'var(--fg-3)', fontWeight: hover === i ? 600 : 500 }}>{b.r}</span>
        ))}
      </div>

      {/* Hover detail */}
      <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: 'repeat(4, 1fr)', gap: 14 }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Bucket</div>
          <div className="mono" style={{ fontSize: 14, fontWeight: 600 }}>{sel.r}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Trades</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{sel.n}</div>
        </div>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>P&L net</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600, color: sel.pnl >= 0 ? 'var(--green)' : 'var(--red)' }}>
            {sel.pnl >= 0 ? '+$' : '−$'}{Math.abs(sel.pnl).toLocaleString('fr-FR')}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Part</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{Math.round((sel.n / buckets.reduce((s, b) => s + b.n, 0)) * 100)}%</div>
        </div>
      </div>
    </div>
  );
}

// ─── Hour-of-day heatmap ──────────────────────────────────────────
function HourHeatmap() {
  // P&L by hour over 30 days (Paris time)
  const hours = [
    null, null, null, null, null, null, null, null,
    -40, 120, 480, 320, 180, -120, 920, 740, 560, 280, -60, 80, null, null, null, null,
  ];
  const trades = [
    0, 0, 0, 0, 0, 0, 0, 0,
    2, 4, 8, 7, 5, 4, 14, 12, 10, 6, 3, 2, 0, 0, 0, 0,
  ];
  const max = Math.max(...hours.filter(v => v != null).map(Math.abs));
  const [hover, setHover] = React.useState(14);

  return (
    <div className="card lift" style={{ padding: '18px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start', marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-.01em' }}>Heures rentables</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>Quand tu trades le mieux · 30 derniers jours</div>
        </div>
        <div style={{ textAlign: 'right' }}>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Top heure</div>
          <div style={{ fontSize: 13, fontWeight: 600 }}>14h–15h <span className="pos num" style={{ marginLeft: 6 }}>+$920</span></div>
        </div>
      </div>

      {/* Session bands */}
      <div style={{ display: 'flex', gap: 1, height: 5, marginBottom: 4 }}>
        {Array.from({ length: 24 }).map((_, i) => {
          const inNY = i >= 14 && i < 17;
          const inPre = i >= 8 && i < 10;
          const inLdn = i >= 9 && i < 18 && !(i >= 14 && i < 17);
          return <div key={i} style={{ flex: 1, background: inNY ? 'rgba(59,130,246,0.20)' : (inPre ? 'rgba(59,130,246,0.10)' : (inLdn ? 'rgba(59,130,246,0.06)' : 'transparent')) }}></div>;
        })}
      </div>

      {/* Heatmap cells */}
      <div style={{ display: 'flex', gap: 2, height: 56 }}>
        {hours.map((v, i) => {
          const intensity = v == null ? 0 : Math.abs(v) / max;
          const tone = v == null ? 'none' : (v > 0 ? 'pos' : 'neg');
          const bg =
            tone === 'pos' ? `rgba(22,163,74, ${0.10 + intensity * 0.65})` :
            tone === 'neg' ? `rgba(239,68,68, ${0.10 + intensity * 0.65})` :
            'var(--bg-elev)';
          const isHov = hover === i;
          return (
            <button key={i}
              onMouseEnter={() => setHover(i)}
              className="tap"
              style={{
                flex: 1, background: bg, borderRadius: 5,
                border: '1.5px solid ' + (isHov ? 'var(--fg)' : 'transparent'),
                cursor: 'pointer',
                transition: 'border-color .15s var(--ease), transform .15s var(--ease)',
                transform: isHov ? 'scaleY(1.05)' : 'scaleY(1)',
                transformOrigin: 'bottom',
                position: 'relative',
                display: 'flex', alignItems: 'flex-end', justifyContent: 'center',
                padding: '0 0 5px', fontFamily: 'inherit',
              }}>
              {v != null && trades[i] >= 5 && <div style={{ width: 3, height: 3, borderRadius: '50%', background: '#fff', opacity: .85 }}></div>}
            </button>
          );
        })}
      </div>

      {/* Hour axis */}
      <div style={{ display: 'flex', gap: 2, marginTop: 6 }}>
        {Array.from({ length: 24 }).map((_, i) => (
          <div key={i} className="mono" style={{ flex: 1, textAlign: 'center', fontSize: 9, color: 'var(--fg-4)', fontWeight: 500 }}>
            {i % 3 === 0 ? String(i).padStart(2, '0') : ''}
          </div>
        ))}
      </div>

      {/* Hover detail */}
      <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 14 }}>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Heure</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{String(hover).padStart(2, '0')}h–{String((hover + 1) % 24).padStart(2, '0')}h</div>
        </div>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Net</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600, color: hours[hover] == null ? 'var(--fg-3)' : (hours[hover] > 0 ? 'var(--green)' : 'var(--red)') }}>
            {hours[hover] == null ? '—' : (hours[hover] > 0 ? '+$' : '−$') + Math.abs(hours[hover])}
          </div>
        </div>
        <div>
          <div style={{ fontSize: 10, fontWeight: 600, color: 'var(--fg-3)', letterSpacing: '.04em', textTransform: 'uppercase', marginBottom: 4 }}>Volume</div>
          <div className="num" style={{ fontSize: 16, fontWeight: 600 }}>{trades[hover]} trades</div>
        </div>
      </div>
    </div>
  );
}

// ─── Day of week performance ──────────────────────────────────────
function DayOfWeekPerf() {
  const days = [
    { d: 'Lun', pnl: 1240, n: 32, w: 22 },
    { d: 'Mar', pnl: 920,  n: 28, w: 19 },
    { d: 'Mer', pnl: 1680, n: 35, w: 24 },
    { d: 'Jeu', pnl: 720,  n: 26, w: 16 },
    { d: 'Ven', pnl: -280, n: 21, w: 9 },
  ];
  const max = Math.max(...days.map(d => Math.abs(d.pnl)));
  const [hover, setHover] = React.useState(2);
  const sel = days[hover];
  return (
    <div className="card lift" style={{ padding: '18px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 4 }}>
        <span style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-.01em' }}>Performance par jour</span>
        <span style={{ fontSize: 11, color: 'var(--fg-3)' }}>Mercredi = ton meilleur jour</span>
      </div>
      <p style={{ fontSize: 11, color: 'var(--fg-3)', margin: '4px 0 14px' }}>Cumulé sur les 90 derniers jours</p>

      <div style={{ display: 'flex', alignItems: 'flex-end', gap: 8, height: 120 }}>
        {days.map((d, i) => {
          const isHov = hover === i;
          const h = (Math.abs(d.pnl) / max) * 100;
          const tone = d.pnl >= 0 ? 'pos' : 'neg';
          const color = tone === 'pos' ? 'var(--green)' : 'var(--red)';
          return (
            <button key={d.d}
              onMouseEnter={() => setHover(i)}
              className="tap"
              style={{
                flex: 1, height: '100%',
                display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'flex-end',
                background: 'transparent', border: 'none', cursor: 'pointer', padding: 0, fontFamily: 'inherit',
              }}>
              <span className="mono" style={{ fontSize: 11, color: isHov ? color : 'var(--fg-3)', marginBottom: 5, fontWeight: 600 }}>
                {d.pnl >= 0 ? '+$' : '−$'}{Math.abs(d.pnl) >= 1000 ? (Math.abs(d.pnl) / 1000).toFixed(1).replace('.', ',') + 'k' : Math.abs(d.pnl)}
              </span>
              <div style={{
                width: '100%', height: `${h}%`,
                background: color,
                opacity: isHov ? 1 : .76,
                borderRadius: 6,
                animation: `bar-grow .55s var(--ease) ${.15 + i * .06}s backwards`,
                transformOrigin: 'bottom', transition: 'opacity .15s var(--ease)',
              }}></div>
            </button>
          );
        })}
      </div>
      <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
        {days.map((d, i) => (
          <span key={d.d} style={{ flex: 1, fontSize: 11, textAlign: 'center', color: hover === i ? 'var(--fg)' : 'var(--fg-3)', fontWeight: hover === i ? 600 : 500, letterSpacing: '-.005em' }}>{d.d}</span>
        ))}
      </div>

      <div style={{ marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--line)', display: 'flex', justifyContent: 'space-between' }}>
        <div>
          <div style={{ fontSize: 11.5, color: 'var(--fg-3)' }}>{sel.d}édi · {sel.n} trades · {Math.round((sel.w / sel.n) * 100)}% W</div>
        </div>
        <div className="num" style={{ fontSize: 16, fontWeight: 600, color: sel.pnl >= 0 ? 'var(--green)' : 'var(--red)', letterSpacing: '-.018em' }}>
          {sel.pnl >= 0 ? '+$' : '−$'}{Math.abs(sel.pnl).toLocaleString('fr-FR')}
        </div>
      </div>
    </div>
  );
}

// ─── Setup performance — bars + perf ──────────────────────────────
function SetupPerformanceCard() {
  const setups = [
    { name: 'Breakout VWAP',  n: 42, win: 0.71, pnl: 2840, exp: 138 },
    { name: 'News Fade',      n: 16, win: 0.68, pnl: 720,  exp: 95  },
    { name: 'Pullback Trend', n: 18, win: 0.61, pnl: 540,  exp: 58  },
    { name: 'Range Asie',     n: 24, win: 0.54, pnl: 480,  exp: 42  },
    { name: 'Reversal Open',  n: 28, win: 0.57, pnl: 920,  exp: 64  },
    { name: 'Open Reversal',  n: 14, win: 0.43, pnl: -220, exp: -28 },
  ];
  const maxAbs = Math.max(...setups.map(s => Math.abs(s.pnl)));
  const [hover, setHover] = React.useState(null);
  return (
    <div className="card lift" style={{ padding: '18px 20px' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 14 }}>
        <div>
          <div style={{ fontSize: 13, fontWeight: 600, letterSpacing: '-.01em' }}>Performance par setup</div>
          <div style={{ fontSize: 11, color: 'var(--fg-3)', marginTop: 4 }}>Quel playbook te rapporte vraiment · 30j</div>
        </div>
        <button className="btn tap" style={{ fontSize: 11.5, padding: '5px 10px' }}>Tous →</button>
      </div>
      {setups.map((s, i) => {
        const pct = Math.abs(s.pnl) / maxAbs;
        const isHover = hover === i;
        const tone = s.pnl >= 0 ? 'pos' : 'neg';
        return (
          <div key={s.name}
            onMouseEnter={() => setHover(i)} onMouseLeave={() => setHover(null)}
            style={{
              padding: '10px 0', borderTop: i ? '1px solid var(--line)' : 'none',
              cursor: 'pointer',
              transition: 'background .15s var(--ease)',
              background: isHover ? 'var(--bg-soft)' : 'transparent',
              borderRadius: 6, marginInline: -8, paddingInline: 8,
            }}>
            <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 6 }}>
              <span style={{ fontSize: 12.5, fontWeight: 500, letterSpacing: '-.005em' }}>{s.name}</span>
              <span className="num" style={{ fontSize: 13.5, fontWeight: 600, color: tone === 'pos' ? 'var(--green)' : 'var(--red)' }}>
                {s.pnl >= 0 ? '+$' : '−$'}{Math.abs(s.pnl).toLocaleString('fr-FR')}
              </span>
            </div>
            <div style={{ height: 3, background: 'var(--bg-elev)', borderRadius: 2, overflow: 'hidden' }}>
              <div style={{
                height: '100%', width: `${pct * 100}%`,
                background: tone === 'pos' ? 'var(--green)' : 'var(--red)',
                opacity: isHover ? 1 : .76,
                borderRadius: 2,
                animation: `draw .8s var(--ease) ${.15 + i * .05}s backwards`,
              }}></div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-between', marginTop: 5 }}>
              <span style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>{s.n} trades · {Math.round(s.win * 100)}% win</span>
              <span style={{ fontSize: 10.5, color: 'var(--fg-3)' }}>Exp <span style={{ color: s.exp >= 0 ? 'var(--green)' : 'var(--red)', fontWeight: 600 }}>{s.exp >= 0 ? '+' : '−'}${Math.abs(s.exp)}</span></span>
            </div>
          </div>
        );
      })}
    </div>
  );
}

Object.assign(window, { RDistribution, HourHeatmap, DayOfWeekPerf, SetupPerformanceCard });
