// Глубина · кликабельный прототип
// Два продукта = два флоу с общими экранами:
//   A) Диагностика — 50 мин, бесплатно
//   B) Аналитическая сессия — 1,5 ч, 80 $ (включает МКП-карту)

const SESSION_TYPES = {
  diagnostic: {
    id: 'diagnostic',
    name: 'Диагностика',
    short: 'Знакомство',
    duration: 50,
    durationLabel: '50 мин',
    price: 'Бесплатно',
    priceShort: '0 $',
    free: true,
    pitch: 'Знакомство, разбор запроса, демонстрация подхода',
    includes: [
      'Разбор твоего запроса',
      'Знакомство с подходом',
      'Дальнейшие шаги',
    ],
    prep: [
      'Подумай о конкретной ситуации',
      'Стабильное соединение и наушники',
      'Час времени без отвлечений',
    ],
  },
  analytical: {
    id: 'analytical',
    name: 'Аналитическая сессия',
    short: 'МКП-карта',
    duration: 90,
    durationLabel: '1 ч 30 мин',
    price: '80 $',
    priceShort: '80 $',
    free: false,
    pitch: 'Глубокий разбор + персональная МКП-карта на руки',
    includes: [
      'Тесты OCEAN, метапрограммы, ВОЗ',
      'Аналитический разбор результатов',
      'Персональная МКП-карта',
      'Запись сессии и заметки',
    ],
    prep: [
      'Сформулируй конкретный запрос',
      '1,5 часа без отвлечений · наушники',
      'Стабильное соединение для Zoom',
    ],
  },
};

// ───────────────────────────────────── Top bar
function GlubinaTopBar({ title, onBack, step, total, sessionType }) {
  const t = useTheme();
  const st = sessionType && SESSION_TYPES[sessionType];
  return (
    <div style={{
      position: 'sticky', top: 0, zIndex: 5,
      background: `linear-gradient(180deg, ${t.deep}ee, ${t.deep}bb)`,
      backdropFilter: 'blur(12px)',
      borderBottom: `1px solid ${t.rule}`,
      padding: '14px 18px', display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <button onClick={onBack} style={{
        width: 32, height: 32, borderRadius: 10,
        border: `1px solid ${t.rule}`, background: 'transparent',
        color: t.ink, cursor: 'pointer', display: 'flex',
        alignItems: 'center', justifyContent: 'center',
        transition: 'background .15s, transform .15s',
      }}
      onMouseEnter={e => e.currentTarget.style.background = `${t.accent}18`}
      onMouseLeave={e => e.currentTarget.style.background = 'transparent'}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
          <path d="M19 12H5"/><path d="m11 18-6-6 6-6"/>
        </svg>
      </button>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
          color: t.accent, fontWeight: 600, display: 'flex', alignItems: 'center', gap: 6,
        }}>
          <span>iliaocean</span>
          {st && (
            <>
              <span style={{ opacity: 0.4 }}>·</span>
              <span style={{ color: st.free ? '#7ec089' : t.accent }}>
                {st.name}
              </span>
            </>
          )}
        </div>
        <div style={{
          fontFamily: THEME_FONTS.serif, fontSize: 17, color: t.ink,
          fontStyle: 'italic', lineHeight: 1.1, marginTop: 1,
        }}>{title}</div>
      </div>
      {step && total && (
        <div style={{
          fontSize: 10, color: t.mist, letterSpacing: '0.18em',
          textTransform: 'uppercase', fontWeight: 500,
        }}>
          <span style={{ color: t.accent, fontFamily: THEME_FONTS.serif, fontSize: 16, fontStyle: 'italic' }}>
            {String(step).padStart(2, '0')}
          </span>
          <span style={{ margin: '0 4px', opacity: 0.5 }}>/</span>
          {String(total).padStart(2, '0')}
        </div>
      )}
    </div>
  );
}

// ───────────────────────────────────── Session-type banner (under top bar)
function SessionBanner({ sessionType }) {
  const t = useTheme();
  const st = SESSION_TYPES[sessionType];
  if (!st) return null;
  return (
    <div style={{
      margin: '12px 22px 0', padding: '12px 14px', borderRadius: 12,
      border: `1px solid ${t.rule}`,
      background: st.free
        ? 'linear-gradient(135deg, rgba(126,192,137,0.12), rgba(126,192,137,0.04))'
        : `linear-gradient(135deg, ${t.accent}1a, ${t.accent}06)`,
      display: 'flex', alignItems: 'center', gap: 12,
    }}>
      <div style={{
        width: 36, height: 36, borderRadius: 10, flexShrink: 0,
        background: st.free ? 'rgba(126,192,137,0.18)' : `${t.accent}22`,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
      }}>
        {st.free ? (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#7ec089" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <circle cx="12" cy="12" r="9" />
            <path d="m9 12 2 2 4-4" />
          </svg>
        ) : (
          <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
            <path d="M3 7h18M3 12h18M3 17h12" />
          </svg>
        )}
      </div>
      <div style={{ flex: 1, minWidth: 0 }}>
        <div style={{
          fontFamily: THEME_FONTS.serif, fontSize: 16, color: t.ink, fontWeight: 500,
          lineHeight: 1.15, display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap',
        }}>
          <span>{st.name}</span>
          <span style={{ fontSize: 12, color: t.mist, fontFamily: THEME_FONTS.sans,
                         letterSpacing: '0.06em', fontStyle: 'normal' }}>· {st.durationLabel}</span>
        </div>
        <div style={{ fontSize: 11.5, color: t.mist, marginTop: 2 }}>{st.pitch}</div>
      </div>
      <div style={{
        fontFamily: THEME_FONTS.serif, fontSize: 20, fontStyle: 'italic',
        color: st.free ? '#7ec089' : t.accent, fontWeight: 500, flexShrink: 0,
        letterSpacing: '-0.005em',
      }}>{st.priceShort}</div>
    </div>
  );
}

