// ═══════════════════════════════════════════════════════════════
// Pau Fit — MODO ENTRENO (fase 2 del roadmap Sweat)
//
// Player de entrenamiento a pantalla completa, HONESTO:
// cronómetro REAL controlado por la usuaria (nada simulado),
// vídeo Bunny opcional, objetivo de minutos opcional.
// El caller guarda el resultado vía onFinish({ durationMs }).
//
// Uso: <EntrenoPlayer T={T} nav={nav} session={...} onClose={...} onFinish={...}/>
// session = { title, subtitle?, targetMinutes?, bunnyGuid?, bunnyGuidVoice? }
// ═══════════════════════════════════════════════════════════════

const useEpState = React.useState;
const useEpEffect = React.useEffect;
const useEpRef = React.useRef;

// mm:ss con ceros (los minutos pueden pasar de 59: 75:03 está bien)
function epFormat(ms) {
  const total = Math.max(0, Math.floor(ms / 1000));
  const m = Math.floor(total / 60);
  const s = total % 60;
  return `${String(m).padStart(2, '0')}:${String(s).padStart(2, '0')}`;
}

// ─────────────────────────────────────────────────────────────
// Vídeo Bunny (mismo flujo que BunnyPlayerModal: fetch → iframe)
// Si falla, mensaje suave: el player sigue siendo útil con crono.
// ─────────────────────────────────────────────────────────────
function EpBunnyVideo({ guid, guidVoice, T }) {
  const [mode, setMode] = useEpState('music'); // 'music' | 'voice'
  const [data, setData] = useEpState(null);
  const [error, setError] = useEpState(null);

  const activeGuid = mode === 'voice' && guidVoice ? guidVoice : guid;

  useEpEffect(() => {
    let abort = false;
    setData(null);
    setError(null);
    (async () => {
      try {
        const res = await fetch(`/api/bunny/playback/${activeGuid}`);
        const json = await res.json();
        if (!res.ok) throw new Error(json.error || 'No se pudo cargar');
        if (!abort) setData(json);
      } catch (e) {
        if (!abort) setError(e.message || 'Error');
      }
    })();
    return () => { abort = true; };
  }, [activeGuid]);

  return (
    <div>
      <div style={{
        width: '100%', aspectRatio: '16 / 9', borderRadius: 20,
        overflow: 'hidden', background: error ? T.card : T.subtle,
        border: error ? `0.5px solid ${T.border}` : 'none',
        position: 'relative',
      }}>
        {/* Cargando: skeleton silencioso */}
        {!data && !error && (
          <div style={{
            position: 'absolute', inset: 0, background: T.subtle,
            animation: 'fade-in 400ms ease',
          }}/>
        )}

        {/* Error suave: se puede entrenar igual */}
        {error && (
          <div style={{
            position: 'absolute', inset: 0, display: 'flex', flexDirection: 'column',
            alignItems: 'center', justifyContent: 'center', gap: 6, padding: 20,
            textAlign: 'center',
          }}>
            <div style={{ fontSize: 28 }}>🎬</div>
            <div style={{ fontSize: 13, fontWeight: 600, color: T.text }}>
              El vídeo no está disponible ahora
            </div>
            <div style={{ fontSize: 11, color: T.muted }}>
              Puedes entrenar igual con el cronómetro
            </div>
          </div>
        )}

        {data && (
          <iframe
            key={activeGuid}
            src={data.iframe}
            allow="accelerometer; gyroscope; autoplay; encrypted-media; picture-in-picture"
            allowFullScreen
            style={{ border: 0, width: '100%', height: '100%', display: 'block' }}
            title={data.title || 'Entreno'}
          />
        )}
      </div>

      {/* Toggle música / solo voz (solo si hay pista de voz) */}
      {guidVoice && !error && (
        <div style={{ display: 'flex', justifyContent: 'center', marginTop: 10 }}>
          <div style={{
            display: 'flex', background: T.subtle, borderRadius: 999, padding: 3,
          }}>
            {[['music', '🎵 Música'], ['voice', '🎙️ Solo voz']].map(([k, label]) => (
              <button key={k} onClick={() => setMode(k)} style={{
                padding: '6px 14px', border: 'none', borderRadius: 999, cursor: 'pointer',
                background: mode === k ? T.card : 'transparent',
                color: mode === k ? T.text : T.muted,
                fontSize: 11, fontWeight: 600, fontFamily: 'inherit',
              }}>{label}</button>
            ))}
          </div>
        </div>
      )}
    </div>
  );
}

