/* Track & Train — Ejection: exercises, athletes, throw logger */

const EJ_EXERCISES = [
  { id: 'w_back',   name: 'Poids en arrière' },
  { id: 'w_front',  name: 'Poids en avant' },
  { id: 'mb_front', name: 'MB en avant' },
  { id: 'mb_left',  name: 'MB gauche' },
  { id: 'mb_right', name: 'MB droite' },
  { id: 'w4_back',  name: 'Poids 4kg en arrière', fixed: 4 },
];
const EX_BY_ID = Object.fromEntries(EJ_EXERCISES.map(e => [e.id, e]));

const normName = (s) => (s || '').normalize('NFD').replace(/[\u0300-\u036f]/g, '').toLowerCase();
const isEjectionType = (ty) => !!ty && normName(ty.name).includes('ejection');
const parseNum = (v) => { const n = parseFloat(String(v).replace(',', '.')); return isFinite(n) && n > 0 ? n : null; };
const fmtNum = (n, d = 2) => n == null ? '—' : n.toLocaleString(getLang(), { maximumFractionDigits: d });
const shortDate = (key) => { const d = parseKey(key); return `${d.getDate()} ${monthShort(d.getMonth())}`; };

// Latest weight used by an athlete on an exercise (across all sessions, newest first)
const lastWeight = (sessions, athleteId, exId) => {
  const list = sessions.slice().sort((a, b) => b.date.localeCompare(a.date) || b.createdAt - a.createdAt);
  for (const s of list) {
    const th = (s.throws || []).slice().reverse().find(x => x.athleteId === athleteId && x.exId === exId);
    if (th) return th.weight;
  }
  return null;
};

const plural = (base, n) => t(base + (n === 1 ? '_one' : '_other'), { n });
const throwsSummary = (s) => {
  const n = s.throws.length, a = new Set(s.throws.map(x => x.athleteId)).size;
  return `${plural('ej_throw', n)} · ${plural('ej_ath', a)}`;
};
// One-line description for session cards
const sessionLine = (s) => {
  const parts = [];
  if (s.throws && s.throws.length) parts.push(throwsSummary(s));
  if (s.prs && s.prs.length) parts.push('PR : ' + s.prs.map(p => `${p.exName} ${fmtNum(p.load)} kg`).join(', '));
  if (s.notes) parts.push(s.notes);
  return parts.join(' — ');
};