// ───────────────────────────────────── Diagnostic intake (4 steps: 3 open Qs + contact)
function GlubinaIntake({ sessionType = 'diagnostic', onBack, onComplete }) {
  const t = useTheme();
  const [step, setStep] = React.useState(0);
  const [answers, setAnswers] = React.useState({
    story: '', history: '', future: '', name: '', tg: '',
  });

  const steps = [
    {
      kind: 'longtext',
      label: 'Сейчас',
      title: 'Что сейчас происходит в жизни?',
      sub: 'Опиши своими словами — без фильтров.',
      key: 'story',
      placeholder: 'Пишу как есть. То, что болит / мешает / не отпускает...',
      minLen: 30,
      showIntro: true,
    },
    {
      kind: 'longtext',
      label: 'История',
      title: 'Как давно это тянется и что уже пробовал(а)?',
      sub: 'Что помогало, что нет — любая попытка уже ценный сигнал.',
      key: 'history',
      placeholder: 'Тянется около... Пробовал(а)... Помогало... Не сработало...',
      minLen: 30,
    },
    {
      kind: 'longtext',
      label: 'Куда',
      title: 'Каким хочешь видеть себя через год?',
      sub: 'Если бы всё получилось — как выглядит обычный день, что внутри?',
      key: 'future',
      placeholder: 'Через год я... В голове... В отношениях... В работе...',
      minLen: 30,
    },
    {
      kind: 'contact',
      label: 'Контакт',
      title: 'Куда прислать ссылку на Zoom?',
      sub: 'Имя и Telegram — на этот контакт пришлю подтверждение слота и ссылку на встречу.',
    },
  ];

  const cur = steps[step];

  const handleNext = () => {
    if (cur.kind === 'longtext') {
      if ((answers[cur.key] || '').trim().length < (cur.minLen || 10)) return;
      if (step < steps.length - 1) setStep(step + 1);
    }
  };

  const handleSubmit = () => {
    if (!answers.name.trim() || !answers.tg.trim()) return;
    onComplete && onComplete(answers);
  };

  const canNextLong = cur.kind === 'longtext'
    && (answers[cur.key] || '').trim().length >= (cur.minLen || 10);
  const canSubmit = answers.name.trim() && answers.tg.trim();

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
      <GlubinaBackdrop />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <GlubinaTopBar title="Анкета" onBack={step > 0 ? () => setStep(step - 1) : onBack}
                       step={step + 1} total={steps.length} sessionType={sessionType} />
        <SessionBanner sessionType={sessionType} />

        <div style={{ padding: '0 22px', marginTop: 18, maxWidth: 520, margin: '18px auto 0' }}>
          <div style={{ display: 'flex', gap: 4 }}>
            {steps.map((_, i) => (
              <div key={i} style={{
                flex: 1, height: 2, borderRadius: 1,
                background: i <= step ? t.accent : `${t.accent}22`,
                transition: 'background .3s ease',
              }} />
            ))}
          </div>
          <div style={{
            marginTop: 10, fontSize: 9, letterSpacing: '0.35em',
            textTransform: 'uppercase', color: t.accent, fontWeight: 600,
            display: 'flex', alignItems: 'center', gap: 8,
          }}>
            <span style={{ fontFamily: THEME_FONTS.serif, fontStyle: 'italic', fontSize: 15, letterSpacing: 0 }}>
              {String(step + 1).padStart(2, '0')}
            </span>
            <span style={{ width: 12, height: 1, background: t.accent }} />
            {cur.label}
          </div>
        </div>

        <div style={{ padding: '22px 22px 40px', maxWidth: 520, margin: '0 auto' }}>
          {cur.showIntro && (
            <div style={{
              padding: '16px 18px', borderRadius: 14, marginBottom: 22,
              border: `1px solid ${t.rule}`,
              background: `linear-gradient(180deg, ${t.lift}66, ${t.deep}66)`,
            }}>
              <div style={{
                fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                color: t.accent, fontWeight: 600, marginBottom: 8,
              }}>Перед встречей</div>
              <div style={{
                fontFamily: THEME_FONTS.serif, fontSize: 15.5, color: t.ink,
                lineHeight: 1.45, fontStyle: 'italic',
              }}>
                Мне важно понять тебя — не как «случай», а как человека с конкретной историей. От этого зависит,
                смогу ли я реально помочь.
              </div>
              <div style={{
                marginTop: 12, paddingTop: 12, borderTop: `1px solid ${t.rule}`,
                display: 'flex', gap: 10, alignItems: 'flex-start',
              }}>
                <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 2 }}>
                  <path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6l-8-4Z"/>
                  <path d="m9 12 2 2 4-4"/>
                </svg>
                <div style={{ fontSize: 12.5, color: t.ink, lineHeight: 1.5 }}>
                  Чем <span style={{ color: t.accent, fontFamily: THEME_FONTS.serif, fontStyle: 'italic', fontSize: 14 }}>честнее, искреннее и подробнее</span> ответы —
                  тем точнее я смогу понять и помочь.
                </div>
              </div>
              <div style={{ marginTop: 10, fontSize: 11, color: t.mist, letterSpacing: '0.02em' }}>
                3 коротких вопроса · 2–3 минуты
              </div>
            </div>
          )}

          <h1 style={{
            margin: 0, fontFamily: THEME_FONTS.serif, fontSize: 26,
            fontWeight: 500, color: t.ink, letterSpacing: '-0.01em', lineHeight: 1.15,
          }}>{cur.title}</h1>
          <p style={{
            margin: '10px 0 0', fontFamily: THEME_FONTS.sans,
            fontSize: 13.5, color: t.mist, lineHeight: 1.55,
          }}>{cur.sub}</p>

          {cur.kind === 'longtext' && (
            <div style={{ marginTop: 22 }}>
              <textarea
                value={answers[cur.key]}
                onChange={e => setAnswers(a => ({ ...a, [cur.key]: e.target.value }))}
                placeholder={cur.placeholder}
                rows={7}
                style={{
                  width: '100%', boxSizing: 'border-box', resize: 'none',
                  padding: '16px 16px', borderRadius: 14,
                  border: `1px solid ${t.rule}`,
                  background: `${t.panel}88`,
                  color: t.ink, fontFamily: THEME_FONTS.sans, fontSize: 14.5,
                  lineHeight: 1.55, outline: 'none',
                  minHeight: 170,
                }}
                onFocus={e => e.target.style.borderColor = t.accent}
                onBlur={e => e.target.style.borderColor = t.rule}
              />
              <div style={{
                marginTop: 8, display: 'flex', alignItems: 'center', justifyContent: 'space-between',
                fontSize: 11, color: t.mist, letterSpacing: '0.05em',
              }}>
                <span>{(answers[cur.key] || '').trim().length === 0
                  ? 'Можно коротко — но конкретно.'
                  : canNextLong ? 'Можно дальше' : `Ещё хотя бы ${(cur.minLen || 30) - (answers[cur.key] || '').trim().length} знаков`}</span>
                <span style={{ color: t.faint }}>{(answers[cur.key] || '').length}</span>
              </div>

              <button onClick={handleNext} disabled={!canNextLong} style={{
                marginTop: 18, width: '100%', maxWidth: 420, padding: '16px 18px', borderRadius: 14,
                border: `1px solid ${canNextLong ? t.accent : t.rule}`,
                background: canNextLong
                  ? `linear-gradient(180deg, ${t.accent}, ${t.accentDim})`
                  : `${t.panel}44`,
                color: canNextLong ? t.deep : t.faint,
                fontFamily: THEME_FONTS.sans, fontWeight: 600,
                fontSize: 15, letterSpacing: '0.01em',
                cursor: canNextLong ? 'pointer' : 'not-allowed',
                boxShadow: canNextLong ? `0 12px 30px -10px ${t.accent}80, inset 0 1px 0 ${t.ink}66` : 'none',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                transition: 'all .2s ease',
              }}>
                {step === steps.length - 2 ? 'К контакту' : 'Дальше'}
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
                </svg>
              </button>
            </div>
          )}

          {cur.kind === 'contact' && (
            <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 14 }}>
              <Field t={t} label="Имя"      value={answers.name} onChange={v => setAnswers(a => ({ ...a, name: v }))} placeholder="Илья" />
              <Field t={t} label="Telegram" value={answers.tg}   onChange={v => setAnswers(a => ({ ...a, tg: v }))}   placeholder="@username" />

              <ZoomFormatNote t={t} />

              <div style={{
                marginTop: 4, padding: '14px 16px',
                borderRadius: 12, border: `1px solid ${t.rule}`,
                background: `${t.accent}08`,
              }}>
                <div style={{
                  fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                  color: t.accent, fontWeight: 600, marginBottom: 8,
                }}>Что я записал</div>
                <Summary answers={answers} sessionType={sessionType} t={t} />
              </div>

              <button onClick={handleSubmit} disabled={!canSubmit} style={{
                marginTop: 4, padding: '16px 18px', borderRadius: 14,
                border: `1px solid ${canSubmit ? t.accent : t.rule}`,
                background: canSubmit
                  ? `linear-gradient(180deg, ${t.accent}, ${t.accentDim})`
                  : `${t.panel}44`,
                color: canSubmit ? t.deep : t.faint,
                fontFamily: THEME_FONTS.sans, fontWeight: 600,
                fontSize: 15, letterSpacing: '0.01em',
                cursor: canSubmit ? 'pointer' : 'not-allowed',
                boxShadow: canSubmit ? `0 12px 30px -10px ${t.accent}80, inset 0 1px 0 ${t.ink}66` : 'none',
                display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
                transition: 'all .2s ease',
              }}>
                Выбрать время
                <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
                  <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
                </svg>
              </button>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}

function Field({ t, label, value, onChange, placeholder }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{
        fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
        color: t.accent, fontWeight: 600, marginBottom: 6,
      }}>{label}</div>
      <input
        value={value}
        onChange={e => onChange(e.target.value)}
        placeholder={placeholder}
        style={{
          width: '100%', boxSizing: 'border-box',
          padding: '14px 16px', borderRadius: 12,
          border: `1px solid ${t.rule}`,
          background: `${t.panel}88`,
          color: t.ink, fontFamily: THEME_FONTS.sans, fontSize: 15,
          outline: 'none',
        }}
        onFocus={e => e.target.style.borderColor = t.accent}
        onBlur={e => e.target.style.borderColor = t.rule}
      />
    </label>
  );
}

function Summary({ answers, sessionType, t }) {
  const st = SESSION_TYPES[sessionType];
  const truncate = (s, n = 60) => {
    const v = (s || '').trim();
    if (!v) return null;
    return v.length > n ? v.slice(0, n).trimEnd() + '…' : v;
  };
  const rows = [
    ['Сессия',  st ? `${st.name} · ${st.durationLabel}` : null],
    ['Сейчас',  truncate(answers.story)],
    ['История', truncate(answers.history)],
    ['Цель',    truncate(answers.future)],
  ].filter(r => r[1]);
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      {rows.map(([k, v]) => (
        <div key={k} style={{ display: 'flex', justifyContent: 'space-between', gap: 12, alignItems: 'baseline' }}>
          <span style={{ color: t.mist, letterSpacing: '0.1em', textTransform: 'uppercase', fontSize: 9.5, flexShrink: 0, paddingTop: 2 }}>{k}</span>
          <span style={{ color: t.ink, fontFamily: THEME_FONTS.serif, fontStyle: 'italic', fontSize: 13, textAlign: 'right', lineHeight: 1.35 }}>{v}</span>
        </div>
      ))}
    </div>
  );
}

// ───────────────────────────────────── Zoom + recording + transcription note (sales)
function ZoomFormatNote({ t }) {
  const rows = [
    {
      k: 'Zoom · запись',
      d: 'Видео-звонок в Zoom с записью сессии — пересматривать инсайты можно сколько угодно раз.',
      icon: (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <rect x="2.5" y="6.5" width="13" height="11" rx="2.5" />
          <path d="M16 10.5 21.5 7v10L16 13.5" />
        </svg>
      ),
    },
    {
      k: 'Полная транскрибация',
      d: 'Текст всего разговора — потом легко найти любое слово или мысль.',
      icon: (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M5 4h11l3 3v13a1 1 0 0 1-1 1H5a1 1 0 0 1-1-1V5a1 1 0 0 1 1-1Z" />
          <path d="M8 11h8M8 14h8M8 17h5" />
        </svg>
      ),
    },
    {
      k: 'Умный планировщик',
      d: 'После встречи приходит выжимка: ключевые точки, домашка и план следующего шага.',
      icon: (
        <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.7" strokeLinecap="round" strokeLinejoin="round">
          <path d="M12 2v3M12 19v3M4.2 4.2l2.1 2.1M17.7 17.7l2.1 2.1M2 12h3M19 12h3M4.2 19.8l2.1-2.1M17.7 6.3l2.1-2.1" />
          <circle cx="12" cy="12" r="3.5" />
        </svg>
      ),
    },
  ];
  return (
    <div style={{
      padding: '14px 14px 12px', borderRadius: 12,
      border: `1px solid ${t.rule}`,
      background: `linear-gradient(180deg, ${t.lift}66, ${t.deep}66)`,
    }}>
      <div style={{
        fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
        color: t.accent, fontWeight: 600, marginBottom: 10,
        display: 'flex', alignItems: 'center', gap: 8,
      }}>
        <span style={{ width: 6, height: 6, borderRadius: '50%', background: t.accent }} />
        Как проходит сессия
      </div>
      <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
        {rows.map((r, i) => (
          <div key={i} style={{ display: 'flex', gap: 11, alignItems: 'flex-start' }}>
            <div style={{
              width: 28, height: 28, borderRadius: 8, flexShrink: 0,
              background: `${t.accent}1a`, color: t.accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
            }}>{r.icon}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 14.5, color: t.ink, fontWeight: 500, lineHeight: 1.2 }}>{r.k}</div>
              <div style={{ fontSize: 12, color: t.mist, marginTop: 3, lineHeight: 1.45 }}>{r.d}</div>
            </div>
          </div>
        ))}
      </div>
    </div>
  );
}

