/* tour.jsx — Guided onboarding tour for ASSYST Academia students */
const { useState: useStateTr, useEffect: useEffectTr } = React;

var TOUR_STEPS = [
  {
    id: 'welcome',
    type: 'modal',
    target: null,
    title: '¡Bienvenido/a a ASSYST Academia!',
    text: 'Te vamos a guiar por la plataforma en menos de 1 minuto.',
    nextLabel: 'Empezar tour',
  },
  {
    id: 'sidebar',
    type: 'highlight',
    target: 'tour-sidebar',
    position: 'right',
    title: 'Panel lateral',
    text: 'Aquí encuentras todo el contenido del curso — módulos, foro, bibliografía del instructor y soporte técnico.',
  },
  {
    id: 'progress',
    type: 'highlight',
    target: 'tour-progress',
    position: 'bottom',
    title: 'Tu progreso',
    text: 'Aquí puedes ver tu avance en tiempo real. Completa todas las lecciones y evaluaciones para obtener tu certificado.',
  },
  {
    id: 'modules',
    type: 'highlight',
    target: 'tour-modules',
    position: 'top',
    title: 'Módulos del curso',
    text: 'El curso tiene varios módulos. Debes completarlos en orden — el botón Siguiente te guía automáticamente.',
  },
  {
    id: 'forum',
    type: 'highlight',
    target: 'tour-forum',
    position: 'right',
    title: 'Foro',
    text: 'Aquí el instructor publica anuncios importantes. También puedes dejar tus comentarios y preguntas.',
  },
  {
    id: 'support',
    type: 'highlight',
    target: 'tour-support',
    position: 'right',
    title: 'Soporte Técnico',
    text: 'Si tienes algún problema técnico o necesitas un nuevo intento en una evaluación, escríbenos aquí.',
  },
  {
    id: 'notifications',
    type: 'highlight',
    target: 'tour-notifications',
    position: 'bottom',
    title: 'Notificaciones',
    text: 'Te notificaremos aquí cuando el instructor publique algo nuevo o responda tus comentarios.',
  },
  {
    id: 'final',
    type: 'modal',
    target: null,
    title: '¡Listo! Ya conoces la plataforma.',
    text: 'Recuerda que al completar el 100% del curso recibirás tu certificado automáticamente. ¡Mucho éxito! 🎓',
    nextLabel: 'Comenzar el curso',
  },
];

var SPOT_PAD = 12;
var CARD_W = 316;
var GAP = 18;

