/* Nexus Signals — Track Record (real Chart.js).
   Full-width cumulative paper-PnL timeline with a regression trendline, plus a
   win/loss doughnut and a wins-by-week bar chart. Brand-matched (Trust Blue /
   Soft Blue / Cool Gray, JetBrains Mono ticks), built when scrolled into view. */
const NSC = window.NexusSignalsDesignSystem_a2976e;

function cssVar(n) { return getComputedStyle(document.documentElement).getPropertyValue(n).trim(); }

function useChart(makeConfig, deps) {
  const ref = React.useRef(null);
  const chartRef = React.useRef(null);
  const builtRef = React.useRef(false);
  React.useEffect(() => {
    const el = ref.current;
    if (!el || typeof Chart === 'undefined') return;
    const build = () => {
      if (builtRef.current) return;
      builtRef.current = true;
      chartRef.current = new Chart(el.getContext('2d'), makeConfig());
    };
    let io;
    if ('IntersectionObserver' in window) {
      io = new IntersectionObserver((entries) => {
        entries.forEach((e) => { if (e.isIntersecting) { build(); io.disconnect(); } });
      }, { threshold: 0.2 });
      io.observe(el);
    }
    const fb = setTimeout(build, 1600); // always render even if IO never fires
    return () => { if (io) io.disconnect(); clearTimeout(fb); if (chartRef.current) chartRef.current.destroy(); };
  }, []);
  return ref;
}

/* shared brand styling for Chart.js */
function brandFont() { return { family: "'JetBrains Mono', monospace", size: 10 }; }
function tooltipStyle() {
  return { backgroundColor: '#0b1018', borderColor: 'rgba(120,173,255,0.4)', borderWidth: 1, padding: 10,
    titleColor: '#B7C1D5', bodyColor: '#F8F6EF', displayColors: false, titleFont: brandFont(), bodyFont: { family: "'JetBrains Mono', monospace", size: 12 } };
}

// 30-day calendar of cumulative paper PnL ($k) with realistic drawdowns
const PNL = [0,2.1,3.4,2.9,5.2,7.8,7.1,9.6,12.3,11.4,14.8,17.2,16.1,19.7,23.4,22.1,25.8,29.3,27.6,31.9,35.2,38.7,36.4,41.8,45.3,44.1,48.9,52.6,56.2,61.4];
function dateLabels() {
  const out = []; const start = new Date(2026, 4, 21); // calendar timeline
  for (let i = 0; i < PNL.length; i++) { const d = new Date(start); d.setDate(start.getDate() + i); out.push(d.toLocaleDateString('en-US', { month: 'short', day: 'numeric' })); }
  return out;
}
function trendline(data) { // least-squares regression -> straight trend
  const n = data.length; let sx = 0, sy = 0, sxy = 0, sxx = 0;
  data.forEach((y, x) => { sx += x; sy += y; sxy += x * y; sxx += x * x; });
  const m = (n * sxy - sx * sy) / (n * sxx - sx * sx); const b = (sy - m * sx) / n;
  return data.map((_, x) => Math.round((m * x + b) * 10) / 10);
}