// ───────────────────────────────────── МКП-карта preview
function GlubinaMKP({ onBack, onBook }) {
  const t = useTheme();
  const oceanData = [
    { k: 'Открытость',    v: 4.0, max: 5 },
    { k: 'Кропотливость', v: 4.4, max: 5 },
    { k: 'Экстраверсия',  v: 4.4, max: 5 },
    { k: 'Аккомодация',   v: 4.0, max: 5 },
    { k: 'Нейротизм',     v: 1.4, max: 5, low: true },
  ];
  const meta = [
    { k: 'Отверженность',   v: 43, hot: true },
    { k: 'Поиск признания', v: 31 },
    { k: 'Надменность',     v: 28 },
    { k: 'Провал',          v: 0 },
    { k: 'Беспомощность',   v: 0 },
    { k: 'Поломанность',    v: 0 },
  ];
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
      <GlubinaBackdrop />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <GlubinaTopBar title="МКП-карта · пример" onBack={onBack} />

        <div style={{ padding: '24px 22px 40px', maxWidth: 520, margin: '0 auto' }}>
          <div style={{
            padding: '32px 0 24px', borderTop: `1px solid ${t.rule}`, borderBottom: `1px solid ${t.rule}`,
            position: 'relative', overflow: 'hidden',
          }}>
            {/* Background mandala */}
            <div style={{
              position: 'absolute', top: '50%', right: -60, transform: 'translateY(-50%)',
              pointerEvents: 'none',
            }}>
              <GlubinaMandala variant="lotus" size={260} opacity={0.18} spin spinDuration={160} strokeWidth={0.5} />
            </div>
            <div style={{ position: 'relative', zIndex: 1 }}>
              <div style={{ fontSize: 9, letterSpacing: '0.4em', textTransform: 'uppercase', color: t.accent, fontWeight: 600 }}>
                КЭТ · Аналитический отчёт
              </div>
              <h1 style={{
                margin: '10px 0 0', fontFamily: THEME_FONTS.serif,
                fontSize: 34, fontWeight: 500, color: t.ink,
                letterSpacing: '-0.015em', lineHeight: 1,
              }}>Персональная<br/>
                <em style={{ color: t.accent, fontStyle: 'italic' }}>МКП-карта</em>
              </h1>
              <div style={{ marginTop: 14, fontSize: 11, color: t.mist, letterSpacing: '0.18em', textTransform: 'uppercase' }}>
                Ян Шевцов · 25 лет · маркетолог
              </div>
            </div>
          </div>

          <div style={{ marginTop: 30 }}>
            <SectionLabel num="01">Общая картина</SectionLabel>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 1,
                          background: t.rule, border: `1px solid ${t.rule}`, borderRadius: 12, overflow: 'hidden' }}>
              {[
                { v: '1.4', l: 'Нейротизм',    s: 'Железные нервы' },
                { v: '4.8', l: 'Ассертивность', s: 'Лучший в комнате' },
                { v: '4.7', l: 'Трудолюбие',    s: 'Встроенная система' },
                { v: '0',   l: 'Провал',        s: 'Нет страха ошибок' },
              ].map((s, i) => (
                <div key={i} style={{ padding: '18px 14px', background: t.deep, textAlign: 'center' }}>
                  <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 38, color: t.accent,
                                fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{s.v}</div>
                  <div style={{ fontSize: 9, letterSpacing: '0.22em', textTransform: 'uppercase',
                                color: t.mist, marginTop: 6, fontWeight: 600 }}>{s.l}</div>
                  <div style={{ fontFamily: THEME_FONTS.serif, fontStyle: 'italic',
                                fontSize: 13, color: t.ink, marginTop: 6 }}>{s.s}</div>
                </div>
              ))}
            </div>
            <p style={{ marginTop: 16, fontFamily: THEME_FONTS.serif, fontSize: 16,
                        color: t.ink, lineHeight: 1.5, fontStyle: 'italic' }}>
              «Один из сильнейших профилей для предпринимательства из тех, что я видел.
              Не паникуешь там, где другие разваливаются. Это не комплимент — это данные.»
            </p>
          </div>

          <div style={{ marginTop: 36 }}>
            <SectionLabel num="02">OCEAN · большая пятёрка</SectionLabel>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              {oceanData.map((d, i) => (
                <div key={i}>
                  <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', fontFamily: THEME_FONTS.sans }}>
                    <span style={{ fontSize: 11, letterSpacing: '0.18em', textTransform: 'uppercase', color: t.mist, fontWeight: 500 }}>{d.k}</span>
                    <span style={{ fontFamily: THEME_FONTS.serif, fontSize: 20, color: t.accent, fontStyle: 'italic', letterSpacing: '-0.01em' }}>
                      {d.v.toFixed(1)}
                      {d.low && <span style={{ fontSize: 10, marginLeft: 6, color: t.accent, letterSpacing: '0.2em' }}>★ РЕДКО</span>}
                    </span>
                  </div>
                  <div style={{ marginTop: 6, height: 4, borderRadius: 2, background: `${t.accent}18`, overflow: 'hidden' }}>
                    <div style={{ height: '100%', width: `${(d.v / d.max) * 100}%`,
                                  background: `linear-gradient(90deg, ${t.accentDim}, ${t.accent})`, borderRadius: 2 }} />
                  </div>
                </div>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 36 }}>
            <SectionLabel num="03">Метапрограммы</SectionLabel>
            <div style={{ display: 'grid', gridTemplateColumns: 'repeat(2, 1fr)', gap: 10 }}>
              {meta.map((m, i) => (
                <div key={i} style={{
                  padding: '14px 14px', borderRadius: 12,
                  border: `1px solid ${m.hot ? t.accent : t.rule}`,
                  background: m.hot
                    ? `linear-gradient(135deg, ${t.accent}24, ${t.accent}06)`
                    : `linear-gradient(180deg, ${t.panel}66, ${t.deep}66)`,
                }}>
                  <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 28, color: m.hot ? t.accent : t.ink,
                                fontWeight: 500, lineHeight: 1, letterSpacing: '-0.02em' }}>{m.v}</div>
                  <div style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
                                color: m.hot ? t.accent : t.mist, marginTop: 6, fontWeight: 600 }}>{m.k}</div>
                  {m.hot && <div style={{ marginTop: 6, fontSize: 11, color: t.ink,
                                          fontFamily: THEME_FONTS.serif, fontStyle: 'italic', lineHeight: 1.3 }}>Горячая точка</div>}
                </div>
              ))}
            </div>
          </div>

          <div style={{ marginTop: 36 }}>
            <SectionLabel num="04">Разбор паттерна</SectionLabel>
            <div style={{ borderTop: `1px solid ${t.rule}` }}>
              {[
                { trig: 'Партнёр обесценивает идею',       react: 'Защитная дистанция, надменность', alt: '«Это факт или значение? — разные вещи»' },
                { trig: 'Команда не делает как ты видишь', react: 'Микроменеджмент, «лучше сам»',     alt: 'Делегировать с чёткими метриками' },
                { trig: 'Большая публичность',             react: 'Невидимый тормоз скорости',        alt: 'Найти первичный опыт — узор детства' },
              ].map((row, i) => (
                <div key={i} style={{ padding: '14px 0', borderBottom: `1px solid ${t.rule}`,
                                      display: 'grid', gridTemplateColumns: '1fr', gap: 6 }}>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                    <span style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                                   color: t.accent, fontWeight: 600, minWidth: 60 }}>Триггер</span>
                    <span style={{ fontFamily: THEME_FONTS.serif, fontSize: 15, color: t.ink, fontStyle: 'italic' }}>{row.trig}</span>
                  </div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                    <span style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                                   color: t.alarmInk, fontWeight: 600, minWidth: 60 }}>Реакция</span>
                    <span style={{ fontSize: 13, color: t.mist, lineHeight: 1.4 }}>{row.react}</span>
                  </div>
                  <div style={{ display: 'flex', gap: 8, alignItems: 'baseline' }}>
                    <span style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                                   color: t.accent, fontWeight: 600, minWidth: 60 }}>Альтерн.</span>
                    <span style={{ fontSize: 13, color: t.ink, lineHeight: 1.4 }}>{row.alt}</span>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* Bottom CTA — paid analytical session */}
          <div style={{ marginTop: 36, padding: '24px 22px', borderRadius: 18,
                        border: `1px solid ${t.rule}`,
                        background: `linear-gradient(180deg, ${t.lift}73, ${t.deep}73)`,
                        textAlign: 'center' }}>
            <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 22, color: t.ink, fontStyle: 'italic', lineHeight: 1.3 }}>
              Хочешь такую же — про себя?
            </div>
            <p style={{ margin: '8px 0 20px', fontSize: 13, color: t.mist, lineHeight: 1.5 }}>
              Аналитическая сессия 1 ч 30 мин + личная МКП-карта.
            </p>
            <GlubinaButton variant="primary" icon="compass"
                           label="Заказать аналитическую сессию" sub="80 $ · с МКП-картой"
                           onClick={onBook} />
            <div style={{ marginTop: 14, fontSize: 11, color: t.mist, letterSpacing: '0.08em' }}>
              Или начни с <button onClick={onBack} style={{
                background: 'transparent', border: 'none', cursor: 'pointer', padding: 0,
                color: t.accent, fontFamily: THEME_FONTS.sans, fontSize: 11, letterSpacing: '0.08em',
                borderBottom: `1px dashed ${t.accent}`,
              }}>бесплатной диагностики (50 мин)</button>
            </div>
          </div>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────── Booking · step 1 — rough preferences