function GuidedTour({ userId, onFinish }) {
  var _step = useStateTr(0);
  var step = _step[0]; var setStep = _step[1];
  var _rect = useStateTr(null);
  var targetRect = _rect[0]; var setTargetRect = _rect[1];

  var totalSteps = TOUR_STEPS.length;
  var cur = TOUR_STEPS[step];
  var isFirst = step === 0;
  var isLast  = step === totalSteps - 1;

  /* ── Measure target element on each step ── */
  useEffectTr(function () {
    if (!cur || !cur.target) { setTargetRect(null); return; }
    function measure() {
      var el = document.querySelector('[data-tour-id="' + cur.target + '"]');
      if (el) {
        var r = el.getBoundingClientRect();
        setTargetRect({ x: r.left, y: r.top, w: r.width, h: r.height });
      } else {
        setTargetRect(null);
      }
    }
    measure();
    var t = setTimeout(measure, 100);
    return function () { clearTimeout(t); };
  }, [step]);

  /* ── Keyboard navigation ── */
  useEffectTr(function () {
    function onKey(e) {
      if (e.key === 'ArrowRight' || e.key === 'Enter') { e.preventDefault(); handleNext(); }
      if (e.key === 'ArrowLeft')                        { e.preventDefault(); handlePrev(); }
      if (e.key === 'Escape')                           { e.preventDefault(); finish(); }
    }
    document.addEventListener('keydown', onKey);
    return function () { document.removeEventListener('keydown', onKey); };
  }, [step]);

  function finish() {
    if (typeof setTourDone === 'function') setTourDone(userId);
    if (onFinish) onFinish();
  }
  function handleSkip() { finish(); }
  function handleNext() { if (isLast) { finish(); } else { setStep(function (s) { return s + 1; }); } }
  function handlePrev() { if (!isFirst) setStep(function (s) { return s - 1; }); }

  /* ── Card positioning ── */
  function getCardStyle() {
    var vw = window.innerWidth;
    var vh = window.innerHeight;
    var base = { position: 'fixed', width: Math.min(CARD_W, vw - 32), zIndex: 9002 };

    if (!targetRect) {
      return Object.assign({}, base, {
        left: '50%',
        top: '50%',
        transform: 'translateX(-50%) translateY(-50%)',
      });
    }

    var pos = cur.position || 'right';
    var sx = targetRect.x; var sy = targetRect.y;
    var sw = targetRect.w; var sh = targetRect.h;
    var cardW = Math.min(CARD_W, vw - 32);
    var cardH = 240; // approx

    if (pos === 'right') {
      var leftR = sx + sw + SPOT_PAD + GAP;
      if (leftR + cardW > vw - 8) leftR = Math.max(8, sx - cardW - SPOT_PAD - GAP);
      return Object.assign({}, base, {
        left: leftR,
        top: Math.max(8, Math.min(sy + sh / 2 - cardH / 2, vh - cardH - 8)),
      });
    }
    if (pos === 'bottom') {
      var topB = sy + sh + SPOT_PAD + GAP;
      if (topB + cardH > vh - 8) topB = Math.max(8, sy - cardH - SPOT_PAD - GAP);
      return Object.assign({}, base, {
        left: Math.max(8, Math.min(sx + sw / 2 - cardW / 2, vw - cardW - 8)),
        top: topB,
      });
    }
    if (pos === 'top') {
      var topT = sy - cardH - SPOT_PAD - GAP;
      if (topT < 8) topT = sy + sh + SPOT_PAD + GAP;
      return Object.assign({}, base, {
        left: Math.max(8, Math.min(sx + sw / 2 - cardW / 2, vw - cardW - 8)),
        top: topT,
      });
    }
    return Object.assign({}, base, { left: 8, top: 8 });
  }

  var cardStyle = getCardStyle();
  var isModal = cur.type === 'modal';

  /* ── Spotlight dimensions ── */
  var spotStyle = targetRect ? {
    position: 'fixed',
    left:   targetRect.x - SPOT_PAD,
    top:    targetRect.y - SPOT_PAD,
    width:  targetRect.w + SPOT_PAD * 2,
    height: targetRect.h + SPOT_PAD * 2,
    borderRadius: 10,
    boxShadow: '0 0 0 9999px rgba(0,0,0,0.76)',
    border: '2px solid #c4b400',
    zIndex: 9001,
    pointerEvents: 'none',
    transition: 'left .22s, top .22s, width .22s, height .22s',
  } : null;

  return (
    <div style={{ fontFamily: "'Montserrat', sans-serif" }}>

      {/* ── Overlay ── */}
      {isModal || !targetRect ? (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.76)', zIndex: 9000 }} />
      ) : (
        <div style={{ position: 'fixed', inset: 0, zIndex: 9000 }} onClick={function (e) { e.stopPropagation(); }} />
      )}

      {/* ── Spotlight ring ── */}
      {!isModal && spotStyle && <div style={spotStyle} />}

      {/* ── Skip button ── */}
      <button
        onClick={handleSkip}
        style={{
          position: 'fixed', top: 14, right: 14,
          background: 'rgba(255,255,255,0.13)',
          color: 'rgba(255,255,255,0.8)',
          border: '1px solid rgba(255,255,255,0.25)',
          borderRadius: 8, padding: '7px 15px',
          fontSize: 11, fontWeight: 700, cursor: 'pointer',
          fontFamily: 'inherit', zIndex: 9003,
          letterSpacing: '0.04em',
          transition: 'background .15s',
        }}
        onMouseOver={function (e) { e.currentTarget.style.background = 'rgba(255,255,255,0.22)'; }}
        onMouseOut={function (e) { e.currentTarget.style.background = 'rgba(255,255,255,0.13)'; }}
      >Saltar tour ✕</button>

      {/* ── Floating card ── */}
      <div style={Object.assign({}, cardStyle, {
        background: 'white',
        borderRadius: 16,
        boxShadow: '0 28px 64px rgba(0,0,0,0.36), 0 0 0 1px rgba(0,0,0,0.06)',
        overflow: 'hidden',
      })}>

        {/* Card header */}
        <div style={{
          background: 'linear-gradient(135deg, #0F2044 0%, #1c79b4 100%)',
          padding: isModal ? '20px 22px 16px' : '14px 20px 12px',
        }}>
          {isModal && (
            <div style={{ display: 'flex', justifyContent: 'center', marginBottom: 10 }}>
              <div style={{ fontSize: 28 }}>🎓</div>
            </div>
          )}
          {!isModal && (
            <div style={{ display: 'flex', alignItems: 'center', gap: 6, marginBottom: 6 }}>
              <div style={{ width: 5, height: 5, background: '#c4b400', borderRadius: '50%' }} />
              <span style={{ fontSize: 9, fontWeight: 700, color: 'rgba(255,255,255,0.5)', textTransform: 'uppercase', letterSpacing: '0.12em' }}>
                Paso {step} de {totalSteps - 2}
              </span>
            </div>
          )}
          <div style={{
            fontSize: isModal ? 16 : 14,
            fontWeight: 800,
            color: 'white',
            lineHeight: 1.3,
            textAlign: isModal ? 'center' : 'left',
          }}>
            {cur.title}
          </div>
        </div>

        {/* Card body */}
        <div style={{ padding: '15px 20px 10px' }}>
          <p style={{
            margin: 0,
            fontSize: 12,
            color: '#374151',
            lineHeight: 1.75,
            textAlign: isModal ? 'center' : 'left',
          }}>
            {cur.text}
          </p>
        </div>

        {/* Progress dots */}
        <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', gap: 5, padding: '8px 20px 12px' }}>
          {TOUR_STEPS.map(function (_, i) {
            var active  = i === step;
            var visited = i < step;
            return (
              <div key={i} style={{
                width:  active ? 20 : 6,
                height: 6,
                borderRadius: 3,
                background: active ? '#1c79b4' : visited ? '#c4b400' : '#e2e8f0',
                transition: 'width .22s, background .22s',
                flexShrink: 0,
              }} />
            );
          })}
        </div>

        {/* Nav buttons */}
        <div style={{ display: 'flex', gap: 8, padding: '0 20px 18px' }}>
          {!isFirst && (
            <button
              onClick={handlePrev}
              style={{
                background: '#f1f5f9', color: '#374151', border: 'none',
                borderRadius: 9, padding: '10px 16px',
                fontSize: 12, fontWeight: 700, cursor: 'pointer',
                fontFamily: 'inherit', transition: 'background .15s', flexShrink: 0,
              }}
              onMouseOver={function (e) { e.currentTarget.style.background = '#e2e8f0'; }}
              onMouseOut={function (e) { e.currentTarget.style.background = '#f1f5f9'; }}
            >← Anterior</button>
          )}
          <button
            onClick={handleNext}
            style={{
              flex: 1,
              background: '#1c79b4', color: 'white', border: 'none',
              borderRadius: 9, padding: '10px 18px',
              fontSize: 12, fontWeight: 800, cursor: 'pointer',
              fontFamily: 'inherit', transition: 'background .15s',
            }}
            onMouseOver={function (e) { e.currentTarget.style.background = '#155f9a'; }}
            onMouseOut={function (e) { e.currentTarget.style.background = '#1c79b4'; }}
          >
            {cur.nextLabel || (isLast ? 'Comenzar el curso' : 'Siguiente →')}
          </button>
        </div>

      </div>
    </div>
  );
}

window.GuidedTour = GuidedTour;
