// fc-plan-strategy.jsx — the interactive fight-week cut-strategy graph for the Plan
// ("Your Camp") screen. One timeline: real weight walked down across camp, then the
// fight-week WATER tactics stepping the last kilos off to make-weight.
//   · Fight-week start is labelled on the axis.
//   · Each tactic is a tappable dot on the fight-week portion, at the point it comes in.
//   · The list below shows each tactic's recommendation (Recommended / Cap / Not advised)
//     and lets the athlete select/deselect it — the descent recomputes live.
// Grounded in §8 (CutStrategy): selected tactics define the fight-week water portion,
// which combines with camp true-weight loss to reach make-weight. Yields are % of
// scale weight; Sweat is capped ≤5% bodyweight.

const PCS_GREEN = '#2f5a24';
const PCS_AMBER = '#a87b22';
const PCS_ACCENT = 'var(--accent)';

// tactic catalogue — timeline `day` = days before weigh-in (fight week ≈ 5-day window)
const PCS_STRATS = [
  { key: 'water',  name: 'Water load',    effect: 'Manipulate water — a temporary ~0.5% drop.',        pct: 0.005, rec: 'no',  day: 4.2 },
  { key: 'fibre',  name: 'Low-fibre day', effect: 'Clears the gut — about 1% of scale weight.',        pct: 0.010, rec: 'rec', day: 3.0 },
  { key: 'sodium', name: 'Low sodium',    effect: '2–3 days drops ~0.5–1% in water.',                  pct: 0.009, rec: 'rec', day: 2.0 },
  { key: 'carb',   name: 'Low carb',      effect: 'Glycogen is your engine — 24h to reload.',          pct: 0.007, rec: 'no',  day: 1.4 },
  { key: 'sweat',  name: 'Sweat / sauna', effect: 'Final 24h — never past 5% of bodyweight.',          pct: 0.012, rec: 'cap', day: 0.7 },
];

const PCS_REC_META = {
  rec: { label: 'Recommended', color: PCS_GREEN },
  cap: { label: 'Capped',      color: PCS_AMBER },
  no:  { label: 'Not advised', color: PCS_ACCENT },
};