function ThrowLogger({ draft, onChange, athletes, sessions, onAddAthlete }) {
  const throws = draft.throws || [];
  const lastTh = throws[throws.length - 1];
  const [athleteId, setAthleteId] = useState(() => lastTh?.athleteId || athletes[0]?.id || null);
  const [exId, setExId] = useState(() => lastTh?.exId || EJ_EXERCISES[0].id);
  const [weight, setWeight] = useState('');
  const [distance, setDistance] = useState('');
  const [newName, setNewName] = useState(null);
  const distRef = useRef(null);

  const others = useMemo(() => sessions.filter(s => s.id !== draft.id), [sessions, draft.id]);
  const pool = useMemo(() => [...others, { ...draft, throws }], [others, draft, throws]);
  const ex = EX_BY_ID[exId];

  // Prefill weight from the athlete's history whenever athlete/exercise changes
  useEffect(() => {
    if (ex.fixed) { setWeight(String(ex.fixed)); return; }
    const w = athleteId ? lastWeight(pool, athleteId, exId) : null;
    setWeight(w != null ? fmtNum(w) : '');
  }, [athleteId, exId]);

  const w = ex.fixed || parseNum(weight);
  const d = parseNum(distance);
  const canAdd = !!athleteId && !!w && !!d;

  const add = () => {
    if (!canAdd) return;
    onChange({ ...draft, throws: [...throws, { id: uid('thr'), athleteId, exId, weight: w, distance: d }] });
    setDistance('');
    setTimeout(() => distRef.current && distRef.current.focus(), 0);
  };
  const remove = (id) => onChange({ ...draft, throws: throws.filter(x => x.id !== id) });
  const createAthlete = () => {
    const n = (newName || '').trim();
    if (!n) return;
    const a = onAddAthlete(n);
    setAthleteId(a.id); setNewName(null);
  };

  // best distance in OTHER sessions per athlete/exercise/weight → PR badge
  const prevBest = useMemo(() => {
    const m = {};
    for (const s of others) for (const x of (s.throws || [])) {
      const k = x.athleteId + '|' + x.exId + '|' + x.weight;
      m[k] = Math.max(m[k] || 0, x.distance);
    }
    return m;
  }, [others]);
  const isPR = (x) => {
    const k = x.athleteId + '|' + x.exId + '|' + x.weight;
    const best = Math.max(...throws.filter(y => y.athleteId === x.athleteId && y.exId === x.exId && y.weight === x.weight).map(y => y.distance));
    return x.distance === best && x.distance > (prevBest[k] || 0);
  };

  const athById = Object.fromEntries(athletes.map(a => [a.id, a]));
  const shown = athletes.filter(a => !a.hidden || a.id === athleteId);
  const groups = [];
  for (const x of throws) {
    let g = groups.find(g => g.athleteId === x.athleteId);
    if (!g) groups.push(g = { athleteId: x.athleteId, items: [] });
    g.items.push(x);
  }

  return (
    <div className="ej">
      <div className="field">
        <label>{t('ej_athlete')}</label>
        {newName != null ? (
          <div className="ej-inline">
            <input className="input" autoFocus value={newName} placeholder={t('ej_athlete_ph')}
              onChange={e => setNewName(e.target.value)}
              onKeyDown={e => { if (e.key === 'Enter') createAthlete(); if (e.key === 'Escape') setNewName(null); }}/>
            <button type="button" className="btn secondary" onClick={() => setNewName(null)} aria-label={t('cancel')}><Icon.close/></button>
            <button type="button" className="btn accent" disabled={!newName.trim()} onClick={createAthlete} aria-label={t('save')}><Icon.check/></button>
          </div>
        ) : (
          <div className="type-grid">
            {shown.map(a => (
              <button key={a.id} type="button" className={'type-chip ' + (athleteId === a.id ? 'on' : '')} onClick={() => setAthleteId(a.id)}>
                <span className="type-dot" style={{ background: athleteId === a.id ? '#fff' : a.color }}></span>{a.name}
              </button>
            ))}
            <button type="button" className="type-chip add" onClick={() => setNewName('')}><Icon.plusSm/> {t('ej_add_athlete')}</button>
          </div>
        )}
      </div>

      {athletes.length > 0 && (
        <div style={{ display: 'contents' }}>
          <div className="field">
            <label>{t('ej_exercise')}</label>
            <div className="ej-ex-grid">
              {EJ_EXERCISES.map(e => (
                <button key={e.id} type="button" className={'ej-ex ' + (exId === e.id ? 'on' : '')} onClick={() => setExId(e.id)}>{e.name}</button>
              ))}
            </div>
          </div>

          <div className="ej-entry">
            <div className="field">
              <label>{t('ej_weight')}</label>
              <div className={'ej-num ' + (ex.fixed ? 'locked' : '')}>
                <input className="input" inputMode="decimal" value={weight} readOnly={!!ex.fixed}
                  placeholder="—" onChange={e => setWeight(e.target.value)}/>
                <span className="unit">kg</span>
              </div>
            </div>
            <div className="field">
              <label>{t('ej_distance')}</label>
              <div className="ej-num">
                <input ref={distRef} className="input" inputMode="decimal" value={distance} placeholder="0,00"
                  onChange={e => setDistance(e.target.value)}
                  onKeyDown={e => { if (e.key === 'Enter') add(); }}/>
                <span className="unit">m</span>
              </div>
            </div>
            <button type="button" className="btn accent ej-add" disabled={!canAdd} onClick={add} aria-label={t('ej_add')}><Icon.plus/></button>
          </div>
        </div>
      )}

      {athletes.length === 0 ? (
        <p className="muted small" style={{ margin: 0 }}>{t('ej_no_athletes')}</p>
      ) : throws.length === 0 ? (
        <p className="muted small" style={{ margin: 0 }}>{t('ej_none')}</p>
      ) : (
        <div className="ej-list">
          {groups.map(g => {
            const a = athById[g.athleteId];
            return (
              <div key={g.athleteId} className="ej-group">
                <div className="ej-group-head"><span className="type-dot" style={{ background: a?.color || 'var(--ink-3)' }}></span>{a?.name || '—'}</div>
                {g.items.map(x => (
                  <div key={x.id} className="ej-item">
                    <span className="ej-item-ex">{EX_BY_ID[x.exId]?.name}</span>
                    <span className="chip">{fmtNum(x.weight)} kg</span>
                    {isPR(x) && <span className="chip accent">PR</span>}
                    <span className="ej-item-d">{fmtNum(x.distance)} m</span>
                    <button type="button" className="ej-item-x" onClick={() => remove(x.id)} aria-label={t('delete')}><Icon.close/></button>
                  </div>
                ))}
              </div>
            );
          })}
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EJ_EXERCISES, EX_BY_ID, isEjectionType, parseNum, fmtNum, shortDate, lastWeight, throwsSummary, sessionLine, ThrowLogger });