function BookingPrefs({ sessionType, onBack, onNext }) {
  const t = useTheme();
  const [prefs, setPrefs] = React.useState({ when: 'week', tod: 'evening', days: 'any' });

  const groups = [
    {
      key: 'when',
      label: 'Когда удобно',
      options: [
        { v: 'week',   t: 'Ближайшие 7 дней' },
        { v: 'two',    t: 'Через 1–2 недели' },
        { v: 'month',  t: 'Через месяц' },
        { v: 'flex',   t: 'Гибко' },
      ],
    },
    {
      key: 'tod',
      label: 'Время суток',
      options: [
        { v: 'morning', t: 'Утро',         d: '08:00 – 12:00' },
        { v: 'day',     t: 'День',          d: '12:00 – 17:00' },
        { v: 'evening', t: 'Вечер',         d: '17:00 – 21:00' },
        { v: 'late',    t: 'Поздний вечер', d: '21:00 – 23:00' },
      ],
    },
    {
      key: 'days',
      label: 'Какие дни',
      options: [
        { v: 'weekday', t: 'Будни' },
        { v: 'weekend', t: 'Выходные' },
        { v: 'any',     t: 'Без разницы' },
      ],
    },
  ];

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
      <GlubinaBackdrop />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <GlubinaTopBar title="Когда тебе удобно" onBack={onBack} step={1} total={2} sessionType={sessionType} />
        <SessionBanner sessionType={sessionType} />

        <div style={{ padding: '20px 22px 40px', maxWidth: 520, margin: '0 auto' }}>
          <h1 style={{ margin: 0, fontFamily: THEME_FONTS.serif, fontSize: 30,
                       fontWeight: 500, color: t.ink, letterSpacing: '-0.01em', lineHeight: 1.1 }}>
            Примерно <em style={{ color: t.accent, fontStyle: 'italic' }}>когда</em>?
          </h1>
          <p style={{ margin: '10px 0 0', fontSize: 13.5, color: t.mist, lineHeight: 1.55 }}>
            Выбери предпочтения — на следующем шаге покажу свободные слоты из моего календаря.
          </p>

          {groups.map((g) => (
            <div key={g.key} style={{ marginTop: 30 }}>
              <div style={{ fontSize: 10, letterSpacing: '0.3em', textTransform: 'uppercase',
                            color: t.accent, fontWeight: 600, marginBottom: 10 }}>{g.label}</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {g.options.map((o) => {
                  const picked = prefs[g.key] === o.v;
                  return (
                    <button key={o.v} onClick={() => setPrefs(p => ({ ...p, [g.key]: o.v }))} style={{
                      flex: '1 1 calc(50% - 4px)', minWidth: 120,
                      padding: '12px 14px', borderRadius: 12,
                      border: `1px solid ${picked ? t.accent : t.rule}`,
                      background: picked
                        ? `linear-gradient(135deg, ${t.accent}26, ${t.accent}08)`
                        : `${t.panel}88`,
                      color: t.ink, fontFamily: THEME_FONTS.sans,
                      cursor: 'pointer', textAlign: 'left',
                      transition: 'all .18s ease',
                    }}>
                      <div style={{
                        fontFamily: THEME_FONTS.serif, fontSize: 16, fontWeight: 500,
                        color: picked ? t.accent : t.ink,
                        fontStyle: picked ? 'italic' : 'normal',
                      }}>{o.t}</div>
                      {o.d && <div style={{ fontSize: 11, color: t.mist, marginTop: 2 }}>{o.d}</div>}
                    </button>
                  );
                })}
              </div>
            </div>
          ))}

          <button onClick={() => onNext(prefs)} style={{
            marginTop: 36, width: '100%', maxWidth: 420, padding: '16px 18px', borderRadius: 14,
            border: `1px solid ${t.accent}`,
            background: `linear-gradient(180deg, ${t.accent}, ${t.accentDim})`,
            color: t.deep, fontFamily: THEME_FONTS.sans, fontWeight: 600,
            fontSize: 15, letterSpacing: '0.01em', cursor: 'pointer',
            boxShadow: `0 12px 30px -10px ${t.accent}80, inset 0 1px 0 ${t.ink}66`,
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
          }}>
            Показать свободные слоты
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M5 12h14"/><path d="m13 6 6 6-6 6"/>
            </svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ───────────────────────────────────── Booking · step 2 — calendar + exact slots
function BookingSlots({ sessionType, prefs, onBack, onConfirm }) {
  const t = useTheme();
  const st = SESSION_TYPES[sessionType];

  // ── Helpers ──────────────────────────────────────────────────────────
  const MONTH_RU = ['Январь','Февраль','Март','Апрель','Май','Июнь',
                    'Июль','Август','Сентябрь','Октябрь','Ноябрь','Декабрь'];
  const DOW_RU   = ['ПН','ВТ','СР','ЧТ','ПТ','СБ','ВС'];

  function buildCalendar(year, month) {
    const first = new Date(year, month, 1).getDay();
    const startOff = first === 0 ? 6 : first - 1;
    const daysInMonth = new Date(year, month + 1, 0).getDate();
    const cells = [];
    for (let i = 0; i < startOff; i++) cells.push(null);
    for (let d = 1; d <= daysInMonth; d++) cells.push(d);
    while (cells.length % 7 !== 0) cells.push(null);
    return cells;
  }

  function isFullyBooked(d) { return d % 13 === 0 || d % 17 === 0; }

  // ── State ─────────────────────────────────────────────────────────────
  const today = new Date();
  const todayD = today.getDate(), todayM = today.getMonth(), todayY = today.getFullYear();

  const [view,     setView]     = React.useState('calendar');
  const [monthOff, setMonthOff] = React.useState(0);

  const [selDate, setSelDate] = React.useState(() => {
    try { return JSON.parse(localStorage.getItem('ilio-sel-date')) || null; } catch { return null; }
  });
  const [slot, setSlot] = React.useState(() => {
    try { return localStorage.getItem('ilio-sel-slot') || null; } catch { return null; }
  });

  const viewYear  = todayY + Math.floor((todayM + monthOff) / 12);
  const viewMonth = (todayM + monthOff) % 12;
  const cells     = buildCalendar(viewYear, viewMonth);
  const padD      = n => String(n).padStart(2, '0');
  const dtOf      = d => padD(d) + '.' + padD(viewMonth + 1);

  const saveDate = (d) => {
    const obj = { d, dt: dtOf(d), month: viewMonth, year: viewYear };
    setSelDate(obj);
    try { localStorage.setItem('ilio-sel-date', JSON.stringify(obj)); } catch {}
    setSlot(null);
    try { localStorage.removeItem('ilio-sel-slot'); } catch {}
    setView('time');
  };
  const saveSlot = (s) => {
    setSlot(s);
    try { localStorage.setItem('ilio-sel-slot', s); } catch {}
  };
  const isWeekend = (d) => { const dw = new Date(viewYear, viewMonth, d).getDay(); return dw === 0 || dw === 6; };
  const isPast    = (d) => new Date(viewYear, viewMonth, d) < new Date(todayY, todayM, todayD);

  // ── Slot data ─────────────────────────────────────────────────────────
  const slotsByTod = st && st.duration === 90 ? {
    morning: ['09:00', '10:30'],
    day:     ['12:00', '14:00', '15:30'],
    evening: ['17:00', '18:30', '20:00'],
    late:    ['21:30'],
  } : {
    morning: ['08:30', '09:30', '10:30', '11:30'],
    day:     ['12:30', '13:30', '14:30', '15:30', '16:30'],
    evening: ['17:30', '18:30', '19:30', '20:30'],
    late:    ['21:30', '22:30'],
  };
  const order = prefs.tod === 'flex'
    ? ['morning', 'day', 'evening', 'late']
    : [prefs.tod, ...['morning','day','evening','late'].filter(k => k !== prefs.tod)];
  const busySlot = (d, s) => { if (!d) return false; return ((d * 7 + parseInt(s, 10)) % 5) === 0; };

  // ══ CALENDAR VIEW ══════════════════════════════════════════════════════
  if (view === 'calendar') {
    return (
      <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
        <GlubinaBackdrop />
        <div style={{ position: 'relative', zIndex: 1 }}>
          <GlubinaTopBar title="Выбор даты" onBack={onBack} step={2} total={2} sessionType={sessionType} />
          <SessionBanner sessionType={sessionType} />
          <div style={{ padding: '18px 22px 40px', maxWidth: 520, margin: '0 auto' }}>

            {/* Sync banner */}
            <div style={{ display: 'flex', alignItems: 'center', gap: 10, padding: '10px 14px', borderRadius: 12, background: t.accent + '10', border: '1px solid ' + t.rule }}>
              <div style={{ width: 8, height: 8, borderRadius: '50%', background: '#5db86a', boxShadow: '0 0 0 3px rgba(93,184,106,0.18)', animation: 'gb-pulse 2s ease-in-out infinite' }} />
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 10, color: t.accent, fontWeight: 600, letterSpacing: '0.2em', textTransform: 'uppercase' }}>Apple Календарь · синхронизировано</div>
                <div style={{ fontSize: 11, color: t.mist, marginTop: 1 }}>Только реально свободное время · обновлено сейчас</div>
              </div>
              <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.5"><rect x="3" y="5" width="18" height="16" rx="2.5" /><path d="M3 9h18M8 3v4M16 3v4" strokeLinecap="round" /></svg>
            </div>
            <style>{'@keyframes gb-pulse { 0%,100%{opacity:1} 50%{opacity:.4} }'}</style>

            {/* Month nav */}
            <div style={{ marginTop: 24, display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
              <button onClick={() => setMonthOff(o => Math.max(0, o - 1))} disabled={monthOff === 0} style={{ background: 'none', border: 'none', color: monthOff === 0 ? t.faint : t.ink, cursor: monthOff === 0 ? 'default' : 'pointer', padding: '6px 10px' }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="m15 18-6-6 6-6"/></svg>
              </button>
              <div style={{ textAlign: 'center' }}>
                <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 30, fontWeight: 500, color: t.ink, fontStyle: 'italic', letterSpacing: '-0.01em', lineHeight: 1 }}>{MONTH_RU[viewMonth]}</div>
                <div style={{ fontSize: 11, color: t.mist, marginTop: 3, letterSpacing: '0.25em' }}>{viewYear}</div>
              </div>
              <button onClick={() => setMonthOff(o => Math.min(2, o + 1))} disabled={monthOff === 2} style={{ background: 'none', border: 'none', color: monthOff === 2 ? t.faint : t.ink, cursor: monthOff === 2 ? 'default' : 'pointer', padding: '6px 10px' }}>
                <svg width="22" height="22" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><path d="m9 18 6-6-6-6"/></svg>
              </button>
            </div>

            {/* DOW header */}
            <div style={{ marginTop: 18, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
              {DOW_RU.map((d, i) => (
                <div key={d} style={{ textAlign: 'center', fontSize: 9, letterSpacing: '0.2em', color: i >= 5 ? t.accent : t.mist, fontWeight: 600, padding: '4px 0' }}>{d}</div>
              ))}
            </div>

            {/* Calendar grid */}
            <div style={{ marginTop: 4, display: 'grid', gridTemplateColumns: 'repeat(7, 1fr)', gap: 4 }}>
              {cells.map((d, i) => {
                if (!d) return <div key={i} />;
                const past     = isPast(d);
                const booked   = isFullyBooked(d);
                const weekend  = isWeekend(d);
                const isToday  = d === todayD && viewMonth === todayM && viewYear === todayY;
                const selected = selDate && selDate.d === d && selDate.month === viewMonth && selDate.year === viewYear;
                const disabled = past || booked;
                return (
                  <button key={i} onClick={() => !disabled && saveDate(d)} style={{
                    aspectRatio: '1', borderRadius: 12, border: 'none',
                    background: selected ? ('linear-gradient(180deg,' + t.accent + ',' + t.accentDim + ')')
                              : isToday  ? (t.accent + '18')
                              : booked   ? t.alarm
                              : (t.panel + '55'),
                    color: selected ? t.deep : past ? t.faint : booked ? t.alarmInk : weekend ? t.accent : t.ink,
                    fontFamily: THEME_FONTS.serif, fontSize: 18, fontWeight: 500,
                    cursor: disabled ? 'not-allowed' : 'pointer',
                    opacity: past ? 0.3 : 1,
                    outline: (isToday && !selected) ? ('1.5px solid ' + t.accent + '55') : 'none',
                    textDecoration: booked ? 'line-through' : 'none',
                    boxShadow: selected ? ('0 6px 16px -4px ' + t.accent + '70') : 'none',
                    transition: 'all .15s ease',
                    display: 'flex', alignItems: 'center', justifyContent: 'center',
                  }}>{d}</button>
                );
              })}
            </div>

            {/* Legend */}
            <div style={{ marginTop: 16, display: 'flex', gap: 16, flexWrap: 'wrap' }}>
              {[{color: t.accent, label:'Выходной'},{color: t.alarmInk, label:'Занято'},{color: t.ink, label:'Свободно'}].map(({color, label}) => (
                <div key={label} style={{ display: 'flex', alignItems: 'center', gap: 5, fontSize: 10, color: t.mist, letterSpacing: '0.1em' }}>
                  <div style={{ width: 8, height: 8, borderRadius: 3, background: color, opacity: 0.7 }} />
                  {label}
                </div>
              ))}
            </div>

            {/* Selected date hint */}
            {selDate && selDate.month === viewMonth && selDate.year === viewYear && (
              <div style={{ marginTop: 18, padding: '14px 18px', borderRadius: 14, background: 'linear-gradient(180deg,' + t.lift + '66,' + t.deep + '66)', border: '1px solid ' + t.accent + '44', display: 'flex', alignItems: 'center', justifyContent: 'space-between' }}>
                <div>
                  <div style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase', color: t.mist }}>Выбрана дата</div>
                  <div style={{ fontFamily: THEME_FONTS.serif, fontStyle: 'italic', fontSize: 22, color: t.accent, marginTop: 2 }}>{selDate.dt}</div>
                </div>
                <button onClick={() => setView('time')} style={{ padding: '10px 18px', borderRadius: 10, background: 'linear-gradient(180deg,' + t.accent + ',' + t.accentDim + ')', border: 'none', color: t.deep, fontFamily: THEME_FONTS.sans, fontWeight: 600, fontSize: 13, cursor: 'pointer', display: 'flex', alignItems: 'center', gap: 6 }}>
                  Выбрать время
                  <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round"><path d="m9 18 6-6-6-6"/></svg>
                </button>
              </div>
            )}
          </div>
        </div>
      </div>
    );
  }

  // ══ TIME SLOTS VIEW ════════════════════════════════════════════════════
  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
      <GlubinaBackdrop />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <GlubinaTopBar title="Выбор времени" onBack={() => setView('calendar')} step={2} total={2} sessionType={sessionType} />
        <SessionBanner sessionType={sessionType} />
        <div style={{ padding: '18px 22px 40px' }}>

          {/* Selected date chip */}
          <div style={{ display: 'inline-flex', alignItems: 'center', gap: 8, padding: '8px 14px', borderRadius: 99, background: t.accent + '18', border: '1px solid ' + t.accent + '44' }}>
            <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="2" strokeLinecap="round"><rect x="3" y="5" width="18" height="16" rx="2.5"/><path d="M3 9h18M8 3v4M16 3v4"/></svg>
            <span style={{ fontFamily: THEME_FONTS.serif, fontSize: 16, fontStyle: 'italic', color: t.accent }}>{selDate && selDate.dt}</span>
            <button onClick={() => setView('calendar')} style={{ background: 'none', border: 'none', color: t.mist, cursor: 'pointer', fontSize: 11, letterSpacing: '0.1em', textDecoration: 'underline', padding: 0 }}>изменить</button>
          </div>

          <h1 style={{ margin: '16px 0 0', fontFamily: THEME_FONTS.serif, fontSize: 26, fontWeight: 500, color: t.ink, letterSpacing: '-0.01em', lineHeight: 1.1 }}>
            Выбери <em style={{ color: t.accent, fontStyle: 'italic' }}>точное время</em>
          </h1>
          <p style={{ margin: '8px 0 0', fontSize: 12.5, color: t.mist, lineHeight: 1.55 }}>
            Время по Москве (МСК) · длительность {st ? st.durationLabel : '50 мин'}
          </p>

          {/* Grouped slots */}
          <div style={{ marginTop: 22, display: 'flex', flexDirection: 'column', gap: 18 }}>
            {order.map(tod => {
              const todLabel = { morning: 'Утро', day: 'День', evening: 'Вечер', late: 'Поздний вечер' }[tod];
              const slots = slotsByTod[tod];
              return (
                <div key={tod}>
                  <div style={{ fontSize: 10, letterSpacing: '0.3em', textTransform: 'uppercase', color: tod === prefs.tod ? t.accent : t.mist, fontWeight: 600, marginBottom: 8, display: 'flex', alignItems: 'center', gap: 8 }}>
                    {todLabel}
                    {tod === prefs.tod && <span style={{ fontSize: 8, padding: '2px 6px', borderRadius: 99, background: t.accent + '22', color: t.accent, letterSpacing: '0.15em' }}>ВЫБРАНО</span>}
                  </div>
                  <div style={{ display: 'grid', gridTemplateColumns: 'repeat(3, 1fr)', gap: 8 }}>
                    {slots.map(s => {
                      const isBusy = busySlot(selDate ? selDate.d : 1, s);
                      const active = slot === s;
                      return (
                        <button key={s} disabled={isBusy} onClick={() => saveSlot(s)} style={{
                          padding: '13px 4px', borderRadius: 12,
                          border: '1px solid ' + (active ? t.accent : t.rule),
                          background: isBusy ? 'transparent' : active ? ('linear-gradient(180deg,' + t.accent + ',' + t.accentDim + ')') : (t.panel + '88'),
                          color: isBusy ? t.faint : active ? t.deep : t.ink,
                          fontFamily: THEME_FONTS.serif, fontSize: 17, fontWeight: 500,
                          letterSpacing: '-0.005em', cursor: isBusy ? 'not-allowed' : 'pointer',
                          textDecoration: isBusy ? 'line-through' : 'none', opacity: isBusy ? 0.45 : 1,
                          transition: 'all .18s ease',
                        }}>{s}</button>
                      );
                    })}
                  </div>
                </div>
              );
            })}
          </div>

          {/* Footer summary */}
          <div style={{ marginTop: 30, padding: '18px 20px', borderRadius: 14, border: '1px solid ' + t.rule, background: 'linear-gradient(180deg,' + t.lift + '66,' + t.deep + '66)', display: 'flex', alignItems: 'center', justifyContent: 'space-between', gap: 12 }}>
            <div>
              <div style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase', color: t.mist, fontWeight: 600 }}>{st && st.free ? 'Стоимость' : 'Сессия'}</div>
              <div style={{ fontFamily: THEME_FONTS.serif, fontSize: 26, color: st && st.free ? '#7ec089' : t.accent, fontWeight: 500, marginTop: 2, letterSpacing: '-0.01em', lineHeight: 1, fontStyle: 'italic' }}>{st ? st.price : '—'}</div>
            </div>
            <div style={{ textAlign: 'right' }}>
              <div style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase', color: t.mist, fontWeight: 600 }}>Выбрано</div>
              <div style={{ fontFamily: THEME_FONTS.serif, fontStyle: 'italic', fontSize: 18, color: t.ink, marginTop: 2 }}>{slot ? ((selDate ? selDate.dt : '') + ' · ' + slot) : 'Выбери время'}</div>
            </div>
          </div>

          <button onClick={() => slot && selDate && onConfirm({ date: selDate.dt, time: slot })} disabled={!slot} style={{
            marginTop: 16, width: '100%', maxWidth: 420, padding: '16px 18px', borderRadius: 14,
            border: '1px solid ' + (slot ? t.accent : t.rule),
            background: slot ? ('linear-gradient(180deg,' + t.accent + ',' + t.accentDim + ')') : (t.panel + '44'),
            color: slot ? t.deep : t.faint, fontFamily: THEME_FONTS.sans, fontWeight: 600,
            fontSize: 15, letterSpacing: '0.01em', cursor: slot ? 'pointer' : 'not-allowed',
            boxShadow: slot ? ('0 12px 30px -10px ' + t.accent + '80, inset 0 1px 0 ' + t.ink + '66') : 'none',
            display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 8,
            transition: 'all .2s ease',
          }}>
            Дальше
            <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round"><path d="M5 12h14"/><path d="m13 6 6 6-6 6"/></svg>
          </button>
        </div>
      </div>
    </div>
  );
}

// ── Cloudflare Worker endpoint ────────────────────────────────────────
// После деплоя замени YOUR_USERNAME на свой Cloudflare username
const WORKER_URL = 'https://iliaocean-booking.YOUR_USERNAME.workers.dev';

// ───────────────────────────────────── ICS / Apple Calendar
function generateICS({ when, sessionType, answers }) {
  const st = SESSION_TYPES[sessionType];
  const [day, month] = (when.date || '01.01').split('.');
  const [hour, minute] = (when.time || '12:00').split(':');
  const year = new Date().getFullYear();
  const pad = n => String(parseInt(n, 10)).padStart(2, '0');
  const dtStart = `${year}${pad(month)}${pad(day)}T${pad(hour)}${pad(minute)}00`;
  const durationMin = st ? st.duration : 60;
  const totalMin = parseInt(hour, 10) * 60 + parseInt(minute, 10) + durationMin;
  const eH = Math.floor(totalMin / 60) % 24;
  const eM = totalMin % 60;
  const dtEnd = `${year}${pad(month)}${pad(day)}T${pad(eH)}${pad(eM)}00`;
  const title = st ? `Сессия с Ильёй · ${st.name}` : 'Сессия с Ильёй';
  const desc = [
    `Формат: Zoom`,
    `Длительность: ${st ? st.durationLabel : '60 мин'}`,
    `Имя: ${answers?.name || '—'}`,
    `Telegram: ${answers?.tg || '—'}`,
    `Ссылка на Zoom придёт в Telegram перед сессией.`,
  ].join('\\n');
  return [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//iliaocean//coaching//RU',
    'CALSCALE:GREGORIAN',
    'METHOD:PUBLISH',
    'BEGIN:VEVENT',
    `UID:booking-${Date.now()}@iliaocean.com`,
    `DTSTART:${dtStart}`,
    `DTEND:${dtEnd}`,
    `SUMMARY:${title}`,
    `DESCRIPTION:${desc}`,
    'LOCATION:Zoom (ссылка придёт в Telegram)',
    'STATUS:CONFIRMED',
    'END:VEVENT',
    'END:VCALENDAR',
  ].join('\r\n');
}

function AppleCalendarButton({ t, when, sessionType, answers }) {
  const [state, setState] = React.useState('idle'); // idle | added

  const handleAdd = () => {
    const ics = generateICS({ when, sessionType, answers });
    const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'session-iliaocean.ics';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);
    setState('added');
    setTimeout(() => setState('idle'), 4000);
  };

  const isAdded = state === 'added';
  return (
    <button onClick={handleAdd} style={{
      flex: 1, padding: '13px 10px', borderRadius: 14, boxSizing: 'border-box',
      border: `1px solid ${isAdded ? t.accent : t.rule}`,
      background: isAdded ? `${t.accent}14` : `${t.lift}55`,
      color: isAdded ? t.accent : t.ink,
      fontFamily: THEME_FONTS.sans, fontSize: 12.5, fontWeight: 500,
      cursor: 'pointer', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', gap: 7,
      textAlign: 'center', lineHeight: 1.2,
      transition: 'all 0.25s ease',
    }}>
      {isAdded ? (
        <>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none"
               stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="m5 12 5 5 9-11"/>
          </svg>
          Добавлено
        </>
      ) : (
        <>
          <svg width="17" height="17" viewBox="0 0 24 24" fill="none"
               stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
            <rect x="3" y="4" width="18" height="18" rx="3"/>
            <path d="M16 2v4M8 2v4M3 10h18"/>
            <path d="M12 14v4M10 16h4"/>
          </svg>
          Apple Calendar
        </>
      )}
    </button>
  );
}