function PnlChart() {
  const ref = useChart(() => {
    const trust = cssVar('--ns-trust') || '#4D83FF';
    const soft = cssVar('--ns-soft') || '#78ADFF';
    const gray = cssVar('--ns-gray') || '#B7C1D5';
    return {
      type: 'line',
      data: { labels: dateLabels(), datasets: [
        { label: 'Cumulative paper PnL', data: PNL, borderColor: trust, borderWidth: 2.5, fill: true, tension: 0.4,
          pointRadius: 0, pointHoverRadius: 5, pointHoverBackgroundColor: '#fff', pointHoverBorderColor: trust,
          backgroundColor: (ctx) => { const { ctx: c, chartArea } = ctx.chart; if (!chartArea) return 'rgba(77,131,255,0.12)';
            const g = c.createLinearGradient(0, chartArea.top, 0, chartArea.bottom);
            g.addColorStop(0, 'rgba(77,131,255,0.34)'); g.addColorStop(1, 'rgba(77,131,255,0)'); return g; } },
        { label: 'Trend', data: trendline(PNL), borderColor: gray, borderWidth: 1.5, borderDash: [6, 6], fill: false, tension: 0, pointRadius: 0, pointHoverRadius: 0 },
      ] },
      options: {
        responsive: true, maintainAspectRatio: false,
        animation: { duration: 1500, easing: 'easeOutQuart' },
        interaction: { mode: 'index', intersect: false },
        plugins: {
          title: { display: true, text: '30-day paper PnL — every logged signal, drawdowns and all', color: '#F8F6EF', align: 'start', font: { family: "'Space Grotesk', sans-serif", size: 15, weight: '600' }, padding: { bottom: 4 } },
          subtitle: { display: true, text: 'Cumulative $ across all tracked wallets · dashed line = trend', color: '#B7C1D5', align: 'start', font: { family: "'Inter', sans-serif", size: 12 }, padding: { bottom: 16 } },
          legend: { display: true, align: 'end', labels: { color: '#B7C1D5', boxWidth: 12, boxHeight: 12, usePointStyle: true, pointStyle: 'rectRounded', font: { family: "'Inter', sans-serif", size: 12 } } },
          tooltip: { ...tooltipStyle(), callbacks: { label: (it) => it.dataset.label + '  ' + (it.parsed.y >= 0 ? '+' : '') + '$' + it.parsed.y.toFixed(1) + 'k' } },
        },
        scales: {
          x: { grid: { display: false }, ticks: { color: 'rgba(183,193,213,0.55)', font: brandFont(), maxTicksLimit: 8, maxRotation: 0 }, border: { color: 'rgba(120,173,255,0.16)' } },
          y: { grid: { color: 'rgba(120,173,255,0.08)' }, ticks: { color: 'rgba(183,193,213,0.55)', font: brandFont(), callback: (v) => '$' + v + 'k' }, border: { display: false } },
        },
      },
    };
  });
  return <canvas ref={ref}></canvas>;
}

function WinChart() {
  const ref = useChart(() => {
    const soft = cssVar('--ns-soft') || '#78ADFF';
    return {
      type: 'doughnut',
      data: { labels: ['Wins', 'Losses'], datasets: [{ data: [62.4, 37.6], backgroundColor: [soft, 'rgba(183,193,213,0.22)'], borderColor: '#0b1018', borderWidth: 3, cutout: '74%' }] },
      options: { responsive: true, maintainAspectRatio: false, animation: { animateRotate: true, duration: 1400, easing: 'easeOutQuart' },
        plugins: { legend: { display: false }, tooltip: { ...tooltipStyle(), callbacks: { label: (it) => it.label + '  ' + it.parsed + '%' } } } },
    };
  });
  return <canvas ref={ref}></canvas>;
}

function WeeklyChart() {
  const ref = useChart(() => {
    const trust = cssVar('--ns-trust') || '#4D83FF';
    const gray = 'rgba(183,193,213,0.30)';
    return {
      type: 'bar',
      data: { labels: ['Wk 1', 'Wk 2', 'Wk 3', 'Wk 4'], datasets: [
        { label: 'Wins', data: [34, 39, 36, 39], backgroundColor: trust, borderRadius: 4, stack: 's' },
        { label: 'Losses', data: [22, 20, 24, 23], backgroundColor: gray, borderRadius: 4, stack: 's' },
      ] },
      options: { responsive: true, maintainAspectRatio: false, animation: { duration: 1300, easing: 'easeOutQuart' },
        plugins: { legend: { display: true, labels: { color: '#B7C1D5', boxWidth: 12, boxHeight: 12, usePointStyle: true, pointStyle: 'rectRounded', font: { family: "'Inter', sans-serif", size: 11 } } },
          tooltip: { ...tooltipStyle(), callbacks: { label: (it) => it.dataset.label + '  ' + it.parsed.y } } },
        scales: {
          x: { stacked: true, grid: { display: false }, ticks: { color: 'rgba(183,193,213,0.55)', font: brandFont() }, border: { color: 'rgba(120,173,255,0.16)' } },
          y: { stacked: true, grid: { color: 'rgba(120,173,255,0.08)' }, ticks: { color: 'rgba(183,193,213,0.55)', font: brandFont() }, border: { display: false } },
        } },
    };
  });
  return <canvas ref={ref}></canvas>;
}

