/* Track & Train — Records tab (ejection progression) */

function ProgressChart({ series, picked, onPick, height = 230 }) {
  const ref = useRef(null);
  const [w, setW] = useState(340);
  useEffect(() => {
    if (!ref.current) return;
    const ro = new ResizeObserver(([e]) => setW(Math.max(240, e.contentRect.width)));
    ro.observe(ref.current);
    return () => ro.disconnect();
  }, []);

  const pts = series.flatMap(s => s.points);
  if (!pts.length) return <div ref={ref} style={{ height }}></div>;

  const P = { l: 40, r: 14, t: 14, b: 28 };
  const xs = pts.map(p => p.x), ys = pts.map(p => p.y);
  let x0 = Math.min(...xs), x1 = Math.max(...xs);
  if (x0 === x1) { x0 -= 86400000 * 7; x1 += 86400000 * 7; }
  let y0 = Math.min(...ys), y1 = Math.max(...ys);
  const pad = Math.max((y1 - y0) * 0.15, 0.5);
  y0 = Math.max(0, Math.floor((y0 - pad) * 2) / 2); y1 = Math.ceil((y1 + pad) * 2) / 2;
  const X = (x) => P.l + (x - x0) / (x1 - x0) * (w - P.l - P.r);
  const Y = (y) => P.t + (1 - (y - y0) / (y1 - y0)) * (height - P.t - P.b);
  const yTicks = [0, 1, 2, 3, 4].map(i => y0 + (y1 - y0) * i / 4);
  const nX = Math.min(4, new Set(xs).size);
  const xTicks = nX <= 1 ? [(x0 + x1) / 2] : Array.from({ length: nX }, (_, i) => x0 + (x1 - x0) * i / (nX - 1));

  return (
    <div ref={ref} className="rec-chart">
      <svg width={w} height={height} style={{ display: 'block' }} onClick={() => onPick(null)}>
        {yTicks.map((v, i) => (
          <g key={i}>
            <line x1={P.l} x2={w - P.r} y1={Y(v)} y2={Y(v)} stroke="var(--line)" strokeDasharray={i === 0 ? '' : '3 4'}/>
            <text x={P.l - 8} y={Y(v) + 4} textAnchor="end" fontSize="10.5" fill="var(--ink-3)" fontFamily="var(--mono)">{fmtNum(v, 1)}</text>
          </g>
        ))}
        {xTicks.map((v, i) => (
          <text key={i} x={X(v)} y={height - 8} fontSize="10.5" fill="var(--ink-3)"
            textAnchor={nX > 1 && i === 0 ? 'start' : nX > 1 && i === nX - 1 ? 'end' : 'middle'}>{shortDate(toKey(new Date(v)))}</text>
        ))}
        {series.map(s => {
          const dim = picked && picked.sid !== s.id;
          const path = s.points.map((p, i) => (i ? 'L' : 'M') + X(p.x).toFixed(1) + ' ' + Y(p.y).toFixed(1)).join(' ');
          return (
            <g key={s.id} opacity={dim ? 0.25 : 1}>
              {s.points.length > 1 && <path d={path} fill="none" stroke={s.color} strokeWidth="2.4" strokeLinejoin="round" strokeLinecap="round"/>}
              {s.points.map((p, i) => {
                const on = picked && picked.sid === s.id && picked.i === i;
                return (
                  <g key={i} onClick={(e) => { e.stopPropagation(); onPick({ sid: s.id, i }); }} style={{ cursor: 'pointer' }}>
                    <circle cx={X(p.x)} cy={Y(p.y)} r="14" fill="transparent"/>
                    {p.pr && <circle cx={X(p.x)} cy={Y(p.y)} r="8" fill="none" stroke={s.color} strokeWidth="1.5" opacity="0.5"/>}
                    <circle cx={X(p.x)} cy={Y(p.y)} r={on ? 5.5 : 4} fill={on ? s.color : '#fff'} stroke={s.color} strokeWidth="2.2"/>
                  </g>
                );
              })}
            </g>
          );
        })}
      </svg>
    </div>
  );
}

function RecordsView(props) {
  const hasPR = props.data.sessions.some(s => s.prs && s.prs.length);
  const [mode, setMode] = useState('ej');
  if (!hasPR) return <EjectionRecords {...props}/>;
  return (
    <div className="fade-in">
      <div className="segmented block" style={{ marginBottom: 6 }}>
        <button className={mode === 'ej' ? 'active' : ''} onClick={() => setMode('ej')}>{t('rec_mode_ej')}</button>
        <button className={mode === 'str' ? 'active' : ''} onClick={() => setMode('str')}>{t('rec_mode_str')}</button>
      </div>
      {mode === 'ej' ? <EjectionRecords {...props}/> : (
        <div style={{ display: 'contents' }}>
          <div className="rec-title">{t('rec_str_title')}</div>
          <StrengthRecords data={props.data}/>
          <p className="muted small text-center" style={{ marginTop: 12 }}>{t('rec_str_hint')}</p>
        </div>
      )}
    </div>
  );
}

