// Compatible con Babel standalone — NO usar imports
function EsperiencyDemoPlayer({ demo, onClose, onCompleted }) {
  const { useState, useEffect, useRef } = React;
  const [useFallback, setUseFallback] = useState(false);
  const [stepIndex, setStepIndex] = useState(0);
  const completedRef = useRef(false);
  const content = window.EsperiencyTutorialContent || {};
  const hub = content.hub || {};
  const steps = (demo && demo.steps) || [];

  useEffect(() => {
    completedRef.current = false;
    setStepIndex(0);
    setUseFallback(false);
  }, [demo && demo.id]);

  useEffect(() => {
    if (!useFallback || !steps.length) return undefined;
    setStepIndex(0);
    let i = 0;
    const id = setInterval(() => {
      i += 1;
      if (i >= steps.length) {
        clearInterval(id);
        if (!completedRef.current) {
          completedRef.current = true;
          if (typeof onCompleted === 'function') onCompleted(demo.id);
        }
        return;
      }
      setStepIndex(i);
    }, 1600);
    return () => clearInterval(id);
  }, [useFallback, demo && demo.id, steps.length, onCompleted]);

  if (!demo) return null;

  const markDone = () => {
    if (!completedRef.current) {
      completedRef.current = true;
      if (typeof onCompleted === 'function') onCompleted(demo.id);
    }
  };

  return (
    <div className="tutorial-demo tutorial-layer" role="dialog" aria-modal="true" aria-labelledby="tutorial-demo-title">
      <div className="tutorial-demo-panel">
        <div className="tutorial-demo-header">
          <div>
            <h3 id="tutorial-demo-title" style={{ margin: 0 }}>
              <i className={`fas ${demo.icon || 'fa-play'} `} style={{ color: 'var(--tutorial-accent)', marginRight: 8 }} aria-hidden="true"></i>
              {demo.title}
            </h3>
            <p style={{ margin: '4px 0 0', color: 'var(--tutorial-muted)', fontSize: '0.85rem' }}>{demo.description}</p>
          </div>
          <button type="button" className="tutorial-btn tutorial-btn-ghost" onClick={onClose} aria-label={hub.close || 'Cerrar'}>
            <i className="fas fa-xmark" aria-hidden="true"></i>
          </button>
        </div>

        <div className="tutorial-demo-stage">
          {!useFallback ? (
            <video
              key={demo.id}
              src={demo.video}
              poster={demo.poster}
              controls
              autoPlay
              playsInline
              onError={() => setUseFallback(true)}
              onEnded={markDone}
            />
          ) : (
            <div className="tutorial-demo-fallback" aria-live="polite">
              {steps.map((s, idx) => (
                <div key={idx} className={`tutorial-demo-step ${idx <= stepIndex ? 'active' : ''}`}>
                  <div className="tutorial-demo-step-num">{idx + 1}</div>
                  <div>
                    <div style={{ fontWeight: 650 }}>{s.label}</div>
                    <div style={{ color: 'var(--tutorial-muted)', fontSize: '0.88rem' }}>{s.detail}</div>
                  </div>
                </div>
              ))}
              {!steps.length && (
                <div style={{ color: 'var(--tutorial-muted)' }}>Demo animada no disponible todavía.</div>
              )}
            </div>
          )}
        </div>

        <div className="tutorial-demo-footer">
          <span style={{ color: 'var(--tutorial-muted)', fontSize: '0.8rem' }}>
            {useFallback ? 'Vista animada (sin video grabado)' : demo.duration || ''}
          </span>
          <div style={{ display: 'flex', gap: 8 }}>
            {useFallback && (
              <button
                type="button"
                className="tutorial-btn tutorial-btn-secondary"
                onClick={() => {
                  completedRef.current = false;
                  setStepIndex(0);
                  // Force remount of fallback animation cycle
                  setUseFallback(false);
                  requestAnimationFrame(() => setUseFallback(true));
                }}
              >
                {hub.replay || 'Ver de nuevo'}
              </button>
            )}
            <button
              type="button"
              className="tutorial-btn tutorial-btn-primary"
              onClick={() => {
                markDone();
                onClose();
              }}
            >
              {hub.close || 'Cerrar'}
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.EsperiencyDemoPlayer = EsperiencyDemoPlayer;
