// ═══ GENESIS BUILD treino-m2-prs · 2026-07-12 ═══
// ═══ GENESIS BUILD prontidao-radar-f4 · 2026-07-11 ═══
// Modo Treino 🤳 — tela imersiva estilo TikTok: vídeo em loop, carrossel de exercícios,
// registro série a série pré-preenchido e relatório de sessão. Mobile-first.
const TREINO_TK = () => localStorage.getItem('genesis_token');
const TREINO_HDR = () => ({ Authorization: `Bearer ${TREINO_TK()}`, 'Content-Type': 'application/json' });

const treinoMatchBank = (bank, ex) => (bank || []).find(b => (ex.exercise_id && b.id === ex.exercise_id) || (b.nome || '').toLowerCase() === (ex.nome || '').toLowerCase());
const treinoRepsNum = (reps) => { const n = parseInt((reps || '').toString().replace(/^\D*/, '')); return isNaN(n) ? null : n; };

// ─── chip do carrossel superior ───
const TreinoChip = ({ ex, idx, ativo, feitas, total, completo, onClick }) => (
  <button onClick={onClick} style={{
    flexShrink: 0, border: 'none', cursor: 'pointer', padding: '8px 13px', borderRadius: 999,
    fontFamily: 'var(--fm)', fontSize: 12, letterSpacing: 0.3, whiteSpace: 'nowrap',
    background: completo ? 'var(--leaf)' : ativo ? 'var(--accent)' : 'rgba(255,255,255,0.14)',
    color: '#fff', outline: ativo ? '2px solid rgba(255,255,255,0.85)' : 'none', outlineOffset: 2,
    backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
  }}>
    {completo ? '✓ ' : ''}{ex.nome}{total ? ` · ${feitas}/${total}` : ''}
  </button>
);

// ─── painel deslizante inferior (registrar / nota) ───
const TreinoSheet = ({ titulo, onClose, children }) => (
  <div style={{ position: 'absolute', inset: 0, zIndex: 30, display: 'flex', alignItems: 'flex-end', background: 'rgba(0,0,0,0.45)' }} onClick={onClose}>
    <div onClick={e => e.stopPropagation()} style={{
      width: '100%', background: 'var(--surface)', borderRadius: '22px 22px 0 0', padding: '18px 20px 26px',
      boxShadow: '0 -12px 40px rgba(0,0,0,0.35)', animation: 'treinoSheetUp .22s ease',
    }}>
      <div style={{ width: 44, height: 5, borderRadius: 3, background: 'var(--line)', margin: '0 auto 14px' }} />
      <div style={{ fontFamily: 'var(--fs)', fontSize: 19, fontWeight: 600, marginBottom: 14 }}>{titulo}</div>
      {children}
    </div>
  </div>
);

