const { useState: useStateOnb, useEffect: useEffectOnb, useLayoutEffect: useLayoutEffectOnb } = React;

// Each step's `target` is a data-onboarding-id attribute on the element we highlight.
// Two walkthroughs: the short Easy tour, and the full Advanced tour (which now also
// explains the Easy/Advanced mode switch).
const BUILD_STEPS = (lang, mode = 'advanced') => {
  const t = (k) => window.__t(k, lang);

  if (mode === 'easy') {
    return [
      { section: null,       icon: 'sparkles',  target: null,           title: t('onbE.1.title'), body: t('onbE.1.body'), placement: 'center' },
      { section: null,       icon: 'sparkles',  target: 'mode-switch',  title: t('onbE.2.title'), body: t('onbE.2.body'), placement: 'corner' },
      { section: 'overview', icon: 'overview',  target: 'nav-overview', title: t('onbE.3.title'), body: t('onbE.3.body'), placement: 'corner' },
      { section: 'chat',     icon: 'chat',      target: 'chat-new-btn', title: t('onbE.4.title'), body: t('onbE.4.body'), placement: 'corner' },
      { section: 'leads',    icon: 'leads',     target: 'nav-leads',    title: t('onbE.5.title'), body: t('onbE.5.body'), placement: 'corner' },
      { section: null,       icon: 'sparkles',  target: null,           title: t('onbE.6.title'), body: t('onbE.6.body'), placement: 'center' }
    ];
  }

  return [
    { section: null,       icon: 'sparkles',  target: null,                 title: t('onb.1.title'), body: t('onb.1.body'), placement: 'center' },
    { section: null,       icon: 'sparkles',  target: 'mode-switch',        title: t('onb.mode.title'), body: t('onb.mode.body'), placement: 'corner' },
    { section: 'overview', icon: 'overview',  target: 'nav-overview',       title: t('onb.2.title'), body: t('onb.2.body'), placement: 'corner' },
    { section: 'chat',     icon: 'chat',      target: 'chat-new-btn',       title: t('onb.3.title'), body: t('onb.3.body'), placement: 'corner' },
    { section: 'leads',    icon: 'leads',     target: 'nav-leads',          title: t('onb.4.title'), body: t('onb.4.body'), placement: 'corner' },
    { section: 'analytics',icon: 'analytics', target: 'nav-analytics',      title: t('onb.5.title'), body: t('onb.5.body'), placement: 'corner' },
    { section: 'settings', icon: 'settings',  target: 'nav-settings',       title: t('onb.6.title'), body: t('onb.6.body'), placement: 'corner' },
    { section: null,       icon: 'globe',     target: 'top-lang',           title: t('onb.7.title'), body: t('onb.7.body'), placement: 'corner' },
    { section: 'chat',     icon: 'sparkles',  target: null,                 title: t('onb.8.title'), body: t('onb.8.body'), placement: 'center' }
  ];
};

// Highlight ring + arrow pointing at target element
const HighlightOverlay = ({ targetId }) => {
  const [rect, setRect] = useStateOnb(null);

  useLayoutEffectOnb(() => {
    if (!targetId) { setRect(null); return; }

    let rafId;
    const measure = () => {
      const el = document.querySelector('[data-onboarding-id="' + targetId + '"]');
      if (el) {
        const r = el.getBoundingClientRect();
        setRect({ top: r.top, left: r.left, width: r.width, height: r.height });
      } else {
        setRect(null);
      }
    };
    measure();
    // Re-measure on resize/scroll + one more frame after paint
    rafId = requestAnimationFrame(measure);
    window.addEventListener('resize', measure);
    window.addEventListener('scroll', measure, true);
    const interval = setInterval(measure, 400); // keep tracking while the tour is active

    return () => {
      cancelAnimationFrame(rafId);
      window.removeEventListener('resize', measure);
      window.removeEventListener('scroll', measure, true);
      clearInterval(interval);
    };
  }, [targetId]);

  if (!targetId || !rect) return null;

  const pad = 6;
  return (
    <>
      {/* Pulsing ring around the target */}
      <div style={{
        position: 'fixed',
        top: rect.top - pad,
        left: rect.left - pad,
        width: rect.width + pad * 2,
        height: rect.height + pad * 2,
        borderRadius: 12,
        border: '2px solid var(--accent)',
        boxShadow: '0 0 0 4px rgba(91,91,214,0.35), 0 0 24px rgba(91,91,214,0.55)',
        pointerEvents: 'none',
        zIndex: 2000,
        animation: 'fnrePulse 1.6s ease-in-out infinite'
      }} />
      <style>{`
        @keyframes fnrePulse {
          0%, 100% { box-shadow: 0 0 0 4px rgba(91,91,214,0.35), 0 0 24px rgba(91,91,214,0.55); transform: scale(1); }
          50%      { box-shadow: 0 0 0 8px rgba(91,91,214,0.18), 0 0 36px rgba(91,91,214,0.7);  transform: scale(1.02); }
        }
      `}</style>
    </>
  );
};