function GoogleCalendarButton({ t, when, sessionType }) {
  const SESSIONS = {
    diagnostic: { name: 'Диагностика',          duration: 50  },
    analytical:  { name: 'Аналитическая сессия', duration: 90  },
  };
  const st = SESSIONS[sessionType] || { name: 'Сессия', duration: 60 };

  const buildGoogleUrl = () => {
    const [day, month] = (when.date || '01.01').split('.');
    const [hour, minute] = (when.time || '12:00').split(':');
    const year = new Date().getFullYear();
    const pad = n => String(parseInt(n, 10)).padStart(2, '0');
    const dtStart = `${year}${pad(month)}${pad(day)}T${pad(hour)}${pad(minute)}00`;
    const totalMin = parseInt(hour, 10) * 60 + parseInt(minute, 10) + st.duration;
    const eH = Math.floor(totalMin / 60) % 24;
    const eM = totalMin % 60;
    const dtEnd = `${year}${pad(month)}${pad(day)}T${pad(eH)}${pad(eM)}00`;
    const title = encodeURIComponent(`Сессия с Ильёй · ${st.name}`);
    const details = encodeURIComponent('Формат: Zoom\nСсылка придёт в Telegram перед сессией.');
    const location = encodeURIComponent('Zoom');
    return `https://www.google.com/calendar/render?action=TEMPLATE&text=${title}&dates=${dtStart}/${dtEnd}&details=${details}&location=${location}`;
  };

  return (
    <a href={buildGoogleUrl()} target="_blank" rel="noopener noreferrer" style={{
      flex: 1, padding: '13px 10px', borderRadius: 14, boxSizing: 'border-box',
      border: `1px solid ${t.rule}`,
      background: `${t.lift}55`,
      color: t.ink, fontFamily: THEME_FONTS.sans, fontSize: 12.5, fontWeight: 500,
      cursor: 'pointer', display: 'flex', flexDirection: 'column',
      alignItems: 'center', justifyContent: 'center', gap: 7,
      textDecoration: 'none', textAlign: 'center', lineHeight: 1.2,
      transition: 'border-color 0.2s',
    }}>
      <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
        <rect x="3" y="4" width="18" height="18" rx="3"/>
        <path d="M16 2v4M8 2v4M3 10h18"/>
        <path d="M8 15h2v2H8z" fill="currentColor" stroke="none"/>
        <path d="M14 15h2v2h-2z" fill="currentColor" stroke="none"/>
      </svg>
      Google Calendar
    </a>
  );
}

