// fc-compare.jsx — "This week vs your usual" cumulative comparison chart.
//
// Apple Health "by this time of day" style applied to the cut: a BOLD cumulative
// line for the live week vs a FAINT average-week line, a NOW marker with a dot on
// each line, a colored-dot two-stat callout, and a plain-language verdict headline.
// New chart TYPE for OnWeight — weekly cut pace, not the long camp trajectory.
// Drives off the same pace states, so "faster than usual" reads amber (over-cutting
// is a problem, not a win).

const WD = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun'];

function _cr(pts, k = 0.5) {
  if (pts.length < 2) return '';
  let d = `M ${pts[0][0].toFixed(2)} ${pts[0][1].toFixed(2)}`;
  for (let i = 0; i < pts.length - 1; i++) {
    const p0 = pts[Math.max(0, i - 1)], p1 = pts[i], p2 = pts[i + 1], p3 = pts[Math.min(pts.length - 1, i + 2)];
    const c1x = p1[0] + (p2[0] - p0[0]) * k / 3, c1y = p1[1] + (p2[1] - p0[1]) * k / 3;
    const c2x = p2[0] - (p3[0] - p1[0]) * k / 3, c2y = p2[1] - (p3[1] - p1[1]) * k / 3;
    d += ` C ${c1x.toFixed(2)} ${c1y.toFixed(2)}, ${c2x.toFixed(2)} ${c2y.toFixed(2)}, ${p2[0].toFixed(2)} ${p2[1].toFixed(2)}`;
  }
  return d;
}

const NOW_DOW = 4;           // today = Thursday (4 days into the week)
const AVG_WEEKLY = 0.62;     // the athlete's usual weekly cut (kg)

function weekCompare(paceKey) {
  const state = window.PACE_STATES[paceKey] || window.PACE_STATES.onTrack;
  const thisVel = Math.abs(state.weeklyVel);
  const days = 7;
  const avg = [];
  for (let d = 0; d <= days; d++) avg.push([d, AVG_WEEKLY * (d / days)]);
  const noise = [1.18, 0.78, 1.22, 0.84, 1.1, 0.92, 1.02];
  const per = thisVel / days;
  const today = [[0, 0]];
  let c = 0;
  for (let d = 1; d <= NOW_DOW; d++) { c += per * noise[(d - 1) % noise.length]; today.push([d, +c.toFixed(3)]); }
  return { today, avg, days, thisNow: today[today.length - 1][1], avgNow: AVG_WEEKLY * (NOW_DOW / days) };
}

const COMPARE_COPY = {
  onTrack:  { tone: 'green', head: 'You’re cutting right around your usual pace this week.' },
  tooFast:  { tone: 'amber', head: 'You’re cutting faster this week than you usually do by Thursday.' },
  trailing: { tone: 'amber', head: 'You’re a little behind your usual pace this week.' },
  danger:   { tone: 'red',   head: 'You’re well behind your usual pace this week.' },
};
const _toneColor = (t) => t === 'red' ? 'var(--t-red)' : t === 'amber' ? 'var(--mustard-deep)' : 'var(--t-green)';

