// Five Nodes Hospital — Onboarding walkthrough
const { useState: useStateOnb, useEffect: useEffectOnb, useLayoutEffect: useLayoutEffectOnb } = React;

const BUILD_STEPS = (lang, mode = 'advanced') => {
  const t = (k) => window.__t(k, lang);

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

  return [
    { section: null,           target: null,                title: t('onb.1.title'),  body: t('onb.1.body'),  placement: 'center' },
    { section: null,           target: 'mode-switch',       title: t('onb.mode.title'), body: t('onb.mode.body'), placement: 'corner' },
    { section: 'overview',     target: 'nav-overview',      title: t('onb.2.title'),  body: t('onb.2.body'),  placement: 'corner' },
    { section: 'inbox',        target: 'nav-inbox',         title: t('onb.3.title'),  body: t('onb.3.body'),  placement: 'corner' },
    { section: 'leads',        target: 'nav-leads',         title: t('onb.4.title'),  body: t('onb.4.body'),  placement: 'corner' },
    { section: 'appointments', target: 'nav-appointments',  title: t('onb.5.title'),  body: t('onb.5.body'),  placement: 'corner' },
    { section: 'schedule',     target: 'nav-schedule',      title: t('onb.6.title'),  body: t('onb.6.body'),  placement: 'corner' },
    { section: 'today',        target: 'nav-today',         title: t('onb.7.title'),  body: t('onb.7.body'),  placement: 'corner' },
    { section: 'analytics',    target: 'nav-analytics',     title: t('onb.8.title'),  body: t('onb.8.body'),  placement: 'corner' },
    { section: null,           target: 'top-lang',          title: t('onb.9.title'),  body: t('onb.9.body'),  placement: 'corner' },
    { section: null,           target: null,                title: t('onb.10.title'), body: t('onb.10.body'), placement: 'center' }
  ];
};

const HighlightOverlay = ({ targetId }) => {
  const [rect, setRect] = useStateOnb(null);
  useLayoutEffectOnb(() => {
    if (!targetId) { setRect(null); return; }
    let raf;
    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();
    raf = requestAnimationFrame(measure);
    window.addEventListener('resize', measure);
    window.addEventListener('scroll', measure, true);
    const interval = setInterval(measure, 400);
    return () => { cancelAnimationFrame(raf); window.removeEventListener('resize', measure); window.removeEventListener('scroll', measure, true); clearInterval(interval); };
  }, [targetId]);
  if (!targetId || !rect) return null;
  const pad = 6;
  return (
    <>
      <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(13,148,136,0.30), 0 0 24px rgba(13,148,136,0.50)',
        pointerEvents: 'none', zIndex: 2000,
        animation: 'fnhspPulse 1.6s ease-in-out infinite'
      }} />
      <style>{`@keyframes fnhspPulse {
        0%,100% { box-shadow: 0 0 0 4px rgba(13,148,136,0.30), 0 0 24px rgba(13,148,136,0.50); transform: scale(1); }
        50%     { box-shadow: 0 0 0 8px rgba(13,148,136,0.16), 0 0 36px rgba(13,148,136,0.65); 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(12,58,71,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: 14, padding: isCenter ? '36px 34px 28px' : '24px 26px 20px',
        boxShadow: 'var(--shadow-md)', 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', background: 'transparent', border: 'none', cursor: 'pointer' }}>
          {t('onb.skip')}
        </button>
        <div style={{
          width: isCenter ? 46 : 36, height: isCenter ? 46 : 36,
          background: 'var(--accent)', color: 'var(--accent-ink)',
          borderRadius: 10, display: 'flex', alignItems: 'center', justifyContent: 'center',
          marginBottom: isCenter ? 18 : 14,
          fontFamily: 'var(--serif, var(--sans))', fontStyle: 'italic',
          fontSize: isCenter ? 22 : 17, fontWeight: 600
        }}>F</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(--accent)' : '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;