function TelegramWithCalendar({ t, tgUrl, when, sessionType, answers }) {
  const [step, setStep] = React.useState('idle'); // idle | sending | downloaded | sent

  const handleClick = async () => {
    setStep('sending');

    // 1. Отправляем на воркер (фоново — не блокируем UI)
    if (WORKER_URL && !WORKER_URL.includes('YOUR_USERNAME')) {
      fetch(WORKER_URL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ sessionType, answers, when }),
      }).catch(() => {}); // молча игнорируем ошибки сети
    }

    // 2. Скачиваем .ics
    const ics = generateICS({ when, sessionType, answers });
    const blob = new Blob([ics], { type: 'text/calendar;charset=utf-8' });
    const url = URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.href = url;
    a.download = 'session-iliaocean.ics';
    document.body.appendChild(a);
    a.click();
    document.body.removeChild(a);
    URL.revokeObjectURL(url);

    // 3. Небольшая пауза → открываем Telegram
    setStep('downloaded');
    setTimeout(() => {
      window.open(tgUrl, '_blank', 'noopener,noreferrer');
      setStep('sent');
    }, 600);
  };

  return (
    <div style={{ marginTop: 18 }}>
      <button onClick={handleClick} disabled={step === 'downloaded'} style={{
        width: '100%', maxWidth: 420, boxSizing: 'border-box',
        padding: '17px 18px', borderRadius: 14,
        border: '1px solid #2aabee',
        background: step === 'sent'
          ? 'linear-gradient(180deg, #1a9e3f, #148030)'
          : 'linear-gradient(180deg, #2aabee, #1f8ac9)',
        color: '#fff', fontFamily: THEME_FONTS.sans, fontWeight: 600,
        fontSize: 15.5, letterSpacing: '0.01em', cursor: 'pointer',
        boxShadow: step === 'sent'
          ? '0 14px 36px -10px rgba(20,128,48,0.55), inset 0 1px 0 rgba(255,255,255,0.25)'
          : '0 14px 36px -10px rgba(42,171,238,0.6), inset 0 1px 0 rgba(255,255,255,0.3)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        transition: 'background 0.3s ease, box-shadow 0.3s ease',
        opacity: step === 'downloaded' ? 0.7 : 1,
      }}>
        {step === 'sent' ? (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="m5 12 5 5 9-11"/>
            </svg>
            Открыт Telegram
          </>
        ) : step === 'downloaded' ? (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none"
                 stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
              <path d="M12 3v12M8 11l4 4 4-4"/>
              <path d="M3 19h18"/>
            </svg>
            Открываю Telegram…
          </>
        ) : (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z"/>
            </svg>
            Отправить в Telegram
          </>
        )}
      </button>

      {/* Hint — appears after download */}
      <div style={{
        marginTop: 10, padding: '11px 14px', borderRadius: 10,
        background: step === 'sent' ? `${t.accent}10` : `${t.accent}08`,
        border: `1px solid ${step === 'sent' ? t.accent + '44' : t.rule}`,
        fontSize: 11.5, color: t.mist, lineHeight: 1.5,
        display: 'flex', gap: 8,
        transition: 'all 0.3s ease',
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none"
             stroke={t.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round"
             style={{ flexShrink: 0, marginTop: 1 }}>
          <circle cx="12" cy="12" r="9"/>
          <path d="M12 8v4M12 16h.01"/>
        </svg>
        <span>
          {step === 'idle' || step === 'sending'
            ? 'Файл .ics скачается автоматически — прикрепи его к сообщению в Telegram, чтобы я получил событие в свой календарь.'
            : step === 'downloaded'
            ? 'Файл скачан — прикрепи его к сообщению в Telegram.'
            : 'Прикрепи скачанный файл к сообщению и нажми «Отправить». Я уже получил уведомление автоматически.'}
        </span>
      </div>
    </div>
  );
}

function TelegramCTA({ t, tgUrl, when, sessionType, answers }) {
  const [step, setStep] = React.useState('idle'); // idle | sending | done

  const handleClick = async () => {
    setStep('sending');

    // 1. Вызов воркера — отправит текст + 2 файла калэндаря тебе в Telegram
    if (WORKER_URL && !WORKER_URL.includes('YOUR_USERNAME')) {
      try {
        await fetch(WORKER_URL, {
          method: 'POST',
          headers: { 'Content-Type': 'application/json' },
          body: JSON.stringify({ sessionType, answers, when }),
        });
      } catch {}
    }

    // 2. Открыть Telegram у клиента
    window.open(tgUrl, '_blank', 'noopener,noreferrer');
    setStep('done');
  };

  return (
    <div style={{ marginTop: 12 }}>
      <button onClick={handleClick} disabled={step === 'sending'} style={{
        width: '100%', boxSizing: 'border-box',
        padding: '17px 18px', borderRadius: 14,
        border: '1px solid #2aabee',
        background: step === 'done'
          ? 'linear-gradient(180deg, #1a9e3f, #148030)'
          : 'linear-gradient(180deg, #2aabee, #1f8ac9)',
        color: '#fff', fontFamily: THEME_FONTS.sans, fontWeight: 600,
        fontSize: 15.5, letterSpacing: '0.01em', cursor: step === 'sending' ? 'default' : 'pointer',
        boxShadow: step === 'done'
          ? '0 14px 36px -10px rgba(20,128,48,0.5), inset 0 1px 0 rgba(255,255,255,0.25)'
          : '0 14px 36px -10px rgba(42,171,238,0.6), inset 0 1px 0 rgba(255,255,255,0.3)',
        display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
        opacity: step === 'sending' ? 0.7 : 1,
        transition: 'background 0.3s, box-shadow 0.3s',
      }}>
        {step === 'sending' ? (
          <>
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round" style={{ animation: 'spin 1s linear infinite' }}>
              <path d="M21 12a9 9 0 1 1-6.219-8.56"/>
            </svg>
            Отправляю…
          </>
        ) : step === 'done' ? (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
              <path d="m5 12 5 5 9-11"/>
            </svg>
            Отправлено
          </>
        ) : (
          <>
            <svg width="20" height="20" viewBox="0 0 24 24" fill="currentColor">
              <path d="M9.78 18.65l.28-4.23 7.68-6.92c.34-.31-.07-.46-.52-.19L7.74 13.3 3.64 12c-.88-.25-.89-.86.2-1.3l15.97-6.16c.73-.33 1.43.18 1.15 1.3l-2.72 12.81c-.19.91-.74 1.13-1.5.71L12.6 16.3l-1.99 1.93c-.23.23-.42.42-.83.42z"/>
            </svg>
            Написать в Telegram
          </>
        )}
      </button>
    </div>
  );
}

// ───────────────────────────────────── Telegram handoff (final step)
function buildTelegramMessage({ answers, when, sessionType }) {
  const st = SESSION_TYPES[sessionType];
  const block = (label, text) => {
    const v = (text || '').trim();
    if (!v) return null;
    return `▸ ${label}\n${v}`;
  };
  const parts = [
    'Здравствуйте, Илья!',
    '',
    `Хочу записаться: ${st ? st.name : '—'} (${st ? st.durationLabel : '—'}${st && !st.free ? ` · ${st.price}` : ''})`,
    `Удобное время: ${when.date} · ${when.time} (МСК)`,
    `Формат: Zoom · с записью и транскрибацией`,
    '',
    `Меня зовут ${answers.name || '—'} (${answers.tg || '—'})`,
    '',
    block('Что сейчас происходит',          answers.story),
    '',
    block('Как давно и что пробовал(а)',    answers.history),
    '',
    block('Каким хочу видеть себя через год', answers.future),
    '',
    st && st.free ? 'Готов(а) к знакомству 🌊' : 'Готов(а) к диагностике 🌊',
  ].filter(s => s !== null);
  // collapse multiple blank lines
  return parts.join('\n').replace(/\n{3,}/g, '\n\n');
}

// ───────────────────────────────────── Tests block (analytical session prep)
const ANALYTICAL_TESTS = [
  {
    n: '01', title: 'OCEAN · 5 голосов',
    desc: 'Большая пятёрка черт личности — базовая карта характера.',
    tag: '~5 минут',
    url: 'https://assessments.exponentialcoachingacademy.com/ocean.html',
  },
  {
    n: '02', title: 'YSQ · метапрограммы',
    desc: 'Глубинные схемы и установки — что управляет реакциями изнутри.',
    tag: '~15 минут',
    url: 'https://assessments.exponentialcoachingacademy.com/ysq.html',
  },
  {
    n: '03', title: 'BAI · шкала тревоги Бэка',
    desc: 'Клиническая шкала уровня тревожности.',
    tag: '~5 минут',
    url: 'https://assessments.exponentialcoachingacademy.com/bai.html',
  },
  {
    n: '04', title: 'BDI · депрессия Бэка',
    desc: 'Эмоциональный тонус и уровень депрессивных проявлений.',
    tag: '~5 минут',
    url: 'https://assessments.exponentialcoachingacademy.com/bdi.html',
  },
  {
    n: '05', title: 'WHOQOL-BREF · качество жизни',
    desc: 'Оценка ВОЗ — физическое, психическое, социальное измерение.',
    tag: '~5 минут',
    url: 'https://assessments.exponentialcoachingacademy.com/bref.html',
  },
];

function TestsBlock({ t, coachEmail = 'ilia.belchenko@gmail.com' }) {
  const [copied, setCopied] = React.useState(false);
  const handleCopy = async () => {
    try {
      await navigator.clipboard.writeText(coachEmail);
      setCopied(true);
      setTimeout(() => setCopied(false), 1500);
    } catch {}
  };

  return (
    <div style={{
      borderRadius: 16, overflow: 'hidden',
      border: `1px solid ${t.accent}55`,
      background: `linear-gradient(180deg, ${t.accent}14, ${t.deep}88)`,
    }}>
      {/* Header */}
      <div style={{ padding: '18px 18px 14px' }}>
        <div style={{
          display: 'flex', alignItems: 'center', gap: 8,
          fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
          color: t.accent, fontWeight: 600,
        }}>
          <span style={{ width: 6, height: 6, borderRadius: '50%', background: t.accent }} />
          Подготовка · 5 тестов
        </div>
        <div style={{
          marginTop: 8, fontFamily: THEME_FONTS.serif, fontSize: 24,
          color: t.ink, fontWeight: 500, letterSpacing: '-0.01em', lineHeight: 1.1,
        }}>
          Пройди тесты <em style={{ color: t.accent, fontStyle: 'italic' }}>до сессии</em>
        </div>
        <p style={{ margin: '10px 0 0', fontSize: 12.5, color: t.mist, lineHeight: 1.55 }}>
          Суммарно ~30 минут. Результаты приходят мне на почту автоматически —
          я собираю на их основе твою <em style={{ color: t.ink, fontFamily: THEME_FONTS.serif, fontSize: 13.5, fontStyle: 'italic' }}>МКП-карту</em>: кто ты есть, почему ты там, где ты есть, и что тебе с этим делать.
        </p>
      </div>

      {/* Coach email */}
      <div style={{
        margin: '0 14px', padding: '12px 14px', borderRadius: 12,
        border: `1px dashed ${t.accent}66`,
        background: `${t.accent}10`,
      }}>
        <div style={{
          display: 'flex', alignItems: 'center', justifyContent: 'space-between',
          fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
          color: t.mist, fontWeight: 600, marginBottom: 6,
        }}>
          <span>Почта коуча · вставлять в каждом тесте</span>
        </div>
        <div style={{ display: 'flex', alignItems: 'center', gap: 8 }}>
          <span style={{
            flex: 1, fontFamily: 'ui-monospace, "SF Mono", monospace',
            fontSize: 13.5, color: t.accent, fontWeight: 500, letterSpacing: '0.01em',
            wordBreak: 'break-all',
          }}>{coachEmail}</span>
          <button onClick={handleCopy} style={{
            flexShrink: 0, padding: '6px 10px', borderRadius: 8,
            border: `1px solid ${copied ? '#7ec089' : t.accent}`,
            background: copied ? 'rgba(126,192,137,0.16)' : 'transparent',
            color: copied ? '#7ec089' : t.accent,
            fontFamily: THEME_FONTS.sans, fontSize: 10.5, fontWeight: 600,
            letterSpacing: '0.12em', textTransform: 'uppercase', cursor: 'pointer',
            display: 'flex', alignItems: 'center', gap: 5,
            transition: 'all .2s ease',
          }}>
            {copied ? (
              <>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round" strokeLinejoin="round">
                  <path d="m5 12 5 5 9-11"/>
                </svg>
                Готово
              </>
            ) : (
              <>
                <svg width="11" height="11" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round">
                  <rect x="8" y="8" width="12" height="12" rx="2"/>
                  <path d="M16 8V5a1 1 0 0 0-1-1H5a1 1 0 0 0-1 1v10a1 1 0 0 0 1 1h3"/>
                </svg>
                Копировать
              </>
            )}
          </button>
        </div>
        <div style={{ marginTop: 8, fontSize: 11, color: t.mist, lineHeight: 1.45, display: 'flex', gap: 6 }}>
          <svg width="12" height="12" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 1 }}>
            <circle cx="12" cy="12" r="9"/>
            <path d="M12 8v4M12 16h.01"/>
          </svg>
          <span>В каждом тесте есть поле <em style={{ fontFamily: THEME_FONTS.serif, fontSize: 12, color: t.ink }}>«Почта коуча»</em> — вставь сюда мою; в поле <em style={{ fontFamily: THEME_FONTS.serif, fontSize: 12, color: t.ink }}>«Твоя почта»</em> — свою.</span>
        </div>
      </div>

      {/* Tests list */}
      <div style={{ padding: '14px 14px 16px', display: 'flex', flexDirection: 'column', gap: 8 }}>
        {ANALYTICAL_TESTS.map((test) => (
          <a key={test.n} href={test.url} target="_blank" rel="noopener noreferrer" style={{
            display: 'flex', alignItems: 'center', gap: 12,
            padding: '12px 14px', borderRadius: 12,
            border: `1px solid ${t.rule}`,
            background: `${t.panel}77`,
            textDecoration: 'none', cursor: 'pointer',
            transition: 'all .18s ease',
          }}
          onMouseEnter={e => {
            e.currentTarget.style.borderColor = t.accent;
            e.currentTarget.style.background = `${t.accent}10`;
            e.currentTarget.style.transform = 'translateX(2px)';
          }}
          onMouseLeave={e => {
            e.currentTarget.style.borderColor = t.rule;
            e.currentTarget.style.background = `${t.panel}77`;
            e.currentTarget.style.transform = 'none';
          }}>
            <div style={{
              flexShrink: 0, width: 36, height: 36, borderRadius: 10,
              background: `${t.accent}1a`, color: t.accent,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              fontFamily: THEME_FONTS.serif, fontSize: 16, fontStyle: 'italic',
              fontWeight: 500, letterSpacing: '-0.02em',
            }}>{test.n}</div>
            <div style={{ flex: 1, minWidth: 0 }}>
              <div style={{
                display: 'flex', alignItems: 'baseline', gap: 8, flexWrap: 'wrap',
              }}>
                <span style={{
                  fontFamily: THEME_FONTS.serif, fontSize: 15.5, color: t.ink,
                  fontWeight: 500, lineHeight: 1.2,
                }}>{test.title}</span>
                <span style={{
                  fontSize: 9.5, color: t.mist, letterSpacing: '0.15em',
                  textTransform: 'uppercase', fontWeight: 500,
                }}>{test.tag}</span>
              </div>
              <div style={{ fontSize: 11.5, color: t.mist, marginTop: 3, lineHeight: 1.4 }}>
                {test.desc}
              </div>
            </div>
            <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0 }}>
              <path d="M7 17 17 7"/>
              <path d="M8 7h9v9"/>
            </svg>
          </a>
        ))}
      </div>

      {/* Footer */}
      <div style={{
        padding: '12px 18px 16px',
        borderTop: `1px solid ${t.rule}`,
        background: `${t.deep}66`,
        display: 'flex', gap: 8, alignItems: 'flex-start',
      }}>
        <svg width="14" height="14" viewBox="0 0 24 24" fill="none" stroke={t.accent} strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" style={{ flexShrink: 0, marginTop: 2 }}>
          <path d="M12 2 4 6v6c0 5 3.5 9 8 10 4.5-1 8-5 8-10V6l-8-4Z"/>
          <path d="m9 12 2 2 4-4"/>
        </svg>
        <div style={{ fontSize: 11.5, color: t.mist, lineHeight: 1.5 }}>
          Результаты <em style={{ color: t.ink, fontFamily: THEME_FONTS.serif, fontSize: 12.5, fontStyle: 'italic' }}>не остаются у тебя</em> — они уходят только мне.
          К сессии я приду с готовой <em style={{ color: t.accent, fontFamily: THEME_FONTS.serif, fontSize: 12.5, fontStyle: 'italic' }}>МКП-картой</em> — кто ты, почему так, и что с этим делать.
        </div>
      </div>
    </div>
  );
}