function PlanCutStrategy({ startW, targetW, water = true, width = 291 }) {
  const cut = Math.max(0.1, startW - targetW);
  // default selection: the plan's recommendation — Recommended + Capped tactics on,
  // Not-advised off. No water window → nothing selectable.
  const [sel, setSel] = React.useState(() => {
    const o = {};
    PCS_STRATS.forEach((s) => { o[s.key] = water && (s.rec === 'rec' || s.rec === 'cap'); });
    return o;
  });
  const toggle = (k) => setSel((p) => ({ ...p, [k]: !p[k] }));

  // selected tactics, earliest (largest day) → latest, each with its water yield in kg
  const chosen = PCS_STRATS.filter((s) => sel[s.key]).sort((a, b) => b.day - a.day);
  const rawWater = chosen.reduce((sum, s) => sum + s.pct * startW, 0);
  const fwWater = Math.min(rawWater, cut);                 // can't shed more water than the whole cut
  const scale = rawWater > cut ? cut / rawWater : 1;       // if over-selected, scale steps to land on target
  const campKg = Math.max(0, cut - fwWater);

  // ── geometry ────────────────────────────────────────────────────────────────
  const W = width, H = 208, padL = 10, padR = 40, padT = 32, padB = 30;
  const innerW = W - padL - padR, innerH = H - padT - padB;
  const bandTop = padT, bandBot = H - padB;
  const campFrac = water && chosen.length ? 0.5 : 0.86;     // camp share of the x-axis
  const fwX0 = padL + innerW * campFrac;                    // fight-week starts here
  const fwX1 = padL + innerW;

  const span = Math.max(0.4, startW - targetW);
  const wTop = startW + span * 0.10, wBot = targetW - span * 0.16;
  const yAt = (w) => bandTop + innerH * (1 - (w - wBot) / (wTop - wBot));
  const xForDay = (day) => fwX1 - ((5 - day) / 5) * (fwX1 - fwX0); // day 5→fwX0, day 0→fwX1

  const yStart = yAt(startW), yTarget = yAt(targetW);
  const fwStartW = targetW + fwWater;                      // weight when fight week begins

  // camp line: eased descent from start → fight-week-start weight
  const campPts = [];
  const nCamp = 5;
  for (let k = 0; k <= nCamp; k++) {
    const t = k / nCamp, ease = 1 - Math.pow(1 - t, 1.8);
    campPts.push([padL + (fwX0 - padL) * t, yAt(startW - campKg * ease)]);
  }
  // fight-week line: straight steps down at each selected tactic's day, landing on target
  const stepNodes = [];
  let w = fwStartW;
  chosen.forEach((s) => {
    const x = xForDay(s.day);
    stepNodes.push({ x, yTop: yAt(w), key: s.key, rec: s.rec, name: s.name });
    w = Math.max(targetW, w - s.pct * startW * scale);
    stepNodes[stepNodes.length - 1].yBot = yAt(w);
  });

  // build the path (camp eased + fight-week steps)
  let d = campPts.map((p, i) => (i ? 'L' : 'M') + p[0].toFixed(1) + ' ' + p[1].toFixed(1)).join(' ');
  let cx = fwX0;
  stepNodes.forEach((n) => { d += ` L ${n.x.toFixed(1)} ${n.yTop.toFixed(1)} L ${n.x.toFixed(1)} ${n.yBot.toFixed(1)}`; cx = n.x; });
  d += ` L ${fwX1.toFixed(1)} ${yTarget.toFixed(1)}`;

  const noneChosen = water && chosen.length === 0;

  return (
    <div style={{ width }}>
      <svg width="100%" viewBox={`0 0 ${W} ${H}`} style={{ display: 'block', overflow: 'visible' }} role="img"
           aria-label={`Cut plan from ${startW.toFixed(1)} to ${targetW.toFixed(1)} kg: ${campKg.toFixed(1)} kg real weight across camp` + (water ? `, then ${fwWater.toFixed(1)} kg of water off in fight week from the selected tactics.` : '.')}>
        {/* fight-week band tint */}
        {water && (
          <rect x={fwX0} y={bandTop} width={fwX1 - fwX0} height={bandBot - bandTop} fill="var(--accent)" opacity="0.05" />
        )}
        {/* start-weight guide + readout */}
        <line x1={padL} y1={yStart} x2={W - padR} y2={yStart} stroke="var(--ink-3)" strokeWidth="1" strokeDasharray="2 3" opacity="0.35" />
        <text x={W - padR + 5} y={yStart + 3} style={{ fontFamily: 'var(--num)', fontSize: 10.5, fill: 'var(--ink-3)' }}>{startW.toFixed(1)}</text>
        {/* make-weight floor + readout */}
        <line x1={padL} y1={yTarget} x2={W - padR} y2={yTarget} stroke="var(--accent)" strokeWidth="1" strokeDasharray="2 4" opacity="0.5" />
        <text x={W - padR + 5} y={yTarget + 3} style={{ fontFamily: 'var(--num)', fontSize: 10.5, fill: 'var(--accent)', fontWeight: 600 }}>{targetW.toFixed(1)}</text>

        {/* fight-week start divider + label */}
        {water && (
          <g>
            <line x1={fwX0} y1={bandTop - 6} x2={fwX0} y2={bandBot} stroke="var(--accent)" strokeWidth="1" strokeDasharray="3 3" opacity="0.55" />
            <text x={fwX0 + 4} y={bandTop - 12} style={{ fontFamily: 'var(--mono)', fontSize: 7.6, letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 700, fill: 'var(--accent)' }}>Fight week</text>
          </g>
        )}
        <text x={padL} y={bandTop - 12} style={{ fontFamily: 'var(--mono)', fontSize: 7.6, letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 700, fill: 'var(--ink-3)' }}>Camp · real weight</text>

        {/* the descent */}
        <path d={d} fill="none" stroke="var(--ink)" strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round" />

        {/* start node */}
        <circle cx={padL} cy={yStart} r="3.2" fill="var(--ink)" stroke="var(--paper)" strokeWidth="2" />

        {/* interactive tactic dots — one per selected tactic, at its entry point */}
        {water && stepNodes.map((n) => {
          const meta = PCS_REC_META[n.rec];
          return (
            <g key={n.key} style={{ cursor: 'pointer' }} onClick={() => toggle(n.key)}>
              <circle cx={n.x} cy={n.yTop} r="10" fill="transparent" />
              <circle cx={n.x} cy={n.yTop} r="5" fill={meta.color} stroke="var(--paper)" strokeWidth="2" />
            </g>
          );
        })}

        {/* weigh-in node */}
        <circle cx={fwX1} cy={yTarget} r="5" fill="var(--accent)" stroke="var(--paper)" strokeWidth="2" />

        {/* baseline labels */}
        <text x={padL} y={H - padB + 15} style={{ fontFamily: 'var(--mono)', fontSize: 8, letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 600, fill: 'var(--ink-3)' }}>Start</text>
        <text x={fwX1} y={H - padB + 15} textAnchor="end" style={{ fontFamily: 'var(--mono)', fontSize: 8, letterSpacing: '0.04em', textTransform: 'uppercase', fontWeight: 700, fill: 'var(--accent)' }}>Weigh-in</text>
      </svg>

      {/* split readout */}
      <div style={{ display: 'flex', marginTop: 14, paddingTop: 12, borderTop: '1px solid var(--rule)' }}>
        <div style={{ flex: 1 }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 10.5, fontWeight: 600, color: 'var(--ink-3)' }}>Real weight · camp</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 3, marginTop: 5 }}><span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 22, letterSpacing: '-0.02em', color: 'var(--ink)' }}>{campKg.toFixed(1)}</span><span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-3)', fontWeight: 600 }}>kg</span></div>
        </div>
        <div style={{ flex: 1, paddingLeft: 16, borderLeft: '1px solid var(--rule)' }}>
          <div style={{ fontFamily: 'var(--sans)', fontSize: 10.5, fontWeight: 600, color: 'var(--ink-3)' }}>Fight-week water</div>
          <div style={{ display: 'flex', alignItems: 'baseline', gap: 3, marginTop: 5 }}><span style={{ fontFamily: 'var(--num)', fontWeight: 300, fontSize: 22, letterSpacing: '-0.02em', color: 'var(--accent)' }}>{fwWater.toFixed(1)}</span><span style={{ fontFamily: 'var(--mono)', fontSize: 9, color: 'var(--ink-3)', fontWeight: 600 }}>kg</span></div>
        </div>
      </div>

      {/* tactic list — recommendation + selectable */}
      <div style={{ marginTop: 16 }}>
        <div style={{ display: 'flex', alignItems: 'baseline', justifyContent: 'space-between', gap: 10, marginBottom: 10 }}>
          <span style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.12em', textTransform: 'uppercase', fontWeight: 700, color: 'var(--ink-3)' }}>Fight-week tactics</span>
          <span style={{ fontFamily: 'var(--sans)', fontSize: 11.5, color: 'var(--ink-3)' }}>Tap to include</span>
        </div>
        {!water && (
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', lineHeight: 1.5, textWrap: 'pretty', background: 'var(--paper-2)', borderRadius: 10, padding: '11px 13px' }}>
            Same-day weigh-in — no rehydration window, so there’s no safe water cut. The whole cut is real weight, walked down across camp.
          </div>
        )}
        {water && (
          <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
            {PCS_STRATS.map((s) => {
              const on = sel[s.key];
              const meta = PCS_REC_META[s.rec];
              return (
                <button key={s.key} onClick={() => toggle(s.key)} style={{ display: 'flex', gap: 11, alignItems: 'flex-start', textAlign: 'left', width: '100%', background: on ? 'var(--paper-2)' : 'transparent', border: '1px solid ' + (on ? 'var(--rule-2)' : 'var(--rule)'), borderRadius: 11, padding: '11px 13px', cursor: 'pointer' }}>
                  {/* selection tick */}
                  <span style={{ flexShrink: 0, marginTop: 1, width: 18, height: 18, borderRadius: 6, border: '1.5px solid ' + (on ? meta.color : 'var(--rule-2)'), background: on ? meta.color : 'transparent', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                    {on && <svg width="10" height="8" viewBox="0 0 11 9" fill="none"><path d="M1 4.5 L4 7.5 L10 1" stroke="#fff" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" /></svg>}
                  </span>
                  <span style={{ flex: 1, minWidth: 0 }}>
                    <span style={{ display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap' }}>
                      <span style={{ fontFamily: 'var(--sans)', fontSize: 14, fontWeight: 600, color: 'var(--ink)' }}>{s.name}</span>
                      <span style={{ fontFamily: 'var(--mono)', fontSize: 8, letterSpacing: '0.05em', textTransform: 'uppercase', fontWeight: 700, color: meta.color, border: '1px solid ' + meta.color, borderRadius: 100, padding: '1.5px 7px' }}>{meta.label}</span>
                    </span>
                    <span style={{ display: 'block', fontFamily: 'var(--sans)', fontSize: 12.5, color: 'var(--ink-3)', marginTop: 3, lineHeight: 1.4 }}>{s.effect}</span>
                  </span>
                </button>
              );
            })}
          </div>
        )}
        {noneChosen && (
          <div style={{ fontFamily: 'var(--sans)', fontSize: 12, color: 'var(--accent)', lineHeight: 1.5, marginTop: 10, textWrap: 'pretty' }}>
            Nothing selected — the whole {cut.toFixed(1)} kg would have to come off as real weight across camp. Add the recommended tactics to keep the cut safe.
          </div>
        )}
      </div>
    </div>
  );
}

Object.assign(window, { PlanCutStrategy });
