// OnboardingTour.jsx — Guided first-use tour with overlay highlight
'use babel';

const STEPS_PROFESSIONAL = [
  { target: '[data-tour="sidebar"]',    title: 'Navegación',    desc: 'Desde aquí accedes a todas las secciones del dashboard.' },
  { target: '[data-tour="buscar"]',     title: 'Buscar box',    desc: 'Encuentra boxes disponibles por especialidad, filtra y reserva en minutos.' },
  { target: '[data-tour="reservas"]',   title: 'Mis reservas',  desc: 'Ve y gestiona todas tus reservas — confirma, cancela o califica.' },
  { target: '[data-tour="calendario"]', title: 'Calendario',    desc: 'Visualiza tus próximas y pasadas reservas por mes.' },
];

const STEPS_OWNER = [
  { target: '[data-tour="sidebar"]',        title: 'Navegación',           desc: 'Desde aquí accedes a todas las secciones.' },
  { target: '[data-tour="boxes"]',          title: 'Mis boxes',            desc: 'Administra tus espacios — actívalos, edítalos y sube fotos.' },
  { target: '[data-tour="reservas-owner"]', title: 'Reservas',             desc: 'Ve quién reservó tu box y en qué horario.' },
  { target: '[data-tour="checkin"]',        title: 'Check-in / Check-out', desc: 'Gestiona la llegada y salida de profesionales en tiempo real.' },
];

const STEPS_PROFESSIONAL_MOBILE = [
  { target: '[data-tour="mobile-inicio"]',   title: 'Inicio',        desc: 'Aquí ves tu resumen, KPIs y calendario de reservas.' },
  { target: '[data-tour="mobile-buscar"]',   title: 'Buscar box',    desc: 'Encuentra y reserva boxes disponibles por especialidad.' },
  { target: '[data-tour="mobile-reservas"]', title: 'Mis reservas',  desc: 'Ve y gestiona todas tus reservas.' },
  { target: '[data-tour="calendario"]',      title: 'Calendario',    desc: 'Visualiza tus próximas y pasadas reservas por mes.' },
];

const STORAGE_KEY = {
  professional: 'lokat_tour_done_professional',
  owner:        'lokat_tour_done_owner',
};

