// Compatible con Babel standalone — NO usar imports
function EsperiencyTour({ steps, onComplete, onSkip, onNavigate }) {
  const { useState, useEffect, useCallback, useRef } = React;
  const [index, setIndex] = useState(0);
  const [rect, setRect] = useState(null);
  const tooltipRef = useRef(null);
  const content = window.EsperiencyTutorialContent || {};
  const ui = content.ui || {};
  const step = steps[index];
  const total = steps.length;

  const measure = useCallback(() => {
    if (!step) return;
    const el = document.querySelector(step.selector);
    if (!el) {
      setRect(null);
      return;
    }
    const r = el.getBoundingClientRect();
    const pad = 8;
    setRect({
      top: Math.max(8, r.top - pad),
      left: Math.max(8, r.left - pad),
      width: Math.min(window.innerWidth - 16, r.width + pad * 2),
      height: Math.min(window.innerHeight - 16, r.height + pad * 2),
    });
    try {
      el.scrollIntoView({ block: 'nearest', inline: 'nearest', behavior: 'smooth' });
    } catch (e) {
      el.scrollIntoView();
    }
  }, [step]);

  useEffect(() => {
    if (!step) return;
    let cancelled = false;
    const go = () => {
      if (cancelled) return;
      if (typeof onNavigate === 'function' && step.page) {
        onNavigate(step.page);
      } else if (typeof window.setCurrentPage === 'function' && step.page) {
        window.setCurrentPage(step.page);
      }
      // wait for page paint / nav transition
      setTimeout(() => {
        if (!cancelled) measure();
      }, 120);
      setTimeout(() => {
        if (!cancelled) measure();
      }, 420);
    };
    go();
    const onResize = () => measure();
    window.addEventListener('resize', onResize);
    window.addEventListener('scroll', onResize, true);
    return () => {
      cancelled = true;
      window.removeEventListener('resize', onResize);
      window.removeEventListener('scroll', onResize, true);
    };
  }, [step, measure, onNavigate]);

  useEffect(() => {
    const onKey = (e) => {
      if (e.key === 'Escape') {
        e.preventDefault();
        if (typeof onSkip === 'function') onSkip();
      } else if (e.key === 'ArrowRight' || e.key === 'Enter') {
        e.preventDefault();
        if (index >= total - 1) {
          if (typeof onComplete === 'function') onComplete();
        } else {
          setIndex((i) => Math.min(total - 1, i + 1));
        }
      } else if (e.key === 'ArrowLeft') {
        e.preventDefault();
        setIndex((i) => Math.max(0, i - 1));
      }
    };
    window.addEventListener('keydown', onKey);
    return () => window.removeEventListener('keydown', onKey);
  }, [index, total, onComplete, onSkip]);

  useEffect(() => {
    const node = tooltipRef.current;
    if (!node) return;
    const focusable = node.querySelector('button');
    if (focusable) focusable.focus();
  }, [index]);

  if (!step) return null;

  const tooltipStyle = (() => {
    if (!rect) {
      return { top: '50%', left: '50%', transform: 'translate(-50%, -50%)' };
    }
    const tipW = 340;
    const tipH = 190;
    let top = rect.top;
    let left = rect.left + rect.width + 14;
    const placement = step.placement || 'right';

    if (placement === 'right' && left + tipW > window.innerWidth - 12) {
      left = Math.max(12, rect.left - tipW - 14);
    }
    if (placement === 'left') {
      left = Math.max(12, rect.left - tipW - 14);
    }
    if (placement === 'bottom') {
      top = rect.top + rect.height + 14;
      left = Math.max(12, Math.min(window.innerWidth - tipW - 12, rect.left));
    }
    if (placement === 'top') {
      top = Math.max(12, rect.top - tipH - 14);
      left = Math.max(12, Math.min(window.innerWidth - tipW - 12, rect.left));
    }
    if (top + tipH > window.innerHeight - 12) {
      top = Math.max(12, window.innerHeight - tipH - 12);
    }
    return { top, left };
  })();

  const counterText = (ui.stepOf || 'Paso {current} de {total}')
    .replace('{current}', String(index + 1))
    .replace('{total}', String(total));

  return (
    <div className="tutorial-tour-overlay tutorial-layer" role="dialog" aria-modal="true" aria-labelledby="tutorial-tour-title">
      <div className="tutorial-backdrop" aria-hidden="true" />
      {rect && (
        <div
          className="tutorial-highlight"
          style={{ top: rect.top, left: rect.left, width: rect.width, height: rect.height }}
          aria-hidden="true"
        />
      )}

      <div className="tutorial-tour-chrome">
        <div className="tutorial-step-counter" aria-live="polite">{counterText}</div>
        <button type="button" className="tutorial-btn tutorial-btn-ghost" onClick={onSkip}>
          <i className="fas fa-xmark" aria-hidden="true"></i> {ui.skipTour || 'Saltar tutorial'}
        </button>
      </div>

      <div className="tutorial-tooltip" ref={tooltipRef} style={tooltipStyle}>
        <h3 id="tutorial-tour-title">
          <i className={`fas ${step.icon || 'fa-circle-info'}`} aria-hidden="true"></i>
          {step.title}
        </h3>
        <p>{step.description}</p>
        <div className="tutorial-tooltip-footer">
          <div className="tutorial-progress-dots" aria-hidden="true">
            {steps.map((s, i) => (
              <span key={s.id} className={i === index ? 'active' : i < index ? 'done' : ''} />
            ))}
          </div>
          <div className="tutorial-tour-nav">
            <button
              type="button"
              className="tutorial-btn tutorial-btn-secondary"
              disabled={index === 0}
              onClick={() => setIndex((i) => Math.max(0, i - 1))}
            >
              {ui.prev || 'Anterior'}
            </button>
            {index >= total - 1 ? (
              <button type="button" className="tutorial-btn tutorial-btn-primary" onClick={onComplete}>
                {ui.finishTour || 'Ir a laboratorios'}
              </button>
            ) : (
              <button
                type="button"
                className="tutorial-btn tutorial-btn-primary"
                onClick={() => setIndex((i) => Math.min(total - 1, i + 1))}
              >
                {ui.next || 'Siguiente'}
              </button>
            )}
          </div>
        </div>
      </div>
    </div>
  );
}

window.EsperiencyTour = EsperiencyTour;