// ─── relatório de fim de sessão ───
const TreinoStat = ({ big, label }) => (
  <div style={{ background: 'var(--cream-2)', borderRadius: 14, padding: '14px 10px', textAlign: 'center' }}>
    <div style={{ fontFamily: 'var(--fs)', fontSize: 26, fontWeight: 700, lineHeight: 1 }}>{big}</div>
    <div style={{ fontFamily: 'var(--fm)', fontSize: 10, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--muted)', marginTop: 6 }}>{label}</div>
  </div>
);

const TreinoRelatorio = ({ resumo, focus, onFechar }) => {
  const grupos = Object.entries(resumo.grupos || {}).sort((a, b) => b[1] - a[1]);
  const maxG = grupos.length ? grupos[0][1] : 1;
  return (
    <div style={{ position: 'absolute', inset: 0, zIndex: 40, background: 'var(--cream)', overflowY: 'auto', padding: '28px 20px 40px' }}>
      <div style={{ maxWidth: 480, margin: '0 auto' }}>
        <div style={{ textAlign: 'center', marginBottom: 22 }}>
          <div style={{ fontSize: 52, lineHeight: 1 }}>🎉</div>
          <div style={{ fontFamily: 'var(--fs)', fontSize: 26, fontWeight: 700, marginTop: 10 }}>Treino concluído!</div>
          {focus ? <div style={{ color: 'var(--muted)', marginTop: 4 }}>{focus}</div> : null}
          <div style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1, color: 'var(--sun)', marginTop: 8 }}>📸 VALIDA COM O PROFESSOR PRA CONTAR NO STREAK</div>
        </div>
        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 10, marginBottom: 18 }}>
          <TreinoStat big={`${resumo.duracao_min}min`} label="duração" />
          <TreinoStat big={resumo.series_total} label="séries" />
          <TreinoStat big={resumo.exercicios} label="exercícios" />
          <TreinoStat big={resumo.volume_kg ? `${resumo.volume_kg}kg` : '—'} label="volume total" />
        </div>
        {(resumo.recordes || []).length ? (
          <div style={{ background: 'linear-gradient(135deg, rgba(198,138,31,0.16), var(--surface))', border: '1px solid var(--sun)', borderRadius: 14, padding: '16px 18px', marginBottom: 14 }}>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--sun)', marginBottom: 10 }}>🏆 recordes pessoais desta sessão</div>
            {resumo.recordes.map((rec, i) => (
              <div key={i} style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', padding: '5px 0', fontSize: 13.5 }}>
                <b>{rec.nome}</b>
                <span style={{ fontFamily: 'var(--fm)' }}><span style={{ color: 'var(--muted)', fontSize: 11 }}>{rec.anterior}kg → </span><b style={{ color: 'var(--sun)', fontSize: 16 }}>{rec.carga}kg</b></span>
              </div>
            ))}
          </div>
        ) : null}
        <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderTop: '3px solid var(--accent)', borderRadius: 14, padding: '16px 18px', marginBottom: 14 }}>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 12 }}>grupamentos trabalhados</div>
          {grupos.length ? grupos.map(([g, n]) => (
            <div key={g} style={{ marginBottom: 10 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 13, marginBottom: 4 }}>
                <span>{g}</span><span style={{ fontFamily: 'var(--fm)', color: 'var(--muted)' }}>{n} série{n > 1 ? 's' : ''}</span>
              </div>
              <div style={{ height: 8, borderRadius: 4, background: 'var(--cream-3)' }}>
                <div style={{ height: '100%', borderRadius: 4, width: `${Math.round(n / maxG * 100)}%`, background: 'var(--teal)' }} />
              </div>
            </div>
          )) : <div style={{ color: 'var(--muted)', fontSize: 13 }}>Sem séries registradas.</div>}
        </div>
        <div style={{ background: 'var(--surface)', border: '1px solid var(--line)', borderRadius: 14, padding: '14px 18px', marginBottom: 22, fontSize: 13, color: 'var(--muted)' }}>
          🔥 <b style={{ color: 'var(--ink)' }}>~{resumo.kcal_estimado} kcal</b> — estimativa por intensidade e duração (base: {resumo.peso_base_kcal}kg){resumo.notas ? <span> · 📝 {resumo.notas} anotação{resumo.notas > 1 ? 'ões' : ''} salva{resumo.notas > 1 ? 's' : ''} pro coach</span> : null}
        </div>
        <button className="btn btn-primary" style={{ width: '100%', padding: '14px', fontSize: 15 }} onClick={onFechar}>Voltar ao Coach</button>
      </div>
    </div>
  );
};

// ─── casca imersiva (módulo — nunca dentro do componente!) ───
const TreinoWrap = ({ children }) => (
  <div style={{ position: 'fixed', inset: 0, zIndex: 300, background: '#101619', color: '#fff' }}>
    <style>{`@keyframes treinoSheetUp { from { transform: translateY(40px); opacity: .6 } to { transform: none; opacity: 1 } }
      .treino-chips::-webkit-scrollbar { display: none }`}</style>
    {children}
  </div>
);

