function ForSpecialists() {
  const [tab, setTab] = React.useState('user'); // 'spec' | 'user'
  const userCardRef = React.useRef(null);
  const specCardRef = React.useRef(null);

  const handleTab = (id) => {
    setTab(id);
    const target = id === 'user' ? userCardRef.current : specCardRef.current;
    if (target && window.matchMedia('(max-width: 880px)').matches) {
      target.scrollIntoView({ behavior: 'smooth', block: 'nearest', inline: 'start' });
    }
  };

  // Sync active tab when user manually scrolls between cards on mobile
  React.useEffect(() => {
    if (!window.matchMedia('(max-width: 880px)').matches) return;
    const els = [
      { id: 'user', el: userCardRef.current },
      { id: 'spec', el: specCardRef.current },
    ].filter(x => x.el);
    if (els.length < 2) return;
    const obs = new IntersectionObserver((entries) => {
      let best = null;
      entries.forEach(e => {
        if (!best || e.intersectionRatio > best.intersectionRatio) best = e;
      });
      if (best && best.intersectionRatio > 0.5) {
        const match = els.find(x => x.el === best.target);
        if (match) setTab(match.id);
      }
    }, { threshold: [0.5, 0.75, 1] });
    els.forEach(x => obs.observe(x.el));
    return () => obs.disconnect();
  }, []);

  const specialistFeats = [
    { dot: 'var(--violet)', text: 'Личный кабинет со всеми клиентами в одном месте' },
    { dot: 'var(--green)',  text: 'Рацион, дефициты, карта здоровья клиентов в реальном времени' },
    { dot: 'var(--amber)',  text: 'Динамика 40+ нутриентов — без уточнений «что вы ели на прошлой неделе»' },
    { dot: 'var(--pink)',   text: 'Назначайте спринты, анкеты и цели — клиент получает их прямо в приложение' },
    { dot: 'var(--violet)', text: 'Корректируйте планы между сессиями — не ждите следующего приёма' },
  ];

  const userFeats = [
    { dot: 'var(--violet)', text: 'Начни сам — данные копятся с первого дня, история не обнуляется' },
    { dot: 'var(--green)',  text: 'Подключи специалиста одним тапом' },
    { dot: 'var(--amber)',  text: 'Ставь цели со специалистом, достигай с Миникорном' },
    { dot: 'var(--pink)',   text: 'Получай рекомендации прямо в приложение — без мессенджеров и таблиц' },
  ];

  return (
    <section id="specialists" className="pad-y-lg" style={{ position: 'relative' }}>
      <div className="wrap">

        {/* ── Header ── */}
        <Reveal>
          <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 24 }}>
            <span className="eyebrow">[ 06 ]</span>
            <span style={{ height: 1, width: 32, background: 'var(--line-2)', flexShrink: 0 }}/>
            <span className="eyebrow" style={{ color: 'var(--ink-3)' }}>Нутрициолог</span>
          </div>
          <h2 className="display" style={{ fontSize: 'clamp(40px, 6vw, 80px)', margin: '0 0 20px', maxWidth: '22ch' }}>
            Работаешь со специалистом?<br/>
            <span style={{
              background: 'linear-gradient(120deg, #ffffff 20%, var(--violet) 55%, var(--green) 100%)',
              WebkitBackgroundClip: 'text', backgroundClip: 'text', color: 'transparent',
            }}>Работай на новом уровне.</span>
          </h2>
          <p className="lede" style={{ marginBottom: 48 }}>
            Подключи специалиста к своему приложению, чтобы он видел полную картину здоровья и давал рекомендации на чистых данных.
          </p>
        </Reveal>

        {/* ── Tab toggle (mobile) ── */}
        <Reveal>
          <div style={{ display: 'flex', gap: 8, marginBottom: 20 }} className="spec-tabs">
            {[
              { id: 'user', label: 'Хочу специалиста' },
              { id: 'spec', label: 'Я специалист' },
            ].map(t => (
              <button key={t.id} onClick={() => handleTab(t.id)} style={{
                appearance: 'none', border: 0, cursor: 'pointer',
                padding: '8px 18px', borderRadius: 999, fontFamily: 'var(--sans)',
                fontSize: 13, fontWeight: 500, transition: 'all .2s',
                background: tab === t.id ? 'var(--violet-2)' : 'rgba(255,255,255,0.06)',
                color: tab === t.id ? 'white' : 'var(--ink-3)',
                boxShadow: tab === t.id ? '0 6px 20px -6px rgba(139,92,246,0.55)' : 'none',
              }}>{t.label}</button>
            ))}
          </div>
        </Reveal>

        {/* ── Main split ── */}
        <Reveal>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr auto 1fr', gap: 0, alignItems: 'stretch' }} className="spec-grid">

            {/* User card (left) */}
            <div ref={userCardRef} className={`glass spec-card ${tab === 'user' ? 'spec-active' : 'spec-dim'}`} style={{
              padding: 36, borderRadius: '24px 0 0 24px',
              border: '1px solid rgba(96,165,250,0.25)',
              background: tab === 'user'
                ? 'linear-gradient(160deg, rgba(96,165,250,0.10), rgba(96,165,250,0.02))'
                : 'rgba(255,255,255,0.02)',
              transition: 'background .4s, opacity .4s',
              opacity: tab === 'spec' ? 0.55 : 1,
              position: 'relative', overflow: 'hidden',
            }}
            onMouseEnter={() => setTab('user')}
            >
              {tab === 'user' && <div aria-hidden style={{
                position: 'absolute', top: -60, right: -60, width: 240, height: 240, borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(96,165,250,0.22), transparent 70%)',
                filter: 'blur(40px)', pointerEvents: 'none',
              }}/>}

              <div style={{ marginBottom: 24 }}>
                <div style={{
                  width: 52, height: 52, borderRadius: '50%', marginBottom: 18,
                  background: 'linear-gradient(135deg, rgba(96,165,250,0.35), rgba(96,165,250,0.12))',
                  border: '1px solid rgba(96,165,250,0.4)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="#60A5FA" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M12 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"/>
                    <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                  </svg>
                </div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em', color: '#60A5FA', textTransform: 'uppercase', marginBottom: 32 }}>
                  Из соло — в команду
                </div>
                <h3 className="display" style={{ fontSize: 'clamp(26px, 3vw, 38px)', margin: '0 0 12px', letterSpacing: '-0.02em' }}>
                  Усиль Миникорна<br/>живой экспертизой.
                </h3>
                <p style={{ color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6, margin: 0 }}>
                  Делись историей здоровья за выбранный период или с самого первого дня. Специалист увидит истинные показатели для действительно глубокой работы.
                </p>
              </div>

              <ul className="clean" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {userFeats.map((f, i) => (
                  <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 14, color: 'var(--ink-2)' }}>
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%',
                      background: f.dot, flexShrink: 0, marginTop: 6,
                      boxShadow: `0 0 6px ${f.dot}`,
                    }}/>
                    {f.text}
                  </li>
                ))}
              </ul>
            </div>

            {/* Center connector */}
            <div style={{
              width: 72, display: 'flex', flexDirection: 'column',
              alignItems: 'center', justifyContent: 'center',
              position: 'relative', zIndex: 2,
            }}>
              {/* Vertical dashed line */}
              <div style={{
                position: 'absolute', top: 0, bottom: 0, left: '50%', width: 1,
                backgroundImage: 'repeating-linear-gradient(180deg, rgba(167,139,250,0.35) 0, rgba(167,139,250,0.35) 6px, transparent 6px, transparent 16px)',
              }}/>
              {/* Sync icon */}
              <div style={{
                width: 44, height: 44, borderRadius: '50%', zIndex: 1,
                background: 'var(--bg-1)',
                border: '1px solid rgba(167,139,250,0.35)',
                display: 'flex', alignItems: 'center', justifyContent: 'center',
                boxShadow: '0 0 20px rgba(167,139,250,0.2)',
              }}>
                <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="var(--violet)" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M21 2v6h-6"/>
                  <path d="M3 22v-6h6"/>
                  <path d="M3.5 9A9 9 0 0 1 19 6.5l2 1.5"/>
                  <path d="M20.5 15A9 9 0 0 1 5 17.5l-2-1.5"/>
                </svg>
              </div>
            </div>

            {/* Specialist card (right) */}
            <div ref={specCardRef} className={`glass-strong spec-card ${tab === 'spec' ? 'spec-active' : 'spec-dim'}`} style={{
              padding: 36, borderRadius: '0 24px 24px 0',
              border: '1px solid rgba(236,72,153,0.28)',
              background: tab === 'spec'
                ? 'linear-gradient(160deg, rgba(236,72,153,0.12), rgba(236,72,153,0.03))'
                : 'rgba(255,255,255,0.02)',
              transition: 'background .4s, opacity .4s',
              opacity: tab === 'user' ? 0.55 : 1,
              position: 'relative', overflow: 'hidden',
            }}
            onMouseEnter={() => setTab('spec')}
            >
              {tab === 'spec' && <div aria-hidden style={{
                position: 'absolute', top: -60, left: -60, width: 240, height: 240, borderRadius: '50%',
                background: 'radial-gradient(circle, rgba(236,72,153,0.22), transparent 70%)',
                filter: 'blur(40px)', pointerEvents: 'none',
              }}/>}

              <div style={{ marginBottom: 24 }}>
                <div style={{
                  width: 52, height: 52, borderRadius: '50%', marginBottom: 18,
                  background: 'linear-gradient(135deg, rgba(236,72,153,0.38), rgba(236,72,153,0.18))',
                  border: '1px solid rgba(236,72,153,0.4)',
                  display: 'flex', alignItems: 'center', justifyContent: 'center',
                }}>
                  <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="var(--pink)" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round">
                    <path d="M12 2a4 4 0 1 0 0 8 4 4 0 0 0 0-8z"/>
                    <path d="M4 20c0-4 3.6-7 8-7s8 3 8 7"/>
                    <path d="M17 11l2 2 4-4" stroke="var(--green)" strokeWidth="1.6"/>
                  </svg>
                </div>
                <div style={{ fontFamily: 'var(--mono)', fontSize: 9, letterSpacing: '0.18em', color: 'var(--pink)', textTransform: 'uppercase', marginBottom: 32 }}>
                  Вы нутрициолог?
                </div>
                <h3 className="display" style={{ fontSize: 'clamp(26px, 3vw, 38px)', margin: '0 0 12px', letterSpacing: '-0.02em' }}>
                  Данные —<br/>вместо догадок.
                </h3>
                <p style={{ color: 'var(--ink-2)', fontSize: 15, lineHeight: 1.6, margin: 0 }}>
                  Миникорн берёт на себя 80% рутины. Вы приходите на консультацию для самого важного — помочь человеку.
                </p>
              </div>

              <ul className="clean" style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
                {specialistFeats.map((f, i) => (
                  <li key={i} style={{ display: 'flex', gap: 12, alignItems: 'flex-start', fontSize: 14, color: 'var(--ink-2)' }}>
                    <span style={{
                      width: 7, height: 7, borderRadius: '50%',
                      background: f.dot, flexShrink: 0, marginTop: 6,
                      boxShadow: `0 0 6px ${f.dot}`,
                    }}/>
                    {f.text}
                  </li>
                ))}
              </ul>
            </div>
          </div>
        </Reveal>

        {/* ── Specialist CTA ── */}
        <Reveal delay={100}>
          <div style={{
            marginTop: 28, display: 'flex', alignItems: 'center',
            justifyContent: 'center', gap: 16, flexWrap: 'wrap',
          }}>
            <span style={{ fontSize: 14, color: 'var(--ink-3)' }}>Вы специалист?</span>
            <a href="nutritionist.html" className="btn ghost" style={{ height: 44, padding: '0 20px', fontSize: 14 }}>
              Узнать про платформу для специалистов <Arrow size={13}/>
            </a>
          </div>
        </Reveal>

      </div>
      <style>{`
        @media (max-width: 880px) {
          .spec-grid {
            display: flex !important;
            overflow-x: auto;
            scroll-snap-type: x mandatory;
            -webkit-overflow-scrolling: touch;
            scrollbar-width: none;
            margin: 0 -16px;
            padding: 0 16px;
            gap: 12px !important;
          }
          .spec-grid::-webkit-scrollbar { display: none; }
          .spec-grid > div:nth-child(2) { display: none !important; }
          .spec-grid > .spec-card {
            flex: 0 0 calc(100% - 16px) !important;
            scroll-snap-align: start;
            border-radius: 24px !important;
            opacity: 1 !important;
          }
          .spec-tabs { display: flex !important; }
        }
        @media (min-width: 881px) {
          .spec-tabs { display: none !important; }
        }
      `}</style>
    </section>
  );
}
window.ForSpecialists = ForSpecialists;