// ─────────────────────────────────────────────────────────────
// EntrenoPlayer — overlay a pantalla completa
// ─────────────────────────────────────────────────────────────
function EntrenoPlayer({ T, nav, session, onClose, onFinish }) {
  const s = session || {};
  const targetMin = typeof s.targetMinutes === 'number' && s.targetMinutes > 0 ? s.targetMinutes : null;

  const [phase, setPhase] = useEpState('timer'); // 'timer' | 'done'
  const [running, setRunning] = useEpState(false);
  const [elapsedMs, setElapsedMs] = useEpState(0);
  const [finishing, setFinishing] = useEpState(false);

  // Crono REAL: base de timestamp para no derivar aunque el tab se duerma.
  const accRef = useEpRef(0);      // ms acumulados en pausas anteriores
  const startRef = useEpRef(null); // Date.now() del último play

  useEpEffect(() => {
    if (!running) return undefined;
    const tick = () => {
      if (startRef.current != null) {
        setElapsedMs(accRef.current + (Date.now() - startRef.current));
      }
    };
    tick();
    const id = setInterval(tick, 1000);
    return () => clearInterval(id);
  }, [running]);

  function togglePlay() {
    if (running) {
      if (startRef.current != null) accRef.current += Date.now() - startRef.current;
      startRef.current = null;
      setElapsedMs(accRef.current);
      setRunning(false);
    } else {
      startRef.current = Date.now();
      setRunning(true);
    }
  }

  function terminar() {
    let total = accRef.current;
    if (running && startRef.current != null) total += Date.now() - startRef.current;
    accRef.current = total;
    startRef.current = null;
    setRunning(false);
    setElapsedMs(total);
    setPhase('done');
  }

  function cerrar() {
    if (running) {
      if (!window.confirm('¿Salir del entreno? El tiempo no se guardará.')) return;
    }
    onClose && onClose();
  }

  // Mantener la pantalla despierta durante el entreno (si hay API)
  useEpEffect(() => {
    let lock = null;
    let released = false;
    (async () => {
      try {
        lock = await (navigator.wakeLock && navigator.wakeLock.request('screen'));
        if (released && lock) { try { await lock.release(); } catch {} }
      } catch {}
    })();
    return () => {
      released = true;
      try { lock && lock.release && lock.release(); } catch {}
    };
  }, []);

  const elapsedMin = elapsedMs / 60000;
  const progress = targetMin ? Math.min(1, elapsedMin / targetMin) : 0;
  const objetivoCumplido = targetMin != null && elapsedMin >= targetMin;
  const puedeTerminar = elapsedMs >= 60000;

  const IconSet = window.Icon || {};
  const playIcon = IconSet.playFilled
    ? IconSet.playFilled({ c: '#fff', size: 26 })
    : (
      <svg width="26" height="26" viewBox="0 0 12 12" fill="none">
        <path d="M3 1.5l7 4.5-7 4.5V1.5z" fill="#fff"/>
      </svg>
    );
  const pauseIcon = (
    <svg width="24" height="24" viewBox="0 0 24 24" fill="none">
      <rect x="5.5" y="4" width="4.5" height="16" rx="1.5" fill="#fff"/>
      <rect x="14" y="4" width="4.5" height="16" rx="1.5" fill="#fff"/>
    </svg>
  );

  const ConfettiCmp = window.Confetti || null;

  return (
    <div style={{
      position: 'fixed', inset: 0, zIndex: 10000,
      background: T.bg, color: T.text,
      display: 'flex', flexDirection: 'column',
      animation: 'fade-in 220ms ease',
    }}>
      {/* ── CABECERA ── */}
      <div style={{
        padding: 'calc(env(safe-area-inset-top, 0px) + 14px) 20px 10px',
        display: 'grid', gridTemplateColumns: '36px 1fr 36px',
        alignItems: 'center', gap: 8, flexShrink: 0,
      }}>
        <button onClick={cerrar} aria-label="Cerrar" style={{
          width: 36, height: 36, borderRadius: 999,
          border: `0.5px solid ${T.border}`, background: T.card,
          color: T.text, fontSize: 15, cursor: 'pointer',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          fontFamily: 'inherit',
        }}>✕</button>
        <div style={{ textAlign: 'center', minWidth: 0 }}>
          <div style={{
            fontSize: 15, fontWeight: 700, letterSpacing: -0.2,
            whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
          }}>{s.title || 'Entreno'}</div>
          {s.subtitle && (
            <div style={{
              fontSize: 11, color: T.muted, marginTop: 1,
              whiteSpace: 'nowrap', overflow: 'hidden', textOverflow: 'ellipsis',
            }}>{s.subtitle}</div>
          )}
        </div>
        <div/>
      </div>

      {/* ── CONTENIDO ── */}
      {phase === 'timer' ? (
        <div style={{
          flex: 1, overflowY: 'auto',
          padding: '8px 20px calc(env(safe-area-inset-bottom, 0px) + 28px)',
          display: 'flex', flexDirection: 'column',
        }}>
          {/* Vídeo Bunny o hero con objetivo */}
          {s.bunnyGuid ? (
            <EpBunnyVideo guid={s.bunnyGuid} guidVoice={s.bunnyGuidVoice} T={T}/>
          ) : (
            <div style={{
              borderRadius: 28, background: T.card, border: `0.5px solid ${T.border}`,
              padding: '32px 20px', textAlign: 'center',
            }}>
              <div style={{ fontSize: 54, lineHeight: 1 }}>💪</div>
              <div style={{ fontSize: 13, fontWeight: 600, color: T.text, marginTop: 12 }}>
                {targetMin ? `Objetivo: ~${targetMin} min` : 'A tu ritmo'}
              </div>
              <div style={{ fontSize: 11, color: T.muted, marginTop: 4 }}>
                Dale al play cuando empieces
              </div>
            </div>
          )}

          {/* Cronómetro protagonista */}
          <div style={{ flex: 1, display: 'flex', flexDirection: 'column', justifyContent: 'center', minHeight: 200 }}>
            <div className="pf-display" style={{
              fontSize: 72, fontWeight: 800, letterSpacing: -1.4,
              textAlign: 'center', fontVariantNumeric: 'tabular-nums',
              color: T.text, lineHeight: 1.05,
            }}>{epFormat(elapsedMs)}</div>

            {targetMin != null && (
              <div style={{ marginTop: 18, padding: '0 12px' }}>
                <div style={{
                  height: 4, borderRadius: 999, background: T.subtle, overflow: 'hidden',
                }}>
                  <div style={{
                    height: '100%', borderRadius: 999, background: T.accent,
                    width: `${progress * 100}%`,
                    transition: 'width 600ms cubic-bezier(.2,.8,.2,1)',
                  }}/>
                </div>
                <div style={{
                  fontSize: 11, marginTop: 8, textAlign: 'center',
                  color: objetivoCumplido ? T.accent : T.muted,
                  fontWeight: objetivoCumplido ? 700 : 500,
                }}>
                  {objetivoCumplido
                    ? '¡Objetivo cumplido! 🎉'
                    : `${Math.floor(elapsedMin)} de ~${targetMin} min`}
                </div>
              </div>
            )}
          </div>

          {/* Controles */}
          <div style={{
            display: 'flex', alignItems: 'center', justifyContent: 'center',
            gap: 16, flexShrink: 0,
          }}>
            <button onClick={togglePlay} aria-label={running ? 'Pausar' : 'Empezar'} style={{
              width: 72, height: 72, borderRadius: 999, border: 'none',
              background: T.accent, cursor: 'pointer',
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: '0 8px 20px rgba(0,0,0,0.16)',
            }}>
              {running ? pauseIcon : (
                <span style={{ display: 'flex', marginLeft: 3 }}>{playIcon}</span>
              )}
            </button>
            <button onClick={terminar} disabled={!puedeTerminar} style={{
              padding: '13px 24px', borderRadius: 999,
              border: `0.5px solid ${T.border}`, background: T.card,
              color: T.text, fontSize: 13, fontWeight: 700, fontFamily: 'inherit',
              cursor: puedeTerminar ? 'pointer' : 'default',
              opacity: puedeTerminar ? 1 : 0.5,
            }}>Terminar</button>
          </div>
        </div>
      ) : (
        /* ── PANTALLA DE CIERRE ── */
        <div style={{
          flex: 1, position: 'relative', overflowY: 'auto',
          padding: '8px 20px calc(env(safe-area-inset-bottom, 0px) + 28px)',
          display: 'flex', flexDirection: 'column',
          alignItems: 'center', justifyContent: 'center',
        }}>
          {ConfettiCmp && <ConfettiCmp show/>}

          <div className="pf-display" style={{
            fontSize: 30, fontWeight: 800, letterSpacing: -0.8,
            textAlign: 'center', color: T.text,
          }}>¡Entreno completado!</div>

          <div className="pf-display" style={{
            fontSize: 56, fontWeight: 800, letterSpacing: -1.2,
            fontVariantNumeric: 'tabular-nums', color: T.text, marginTop: 18,
          }}>{epFormat(elapsedMs)}</div>
          <div style={{ fontSize: 11, color: T.muted, marginTop: 4 }}>
            de entreno real
          </div>

          <button
            onClick={() => {
              if (finishing) return;
              setFinishing(true);
              onFinish && onFinish({ durationMs: elapsedMs });
            }}
            disabled={finishing}
            style={{
              marginTop: 32, width: '100%', maxWidth: 320, padding: '15px',
              border: 'none', borderRadius: 999, cursor: 'pointer',
              background: T.accent, color: '#fff',
              fontSize: 14, fontWeight: 700, letterSpacing: -0.1, fontFamily: 'inherit',
              opacity: finishing ? 0.6 : 1,
              boxShadow: '0 8px 20px rgba(0,0,0,0.16)',
            }}
          >Completar día ✓</button>

          <button onClick={() => setPhase('timer')} style={{
            marginTop: 10, padding: '12px 20px',
            border: 'none', background: 'transparent', cursor: 'pointer',
            color: T.muted, fontSize: 13, fontWeight: 600, fontFamily: 'inherit',
          }}>Volver</button>
        </div>
      )}
    </div>
  );
}

Object.assign(window, { EntrenoPlayer });