const OnboardingOverlay = ({ section, setSection, onDone, lang, mode }) => {
  const steps = BUILD_STEPS(lang || window.__lang || 'en', mode || 'advanced');
  const [step, setStep] = useStateOnb(0);
  const current = steps[step];
  const isLast = step === steps.length - 1;
  const t = (k) => window.__t(k, lang);
  const isRtl = (lang === 'ar');

  useEffectOnb(() => {
    if (current.section && current.section !== section) {
      setSection(current.section);
    }
  }, [step]);

  const next = () => { if (isLast) onDone(); else setStep(s => s + 1); };
  const back = () => { if (step > 0) setStep(s => s - 1); };

  const isCenter = current.placement === 'center';
  const cardStyle = isCenter
    ? { position: 'fixed', top: '50%', left: '50%', transform: 'translate(-50%, -50%)', width: 480 }
    : (isRtl
        ? { position: 'fixed', bottom: 32, left: 32, width: 360 }
        : { position: 'fixed', bottom: 32, right: 32, width: 360 });

  return (
    <>
      {isCenter && (
        <div style={{
          position: 'fixed', inset: 0, background: 'rgba(10,10,10,0.55)',
          backdropFilter: 'blur(5px)', zIndex: 1999
        }} />
      )}

      {!isCenter && current.target && <HighlightOverlay targetId={current.target} />}

      <div style={{
        ...cardStyle,
        background: 'var(--bg-elev)', border: '1px solid var(--line)',
        borderRadius: 'var(--radius-lg)', padding: isCenter ? '36px 34px 28px' : '24px 26px 20px',
        boxShadow: '0 14px 44px rgba(0,0,0,0.22)',
        zIndex: 2001,
        direction: isRtl ? 'rtl' : 'ltr'
      }}>
        <button
          onClick={onDone}
          className="mono"
          style={{
            position: 'absolute', top: 14, [isRtl ? 'left' : 'right']: 16,
            fontSize: 10, color: 'var(--fg-4)',
            textTransform: 'uppercase', letterSpacing: '0.14em', padding: '4px 8px'
          }}
        >{t('onb.skip')}</button>

        <div style={{
          width: isCenter ? 46 : 36, height: isCenter ? 46 : 36,
          background: 'var(--fg)', color: 'var(--bg-elev)',
          borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: isCenter ? 18 : 14
        }}>
          <Icon name={current.icon} size={isCenter ? 20 : 16} strokeWidth={1.6} />
        </div>

        <div className="mono" style={{
          fontSize: 10, color: 'var(--fg-3)', textTransform: 'uppercase',
          letterSpacing: '0.16em', marginBottom: 8
        }}>{t('onb.step')} {step + 1} {t('onb.of')} {steps.length}</div>

        <h3 style={{
          fontFamily: 'var(--serif, var(--sans))', fontWeight: 500,
          fontSize: isCenter ? 22 : 17, letterSpacing: '-0.01em',
          margin: '0 0 10px', lineHeight: 1.25
        }}>{current.title}</h3>

        <p style={{
          color: 'var(--fg-2)',
          fontSize: isCenter ? 14 : 13,
          lineHeight: 1.6, margin: '0 0 22px'
        }}>{current.body}</p>

        <div style={{ display: 'flex', gap: 3, marginBottom: 18 }}>
          {steps.map((_, i) => (
            <div key={i} style={{
              height: 2, flex: 1,
              background: i <= step ? 'var(--fg)' : 'var(--line-2)',
              transition: 'background 0.2s'
            }} />
          ))}
        </div>

        <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
          <button
            onClick={back}
            disabled={step === 0}
            className="btn"
            style={{ opacity: step === 0 ? 0.3 : 1, cursor: step === 0 ? 'not-allowed' : 'pointer', fontSize: 12, padding: '6px 12px' }}
          >{t('onb.back')}</button>
          <button
            onClick={next}
            className="btn primary"
            style={{ fontSize: 12, padding: '6px 14px' }}
          >
            {isLast ? t('onb.getStarted') : t('onb.next')}
          </button>
        </div>
      </div>
    </>
  );
};

window.OnboardingOverlay = OnboardingOverlay;