function GlubinaHandoff({ sessionType = 'diagnostic', answers, when, onBack, onHome, telegramHandle = 'iliaocean' }) {
  const t = useTheme();
  const st = SESSION_TYPES[sessionType];
  const msg = buildTelegramMessage({ answers, when, sessionType });
  const tgUrl = `https://t.me/${telegramHandle}?text=${encodeURIComponent(msg)}`;

  return (
    <div style={{ position: 'relative', width: '100%', height: '100%', overflow: 'auto', background: t.deep }}>
      <GlubinaBackdrop />
      <div style={{ position: 'relative', zIndex: 1 }}>
        <GlubinaTopBar title="Почти готово" onBack={onBack} sessionType={sessionType} />

        <div style={{ padding: '28px 22px 40px', maxWidth: 520, margin: '0 auto' }}>
          {/* Checkmark hero + mandala */}
          <div style={{ display: 'flex', justifyContent: 'center', position: 'relative' }}>
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              pointerEvents: 'none',
            }}>
              <GlubinaMandala variant="compass" size={220} opacity={0.28} spin spinDuration={140} strokeWidth={0.55} />
            </div>
            <div style={{
              position: 'absolute', inset: 0,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              pointerEvents: 'none',
            }}>
              <GlubinaMandala variant="wave" size={160} opacity={0.35} spin spinDuration={90} strokeWidth={0.5} />
            </div>
            <div style={{
              width: 78, height: 78, borderRadius: '50%',
              background: `linear-gradient(135deg, ${t.accent}, ${t.accentDim})`,
              display: 'flex', alignItems: 'center', justifyContent: 'center',
              boxShadow: `0 18px 50px -10px ${t.accent}80`,
              position: 'relative', zIndex: 2,
            }}>
              <svg width="32" height="32" viewBox="0 0 24 24" fill="none"
                   stroke={t.deep} strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
                <path d="m5 12 5 5 9-11"/>
              </svg>
            </div>
          </div>

          <h1 style={{
            margin: '24px 0 0', textAlign: 'center', fontFamily: THEME_FONTS.serif,
            fontSize: 32, fontWeight: 500, color: t.ink,
            letterSpacing: '-0.015em', lineHeight: 1.05,
          }}>
            Время <em style={{ color: t.accent, fontStyle: 'italic' }}>забронировано</em>
          </h1>
          <p style={{
            margin: '12px auto 0', maxWidth: 300, textAlign: 'center',
            fontSize: 13.5, color: t.mist, lineHeight: 1.55,
          }}>
            Остался один шаг — отправить мне сообщение в Telegram. Текст уже готов,
            тебе нужно только нажать «отправить».
          </p>

          {/* Summary card */}
          <div style={{
            marginTop: 24, padding: '20px 22px', borderRadius: 16,
            border: `1px solid ${t.rule}`,
            background: `linear-gradient(180deg, ${t.lift}66, ${t.deep}66)`,
          }}>
            <div style={{ fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                          color: t.accent, fontWeight: 600, marginBottom: 14 }}>Сводка</div>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 10 }}>
              <Row t={t} k="Сессия"        v={st ? `${st.name} · ${st.durationLabel}` : '—'} />
              <Row t={t} k="Стоимость"     v={st ? st.price : '—'}
                   color={st && st.free ? '#7ec089' : t.accent} accent />
              <Row t={t} k="Дата · время"  v={`${when.date} · ${when.time}`} accent />
              <Row t={t} k="Формат"        v="Zoom · запись + транскрибация" />
              <Row t={t} k="Имя"           v={answers.name} />
              <Row t={t} k="Telegram"      v={answers.tg} />
            </div>
          </div>

          {/* Zoom format note — sales recap */}
          <div style={{ marginTop: 18 }}>
            <ZoomFormatNote t={t} />
          </div>

          {/* Tests block — analytical only */}
          {sessionType === 'analytical' && (
            <div style={{ marginTop: 18 }}>
              <TestsBlock t={t} coachEmail="ilia.belchenko@gmail.com" />
            </div>
          )}

          {/* What to prepare */}
          {st && (
            <div style={{
              marginTop: 18, padding: '16px 18px', borderRadius: 14,
              border: `1px solid ${t.rule}`,
              background: `${t.accent}08`,
            }}>
              <div style={{
                fontSize: 9, letterSpacing: '0.3em', textTransform: 'uppercase',
                color: t.accent, fontWeight: 600, marginBottom: 10,
              }}>Что подготовить</div>
              {st.prep.map((s, i) => (
                <div key={i} style={{
                  display: 'flex', gap: 10, marginTop: i === 0 ? 0 : 8,
                  fontSize: 13, color: t.ink, lineHeight: 1.4,
                }}>
                  <span style={{
                    flexShrink: 0, marginTop: 6, width: 5, height: 5, borderRadius: '50%',
                    background: t.accent,
                  }} />
                  {s}
                </div>
              ))}
            </div>
          )}

          {/* Calendar buttons — Apple + Google */}
          <div style={{ marginTop: 18, display: 'flex', gap: 10 }}>
            <AppleCalendarButton t={t} when={when} sessionType={sessionType} answers={answers} />
            <GoogleCalendarButton t={t} when={when} sessionType={sessionType} />
          </div>

          {/* Telegram message preview */}
          <div style={{
            marginTop: 22, borderRadius: 16, overflow: 'hidden',
            border: `1px solid ${t.rule}`, background: '#17212b',
          }}>
            <div style={{ padding: '10px 14px', background: '#242f3d',
                          display: 'flex', alignItems: 'center', gap: 10,
                          borderBottom: '1px solid rgba(255,255,255,0.06)' }}>
              <div style={{ width: 24, height: 24, borderRadius: '50%',
                            background: `linear-gradient(135deg, ${t.accent}, ${t.accentDim})`,
                            display: 'flex', alignItems: 'center', justifyContent: 'center',
                            fontFamily: THEME_FONTS.serif, fontSize: 13, color: t.deep, fontStyle: 'italic' }}>и</div>
              <div style={{ flex: 1 }}>
                <div style={{ fontSize: 13, color: '#fff', fontWeight: 500 }}>Илья Бельченко</div>
                <div style={{ fontSize: 10, color: '#7e8e9d' }}>@{telegramHandle} · был(а) недавно</div>
              </div>
              <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="#5da4d6" strokeWidth="1.8">
                <path d="M21.5 3.5 2 11l6.5 2.2L11 21l3.2-5.4L20 19l1.5-15.5Z" strokeLinejoin="round" />
              </svg>
            </div>
            <div style={{ padding: '14px', background: '#0e1621' }}>
              <div style={{
                background: '#182533', borderRadius: 12, padding: '10px 12px',
                color: '#e8eef4', fontFamily: '-apple-system, "Segoe UI", sans-serif',
                fontSize: 12.5, lineHeight: 1.5, whiteSpace: 'pre-wrap',
                maxWidth: '92%',
              }}>{msg}
                <div style={{ textAlign: 'right', fontSize: 9, color: '#5e7180', marginTop: 4 }}>только что</div>
              </div>
            </div>
          </div>

          {/* Main CTA — Telegram + worker */}
          <TelegramCTA t={t} tgUrl={tgUrl} when={when} sessionType={sessionType} answers={answers} />

          <button onClick={onHome} style={{
            marginTop: 16, width: '100%', maxWidth: 420, padding: '12px 16px', borderRadius: 12,
            border: `1px solid ${t.rule}`, background: 'transparent', color: t.mist,
            fontFamily: THEME_FONTS.sans, fontSize: 12, letterSpacing: '0.05em', cursor: 'pointer',
          }}>На главную</button>
        </div>
      </div>
    </div>
  );
}

