// workout.jsx — treino com timers automáticos + bips/voz (sem tocar para contar reps)
const { useState: useW, useEffect: useWE, useRef: useWR } = React;

function fmt(s) {
  if (s >= 60) { const m = Math.floor(s / 60), r = s % 60; return `${m}:${String(r).padStart(2, '0')}`; }
  return String(s);
}

/* mini player de música (simulado) */
function MusicBar({ playing, onToggle }) {
  return (
    <div style={{ display: 'flex', alignItems: 'center', gap: 12, padding: '10px 14px',
      background: 'var(--surface)', borderRadius: 'var(--r-md)', boxShadow: 'inset 0 0 0 1px var(--line)' }}>
      <div className="slot" style={{ width: 40, height: 40, borderRadius: 8, flex: 'none', fontSize: 7 }}>CAPA</div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{ fontSize: 13, fontWeight: 600, whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis' }}>Beast Mode · Mix de Treino</div>
        <div className="mono" style={{ fontSize: 10, color: 'var(--muted)' }}>136 BPM · PLAYLIST PRINCIPAL</div>
      </div>
      <button onClick={onToggle} style={{ color: 'var(--accent)', display: 'flex' }}>
        <Icon name={playing ? 'pause' : 'play'} size={26} />
      </button>
      <span style={{ display: 'flex', color: 'var(--muted)' }}><Icon name="music" size={20} /></span>
    </div>
  );
}

function SoundToggle({ muted, onToggle }) {
  return (
    <button onClick={onToggle} title={muted ? 'Som desligado' : 'Som ligado'}
      style={{ width: 38, height: 38, borderRadius: '50%', display: 'flex', alignItems: 'center', justifyContent: 'center',
        background: 'var(--surface)', boxShadow: 'inset 0 0 0 1px var(--line)', color: muted ? 'var(--muted-2)' : 'var(--accent)' }}>
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M4 9v6h4l5 4V5L8 9z" />
        {muted
          ? <path d="M17 9l4 6M21 9l-4 6" />
          : <React.Fragment><path d="M16.5 8.5a5 5 0 0 1 0 7" /><path d="M19 6a8 8 0 0 1 0 12" /></React.Fragment>}
      </svg>
    </button>
  );
}

function Workout({ user, onExit, onFinish }) {
  const W = TODAY_WORKOUT;
  const blocks = W.blocks;
  const level = user.level || 'iniciante';
  const sex = user.sex || 'masc';

  const [bi, setBi] = useW(0);
  const [set, setSet] = useW(1);
  const [phase, setPhase] = useW('ready');   // ready | exercise | rest | complete
  const [readyLeft, setReadyLeft] = useW(3);
  const [exLeft, setExLeft] = useW(0);
  const [exDur, setExDur] = useW(1);
  const [restLeft, setRestLeft] = useW(0);
  const [running, setRunning] = useW(true);
  const [music, setMusic] = useW(true);
  const [muted, setMuted] = useW(false);
  const mref = useWR(muted);
  mref.current = muted;

  const block = blocks[bi];
  const dur = (b) => blockDuration(b, level);

  const say = (text) => { if (!mref.current) ZAudio.speak(text, sex); };
  const ping = (fn) => { if (!mref.current) fn(); };

  // progresso geral
  const totalSets = blocks.reduce((a, b) => a + b.sets, 0);
  const doneSets = blocks.slice(0, bi).reduce((a, b) => a + b.sets, 0) + (set - 1);
  const overall = phase === 'complete' ? 1 : doneSets / totalSets;

  // inicia uma série: fase de preparação
  function startReady(nbi, nset) {
    setBi(nbi); setSet(nset);
    setReadyLeft(3); setPhase('ready'); setRunning(true);
    const b = blocks[nbi];
    say(`${b.name}. Série ${nset}. Prepare-se.`);
  }

  // monta o primeiro exercício ao abrir
  useWE(() => { ZAudio.ensure(); startReady(0, 1); /* eslint-disable-next-line */ }, []);

  // ---- contagem de PREPARAÇÃO ----
  useWE(() => {
    if (phase !== 'ready') return;
    if (readyLeft <= 0) {
      const d = dur(block);
      setExDur(d); setExLeft(d); setPhase('exercise');
      ping(ZAudio.beepGo); say('Vai!');
      return;
    }
    const id = setTimeout(() => {
      const nv = readyLeft - 1;
      setReadyLeft(nv);
      if (nv > 0) { ping(ZAudio.beepPrep); say(ZAudio.numWord(nv)); }
    }, 1000);
    return () => clearTimeout(id);
  }, [phase, readyLeft]);

  // ---- contagem do EXERCÍCIO ----
  useWE(() => {
    if (phase !== 'exercise' || !running) return;
    if (exLeft <= 0) { finishExercise(); return; }
    const id = setTimeout(() => {
      const nv = exLeft - 1;
      setExLeft(nv);
      if (nv > 0 && nv <= 5) { ping(ZAudio.beepExercise); say(ZAudio.numWord(nv)); } // aviso 5s finais
    }, 1000);
    return () => clearTimeout(id);
  }, [phase, running, exLeft]);

  // ---- contagem do DESCANSO ----
  useWE(() => {
    if (phase !== 'rest') return;
    if (restLeft <= 0) { advance(); return; }
    const id = setTimeout(() => {
      const nv = restLeft - 1;
      setRestLeft(nv);
      if (nv > 0 && nv <= 3) { ping(ZAudio.beepRest); say(ZAudio.numWord(nv)); } // aviso 3s finais
    }, 1000);
    return () => clearTimeout(id);
  }, [phase, restLeft]);

  function finishExercise() {
    const lastSet = set >= block.sets;
    const lastBlock = bi >= blocks.length - 1;
    if (lastSet && lastBlock) {
      setPhase('complete');
      ping(ZAudio.beepDone); say('Treino concluído. Mandou muito bem!');
      return;
    }
    const rest = block.rest || 0;
    if (rest > 0) { setRestLeft(rest); setPhase('rest'); say('Descanse.'); }
    else { advance(); }
  }

  function advance() {
    if (set >= block.sets) startReady(bi + 1, 1);
    else startReady(bi, set + 1);
  }

  function skip() {
    ZAudio.stopVoice();
    if (phase === 'rest') advance();
    else finishExercise();
  }

  function exitWorkout() { ZAudio.stopVoice(); onExit(); }
  function finishWorkout() { ZAudio.stopVoice(); onFinish(); }

  const isTime = block && block.type === 'time';
  const nextLabel = (() => {
    if (set < block.sets) return `Série ${set + 1} · ${block.name}`;
    if (bi < blocks.length - 1) return blocks[bi + 1].name;
    return 'Fim do treino';
  })();

  /* ---------- COMPLETE ---------- */
  if (phase === 'complete') {
    return (
      <div className="fade-in" style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 26px 40px', textAlign: 'center' }}>
        <div style={{ margin: '0 auto 8px' }}>
          <ProgressRing size={170} stroke={10} progress={1}>
            <span style={{ color: 'var(--accent)', display: 'flex' }}><Icon name="check" size={64} stroke={2.4} /></span>
          </ProgressRing>
        </div>
        <div className="kicker" style={{ color: 'var(--accent)', marginTop: 14 }}>TREINO CONCLUÍDO</div>
        <h2 className="h1" style={{ fontSize: 44, margin: '8px 0 18px' }}>Dia {W.day}<br/>finalizado</h2>
        <div style={{ display: 'flex', gap: 10, marginBottom: 22 }}>
          {[['+120','XP'],['~30','MIN'],[user.streak+1,'STREAK']].map(([v,l]) => (
            <div key={l} className="card" style={{ flex: 1, padding: '14px 8px' }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 28, color: 'var(--accent)', lineHeight: 1 }}>{v}</div>
              <div className="mono" style={{ fontSize: 10, color: 'var(--muted)', marginTop: 4 }}>{l}</div>
            </div>
          ))}
        </div>
        <p className="lead" style={{ marginBottom: 26, color: 'var(--text)' }}>"{PROGRAM_30[W.day-1].frase}"</p>
        <button className="btn btn--accent" onClick={finishWorkout}>Voltar ao início</button>
      </div>
    );
  }

  /* ---------- REST ---------- */
  if (phase === 'rest') {
    const restTotal = block.rest || 1;
    const near = restLeft <= 3;
    return (
      <div className="fade-in" style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', padding: '0 26px 40px', textAlign: 'center' }}>
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', marginBottom: 8 }}>
          <span className="kicker" style={{ color: 'var(--accent)' }}>DESCANSO</span>
          <SoundToggle muted={muted} onToggle={() => { setMuted(m => !m); ZAudio.ensure(); }} />
        </div>
        <div style={{ margin: '14px auto 24px' }}>
          <ProgressRing size={236} stroke={12} progress={restLeft / restTotal} color="var(--accent)">
            <div style={{ transform: near ? 'scale(1.08)' : 'none', transition: 'transform .2s' }}>
              <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 78, lineHeight: 1, color: near ? 'var(--accent)' : 'var(--text)' }}>{restLeft}</div>
              <div className="mono" style={{ fontSize: 12, color: 'var(--muted)' }}>SEGUNDOS</div>
            </div>
          </ProgressRing>
        </div>
        <div className="card" style={{ padding: '12px 16px', marginBottom: 18 }}>
          <div className="kicker" style={{ marginBottom: 3 }}>A SEGUIR</div>
          <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 700, fontSize: 20, textTransform: 'uppercase' }}>{nextLabel}</div>
        </div>
        <button className="btn btn--ghost" onClick={skip}>Pular descanso<Icon name="next" size={18} /></button>
      </div>
    );
  }

  /* ---------- READY (preparação) ---------- */
  if (phase === 'ready') {
    return (
      <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
        <div style={{ padding: '4px 20px 12px' }}>
          <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
            <button onClick={exitWorkout} style={{ color: 'var(--muted)', display: 'flex' }}>
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
            </button>
            <div style={{ flex: 1, height: 5, borderRadius: 3, background: 'var(--surface-2)', overflow: 'hidden' }}>
              <div style={{ height: '100%', width: `${overall*100}%`, background: 'var(--accent)', borderRadius: 3, transition: 'width .4s ease' }} />
            </div>
            <SoundToggle muted={muted} onToggle={() => { setMuted(m => !m); ZAudio.ensure(); }} />
          </div>
        </div>
        <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', alignItems: 'center', textAlign: 'center', padding: '0 26px 30px' }}>
          <div className="kicker" style={{ color: 'var(--accent)' }}>{block.phase.toUpperCase()} · SÉRIE {set} DE {block.sets}</div>
          <h2 className="h1" style={{ fontSize: 44, margin: '10px 0 4px' }}>{block.name}</h2>
          <p className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginBottom: 26 }}>
            {isTime ? `SEGURE ${block.target}s` : `${block.target} REPS · ~${dur(block)}s`}
          </p>
          <div key={readyLeft} style={{ animation: 'countPulse .4s ease' }}>
            <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 150, lineHeight: 0.85, color: 'var(--accent)' }}>{readyLeft}</div>
          </div>
          <div className="kicker" style={{ marginTop: 8 }}>PREPARE-SE</div>
        </div>
      </div>
    );
  }

  /* ---------- EXERCISE ---------- */
  const prog = (exDur - exLeft) / exDur;
  const near = exLeft <= 5;
  return (
    <div style={{ flex: 1, display: 'flex', flexDirection: 'column', overflow: 'hidden' }}>
      {/* top bar */}
      <div style={{ padding: '4px 20px 12px' }}>
        <div style={{ display: 'flex', alignItems: 'center', gap: 14, marginBottom: 12 }}>
          <button onClick={exitWorkout} style={{ color: 'var(--muted)', display: 'flex' }}>
            <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.2" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18"/></svg>
          </button>
          <div style={{ flex: 1, height: 5, borderRadius: 3, background: 'var(--surface-2)', overflow: 'hidden' }}>
            <div style={{ height: '100%', width: `${overall*100}%`, background: 'var(--accent)', borderRadius: 3, transition: 'width .4s ease' }} />
          </div>
          <SoundToggle muted={muted} onToggle={() => { setMuted(m => !m); ZAudio.ensure(); }} />
        </div>
        <div className="kicker" style={{ color: 'var(--accent)' }}>{block.phase.toUpperCase()} · SÉRIE {set} DE {block.sets}</div>
      </div>

      <div className="screen" style={{ flex: 1 }}>
        <div style={{ padding: '0 22px 24px', display: 'flex', flexDirection: 'column', minHeight: '100%' }}>
          <h2 className="h1" style={{ fontSize: 40, margin: '4px 0 8px' }}>{block.name}</h2>
          <p className="lead" style={{ marginBottom: 16 }}>{block.cue}</p>

          <div className="slot" style={{ height: 132, borderRadius: 'var(--r-lg)', marginBottom: 20, flexDirection: 'column', gap: 5 }}>
            <span>ANIMAÇÃO DO EXERCÍCIO</span><span style={{ opacity: .6 }}>{block.name}</span>
          </div>

          {/* timer automático */}
          <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 14 }}>
            <button onClick={() => setRunning(r => !r)} style={{ borderRadius: '50%' }}>
              <ProgressRing size={252} stroke={13} progress={prog} color="var(--accent)">
                <div key={exLeft} style={{ animation: 'countPulse .35s ease' }}>
                  <div style={{ fontFamily: 'var(--ff-display)', fontWeight: 800, fontSize: 96, lineHeight: 0.85, color: near ? 'var(--accent)' : 'var(--text)' }}>
                    {fmt(exLeft)}
                  </div>
                  <div className="mono" style={{ fontSize: 12, color: 'var(--muted)', marginTop: 6 }}>
                    {!running ? 'PAUSADO · TOQUE P/ SEGUIR' : isTime ? 'SEGUNDOS' : `${block.target} REPS · NO SEU RITMO`}
                  </div>
                </div>
              </ProgressRing>
            </button>
          </div>

          {/* controle de pausa */}
          <div style={{ display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 12, marginBottom: 16 }}>
            <button onClick={() => setRunning(r => !r)} style={{ display: 'inline-flex', alignItems: 'center', gap: 8,
              padding: '10px 18px', borderRadius: 999, background: 'var(--surface)', boxShadow: 'inset 0 0 0 1px var(--line)', color: 'var(--text)', fontSize: 13, fontWeight: 600 }}>
              <Icon name={running ? 'pause' : 'play'} size={18} />{running ? 'Pausar' : 'Retomar'}
            </button>
          </div>

          <div style={{ flex: 1 }} />

          <div style={{ marginBottom: 12 }}><MusicBar playing={music} onToggle={() => setMusic(m => !m)} /></div>
          <button className="btn btn--accent" onClick={skip}>
            {set >= block.sets && bi >= blocks.length - 1 ? 'Finalizar treino' : 'Concluir agora'}
            <Icon name="check" size={20} />
          </button>
        </div>
      </div>
    </div>
  );
}

Object.assign(window, { Workout });