function FCWeekCompareChart({ paceKey = 'onTrack', width = 360, height = 184 }) {
  const d = weekCompare(paceKey);
  const tone = (COMPARE_COPY[paceKey] || COMPARE_COPY.onTrack).tone;
  const toneColor = _toneColor(tone);
  const avgColor = 'var(--rule-2)';
  const W = width, H = height, padL = 6, padR = 6, padT = 12, padB = 26;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const maxY = (Math.max(d.avg[d.days][1], ...d.today.map(p => p[1])) || 1) * 1.2;
  const xS = (day) => padL + (day / d.days) * innerW;
  const yS = (v) => padT + (1 - v / maxY) * innerH;
  const baseY = padT + innerH;

  const avgPts = d.avg.map(p => [xS(p[0]), yS(p[1])]);
  const todayPts = d.today.map(p => [xS(p[0]), yS(p[1])]);
  const nowX = xS(NOW_DOW);
  const nowYToday = yS(d.thisNow), nowYAvg = yS(d.avgNow);
  const uid = React.useId().replace(/:/g, '');
  let len = 0;
  for (let i = 1; i < todayPts.length; i++) len += Math.hypot(todayPts[i][0] - todayPts[i - 1][0], todayPts[i][1] - todayPts[i - 1][1]) * 1.05;

  return (
    <svg width={W} height={H} viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', overflow: 'visible', shapeRendering: 'geometricPrecision' }} role="img"
      aria-label={`This week versus usual cut pace. Down ${d.thisNow.toFixed(1)} kg this week versus ${d.avgNow.toFixed(1)} kg on an average week by Thursday.`}>
      <defs>
        <style>{`@keyframes wk-${uid}{from{stroke-dashoffset:${len.toFixed(0)}}to{stroke-dashoffset:0}}.wkl-${uid}{stroke-dasharray:${len.toFixed(0)};animation:wk-${uid} 950ms cubic-bezier(.65,.05,.36,1) 120ms}@media (prefers-reduced-motion:reduce){.wkl-${uid}{animation:none}}`}</style>
      </defs>

      {/* dotted baseline axis */}
      <line x1={padL} x2={W - padR} y1={baseY} y2={baseY} stroke="var(--rule-2)" strokeWidth="1" strokeDasharray="0.5 4" strokeLinecap="round" opacity="0.7" />
      {/* weekday ticks */}
      {WD.map((_, i) => (
        <line key={i} x1={xS(i)} x2={xS(i)} y1={baseY} y2={baseY + 3.5} stroke="var(--rule-2)" strokeWidth="1" opacity="0.6" />
      ))}

      {/* NOW marker */}
      <line x1={nowX} x2={nowX} y1={padT - 2} y2={baseY} stroke="var(--rule-2)" strokeWidth="1" opacity="0.8" />

      {/* average week — faint, smooth, full width */}
      <path d={_cr(avgPts, 0.6)} fill="none" stroke={avgColor} strokeWidth="3" strokeLinecap="round" strokeLinejoin="round" opacity="0.55" />

      {/* this week — bold tone line to now */}
      <path className={`wkl-${uid}`} d={'M ' + todayPts.map(p => `${p[0].toFixed(2)} ${p[1].toFixed(2)}`).join(' L ')} fill="none" stroke={toneColor} strokeWidth="3.4" strokeLinejoin="round" strokeLinecap="round" />

      {/* dots at the NOW marker */}
      <circle cx={nowX} cy={nowYAvg} r="4.5" fill={avgColor} />
      <circle cx={nowX} cy={nowYToday} r="5" fill={toneColor} />

      {/* axis labels */}
      <g style={{ fontFeatureSettings: '"tnum"' }}>
        <text x={padL} y={baseY + 16} textAnchor="start" fontFamily="var(--sans)" fontSize="11" fill="var(--ink-3)" fontWeight="500">Mon</text>
        <text x={nowX} y={baseY + 16} textAnchor="middle" fontFamily="var(--sans)" fontSize="11" fill="var(--ink-2)" fontWeight="600">Thu</text>
        <text x={W - padR} y={baseY + 16} textAnchor="end" fontFamily="var(--sans)" fontSize="11" fill="var(--ink-3)" fontWeight="500">Sun</text>
      </g>
    </svg>
  );
}

function CmpStat({ label, val, color, i }) {
  return (
    <div style={{ flex: 1 }}>
      <div style={{ display: 'flex', alignItems: 'center', gap: 7 }}>
        <span style={{ width: 9, height: 9, borderRadius: '50%', background: color }} />
        <span style={{ fontFamily: 'var(--sans)', fontSize: 13.5, fontWeight: 600, color: 'var(--ink-2)' }}>{label}</span>
      </div>
      <div style={{ display: 'flex', alignItems: 'baseline', gap: 4, marginTop: 7 }}>
        <span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 30, letterSpacing: '-0.02em', color }}>{val}</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 11, color: 'var(--ink-3)', fontWeight: 600 }}>kg down</span>
      </div>
    </div>
  );
}

function FCWeekCompareCard({ paceKey = 'onTrack', width = 360, compact = false }) {
  const d = weekCompare(paceKey);
  const cc = COMPARE_COPY[paceKey] || COMPARE_COPY.onTrack;
  const toneColor = _toneColor(cc.tone);
  return (
    <div style={{ width: '100%' }}>
      <div style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: toneColor, fontWeight: 600 }}>This week vs usual</div>
      <div style={{ fontFamily: 'var(--sans)', fontSize: compact ? 17 : 20, fontWeight: 700, lineHeight: 1.22, letterSpacing: '-0.01em', color: 'var(--ink)', marginTop: 8, textWrap: 'balance' }}>{cc.head}</div>
      {!compact && (
        <div style={{ display: 'flex', gap: 20, marginTop: 18, paddingTop: 16, borderTop: '1px solid var(--rule)' }}>
          <CmpStat label="This week" val={d.thisNow.toFixed(1)} color={toneColor} />
          <CmpStat label="Average" val={d.avgNow.toFixed(1)} color="var(--rule-2)" />
        </div>
      )}
      <div style={{ marginTop: compact ? 12 : 16 }}>
        <FCWeekCompareChart paceKey={paceKey} width={width} height={compact ? 150 : 184} />
      </div>
    </div>
  );
}

Object.assign(window, { FCWeekCompareChart, FCWeekCompareCard, weekCompare });