function Row({ t, k, v, accent, color }) {
  return (
    <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', gap: 12 }}>
      <span style={{ fontSize: 10, letterSpacing: '0.18em', textTransform: 'uppercase',
                     color: t.mist, fontWeight: 500, flexShrink: 0 }}>{k}</span>
      <span style={{
        fontFamily: THEME_FONTS.serif, fontSize: accent ? 18 : 15,
        fontStyle: 'italic', color: color || (accent ? t.accent : t.ink),
        textAlign: 'right',
      }}>{v || '—'}</span>
    </div>
  );
}

// ───────────────────────────────────── Prototype shell
function GlubinaPrototype({ theme = 'gold', telegramHandle = 'iliaocean', animated = false, layout = 'mobile' }) {
  const [stack, setStack] = React.useState(['home']);
  const [sessionType, setSessionType] = React.useState(null);
  const [answers, setAnswers] = React.useState(null);
  const [prefs, setPrefs] = React.useState(null);
  const [when, setWhen] = React.useState(null);
  const screen = stack[stack.length - 1];
  const t = GLUBINA_THEMES[theme] || GLUBINA_THEMES.gold;

  const push = (s) => setStack(st => [...st, s]);
  const back = () => setStack(st => st.length > 1 ? st.slice(0, -1) : st);
  const home = () => {
    setStack(['home']);
    setSessionType(null); setAnswers(null); setPrefs(null); setWhen(null);
  };

  // Routing helper:  target may be 'mkp' (preview only) or a session type
  const startFlow = (target) => {
    if (target === 'mkp') { push('mkp'); return; }
    // Otherwise it's a session type — start intake
    setSessionType(target);
    push('intake');
  };

  return (
    <ThemeCtx.Provider value={t}>
      <div style={{
        width: '100%', height: '100%', position: 'relative', overflow: 'hidden',
        background: t.deep,
      }}>
        <ScreenSlot active={screen === 'home'}>
          {layout === 'desktop'
            ? <GlubinaDesktop theme={theme} onCTA={startFlow} />
            : <GlubinaAnimated theme={theme} onCTA={startFlow} />}
        </ScreenSlot>

        <ScreenSlot active={screen === 'mkp'}>
          <GlubinaMKP onBack={back} onBook={() => { setSessionType('analytical'); push('intake'); }} />
        </ScreenSlot>

        <ScreenSlot active={screen === 'intake'}>
          <GlubinaIntake
            sessionType={sessionType || 'diagnostic'}
            onBack={back}
            onComplete={(a) => { setAnswers(a); push('bookingPrefs'); }} />
        </ScreenSlot>

        <ScreenSlot active={screen === 'bookingPrefs'}>
          <BookingPrefs
            sessionType={sessionType || 'diagnostic'}
            onBack={back}
            onNext={(p) => { setPrefs(p); push('bookingSlots'); }} />
        </ScreenSlot>

        <ScreenSlot active={screen === 'bookingSlots'}>
          <BookingSlots
            sessionType={sessionType || 'diagnostic'}
            prefs={prefs || { tod: 'evening', days: 'any', when: 'week' }}
            onBack={back}
            onConfirm={(w) => { setWhen(w); push('handoff'); }} />
        </ScreenSlot>

        <ScreenSlot active={screen === 'handoff'}>
          <GlubinaHandoff
            sessionType={sessionType || 'diagnostic'}
            answers={answers || { topic: 'emotion', format: 'video', name: '—', tg: '—' }}
            when={when || { date: '20.05', time: '18:30' }}
            telegramHandle={telegramHandle}
            onBack={back}
            onHome={home} />
        </ScreenSlot>
      </div>
    </ThemeCtx.Provider>
  );
}

function ScreenSlot({ active, children }) {
  return (
    <div style={{
      position: 'absolute', inset: 0,
      opacity: active ? 1 : 0,
      transform: active ? 'translateX(0)' : 'translateX(24px)',
      pointerEvents: active ? 'auto' : 'none',
      transition: 'opacity .35s ease, transform .35s ease',
    }}>
      {children}
    </div>
  );
}

Object.assign(window, {
  GlubinaPrototype, GlubinaIntake, GlubinaMKP,
  BookingPrefs, BookingSlots, GlubinaHandoff, GlubinaTopBar,
  SESSION_TYPES, buildTelegramMessage,
});