const OnboardingTour = ({ role, onDone }) => {
  const isMobile = window.innerWidth <= 768;
  const steps = role === 'owner' ? STEPS_OWNER : (isMobile ? STEPS_PROFESSIONAL_MOBILE : STEPS_PROFESSIONAL);
  const storageKey = STORAGE_KEY[role] || STORAGE_KEY.professional;

  const [current, setCurrent] = React.useState(0);
  const [rect, setRect]       = React.useState(() => {
    const el = document.querySelector(STEPS_PROFESSIONAL[0]?.target);
    if (el) {
      const r = el.getBoundingClientRect();
      if (r.width > 0) return { top: r.top, left: r.left, width: r.width, height: r.height };
    }
    return null;
  });
  const [visible, setVisible] = React.useState(false);

  // Check if tour already done
  React.useEffect(() => {
    if (localStorage.getItem(storageKey)) return;
    setVisible(true);
  }, [storageKey]);

  // Measure target element whenever step changes
  React.useLayoutEffect(() => {
    if (!visible) return;
    let attempts = 0;
    const measure = () => {
      const el = document.querySelector(steps[current]?.target);
      if (el) {
        const r = el.getBoundingClientRect();
        if (r.width > 0 && r.height > 0) {
          el.scrollIntoView({ behavior: 'smooth', block: 'center' });
          // Esperar que el scroll termine antes de medir de nuevo
          setTimeout(() => {
            const r2 = el.getBoundingClientRect();
            setRect({ top: r2.top, left: r2.left, width: r2.width, height: r2.height });
          }, 400);
          return;
        }
      }
      // Elemento no encontrado o sin dimensiones — reintentar
      attempts++;
      if (attempts < 20) {
        setTimeout(measure, 100);
      }
    };
    setTimeout(measure, 100);
    window.addEventListener('resize', measure);
    return () => window.removeEventListener('resize', measure);
  }, [current, visible]);

  const finish = () => {
    localStorage.setItem(storageKey, '1');
    setVisible(false);
    if (onDone) onDone();
  };

  const next = () => {
    if (current < steps.length - 1) {
      setCurrent(c => c + 1);
    } else {
      finish();
    }
  };

  if (!visible) return null;

  const step = steps[current];
  const PAD = 8;           // padding around highlighted element
  const BANNER_HEIGHT = 40; // fixed beta banner at top

  // Highlight box position — clamp top so it never hides under the banner
  const hlTop    = rect ? Math.max(rect.top    - PAD, BANNER_HEIGHT) : 0;
  const hlLeft   = rect ? rect.left   - PAD : 0;
  const hlWidth  = rect ? rect.width  + PAD * 2 : 0;
  const hlHeight = rect ? Math.max(rect.height + PAD * 2 - Math.max(0, BANNER_HEIGHT - (rect.top - PAD)), 0) : 0;

  const isSidebarStep = step.target.includes('sidebar');

  let tooltipLeft, tooltipTop, isLeftElement;

  if (isSidebarStep) {
    // Sidebar: tooltip a la derecha fijo
    tooltipLeft = 228;
    tooltipTop = 60;
    isLeftElement = true;
  } else if (rect) {
    // Elementos en el sidebar nav (buscar, reservas) — también a la derecha
    if (rect.left < 220) {
      tooltipLeft = 228;
      tooltipTop = rect.top;
      isLeftElement = true;
    }
    // Elementos en el contenido principal (calendario) — a la izquierda del elemento
    else {
      tooltipLeft = Math.max(rect.left - 316, 16);
      tooltipTop = Math.max(rect.top, 60);
      isLeftElement = false;
    }
  } else {
    tooltipLeft = window.innerWidth / 2 - 150;
    tooltipTop = window.innerHeight / 2 - 80;
    isLeftElement = false;
  }

  // Override para mobile con bottom bar: tooltip encima del elemento
  if (isMobile && rect && rect.top > window.innerHeight * 0.7) {
    tooltipTop = rect.top - 180;
    tooltipLeft = Math.max(rect.left - 80, 8);
    isLeftElement = false;
  }

  // Arrow direction: sidebar tooltip opens to the right (no vertical arrow needed)
  const arrowDown  = false;
  const arrowStyle = {
    width: 0, height: 0,
    borderLeft: '8px solid transparent',
    borderRight: '8px solid transparent',
    ...(arrowDown
      ? { borderTop: '10px solid #fff', marginBottom: 8 }
      : { borderBottom: '10px solid #fff', marginTop: 8 }),
  };

  return (
    <div style={{ position: 'fixed', inset: 0, zIndex: 9999, pointerEvents: 'none' }}>

      {/* Dark overlay using box-shadow trick on highlight element */}
      {rect ? (
        <div style={{
          position:    'fixed',
          top:         hlTop,
          left:        hlLeft,
          width:       hlWidth,
          height:      hlHeight,
          borderRadius: 8,
          boxShadow:   '0 0 0 9999px rgba(0,0,0,0.75)',
          pointerEvents: 'none',
          transition:  'top 0.3s, left 0.3s, width 0.3s, height 0.3s',
        }} />
      ) : (
        <div style={{ position: 'fixed', inset: 0, background: 'rgba(0,0,0,0.75)', pointerEvents: 'none' }} />
      )}

      {/* Tooltip */}
      <div style={{
        position:     'fixed',
        top:          tooltipTop,
        left:         tooltipLeft,
        width:        isLeftElement ? 220 : 300,
        background:   '#fff',
        borderRadius: 12,
        padding:      '16px 18px',
        boxShadow:    '0 8px 32px rgba(0,0,0,0.25)',
        pointerEvents: 'auto',
        transition:   'top 0.3s, left 0.3s',
        fontFamily:   "'Helvetica Neue', Helvetica, Arial, sans-serif",
        zIndex:       10000,
      }}>
        {/* Arrow */}
        <div style={{ display: 'flex', justifyContent: 'flex-start', paddingLeft: 16,
          ...(arrowDown ? { order: 1, marginTop: 4 } : { marginBottom: 4 }) }}>
          {arrowDown
            ? <div style={{ width:0, height:0, borderLeft:'8px solid transparent', borderRight:'8px solid transparent', borderTop:'10px solid #fff', filter:'drop-shadow(0 2px 2px rgba(0,0,0,0.15))' }} />
            : <div style={{ width:0, height:0, borderLeft:'8px solid transparent', borderRight:'8px solid transparent', borderBottom:'10px solid #fff', filter:'drop-shadow(0 -2px 2px rgba(0,0,0,0.15))' }} />
          }
        </div>

        {/* Step counter */}
        <div style={{ fontSize: 10, fontWeight: 600, color: '#adb5bd', letterSpacing: 1, textTransform: 'uppercase', marginBottom: 6 }}>
          Paso {current + 1} de {steps.length}
        </div>

        {/* Title */}
        <div style={{ fontSize: 16, fontWeight: 700, color: '#1a1d23', marginBottom: 4 }}>
          {step.title}
        </div>

        {/* Description */}
        <div style={{ fontSize: 13, color: '#636e72', lineHeight: 1.5, marginBottom: 14 }}>
          {step.desc}
        </div>

        {/* Progress dots */}
        <div style={{ display: 'flex', gap: 4, marginBottom: 14 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              width: i === current ? 18 : 6,
              height: 6,
              borderRadius: 3,
              background: i === current ? '#0984e3' : '#dee2e6',
              transition: 'width 0.2s',
            }} />
          ))}
        </div>

        {/* Buttons */}
        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button
            onClick={finish}
            style={{ background: 'none', border: 'none', color: '#adb5bd', fontSize: 12, cursor: 'pointer', fontFamily: 'inherit', padding: 0 }}
          >
            Saltar tour
          </button>
          <button
            onClick={next}
            style={{ background: '#0984e3', color: '#fff', border: 'none', borderRadius: 8, padding: '8px 20px', fontSize: 13, fontWeight: 600, cursor: 'pointer', fontFamily: 'inherit' }}
          >
            {current < steps.length - 1 ? 'Siguiente →' : 'Comenzar'}
          </button>
        </div>
      </div>
    </div>
  );
};

window.OnboardingTour = OnboardingTour;