// ─── a página ───
const Treino = ({ state, setState, setPage }) => {
  const toast = useToast();
  const [plan, setPlan] = useState(null);
  const [bank, setBank] = useState([]);
  const [sessao, setSessao] = useState(null);       // sessão ativa do backend
  const [series, setSeries] = useState([]);          // séries registradas na sessão
  const [exIdx, setExIdx] = useState(0);
  const [sheet, setSheet] = useState(null);           // 'registrar' | 'nota' | null
  const [carga, setCarga] = useState('');
  const [reps, setReps] = useState('');
  const [nota, setNota] = useState('');
  const [salvando, setSalvando] = useState(false);
  const [relatorio, setRelatorio] = useState(null);
  const [carregado, setCarregado] = useState(false);
  const [prontidao, setProntidao] = useState(null);

  const dayName = ['Dom', 'Seg', 'Ter', 'Qua', 'Qui', 'Sex', 'Sáb'][new Date().getDay()];

  useEffect(() => {
    const hdr = { headers: { Authorization: `Bearer ${TREINO_TK()}` } };
    Promise.all([
      fetch('/api/saude/plan/me', hdr).then(r => r.ok ? r.json() : null),
      fetch('/api/saude/exercises', hdr).then(r => r.ok ? r.json() : []),
      fetch('/api/treino/sessoes/ativa', hdr).then(r => r.ok ? r.json() : null),
      fetch('/api/treino/prontidao', hdr).then(r => r.ok ? r.json() : null).catch(() => null),
    ]).then(([p, b, at, pr]) => {
      setProntidao(pr && !pr.sem_checkin ? pr : null);
      setPlan(p); setBank(Array.isArray(b) ? b : []);
      if (at && at.id) { setSessao(at); setSeries(at.series || []); }
      setCarregado(true);
    }).catch(() => setCarregado(true));
  }, []);

  const diaHoje = plan && plan.week ? plan.week.find(d => d.day === dayName) : null;
  const exercicios = (diaHoje && diaHoje.exercises) || [];
  const ex = exercicios[exIdx] || null;
  const be = ex ? treinoMatchBank(bank, ex) : null;

  const feitasDe = (nome) => series.filter(s => (s.exercise_nome || '').toLowerCase() === (nome || '').toLowerCase()).length;
  const completo = (e2) => e2.series ? feitasDe(e2.nome) >= e2.series : feitasDe(e2.nome) > 0;
  const tudoCompleto = exercicios.length > 0 && exercicios.every(completo);
  const serieAtual = ex ? feitasDe(ex.nome) + 1 : 1;

  const iniciar = () => {
    fetch('/api/treino/sessoes', { method: 'POST', headers: TREINO_HDR(), body: JSON.stringify({ dia_label: dayName, focus: diaHoje ? diaHoje.focus : null }) })
      .then(r => r.json()).then(s => { if (s.id) { setSessao(s); setSeries([]); } })
      .catch(() => toast.push({ icon: 'x', title: 'Sem rede — tenta de novo' }));
  };

  const abrirRegistrar = () => {
    if (!ex) return;
    setCarga(''); setReps('');
    const q = ex.exercise_id || (be && be.id) ? `exercise_id=${ex.exercise_id || be.id}` : `nome=${encodeURIComponent(ex.nome)}`;
    fetch(`/api/treino/ultima?${q}`, { headers: { Authorization: `Bearer ${TREINO_TK()}` } })
      .then(r => r.ok ? r.json() : null)
      .then(u => {
        if (u) { setCarga(u.carga != null ? String(Number(u.carga)) : ''); setReps(u.reps || ''); }
        else { setCarga((ex.carga || '').toString().replace(/[^\d.,]/g, '')); setReps(treinoRepsNum(ex.reps) ? String(treinoRepsNum(ex.reps)) : ''); }
      }).catch(() => {});
    setSheet('registrar');
  };

  const confirmarSerie = () => {
    if (!sessao || !ex || salvando) return;
    setSalvando(true);
    fetch(`/api/treino/sessoes/${sessao.id}/serie`, {
      method: 'POST', headers: TREINO_HDR(),
      body: JSON.stringify({ exercise_id: ex.exercise_id || (be && be.id) || null, exercise_nome: ex.nome, serie_num: serieAtual, carga: carga === '' ? null : carga.replace(',', '.'), reps }),
    }).then(r => r.json()).then(sr => {
      setSalvando(false);
      if (!sr.id) { toast.push({ icon: 'x', title: sr.error || 'Não salvou' }); return; }
      const novas = [...series, sr];
      setSeries(novas);
      setSheet(null);
      const done = ex.series ? novas.filter(s => (s.exercise_nome || '').toLowerCase() === ex.nome.toLowerCase()).length >= ex.series : true;
      if (sr.pr) {
        toast.push({ icon: 'check', title: `🏆 RECORDE PESSOAL!`, body: `${ex.nome}: ${carga}kg — antes era ${sr.recorde_anterior}kg 🔥` });
      }
      if (done) {
        if (!sr.pr) toast.push({ icon: 'check', title: `${ex.nome} completo! 💪` });
        const prox = exercicios.findIndex((e2, i) => i !== exIdx && !((e2.series ? novas.filter(s => (s.exercise_nome || '').toLowerCase() === e2.nome.toLowerCase()).length >= e2.series : novas.some(s => (s.exercise_nome || '').toLowerCase() === e2.nome.toLowerCase()))));
        if (prox >= 0) setExIdx(prox);
      } else {
        toast.push({ icon: 'check', title: `Série ${serieAtual} ✓` });
      }
    }).catch(() => { setSalvando(false); toast.push({ icon: 'x', title: 'Sem rede — a série não foi salva' }); });
  };

  const salvarNota = () => {
    if (!sessao || !ex || !nota.trim() || salvando) return;
    setSalvando(true);
    fetch(`/api/treino/sessoes/${sessao.id}/nota`, { method: 'POST', headers: TREINO_HDR(), body: JSON.stringify({ exercise_nome: ex.nome, texto: nota }) })
      .then(r => r.json()).then(() => { setSalvando(false); setNota(''); setSheet(null); toast.push({ icon: 'check', title: 'Anotação salva 📝' }); })
      .catch(() => { setSalvando(false); toast.push({ icon: 'x', title: 'Sem rede' }); });
  };

  const finalizar = () => {
    if (!sessao || salvando) return;
    setSalvando(true);
    fetch(`/api/treino/sessoes/${sessao.id}/finalizar`, { method: 'POST', headers: TREINO_HDR() })
      .then(r => r.json()).then(f => { setSalvando(false); if (f.resumo) setRelatorio(f.resumo); else toast.push({ icon: 'x', title: f.error || 'Erro ao finalizar' }); })
      .catch(() => { setSalvando(false); toast.push({ icon: 'x', title: 'Sem rede' }); });
  };

  const sair = () => setPage('saude');

  if (!carregado) return <TreinoWrap><div style={{ display: 'grid', placeItems: 'center', height: '100%', fontFamily: 'var(--fm)', fontSize: 13, letterSpacing: 1 }}>CARREGANDO…</div></TreinoWrap>;

  if (relatorio) return <TreinoWrap><TreinoRelatorio resumo={relatorio} focus={diaHoje ? diaHoje.focus : null} onFechar={sair} /></TreinoWrap>;

  // lobby: sem sessão ativa ainda
  if (!sessao) return (
    <TreinoWrap>
      <div style={{ display: 'flex', flexDirection: 'column', height: '100%', padding: '26px 22px', maxWidth: 480, margin: '0 auto' }}>
        <button onClick={sair} style={{ alignSelf: 'flex-start', background: 'rgba(255,255,255,0.12)', border: 'none', color: '#fff', borderRadius: 999, padding: '8px 16px', cursor: 'pointer', fontFamily: 'var(--fm)', fontSize: 12 }}>✕ sair</button>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center' }}>
          <div style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 2, textTransform: 'uppercase', color: 'var(--accent)' }}>{dayName} · treino de hoje</div>
          <div style={{ fontFamily: 'var(--fs)', fontSize: 32, fontWeight: 700, margin: '8px 0 12px' }}>{diaHoje && diaHoje.focus ? diaHoje.focus : 'Sem plano pra hoje'}</div>
          {prontidao ? (
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, background: 'rgba(255,255,255,0.07)', borderRadius: 14, padding: '11px 15px', marginBottom: 16 }}>
              <span style={{ fontFamily: 'var(--fs)', fontSize: 26, fontWeight: 700, color: prontidao.score >= 75 ? 'var(--leaf)' : prontidao.score >= 50 ? 'var(--sun)' : 'var(--rose)' }}>{prontidao.score}</span>
              <span style={{ fontSize: 13, color: 'rgba(255,255,255,0.85)' }}>{prontidao.recomendacao.emoji} {prontidao.recomendacao.frase}</span>
            </div>
          ) : null}
          {exercicios.length ? (
            <div style={{ display: 'flex', flexDirection: 'column', gap: 8, marginBottom: 26 }}>
              {exercicios.map((e2, i) => (
                <div key={i} style={{ display: 'flex', justifyContent: 'space-between', padding: '11px 15px', background: 'rgba(255,255,255,0.07)', borderRadius: 12, fontSize: 14 }}>
                  <span>{e2.nome}</span>
                  <span style={{ fontFamily: 'var(--fm)', fontSize: 12, color: 'rgba(255,255,255,0.55)' }}>{e2.series || '—'}× {e2.reps || ''}</span>
                </div>
              ))}
            </div>
          ) : (
            <div style={{ color: 'rgba(255,255,255,0.6)', marginBottom: 26 }}>{diaHoje && diaHoje.nota ? diaHoje.nota : 'Dia de descanso no plano — ou o coach ainda não montou. Aproveita o convés. 🌙'}</div>
          )}
          {exercicios.length ? (
            <button onClick={iniciar} style={{ background: 'var(--accent)', color: '#fff', border: 'none', borderRadius: 16, padding: '17px', fontSize: 17, fontWeight: 700, cursor: 'pointer', fontFamily: 'var(--fs)' }}>▶ Iniciar treino</button>
          ) : null}
        </div>
      </div>
    </TreinoWrap>
  );

  // player imersivo
  return (
    <TreinoWrap>
      {/* vídeo / fundo */}
      <div style={{ position: 'absolute', inset: 0 }}>
        {be && be.media_url
          ? <video key={be.media_url} src={be.media_url} autoPlay loop muted playsInline poster={be.image_url || undefined} style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
          : be && be.image_url
            ? <img src={be.image_url} alt="" style={{ width: '100%', height: '100%', objectFit: 'cover' }} />
            : <div style={{ display: 'grid', placeItems: 'center', height: '100%', background: 'radial-gradient(circle at 50% 35%, #23343B, #101619)' }}><div style={{ fontSize: 84, opacity: 0.5 }}>🏋️</div></div>}
        <div style={{ position: 'absolute', inset: 0, background: 'linear-gradient(180deg, rgba(10,14,16,0.78) 0%, rgba(10,14,16,0) 26%, rgba(10,14,16,0) 55%, rgba(10,14,16,0.88) 100%)' }} />
      </div>

      {/* overlay superior: sair + finalizar + carrossel */}
      <div style={{ position: 'absolute', top: 0, left: 0, right: 0, padding: '16px 14px 8px' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', marginBottom: 12 }}>
          <button onClick={sair} style={{ background: 'rgba(255,255,255,0.14)', border: 'none', color: '#fff', borderRadius: 999, padding: '8px 15px', cursor: 'pointer', fontFamily: 'var(--fm)', fontSize: 12, backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)' }}>✕</button>
          {series.length ? (
            <button onClick={finalizar} disabled={salvando} style={{ background: tudoCompleto ? 'var(--leaf)' : 'rgba(255,255,255,0.14)', border: 'none', color: '#fff', borderRadius: 999, padding: '8px 16px', cursor: 'pointer', fontFamily: 'var(--fm)', fontSize: 12, fontWeight: 700, backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)' }}>🏁 Finalizar{tudoCompleto ? ' treino!' : ''}</button>
          ) : null}
        </div>
        <div className="treino-chips" style={{ display: 'flex', gap: 8, overflowX: 'auto', paddingBottom: 6, scrollbarWidth: 'none' }}>
          {exercicios.map((e2, i) => (
            <TreinoChip key={i} ex={e2} idx={i} ativo={i === exIdx} feitas={feitasDe(e2.nome)} total={e2.series || 0} completo={completo(e2)} onClick={() => setExIdx(i)} />
          ))}
        </div>
      </div>

      {/* overlay inferior: exercício atual + ações */}
      {ex ? (
        <div style={{ position: 'absolute', left: 0, right: 0, bottom: 0, padding: '0 18px calc(22px + env(safe-area-inset-bottom, 0px))' }}>
          <div style={{ maxWidth: 480, margin: '0 auto' }}>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1.5, textTransform: 'uppercase', color: 'var(--accent)', marginBottom: 5 }}>
              {completo(ex) ? '✓ completo' : `série ${serieAtual}${ex.series ? ` de ${ex.series}` : ''}`}
            </div>
            <div style={{ fontFamily: 'var(--fs)', fontSize: 27, fontWeight: 700, lineHeight: 1.12, marginBottom: 6, textShadow: '0 2px 14px rgba(0,0,0,0.6)' }}>{ex.nome}</div>
            <div style={{ fontFamily: 'var(--fm)', fontSize: 13, color: 'rgba(255,255,255,0.72)', marginBottom: 16 }}>
              meta: {ex.series || '—'}× {ex.reps || '—'}{ex.carga ? ` · ${ex.carga}` : ''}{ex.nota ? ` · ${ex.nota}` : ''}
            </div>
            <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
              <button onClick={abrirRegistrar} disabled={salvando} style={{
                flex: 1, background: completo(ex) ? 'rgba(255,255,255,0.16)' : 'var(--accent)', color: '#fff', border: 'none',
                borderRadius: 999, padding: '16px', fontSize: 16, fontWeight: 700, cursor: 'pointer', fontFamily: 'var(--fs)',
                boxShadow: completo(ex) ? 'none' : '0 6px 26px rgba(217,105,75,0.5)',
              }}>▶ Registrar {completo(ex) ? 'extra' : `série ${serieAtual}`}</button>
              <button onClick={() => { setNota(''); setSheet('nota'); }} title="Anotações do exercício" style={{
                width: 56, height: 56, borderRadius: '50%', border: 'none', cursor: 'pointer', fontSize: 21,
                background: 'rgba(255,255,255,0.14)', color: '#fff', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
              }}>📝</button>
            </div>
          </div>
        </div>
      ) : null}

      {/* sheets */}
      {sheet === 'registrar' && ex ? (
        <TreinoSheet titulo={`${ex.nome} — série ${serieAtual}`} onClose={() => setSheet(null)}>
          <div style={{ display: 'flex', gap: 10, marginBottom: 14 }}>
            <div style={{ flex: 1 }}>
              <label style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--muted)' }}>Carga (kg)</label>
              <input className="input" type="number" inputMode="decimal" step="0.5" value={carga} onChange={e => setCarga(e.target.value)} placeholder="—" style={{ width: '100%', fontSize: 20, textAlign: 'center', marginTop: 5 }} />
            </div>
            <div style={{ flex: 1 }}>
              <label style={{ fontFamily: 'var(--fm)', fontSize: 11, letterSpacing: 1, textTransform: 'uppercase', color: 'var(--muted)' }}>Repetições</label>
              <input className="input" inputMode="numeric" value={reps} onChange={e => setReps(e.target.value)} placeholder="—" style={{ width: '100%', fontSize: 20, textAlign: 'center', marginTop: 5 }} />
            </div>
          </div>
          <div style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 14 }}>Pré-preenchido com tua última entrada — ajusta se evoluiu. 💪</div>
          <button className="btn btn-primary" disabled={salvando} onClick={confirmarSerie} style={{ width: '100%', padding: '14px', fontSize: 15 }}>{salvando ? 'Salvando…' : `Confirmar série ${serieAtual} ✓`}</button>
        </TreinoSheet>
      ) : null}
      {sheet === 'nota' && ex ? (
        <TreinoSheet titulo={`📝 ${ex.nome}`} onClose={() => setSheet(null)}>
          <textarea className="input" rows={3} value={nota} onChange={e => setNota(e.target.value)} placeholder="Ex.: banco no furo 3, sentiu o ombro na última série…" style={{ width: '100%', resize: 'none', marginBottom: 14 }} />
          <button className="btn btn-primary" disabled={salvando || !nota.trim()} onClick={salvarNota} style={{ width: '100%', padding: '13px' }}>Salvar anotação</button>
        </TreinoSheet>
      ) : null}
    </TreinoWrap>
  );
};