function EjectionRecords({ data, onUpdateAthlete }) {
  const athletes = data.athletes || [];
  const visible = athletes.filter(a => !a.hidden);
  const [manage, setManage] = useState(false);
  const throwsOf = useMemo(() => {
    const m = {};
    for (const s of data.sessions) for (const x of (s.throws || [])) (m[x.athleteId] = m[x.athleteId] || []).push({ ...x, date: s.date, createdAt: s.createdAt });
    return m;
  }, [data.sessions]);
  const ordered = useMemo(() => visible.filter(a => throwsOf[a.id]).sort((a, b) => throwsOf[b.id].length - throwsOf[a.id].length || a.name.localeCompare(b.name)), [visible, throwsOf]);

  const [athId, setAthId] = useState(null);
  useEffect(() => { if (!ordered.find(a => a.id === athId)) setAthId(ordered[0]?.id || null); }, [ordered, athId]);
  const [openEx, setOpenEx] = useState(null);
  const [weight, setWeight] = useState('all');
  const [picked, setPicked] = useState(null);
  useEffect(() => { setOpenEx(null); }, [athId]);
  useEffect(() => { setWeight('all'); setPicked(null); }, [openEx, athId]);
  useEffect(() => setPicked(null), [weight]);

  const ath = athletes.find(a => a.id === athId);
  const mine = throwsOf[athId] || [];

  const cards = useMemo(() => EJ_EXERCISES.map(ex => {
    const list = mine.filter(x => x.exId === ex.id);
    if (!list.length) return { ex, list };
    const pr = list.reduce((b, x) => x.distance > b.distance ? x : b, list[0]);
    const days = {};
    for (const x of list) if (!days[x.date] || x.distance > days[x.date].distance) days[x.date] = x;
    const chrono = Object.values(days).sort((a, b) => a.date.localeCompare(b.date));
    return { ex, list, pr, chrono, weights: [...new Set(list.map(x => x.weight))].sort((a, b) => a - b) };
  }), [mine]);

  const manageSheet = (
    <Sheet open={manage} onClose={() => setManage(false)} title={t('rec_manage_title')}>
      <p className="muted small" style={{ margin: '-2px 0 14px' }}>{t('rec_manage_msg')}</p>
      <div className="ath-vis-list">
        {athletes.map(a => (
          <button key={a.id} className={'ath-vis ' + (a.hidden ? 'off' : '')} onClick={() => onUpdateAthlete({ id: a.id, hidden: !a.hidden })}>
            <span className="type-dot" style={{ background: a.color }}></span>
            <span className="ath-vis-name">{a.name}</span>
            <span className="switch" aria-checked={!a.hidden} role="switch"><span></span></span>
          </button>
        ))}
      </div>
    </Sheet>
  );
  const hiddenN = athletes.filter(a => a.hidden).length;

  if (!ordered.length) {
    return (
      <div className="empty fade-in">
        <div className="emoji-icon"><Icon.trophy/></div>
        <h3>{t('rec_empty_title')}</h3>
        <p>{t('rec_empty_msg')}</p>
        {hiddenN > 0 && <button className="btn secondary" onClick={() => setManage(true)}><Icon.eye/> {t('rec_manage')} ({hiddenN})</button>}
        {manageSheet}
      </div>
    );
  }

  const sessionsN = new Set(mine.map(x => x.date)).size;

  return (
    <div className="fade-in">
      <div className="section-label" style={{ paddingTop: 10 }}>
        <span>{t('ej_athlete')}</span>
        <button className="rec-reset rec-manage" onClick={() => setManage(true)}><Icon.eye/> {t('rec_manage')}{hiddenN ? ` (${hiddenN})` : ''}</button>
      </div>
      <div className="type-scroller">
        {ordered.map(a => (
          <button key={a.id} className={'type-pill ' + (a.id === athId ? 'on' : '')} onClick={() => setAthId(a.id)}>
            <span className="type-dot" style={{ background: a.id === athId ? '#fff' : a.color }}></span>{a.name}
          </button>
        ))}
      </div>

      {ath && (
        <div className="bt-hero" style={{ marginBottom: 16 }}>
          <div className="bt-eyebrow"><span className="type-dot" style={{ background: ath.color }}></span> {t('rec_title')}</div>
          <div className="bt-name">{ath.name}</div>
          <div className="bt-grid">
            <div className="bt-stat"><div className="k">{t('rec_sessions')}</div><div className="v">{sessionsN}</div></div>
            <div className="bt-stat"><div className="k">{t('rec_throws')}</div><div className="v">{mine.length}</div></div>
            <div className="bt-stat"><div className="k">{t('rec_last')}</div><div className="v" style={{ fontSize: 16, paddingTop: 3 }}>{mine.length ? shortDate(mine.reduce((m, x) => x.date > m ? x.date : m, '')) : '—'}</div></div>
          </div>
        </div>
      )}

      <div className="section-label"><span>{t('rec_ranking')}</span></div>
      <div className="flex" style={{ flexDirection: 'column', gap: 10 }}>
        {cards.map(c => {
          const open = openEx === c.ex.id;
          if (!c.list.length) return (
            <div key={c.ex.id} className="card pr-card rec-ex-empty">
              <span className="pr-card-top"><span className="pr-card-name">{c.ex.name}</span><span className="muted small">{t('rec_no_throw')}</span></span>
            </div>
          );
          const scoped = weight === 'all' ? c.list : c.list.filter(x => x.weight === weight);
          const days = {};
          for (const x of scoped) if (!days[x.date] || x.distance > days[x.date].distance) days[x.date] = x;
          const chrono = Object.values(days).sort((a, b) => a.date.localeCompare(b.date));
          const scopedPr = scoped.reduce((b, x) => x.distance > b.distance ? x : b, scoped[0]);
          const pts = chrono.map(x => ({ x: parseKey(x.date).getTime(), y: x.distance, pr: x === scopedPr || (x.date === scopedPr.date && x.distance === scopedPr.distance), src: x }));
          const pp = picked && pts[picked.i];
          const entries = scoped.slice().sort((a, b) => b.date.localeCompare(a.date) || b.distance - a.distance);
          return (
            <div key={c.ex.id} className={'card pr-card ' + (open ? 'open' : '')}>
              <button className="pr-card-btn" onClick={() => setOpenEx(open ? null : c.ex.id)}>
                <span className="pr-card-top">
                  <span className="pr-card-name">{c.ex.name}</span>
                  <Sparkline values={c.chrono.map(x => x.distance)} color={ath.color}/>
                  <span className="rec-pr">{fmtNum(c.pr.distance)}<small> m</small></span>
                </span>
                <span className="row-sub">{shortDate(c.pr.date)} {parseKey(c.pr.date).getFullYear()} · {fmtNum(c.pr.weight)} kg · {plural('ej_throw', c.list.length)}</span>
              </button>
              {open && (
                <div className="rec-detail">
                  {c.weights.length > 1 && (
                    <div className="segmented block" style={{ margin: '4px 0 10px', overflowX: 'auto' }}>
                      <button className={weight === 'all' ? 'active' : ''} onClick={() => setWeight('all')}>{t('rec_all_weights')}</button>
                      {c.weights.map(wv => <button key={wv} className={weight === wv ? 'active' : ''} onClick={() => setWeight(wv)}>{fmtNum(wv)} kg</button>)}
                    </div>
                  )}
                  {pts.length > 1 && (
                    <div style={{ display: 'contents' }}>
                      <div className="rec-tip">
                        {pp ? (
                          <span style={{ display: 'contents' }}>
                            <span className="muted">{shortDate(pp.src.date)} {parseKey(pp.src.date).getFullYear()}</span>
                            <span className="rec-tip-d">{fmtNum(pp.y)} m</span>
                            <span className="chip">{fmtNum(pp.src.weight)} kg</span>
                            {pp.pr && <span className="chip accent">PR</span>}
                          </span>
                        ) : <span className="muted">{t('rec_tap_hint')}</span>}
                      </div>
                      <ProgressChart height={190} series={[{ id: ath.id, color: ath.color, points: pts }]} picked={picked ? { sid: ath.id, i: picked.i } : null} onPick={(p) => setPicked(p ? { i: p.i } : null)}/>
                    </div>
                  )}
                  <div className="pr-hist">
                    {entries.map(x => {
                      const isPr = x.distance === scopedPr.distance && x.date === scopedPr.date;
                      return (
                        <span key={x.id} className="pr-hist-row">
                          <span className="muted" style={{ minWidth: 92 }}>{shortDate(x.date)} {parseKey(x.date).getFullYear()}</span>
                          <span className="pr-hist-info">{fmtNum(x.weight)} kg</span>
                          {isPr && <span className="chip accent">PR</span>}
                          <strong>{fmtNum(x.distance)} m</strong>
                        </span>
                      );
                    })}
                  </div>
                </div>
              )}
            </div>
          );
        })}
      </div>
      <p className="muted small text-center" style={{ marginTop: 12 }}>{t('rec_ex_hint')}</p>
      {manageSheet}
    </div>
  );
}

Object.assign(window, { RecordsView, EjectionRecords, ProgressChart });
