// Split Calculator — even or negative-split splits for any target distance/time.

window.TOOL_HANDLERS['split-calculator'] = function SplitCalculatorTool() {
  const S = window.MMSports;
  const [unit, setUnit] = React.useState('km');
  const [distance, setDistance] = React.useState('10');
  const [target, setTarget] = React.useState('0:50:00');
  const [strategy, setStrategy] = React.useState('even'); // 'even' | 'negative' | 'positive'
  const [delta, setDelta] = React.useState(3); // % faster/slower for second half

  const splits = React.useMemo(() => {
    const d = Math.floor(Number(distance));
    const totalSec = S.parseTimeToSeconds(target);
    if (!d || !totalSec) return null;
    const wholeUnits = d;
    const fractional = Number(distance) - d;
    const out = [];
    if (strategy === 'even') {
      const perUnit = totalSec / Number(distance);
      for (let i = 1; i <= wholeUnits; i++) {
        out.push({ km: i, split: perUnit, cumulative: perUnit * i });
      }
      if (fractional > 0.01) {
        out.push({ km: Number(distance), split: perUnit * fractional, cumulative: totalSec, fractional: true });
      }
    } else {
      // Linear ramp from start to end so total time matches.
      const sign = strategy === 'negative' ? -1 : 1;
      const halfDelta = (delta / 100) * sign;     // % between first and last unit
      const pBar = totalSec / Number(distance);   // average pace
      // Slope: each unit is (i / N - 0.5) × 2 × halfDelta × pBar slower than mean.
      let cumulative = 0;
      for (let i = 1; i <= wholeUnits; i++) {
        const offset = ((i - 0.5) / Number(distance) - 0.5) * 2 * halfDelta;
        const split = pBar * (1 + offset);
        cumulative += split;
        out.push({ km: i, split, cumulative });
      }
      if (fractional > 0.01) {
        const offset = ((wholeUnits + fractional / 2) / Number(distance) - 0.5) * 2 * halfDelta;
        const split = pBar * (1 + offset) * fractional;
        cumulative += split;
        out.push({ km: Number(distance), split, cumulative, fractional: true });
      }
      // Re-normalise so cumulative matches totalSec exactly.
      const factor = totalSec / cumulative;
      out.forEach((row) => { row.split *= factor; row.cumulative *= factor; });
    }
    return out;
  }, [distance, target, strategy, delta, unit]);

  return (
    <div className="mini-tool sport-tool">
      <S.SportsToolHeader title="Split Calculator" sub="Even, negative or positive splits for any target time." icon="clock" />

      <div className="sport-mode-row">
        {[
          { id: 'even', label: 'Even' },
          { id: 'negative', label: 'Negative split' },
          { id: 'positive', label: 'Positive split' },
        ].map((s) => (
          <button key={s.id} type="button"
                  className={`sport-mode-btn ${strategy === s.id ? 'active' : ''}`}
                  onClick={() => setStrategy(s.id)}>{s.label}</button>
        ))}
        <div className="sport-mode-spacer" />
        <S.UnitToggle unit={unit} setUnit={setUnit} />
      </div>

      <div className="sport-input-grid">
        <div className="mini-field">
          <label className="mini-label">Distance ({unit})</label>
          <input type="number" min="0.1" step="0.1" className="mini-input"
                 value={distance} onChange={(e) => setDistance(e.target.value)} />
        </div>
        <div className="mini-field">
          <label className="mini-label">Target time</label>
          <input type="text" className="mini-input" placeholder="hh:mm:ss"
                 value={target} onChange={(e) => setTarget(e.target.value)} />
        </div>
        {strategy !== 'even' && (
          <div className="mini-field">
            <label className="mini-label">Δ % first → last</label>
            <input type="number" min="1" max="20" className="mini-input"
                   value={delta} onChange={(e) => setDelta(Number(e.target.value) || 0)} />
          </div>
        )}
      </div>

      <div className="sport-table-wrap">
        <table className="sport-table">
          <thead>
            <tr>
              <th>{unit === 'km' ? 'KM' : 'Mile'}</th>
              <th>Split</th>
              <th>Cumulative</th>
              <th>Pace / {unit}</th>
            </tr>
          </thead>
          <tbody>
            {(!splits || splits.length === 0) && (
              <tr><td colSpan="4" className="sport-empty-row">Enter distance and target time.</td></tr>
            )}
            {splits && splits.map((row, i) => (
              <tr key={i}>
                <td>{row.fractional ? row.km.toFixed(2) : row.km}</td>
                <td>{S.formatHMS(row.split)}</td>
                <td>{S.formatHMS(row.cumulative, { alwaysHours: row.cumulative >= 3600 })}</td>
                <td>{row.fractional ? '—' : S.formatPace(row.split)}</td>
              </tr>
            ))}
          </tbody>
        </table>
      </div>
    </div>
  );
};
