// Training Load (ACWR) — acute:chronic workload ratio for injury risk.
// Acute = current week. Chronic = average of the previous 3-4 weeks (rolling).
// Sweet spot: 0.8 – 1.3.   Danger: > 1.5.

window.TOOL_HANDLERS['training-load'] = function TrainingLoadTool() {
  const S = window.MMSports;
  const [weeks, setWeeks] = React.useState([18, 22, 25, 28, 32]); // 4 prior + this week
  const [unit, setUnit] = React.useState('km');

  const update = (i, v) => {
    setWeeks((prev) => prev.map((x, idx) => idx === i ? Number(v) || 0 : x));
  };

  const acute = weeks[weeks.length - 1] || 0;
  const chronic = weeks.slice(0, -1).reduce((a, b) => a + b, 0) / Math.max(1, weeks.length - 1);
  const acwr = chronic > 0 ? acute / chronic : 0;

  const zone = acwr >= 0.8 && acwr <= 1.3
    ? { label: 'Sweet spot', color: '#16a34a', advice: 'Optimal load — small, steady increases.' }
    : acwr < 0.8
    ? { label: 'Detraining', color: '#2563eb', advice: 'Below baseline. Add some volume to retain fitness.' }
    : acwr <= 1.5
    ? { label: 'Caution', color: '#f97316', advice: 'Spike in load — keep an eye on fatigue and sleep.' }
    : { label: 'Danger', color: '#dc2626', advice: 'High injury risk. Cut volume or insert a recovery week.' };

  const totalThisMonth = weeks.reduce((a, b) => a + b, 0);
  const trend = weeks[weeks.length - 1] - weeks[0];

  // Tiny inline bar chart.
  const max = Math.max(...weeks, 1);

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="Training Load (ACWR)" sub="Spot risky spikes before they become injuries." icon="chart" accent="#dc2626" />

      <div className="sport-mode-row">
        <div className="sport-mode-spacer" />
        <S.UnitToggle unit={unit} setUnit={setUnit} />
      </div>

      <div className="sport-input-grid">
        {weeks.map((w, i) => (
          <div className="mini-field" key={i}>
            <label className="mini-label">{i === weeks.length - 1 ? 'This week' : `${weeks.length - 1 - i} wk ago`} ({unit})</label>
            <input type="number" min="0" step="1" className="mini-input"
                   value={w} onChange={(e) => update(i, e.target.value)} />
          </div>
        ))}
      </div>

      <div className="sport-bars">
        {weeks.map((w, i) => (
          <div key={i} className="sport-bar-col">
            <div className="sport-bar-bg">
              <div className="sport-bar-fill"
                   style={{ height: `${(w / max) * 100}%`, background: i === weeks.length - 1 ? zone.color : '#94a3b8' }} />
            </div>
            <div className="sport-bar-l">{i === weeks.length - 1 ? 'Now' : `−${weeks.length - 1 - i}`}</div>
            <div className="sport-bar-v">{w}</div>
          </div>
        ))}
      </div>

      <div className="sport-results">
        <S.ResultTile label="Acute (this week)" value={`${acute} ${unit}`} />
        <S.ResultTile label="Chronic (avg)" value={`${chronic.toFixed(1)} ${unit}`} sub="rolling baseline" />
        <S.ResultTile label="ACWR" value={acwr.toFixed(2)} sub={zone.label} accent={zone.color} />
        <S.ResultTile label="Block total" value={`${totalThisMonth} ${unit}`} sub={`Δ ${trend > 0 ? '+' : ''}${trend} ${unit} vs. start`} />
      </div>

      <div className="sport-zone-note" style={{ borderColor: zone.color, color: zone.color }}>
        <strong>{zone.label}.</strong> {zone.advice}
      </div>

      <details className="sport-details">
        <summary>What is ACWR?</summary>
        <p style={{ margin: '8px 0 0', color: 'var(--id-text-muted)', fontSize: 13 }}>
          The acute:chronic workload ratio (Gabbett, 2016) compares this week's load to your recent baseline. Loads that ramp up faster than fitness builds correlate with non-contact injuries. Aim for 0.8 – 1.3 most weeks; spend brief windows above that for race build-ups, then back off.
        </p>
      </details>
    </div>
  );
};
