// fc-gauge.jsx, the two-signal safety readout (Logic & Flows §14.1).
// A SINGLE bar can't carry "too slow" and "too fast" at once, so this shows two:
//   1. Pace, a symmetric arc of current 7-day loss %bw/wk, with a hard red zone
//      at ≥1.0%/wk (the muscle-loss ceiling) and a green band around the plan.
//   2. Projection, will the cone land at/under the limit by weigh-in (§4.4).
// Theme/tone-aware via CSS vars.

const _GTONE = (t) => t === 'red' ? 'var(--t-red)' : t === 'amber' ? 'var(--mustard-deep)' : 'var(--t-green)';

function FCPaceArc({ paceKey = 'onTrack', width = 300 }) {
  const target = window.plannedRatePct();
  const r = window.currentRatePct(paceKey);
  const zone = window.paceZone(r, target);
  const tone = _GTONE(zone.tone);
  const maxR = 1.3;                                   // arc spans 0 → 1.3 %/wk
  const W = width, H = width * 0.60, cx = W / 2, cy = H - 8, rad = Math.min(W / 2 - 14, H - 22);
  const a = (f) => Math.PI + Math.max(0, Math.min(1, f)) * Math.PI;   // 180° sweep
  const pt = (f, rr) => [cx + rr * Math.cos(a(f)), cy + rr * Math.sin(a(f))];
  const arc = (f0, f1, rr) => { const [x0, y0] = pt(f0, rr), [x1, y1] = pt(f1, rr); return `M ${x0.toFixed(1)} ${y0.toFixed(1)} A ${rr} ${rr} 0 0 1 ${x1.toFixed(1)} ${y1.toFixed(1)}`; };
  const fOf = (v) => v / maxR;
  // zone boundaries
  const greenLo = target - 0.15, greenHi = target + 0.20, ceiling = 1.0;
  const needle = pt(fOf(r), rad - 10);
  const sw = 14;

  return (
    <svg width={W} height={H + 30} viewBox={`0 0 ${W} ${H + 30}`} style={{ display: 'block', overflow: 'visible' }} role="img"
      aria-label={`Pace: ${r.toFixed(2)} percent body weight per week. ${zone.label}.`}>
      {/* track */}
      <path d={arc(0, 1, rad)} fill="none" stroke="var(--rule)" strokeWidth={sw} strokeLinecap="round" />
      {/* behind (amber) below green */}
      <path d={arc(0, fOf(greenLo), rad)} fill="none" stroke="var(--mustard-deep)" strokeWidth={sw} opacity="0.55" />
      {/* on-plan band (green) */}
      <path d={arc(fOf(greenLo), fOf(greenHi), rad)} fill="none" stroke="var(--t-green)" strokeWidth={sw} />
      {/* fast (amber) green→ceiling */}
      <path d={arc(fOf(greenHi), fOf(ceiling), rad)} fill="none" stroke="var(--mustard-deep)" strokeWidth={sw} opacity="0.55" />
      {/* unsafe (red) ≥ ceiling */}
      <path d={arc(fOf(ceiling), 1, rad)} fill="none" stroke="var(--t-red)" strokeWidth={sw} opacity="0.9" />
      {/* ceiling tick + label */}
      {(() => { const [tx, ty] = pt(fOf(ceiling), rad + sw / 2 + 2); const [tx2, ty2] = pt(fOf(ceiling), rad - sw / 2 - 2); return (
        <g><line x1={tx} y1={ty} x2={tx2} y2={ty2} stroke="var(--paper)" strokeWidth="2" />
        <text x={pt(fOf(ceiling), rad + 16)[0]} y={pt(fOf(ceiling), rad + 16)[1]} textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="var(--t-red)" fontWeight="700">1.0% MAX</text></g>
      ); })()}
      {/* plan marker */}
      {(() => { const [mx, my] = pt(fOf(target), rad + sw / 2 + 1), [mx2, my2] = pt(fOf(target), rad - sw / 2 - 1); return (
        <g><line x1={mx} y1={my} x2={mx2} y2={my2} stroke="var(--ink)" strokeWidth="1.4" strokeDasharray="2 2" opacity="0.6" />
        <text x={pt(fOf(target), rad + 16)[0]} y={pt(fOf(target), rad + 16)[1]} textAnchor="middle" fontFamily="var(--mono)" fontSize="8" fill="var(--ink-3)" fontWeight="600">PLAN</text></g>
      ); })()}
      {/* needle */}
      <line x1={cx} y1={cy} x2={needle[0].toFixed(1)} y2={needle[1].toFixed(1)} stroke="var(--ink)" strokeWidth="3" strokeLinecap="round" />
      <circle cx={cx} cy={cy} r="5" fill="var(--ink)" />
      {/* value */}
      <text x={cx} y={cy - rad * 0.50} textAnchor="middle" fontFamily="var(--num)" fontWeight="300" fontSize="27" letterSpacing="-0.02em" fill={tone}>{r.toFixed(2)}<tspan fontFamily="var(--mono)" fontSize="11" dx="2" fill="var(--ink-3)" fontWeight="600">%/wk</tspan></text>
      <text x={cx} y={cy - rad * 0.50 + 16} textAnchor="middle" fontFamily="var(--display)" fontSize="10.5" letterSpacing="0.14em" fontWeight="700" fill={tone}>{zone.label.toUpperCase()}</text>
    </svg>
  );
}

// the projection signal, a compact verdict chip + mini meaning line
function ProjSignal({ paceKey }) {
  const v = window.projectionVerdict(paceKey);
  const p = window.computePace(paceKey);
  const tone = _GTONE(v.tone);
  const dot = v.key === 'clear' ? 'var(--t-green)' : v.key === 'miss' ? 'var(--t-red)' : 'var(--mustard-deep)';
  return (
    <div style={{ padding: '13px 0 0', marginTop: 13, borderTop: '1px solid var(--rule)' }}>
      <div style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.16em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600, marginBottom: 10 }}>Making weight</div>
      <div style={{ display: 'flex', alignItems: 'center', gap: 11 }}>
        <span style={{ width: 10, height: 10, borderRadius: '50%', background: dot, flexShrink: 0 }} />
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 14.5, fontWeight: 600, color: 'var(--ink)', lineHeight: 1.25 }}>{v.label}</div>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', marginTop: 2 }}>Projected {p.projectedScale.toFixed(1)} kg at weigh-in vs {window.FC.goalWeight.toFixed(1)} limit</div>
        </div>
      </div>
    </div>
  );
}

// Card combining both signals, the §14.1 readout.
function FCPaceGaugeCard({ paceKey = 'onTrack', width = 331, showProjection = true }) {
  return (
    <div style={{ background: 'var(--paper)', borderRadius: 'var(--radius)', boxShadow: 'var(--card-shadow)', border: 'var(--card-border)', padding: 20 }}>
      <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between' }}>
        <span style={{ fontFamily: 'var(--display)', fontSize: 10.5, letterSpacing: '0.18em', textTransform: 'uppercase', color: 'var(--ink-3)', fontWeight: 600 }}>Safe pace</span>
        <span style={{ fontFamily: 'var(--mono)', fontSize: 10, letterSpacing: '0.04em', color: 'var(--ink-3)', fontWeight: 600 }}>7-DAY RATE</span>
      </div>
      <div style={{ display: 'flex', justifyContent: 'center', marginTop: 6 }}>
        <FCPaceArc paceKey={paceKey} width={Math.min(width, 300)} />
      </div>
      {showProjection && <ProjSignal paceKey={paceKey} />}
    </div>
  );
}

Object.assign(window, { FCPaceArc, FCPaceGaugeCard });