function TrackRecord() {
  const { GlassPanel } = NSC;
  return (
    <section id="track-record" style={{ paddingTop: 'var(--section-pad-y)', paddingBottom: 'var(--section-pad-y)', position: 'relative', zIndex: 1 }}>
      <div className="ns-container">
        <window.SectionHead eyebrow="The receipts · 30-day paper record" title="Up and to the right — with the dips left in" sub="Here's the full paper track record across every logged signal. We don't airbrush the drawdowns; the honest line is the whole point." />

        {/* full-width PnL timeline */}
        <GlassPanel padding="22px 22px 18px" data-anim="reveal" style={{ marginTop: '32px' }}>
          <div style={{ position: 'relative', height: 'clamp(280px, 38vw, 420px)' }}><PnlChart /></div>
        </GlassPanel>

        {/* supporting charts */}
        <div className="track-grid" data-anim="stagger" style={{ marginTop: '18px' }}>
          <GlassPanel padding="22px" style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '15px', color: 'var(--text-primary)', marginBottom: '4px' }}>Win / loss split</span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: '12px', color: 'var(--text-muted)', marginBottom: '14px' }}>Last 30 days · 237 signals logged</span>
            <div style={{ position: 'relative', height: '190px' }}>
              <WinChart />
              <div style={{ position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', pointerEvents: 'none' }}>
                <span style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: '30px', color: 'var(--text-primary)', lineHeight: 1 }}>62.4%</span>
                <span style={{ fontFamily: 'var(--font-body)', fontSize: '11px', color: 'var(--text-muted)', marginTop: '4px' }}>win rate</span>
              </div>
            </div>
            <div style={{ display: 'flex', justifyContent: 'space-around', marginTop: '14px', paddingTop: '14px', borderTop: '1px solid var(--border-subtle)' }}>
              <div style={{ textAlign: 'center' }}><div style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: '18px', color: 'var(--ns-soft)' }}>148</div><div style={{ fontFamily: 'var(--font-body)', fontSize: '11px', color: 'var(--text-muted)' }}>wins</div></div>
              <div style={{ textAlign: 'center' }}><div style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: '18px', color: 'var(--text-muted)' }}>89</div><div style={{ fontFamily: 'var(--font-body)', fontSize: '11px', color: 'var(--text-muted)' }}>losses</div></div>
              <div style={{ textAlign: 'center' }}><div style={{ fontFamily: 'var(--font-mono)', fontWeight: 700, fontSize: '18px', color: 'var(--text-primary)' }}>237</div><div style={{ fontFamily: 'var(--font-body)', fontSize: '11px', color: 'var(--text-muted)' }}>logged</div></div>
            </div>
          </GlassPanel>

          <GlassPanel padding="22px" style={{ display: 'flex', flexDirection: 'column' }}>
            <span style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '15px', color: 'var(--text-primary)', marginBottom: '4px' }}>Signals by week</span>
            <span style={{ fontFamily: 'var(--font-body)', fontSize: '12px', color: 'var(--text-muted)', marginBottom: '14px' }}>Wins and losses, side by side</span>
            <div style={{ position: 'relative', height: '232px' }}><WeeklyChart /></div>
          </GlassPanel>
        </div>

        <p style={{ fontFamily: 'var(--font-mono)', fontSize: '11px', color: 'var(--text-muted)', letterSpacing: '0.04em', marginTop: '18px', textAlign: 'center' }}>
          Illustrative paper results for research and education. Past performance is not indicative of future results. Not financial advice.
        </p>
      </div>
    </section>
  );
}

Object.assign(window, { TrackRecord });
