/* Quiz modal + sticky mobile bottom bar — спеку см. QUIZ-SPEC.md */

const QUIZ_DRAFT_KEY = 'assuta_quiz_draft';
const QUIZ_DRAFT_TTL = 72 * 3600 * 1000; // 72 часа

const WA_LINK = 'https://api.whatsapp.com/send?phone=972526512654&text=%D0%97%D0%B4%D1%80%D0%B0%D0%B2%D1%81%D1%82%D0%B2%D1%83%D0%B9%D1%82%D0%B5%21%20%D0%98%D0%BD%D1%82%D0%B5%D1%80%D0%B5%D1%81%D1%83%D0%B5%D1%82%20%D0%BB%D0%B5%D1%87%D0%B5%D0%BD%D0%B8%D0%B5%20%D0%B2%20%D0%BA%D0%BB%D0%B8%D0%BD%D0%B8%D0%BA%D0%B5%20%D0%90%D1%81%D1%81%D1%83%D1%82%D0%B0.';

const defaultAnswers = () => ({
  forWhom: '',
  direction: '',
  directionOther: '',
  diagnosis: '',
  diagnosisOther: '',
  diagnostics: [],
  diagnosticsOther: '',
  urgency: '',
  urgencyOther: '',
  name: '',
  phone: '',
  channel: 'WhatsApp',
  email: '',
  consent: false,
});

const FOR_WHOM = [
  { v: 'self', label: 'Для себя' },
  { v: 'parent', label: 'Для родителя' },
  { v: 'spouse', label: 'Для супруга / супруги' },
  { v: 'child', label: 'Для ребёнка' },
  { v: 'other', label: 'Для другого близкого человека' },
];

const DIRECTIONS = [
  { v: 'oncology', label: 'Онкология' },
  { v: 'cardiology', label: 'Кардиология' },
  { v: 'orthopedics', label: 'Ортопедия и хирургия позвоночника' },
  { v: 'diagnostics', label: 'Диагностика и second opinion' },
  { v: 'other', label: 'Другое направление', withText: true },
];

const DIAGNOSIS_OPTIONS = {
  oncology: {
    q: 'Какая локализация опухоли?',
    opts: [
      { v: 'breast', label: 'Рак молочной железы' },
      { v: 'lung', label: 'Рак лёгких' },
      { v: 'prostate', label: 'Рак предстательной железы' },
      { v: 'uterus_ovary', label: 'Рак матки или яичников' },
      { v: 'stomach', label: 'Рак желудка' },
      { v: 'colon', label: 'Рак кишечника' },
      { v: 'brain', label: 'Опухоль головного мозга' },
      { v: 'other', label: 'Другая локализация', withText: true },
      { v: 'pending', label: 'Диагноз ещё уточняется' },
    ],
  },
  cardiology: {
    q: 'Какое заболевание вас беспокоит?',
    opts: [
      { v: 'ihd', label: 'ИБС / стенокардия' },
      { v: 'valve', label: 'Порок сердца / клапаны' },
      { v: 'arrhythmia', label: 'Аритмия' },
      { v: 'cabg', label: 'Требуется шунтирование или стентирование' },
      { v: 'other', label: 'Другое', withText: true },
      { v: 'pending', label: 'Диагноз уточняется' },
    ],
  },
  orthopedics: {
    q: 'Что требует лечения?',
    opts: [
      { v: 'joint', label: 'Эндопротезирование сустава' },
      { v: 'spine', label: 'Межпозвоночная грыжа / операция на позвоночнике' },
      { v: 'trauma', label: 'Травма / последствия травмы' },
      { v: 'other', label: 'Другое', withText: true },
      { v: 'pending', label: 'Диагноз уточняется' },
    ],
  },
  other: {
    q: 'Опишите коротко, что беспокоит',
    opts: null, // только текстовое поле
  },
};

const DIAGNOSTICS = [
  { v: 'epicrisis', label: 'Выписка / эпикриз лечащего врача' },
  { v: 'blood', label: 'Результаты анализов крови' },
  { v: 'biopsy', label: 'Биопсия / гистология' },
  { v: 'pet_ct', label: 'ПЭТ-КТ' },
  { v: 'ct_mri', label: 'КТ или МРТ' },
  { v: 'markers', label: 'Онкомаркеры' },
  { v: 'ultrasound', label: 'УЗИ' },
  { v: 'ecg', label: 'ЭКГ / Эхо-КГ' },
  { v: 'xray', label: 'Рентген / снимки' },
  { v: 'other', label: 'Другое', withText: true },
  { v: 'none', label: 'Пока ничего нет', exclusive: true },
];

const URGENCY = [
  { v: 'urgent', label: 'Как можно скорее — состояние острое' },
  { v: '2_3_weeks', label: 'В ближайшие 2–3 недели' },
  { v: '1_2_months', label: 'В течение 1–2 месяцев' },
  { v: 'researching', label: 'Пока собираю информацию, сравниваю клиники' },
  { v: 'other', label: 'Другой срок', withText: true },
];

const CHANNELS = ['WhatsApp', 'Telegram', 'Звонок', 'Viber'];

const STEP_META = [
  { n: 0, pct: 0,   micro: 'Несколько вопросов — чтобы подготовить ответ именно для вас', trust: 'Анна, координатор отделения для иностранных пациентов, готовит ответ индивидуально.' },
  { n: 1, pct: 15,  micro: 'Подбираем специалиста',                                       trust: 'В Ассуте принимают профессора Меримский, Гринберг, Пекарский и другие ведущие специалисты Израиля.' },
  { n: 2, pct: 30,  micro: 'Уточняем профиль',                                            trust: 'Мы не передаём эти данные третьим лицам. Файлы хранятся в защищённой системе клиники.' },
  { n: 3, pct: 50,  micro: 'Собираем медицинский контекст',                               trust: 'Перевод документов на иврит — бесплатно, силами клиники.' },
  { n: 4, pct: 70,  micro: 'Планируем сроки',                                             trust: 'При срочных случаях Ассута принимает пациентов в течение 5–7 дней с момента получения документов.' },
  { n: 5, pct: 90,  micro: 'Почти готово — Анна уже в курсе',                             trust: 'Данные защищены врачебной тайной. Не передаются третьим лицам, страховым компаниям и государственным органам.' },
];

const TOTAL_STEPS = 6;

const Quiz = ({open = true, onClose, variant = 'modal'}) => {
  const isModal = variant === 'modal';
  const [step, setStep] = React.useState(0);
  const [ans, setAns] = React.useState(defaultAnswers);
  const [done, setDone] = React.useState(false);
  const [errors, setErrors] = React.useState({});

  // Load draft from localStorage on mount / open
  React.useEffect(() => {
    if (isModal && !open) return;
    try {
      const raw = window.localStorage?.getItem(QUIZ_DRAFT_KEY);
      if (raw) {
        const draft = JSON.parse(raw);
        if (draft.timestamp && (Date.now() - draft.timestamp) < QUIZ_DRAFT_TTL) {
          setAns({ ...defaultAnswers(), ...draft.ans });
          setStep(draft.step || 0);
        }
      }
    } catch (e) { /* ignore */ }
  }, [open, isModal]);

  // Save draft debounced
  React.useEffect(() => {
    if ((isModal && !open) || done) return;
    const id = setTimeout(() => {
      try {
        window.localStorage?.setItem(QUIZ_DRAFT_KEY, JSON.stringify({ step, ans, timestamp: Date.now() }));
      } catch (e) { /* ignore */ }
    }, 500);
    return () => clearTimeout(id);
  }, [ans, step, open, done, isModal]);

  // Escape handler + body scroll lock (modal only)
  React.useEffect(() => {
    if (!isModal || !open) return;
    const onKey = (e) => { if (e.key === 'Escape') onClose?.(); };
    window.addEventListener('keydown', onKey);
    document.body.style.overflow = 'hidden';
    return () => { window.removeEventListener('keydown', onKey); document.body.style.overflow = ''; };
  }, [open, onClose, isModal]);

  if (isModal && !open) return null;

  const meta = STEP_META[Math.min(step, TOTAL_STEPS - 1)];
  const update = (k, v) => setAns(a => ({ ...a, [k]: v }));
  const toggleDiag = (v, exclusive) => {
    setAns(a => {
      if (exclusive) return { ...a, diagnostics: a.diagnostics.includes(v) ? [] : [v] };
      const next = a.diagnostics.includes(v)
        ? a.diagnostics.filter(x => x !== v)
        : a.diagnostics.filter(x => x !== 'none').concat(v);
      return { ...a, diagnostics: next };
    });
  };

  // Skip Step 2 if direction = diagnostics
  const nextStep = () => {
    if (step === 1 && ans.direction === 'diagnostics') setStep(3);
    else setStep(s => s + 1);
  };
  const prevStep = () => {
    if (step === 3 && ans.direction === 'diagnostics') setStep(1);
    else setStep(s => Math.max(0, s - 1));
  };

  const canGoNext = () => {
    if (step === 0) return !!ans.forWhom;
    if (step === 1) return !!ans.direction && (ans.direction !== 'other' || ans.directionOther.trim().length >= 3);
    if (step === 2) {
      if (ans.direction === 'other') return ans.diagnosisOther.trim().length >= 3;
      return !!ans.diagnosis && (ans.diagnosis !== 'other' || ans.diagnosisOther.trim().length >= 3);
    }
    if (step === 3) return true; // пропускаемый
    if (step === 4) return !!ans.urgency && (ans.urgency !== 'other' || ans.urgencyOther.trim().length >= 3);
    return true;
  };

  const validateSubmit = () => {
    const err = {};
    if (!ans.name.trim() || ans.name.trim().length < 2) err.name = 'Введите имя (от 2 символов)';
    const digits = ans.phone.replace(/\D/g, '');
    if (digits.length < 10) err.phone = 'Введите номер в формате +7 900 000 00 00';
    if (ans.email && !/^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/.test(ans.email)) err.email = 'Проверьте адрес почты';
    if (!ans.consent) err.consent = 'Нужно согласие для отправки данных';
    setErrors(err);
    return Object.keys(err).length === 0;
  };

  const submit = () => {
    if (!validateSubmit()) return;
    // TODO (backend): POST /api/leads/assuta — пока только local state + analytics dataLayer hook.
    try {
      window.dataLayer?.push({
        event: 'quiz_submit',
        forWhom: ans.forWhom,
        direction: ans.direction,
        urgency: ans.urgency,
      });
    } catch (e) { /* ignore */ }
    try { window.localStorage?.removeItem(QUIZ_DRAFT_KEY); } catch (e) { /* ignore */ }
    setDone(true);
  };

  const resetQuiz = () => {
    if (!window.confirm('Очистить все ответы и начать заново?')) return;
    setStep(0);
    setAns(defaultAnswers());
    setErrors({});
    setDone(false);
    try { window.localStorage?.removeItem(QUIZ_DRAFT_KEY); } catch (e) { /* ignore */ }
  };

  const Shell = isModal ? ModalShell : SectionShell;

  return (
    <Shell onClose={onClose}>
      <style>{`
        .quiz-backdrop {
          position: fixed; inset: 0; z-index: 200;
          background: rgba(14, 30, 54, 0.72);
          backdrop-filter: blur(6px);
          display: grid; place-items: center;
          padding: 20px;
          animation: fade .25s ease;
        }
        @keyframes fade { from { opacity: 0 } }
        .quiz-section { background: var(--paper-2); padding: 64px 0; }
        @media (max-width: 640px) { .quiz-section { padding: 40px 0; } }
        /* Секция всегда видна (не зависит от IntersectionObserver родителя) */
        .quiz-section .reveal { opacity: 1 !important; transform: none !important; }
        .quiz-section-head { max-width: 640px; margin-bottom: 32px; }
        .quiz-section-head .eyebrow { color: var(--clay-dark); }
        .quiz-section-head h2 { margin: 10px 0 12px; }
        .quiz-section-lede { font-size: 17px; color: var(--ink-60); line-height: 1.55; margin: 0; }
        .quiz-section .quiz-card {
          max-width: 780px; border: 1px solid var(--ink-10); box-shadow: var(--shadow-sm);
          padding: 32px 32px 0; margin: 0 auto; position: relative; border-radius: var(--r-xl);
          background: var(--paper); color: var(--ink);
          max-height: min(calc(100vh - 120px), 760px);
          overflow-y: auto;
        }
        @media (max-width: 640px) { .quiz-section .quiz-card { padding: 24px 18px 0; max-height: calc(100vh - 80px); } .quiz-section-head { margin-bottom: 24px; } }
        /* Sticky nav — "Далее" всегда виден при прокрутке карточки */
        .quiz-section .quiz-card .quiz-nav,
        .quiz-backdrop .quiz-card .quiz-nav {
          position: sticky; bottom: 0;
          background: var(--paper);
          padding: 16px 0;
          margin-top: 20px;
          border-top: 1px solid var(--ink-10);
          z-index: 2;
        }
        .quiz-card {
          background: var(--paper); color: var(--ink);
          border-radius: var(--r-xl);
          width: 100%; max-width: 640px;
          padding: 32px;
          position: relative;
          animation: pop .3s cubic-bezier(.2,.7,.2,1);
          max-height: calc(100vh - 40px);
          overflow-y: auto;
        }
        @keyframes pop { from { transform: translateY(18px) scale(.98); opacity: 0 } }
        @media (max-width: 520px) {
          .quiz-backdrop { align-items: end; padding: 0; }
          .quiz-card { border-radius: 24px 24px 0 0; max-width: 100%; padding: 24px 18px 28px; max-height: 92vh; }
        }
        .quiz-close {
          position: absolute; top: 14px; right: 14px;
          width: 36px; height: 36px; border-radius: 50%;
          background: var(--ink-05); display: grid; place-items: center;
          font-size: 18px; color: var(--ink-60); z-index: 2;
        }
        .quiz-close:hover { background: var(--ink); color: var(--paper); }
        .quiz-bar { height: 3px; background: var(--ink-10); border-radius: 2px; overflow: hidden; margin: 8px 0 10px; }
        .quiz-bar div { height: 100%; background: var(--clay); transition: width .3s ease; }
        .quiz-meta { display: flex; justify-content: space-between; gap: 12px; font-family: var(--font-mono); font-size: 10.5px; letter-spacing: .12em; text-transform: uppercase; color: var(--ink-60); margin-bottom: 16px; padding-right: 44px; }
        .quiz-micro { font-size: 12px; color: var(--ink-60); margin: -6px 0 18px; font-style: italic; }
        .quiz-q { font-family: var(--font-display); font-size: 26px; font-weight: 380; letter-spacing: -0.015em; line-height: 1.2; margin: 0 0 6px; text-wrap: balance; }
        @media (max-width: 520px) { .quiz-q { font-size: 22px; } }
        .quiz-helper { font-size: 13px; color: var(--ink-60); margin: 0 0 20px; line-height: 1.5; }

        .quiz-opts { display: flex; flex-direction: column; gap: 8px; }
        .quiz-opt {
          text-align: left; padding: 14px 16px;
          border: 1px solid var(--ink-20);
          border-radius: var(--r-md);
          background: var(--snow);
          font-size: 14.5px;
          transition: background .2s, border-color .2s;
          display: flex; justify-content: space-between; align-items: center; gap: 12px;
          width: 100%;
        }
        .quiz-opt:hover, .quiz-opt.selected { background: var(--ink); color: var(--paper); border-color: var(--ink); }
        .quiz-opt.check-opt { display: grid; grid-template-columns: 20px 1fr; align-items: center; gap: 14px; }
        .quiz-opt.check-opt .cb { width: 20px; height: 20px; border: 1.5px solid var(--ink-40); border-radius: 4px; display: grid; place-items: center; flex-shrink: 0; }
        .quiz-opt.check-opt.selected .cb { background: var(--clay); border-color: var(--clay); color: var(--paper); }
        .quiz-opt.check-opt:hover { background: var(--paper-2); color: var(--ink); border-color: var(--ink-40); }
        .quiz-opt.check-opt.selected { background: color-mix(in oklab, var(--clay) 12%, var(--paper)); color: var(--ink); border-color: var(--clay); }

        .quiz-textinput {
          margin-top: 8px;
          padding: 12px 14px; border: 1px solid var(--ink-20); border-radius: var(--r-sm);
          font-size: 14px; font-family: inherit; background: var(--snow); width: 100%;
          color: var(--ink);
        }
        .quiz-textinput:focus { outline: none; border-color: var(--ink); box-shadow: 0 0 0 3px var(--ink-10); }

        .quiz-skip { margin-top: 14px; text-align: center; }
        .quiz-skip button { font-size: 13px; color: var(--ink-60); text-decoration: underline; text-underline-offset: 3px; }
        .quiz-skip button:hover { color: var(--clay); }

        .quiz-final { display: flex; flex-direction: column; gap: 14px; }
        .quiz-field { display: flex; flex-direction: column; gap: 6px; }
        .quiz-field label { font-size: 12px; color: var(--ink-80); font-weight: 500; }
        .quiz-field label .req { color: var(--clay); }
        .quiz-field label .opt { color: var(--ink-60); font-weight: 400; }
        .quiz-err { font-size: 12px; color: #A63A1E; }

        .channels-quiz { display: flex; gap: 4px; padding: 4px; background: var(--ink-05); border-radius: var(--r-pill); flex-wrap: wrap; }
        .channels-quiz button { flex: 1 1 60px; padding: 9px 10px; border-radius: var(--r-pill); font-size: 12px; color: var(--ink-60); min-width: 0; }
        .channels-quiz button.active { background: var(--ink); color: var(--paper); }

        .consent-row { display: flex; gap: 10px; align-items: flex-start; font-size: 12px; color: var(--ink-60); line-height: 1.45; }
        .consent-row input { margin-top: 2px; accent-color: var(--clay); }

        .quiz-trust { margin-top: 18px; padding: 12px 14px; background: var(--paper-2); border-radius: var(--r-sm); font-size: 12px; color: var(--ink-60); line-height: 1.45; display: flex; gap: 10px; align-items: flex-start; }
        .quiz-trust svg { flex-shrink: 0; color: var(--clay); margin-top: 2px; }

        .quiz-nav { display: flex; justify-content: space-between; align-items: center; gap: 12px; margin-top: 24px; }
        .quiz-nav .left, .quiz-nav .right { display: flex; align-items: center; gap: 10px; }
        .quiz-back {
          width: 42px; height: 42px; border-radius: 50%;
          background: var(--ink-10); color: var(--ink);
          display: grid; place-items: center;
          border: 1px solid var(--ink-20);
          transition: background .2s, color .2s, border-color .2s;
        }
        .quiz-back:hover { background: var(--ink); color: var(--paper); border-color: var(--ink); }
        .quiz-back:disabled { opacity: 0.5; cursor: not-allowed; background: var(--ink-05); color: var(--ink-40); }
        .quiz-reset {
          background: transparent;
          border: 0;
          color: var(--ink-60);
          font-size: 13px;
          padding: 8px 4px;
          cursor: pointer;
          text-decoration: underline;
          text-underline-offset: 3px;
          text-decoration-color: var(--ink-20);
        }
        .quiz-reset:hover { color: var(--ink); text-decoration-color: var(--ink); }
        @media (max-width: 480px) { .quiz-reset { font-size: 12px; } }
        .quiz-next { padding: 12px 22px; border-radius: var(--r-pill); background: var(--ink); color: var(--paper); font-size: 14px; font-weight: 500; display: inline-flex; align-items: center; gap: 8px; }
        .quiz-next:disabled { opacity: 0.4; cursor: not-allowed; }
        .quiz-next.cta { background: var(--clay); color: var(--paper); }
        .quiz-hint { font-size: 11px; color: var(--ink-60); font-family: var(--font-mono); letter-spacing: .08em; text-transform: uppercase; }

        /* Success screen */
        .quiz-done { display: flex; flex-direction: column; gap: 14px; align-items: center; text-align: center; padding: 6px 0; }
        .quiz-done .avatar {
          width: 72px; height: 72px; border-radius: 50%;
          background: var(--clay); color: var(--paper);
          display: grid; place-items: center;
          font-family: var(--font-display); font-size: 28px; font-weight: 500;
          position: relative;
        }
        .quiz-done .avatar::after { content: ''; position: absolute; right: -2px; bottom: -2px; width: 14px; height: 14px; background: var(--sage); border-radius: 50%; border: 2px solid var(--paper); animation: pulse 2s infinite; }
        .quiz-done h3 { font-family: var(--font-display); font-size: 26px; font-weight: 380; margin: 4px 0 0; line-height: 1.2; }
        .quiz-done .anna-line { font-size: 13px; color: var(--ink-60); font-weight: 500; }
        .quiz-done .body { font-size: 14px; color: var(--ink-80); line-height: 1.55; max-width: 460px; text-align: left; }
        .quiz-done .body ul { padding-left: 18px; margin: 8px 0 0; }
        .quiz-done .body li { margin-bottom: 4px; }
        .quiz-done .ctas { display: flex; flex-direction: column; gap: 8px; width: 100%; max-width: 360px; margin-top: 8px; }
        .quiz-done .ctas .btn { width: 100%; justify-content: center; }
        .quiz-done .privacy { font-size: 11px; color: var(--ink-40); line-height: 1.5; margin-top: 12px; max-width: 460px; }
      `}</style>
      <div className="quiz-card" onClick={e => e.stopPropagation()}>
        {isModal && <button className="quiz-close" onClick={onClose} aria-label="Закрыть">×</button>}

        {!done && (
          <>
            <div className="quiz-meta">
              <span>Шаг {Math.min(step + 1, TOTAL_STEPS)} из {TOTAL_STEPS}</span>
              <span>{meta.pct}%</span>
            </div>
            <div className="quiz-bar" role="progressbar" aria-valuenow={meta.pct} aria-valuemin="0" aria-valuemax="100">
              <div style={{ width: `${meta.pct}%` }}/>
            </div>
            <div className="quiz-micro">{meta.micro}</div>
          </>
        )}

        {/* STEP 0 — Для кого */}
        {!done && step === 0 && (
          <>
            <h3 className="quiz-q" id="quiz-title">Для кого вы ищете лечение?</h3>
            <p className="quiz-helper">Это поможет правильно подготовить документы и связаться с нужным специалистом.</p>
            <div className="quiz-opts" role="radiogroup" aria-labelledby="quiz-title">
              {FOR_WHOM.map(o => (
                <button key={o.v} role="radio" aria-checked={ans.forWhom === o.v}
                  className={`quiz-opt ${ans.forWhom === o.v ? 'selected' : ''}`}
                  onClick={() => update('forWhom', o.v)}>
                  <span>{o.label}</span>
                  {ans.forWhom === o.v && <I.Check size={14}/>}
                </button>
              ))}
            </div>
          </>
        )}

        {/* STEP 1 — Направление */}
        {!done && step === 1 && (
          <>
            <h3 className="quiz-q" id="quiz-title">Какое направление вас интересует?</h3>
            <p className="quiz-helper">Если диагноз ещё не подтверждён — выберите предполагаемое направление.</p>
            <div className="quiz-opts" role="radiogroup" aria-labelledby="quiz-title">
              {DIRECTIONS.map(o => (
                <button key={o.v} role="radio" aria-checked={ans.direction === o.v}
                  className={`quiz-opt ${ans.direction === o.v ? 'selected' : ''}`}
                  onClick={() => update('direction', o.v)}>
                  <span>{o.label}</span>
                  {ans.direction === o.v && <I.Check size={14}/>}
                </button>
              ))}
              {ans.direction === 'other' && (
                <input className="quiz-textinput" placeholder="Укажите направление"
                  value={ans.directionOther} onChange={e => update('directionOther', e.target.value)} autoFocus/>
              )}
            </div>
          </>
        )}

        {/* STEP 2 — Диагноз (conditional) */}
        {!done && step === 2 && (() => {
          const cfg = DIAGNOSIS_OPTIONS[ans.direction] || DIAGNOSIS_OPTIONS.other;
          return (
            <>
              <h3 className="quiz-q" id="quiz-title">{cfg.q}</h3>
              <p className="quiz-helper">Если точного диагноза нет — укажите, что предполагают врачи. Все данные защищены врачебной тайной.</p>
              {cfg.opts && (
                <div className="quiz-opts" role="radiogroup" aria-labelledby="quiz-title">
                  {cfg.opts.map(o => (
                    <button key={o.v} role="radio" aria-checked={ans.diagnosis === o.v}
                      className={`quiz-opt ${ans.diagnosis === o.v ? 'selected' : ''}`}
                      onClick={() => update('diagnosis', o.v)}>
                      <span>{o.label}</span>
                      {ans.diagnosis === o.v && <I.Check size={14}/>}
                    </button>
                  ))}
                  {ans.diagnosis === 'other' && (
                    <input className="quiz-textinput" placeholder="Опишите диагноз или локализацию"
                      value={ans.diagnosisOther} onChange={e => update('diagnosisOther', e.target.value)} autoFocus/>
                  )}
                </div>
              )}
              {!cfg.opts && (
                <input className="quiz-textinput" placeholder="Коротко опишите, что беспокоит"
                  value={ans.diagnosisOther} onChange={e => update('diagnosisOther', e.target.value)} autoFocus/>
              )}
            </>
          );
        })()}

        {/* STEP 3 — Диагностика (multi-select, skip) */}
        {!done && step === 3 && (
          <>
            <h3 className="quiz-q" id="quiz-title">Какие обследования уже проведены?</h3>
            <p className="quiz-helper">Отметьте всё, что есть на руках. Это ускорит подбор программы. Если ничего нет — пропустите шаг, мы поможем организовать диагностику в Ассуте.</p>
            <div className="quiz-opts" role="group" aria-labelledby="quiz-title">
              {DIAGNOSTICS.map(o => {
                const checked = ans.diagnostics.includes(o.v);
                return (
                  <button key={o.v} role="checkbox" aria-checked={checked}
                    className={`quiz-opt check-opt ${checked ? 'selected' : ''}`}
                    onClick={() => toggleDiag(o.v, o.exclusive)}>
                    <span className="cb">{checked && <I.Check size={12}/>}</span>
                    <span>{o.label}</span>
                  </button>
                );
              })}
              {ans.diagnostics.includes('other') && (
                <input className="quiz-textinput" placeholder="Укажите обследования через запятую"
                  value={ans.diagnosticsOther} onChange={e => update('diagnosticsOther', e.target.value)}/>
              )}
            </div>
            <div className="quiz-skip">
              <button type="button" onClick={() => setStep(s => s + 1)}>Пропустить — документы обсудим с координатором</button>
            </div>
          </>
        )}

        {/* STEP 4 — Сроки */}
        {!done && step === 4 && (
          <>
            <h3 className="quiz-q" id="quiz-title">Когда планируете приехать на лечение?</h3>
            <p className="quiz-helper">Это ориентир — окончательные сроки согласуем с врачом по вашему состоянию.</p>
            <div className="quiz-opts" role="radiogroup" aria-labelledby="quiz-title">
              {URGENCY.map(o => (
                <button key={o.v} role="radio" aria-checked={ans.urgency === o.v}
                  className={`quiz-opt ${ans.urgency === o.v ? 'selected' : ''}`}
                  onClick={() => update('urgency', o.v)}>
                  <span>{o.label}</span>
                  {ans.urgency === o.v && <I.Check size={14}/>}
                </button>
              ))}
              {ans.urgency === 'other' && (
                <input className="quiz-textinput" placeholder="Укажите желаемый срок"
                  value={ans.urgencyOther} onChange={e => update('urgencyOther', e.target.value)} autoFocus/>
              )}
            </div>
          </>
        )}

        {/* STEP 5 — Контакты */}
        {!done && step === 5 && (
          <>
            <h3 className="quiz-q" id="quiz-title">Последний шаг — куда отправить ответ координатора</h3>
            <p className="quiz-helper">Анна перезвонит или напишет в удобный вам мессенджер в течение ~7 минут в рабочее время (09:00–20:00 Израиль).</p>
            <div className="quiz-final">
              <div className="quiz-field">
                <label>Имя <span className="req">*</span></label>
                <input className="quiz-textinput" placeholder="Как к вам обращаться"
                  value={ans.name} onChange={e => update('name', e.target.value)} autoComplete="name"/>
                {errors.name && <div className="quiz-err">{errors.name}</div>}
              </div>
              <div className="quiz-field">
                <label>Телефон <span className="req">*</span></label>
                <input className="quiz-textinput" type="tel" inputMode="tel" autoComplete="tel"
                  placeholder="Номер с кодом страны"
                  value={ans.phone} onChange={e => update('phone', e.target.value)}/>
                {errors.phone && <div className="quiz-err">{errors.phone}</div>}
              </div>
              <div className="quiz-field">
                <label>Удобный канал связи</label>
                <div className="channels-quiz" role="radiogroup" aria-label="Канал связи">
                  {CHANNELS.map(c => (
                    <button key={c} role="radio" aria-checked={ans.channel === c}
                      className={ans.channel === c ? 'active' : ''}
                      onClick={() => update('channel', c)}>{c}</button>
                  ))}
                </div>
              </div>
              <div className="quiz-field">
                <label>Email <span className="opt">(необязательно)</span></label>
                <input className="quiz-textinput" type="email" inputMode="email" autoComplete="email"
                  placeholder="Для отправки программы лечения и сметы"
                  value={ans.email} onChange={e => update('email', e.target.value)}/>
                {errors.email && <div className="quiz-err">{errors.email}</div>}
              </div>
              <label className="consent-row">
                <input type="checkbox" checked={ans.consent} onChange={e => update('consent', e.target.checked)}/>
                <span>Согласен на обработку персональных данных. Данные используются только для медицинской консультации.</span>
              </label>
              {errors.consent && <div className="quiz-err">{errors.consent}</div>}
            </div>
          </>
        )}

        {/* TRUST line (кроме success) */}
        {!done && (
          <div className="quiz-trust">
            <I.Shield size={14}/>
            <span>{meta.trust}</span>
          </div>
        )}

        {/* NAVIGATION */}
        {!done && (
          <div className="quiz-nav">
            <div className="left">
              {step > 0 && (
                <>
                  <button className="quiz-back" onClick={prevStep} aria-label="Назад">
                    <span style={{display:'inline-flex', transform: 'rotate(180deg)'}}><I.Arrow size={16}/></span>
                  </button>
                  <button type="button" className="quiz-reset" onClick={resetQuiz}>Начать заново</button>
                </>
              )}
            </div>
            <div className="right">
              {step < 5 && (
                <>
                  <span className="quiz-hint hide-mobile">или нажмите Enter</span>
                  <button className="quiz-next" onClick={nextStep} disabled={!canGoNext()}>
                    Далее <I.ArrowUpRight size={14}/>
                  </button>
                </>
              )}
              {step === 5 && (
                <button className="quiz-next cta" onClick={submit}>
                  Получить ответ координатора <I.ArrowUpRight size={14}/>
                </button>
              )}
            </div>
          </div>
        )}

        {/* SUCCESS */}
        {done && (
          <div className="quiz-done">
            <div className="avatar">А</div>
            <h3>Заявка принята. Анна готовит ответ.</h3>
            <div className="anna-line">Анна Левина, координатор международного отделения Ассуты</div>
            <div className="body">
              <p style={{margin: '8px 0 0'}}>Координатор получит ваши данные в течение минуты и подготовит предварительный ответ за ~7 минут. В ответе будет:</p>
              <ul>
                <li>Предварительная оценка программы и сроков</li>
                <li>Список врачей, подходящих по профилю</li>
                <li>Что нужно прислать для точной сметы</li>
              </ul>
              <p style={{margin: '10px 0 0'}}>Если вы обратились после 20:00 по израильскому времени, Анна свяжется с вами утром — до 10:00.</p>
            </div>
            <div className="ctas">
              <a href={WA_LINK} target="_blank" rel="noopener" className="btn btn-clay">
                <I.WhatsApp size={14}/> Написать Анне в WhatsApp
              </a>
              <a href="tel:+972526512654" className="btn btn-ghost">
                <I.Phone size={14}/> Позвонить: +972-52-651-2654
              </a>
            </div>
            <div className="privacy">Ваша заявка зашифрована и доступна только сотрудникам международного отделения. Хранится в защищённой системе клиники в соответствии с законом Израиля о правах пациента.</div>
          </div>
        )}
      </div>
    </Shell>
  );
};

/* Stable module-level wrappers — избежать пересоздания компонента на render
   (иначе React рвёт поддерево и input теряет focus). */
const ModalShell = ({children, onClose}) => (
  <div className="quiz-backdrop" role="dialog" aria-modal="true" aria-labelledby="quiz-title" onClick={onClose}>
    {children}
  </div>
);

const SectionShell = ({children}) => (
  <section className="quiz-section section" id="quiz">
    <div className="container">
      <div className="quiz-section-head reveal">
        <span className="eyebrow">Предварительная оценка · ~2 минуты</span>
        <h2 className="display-lg">Узнайте, что Ассута может предложить в вашем случае.</h2>
        <p className="quiz-section-lede">Ответьте на 5 коротких вопросов — Анна пришлёт предварительную оценку программы и список подходящих врачей за ~7 минут.</p>
      </div>
      {children}
    </div>
  </section>
);

/* Convenience export: inline variant of Quiz — renders as a page section */
const QuizSection = () => <Quiz variant="section" />;

/* Sticky mobile bottom bar */
const StickyBar = ({onOpenQuiz}) => {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    const onScroll = () => setVisible(window.scrollY > 720);
    window.addEventListener('scroll', onScroll, {passive: true});
    document.body.classList.add('sticky-padded');
    return () => {
      window.removeEventListener('scroll', onScroll);
      document.body.classList.remove('sticky-padded');
    };
  }, []);
  return (
    <div className={`sticky-bar ${visible ? 'show' : ''}`}>
      <style>{`
        .sticky-bar {
          position: fixed; left: 12px; right: 12px; bottom: 12px; z-index: 90;
          background: var(--ink); color: var(--paper);
          border-radius: var(--r-pill);
          padding: 10px 10px 10px 16px;
          display: none;
          align-items: center; gap: 10px;
          box-shadow: 0 12px 32px -8px rgba(14,30,54,.4);
          transform: translateY(150%); transition: transform .3s ease;
        }
        .sticky-bar.show { transform: translateY(0); }
        @media (max-width: 880px) {
          .sticky-bar { display: flex; }
          body.sticky-padded { padding-bottom: 84px; }
        }
        .sb-avatar { width: 36px; height: 36px; border-radius: 50%; background: var(--clay); color: var(--paper); display:grid; place-items:center; font-family: var(--font-display); font-size: 14px; position: relative; flex-shrink: 0; }
        .sb-avatar::after { content: ''; position: absolute; right: -2px; bottom: -2px; width: 10px; height: 10px; background: var(--sage); border-radius: 50%; border: 2px solid var(--ink); animation: pulse 2s infinite; }
        .sb-copy { flex: 1; min-width: 0; overflow: hidden; }
        .sb-copy .n { font-size: 13px; font-weight: 500; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .sb-copy .s { font-size: 11px; color: rgba(244,246,248,.88); white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
        .sb-actions { display: flex; gap: 6px; flex-shrink: 0; }
        .sb-actions .btn-sm { padding: 10px 14px; font-size: 13px; }
        .sb-wa { background: #25D366; color: #072E1D; }
        .sb-wa:hover { background: #1fb855; }
        .hide-mobile { display: inline; }
        @media (max-width: 520px) { .hide-mobile { display: none; } }
      `}</style>
      <div className="sb-avatar">А</div>
      <div className="sb-copy">
        <div className="n">Анна · координатор</div>
        <div className="s">онлайн · ответит за 7 минут</div>
      </div>
      <div className="sb-actions">
        <a href={WA_LINK} target="_blank" rel="noopener" className="btn sb-wa btn-sm" aria-label="WhatsApp"><I.WhatsApp size={14}/></a>
        <button className="btn btn-clay btn-sm" onClick={onOpenQuiz}>Консультация</button>
      </div>
    </div>
  );
};

/* Back-to-top button — появляется при scrollY > 600, на мобиле над sticky-bar */
const BackToTop = () => {
  const [visible, setVisible] = React.useState(false);
  React.useEffect(() => {
    let ticking = false;
    const onScroll = () => {
      if (ticking) return;
      ticking = true;
      requestAnimationFrame(() => {
        setVisible(window.scrollY > 600);
        ticking = false;
      });
    };
    window.addEventListener('scroll', onScroll, {passive: true});
    return () => window.removeEventListener('scroll', onScroll);
  }, []);
  return (
    <button
      type="button"
      className={`back-to-top ${visible ? 'show' : ''}`}
      onClick={() => window.scrollTo({top: 0, behavior: 'smooth'})}
      aria-label="Вернуться наверх"
    >
      <style>{`
        .back-to-top {
          position: fixed; right: 20px; bottom: 20px;
          z-index: 85;
          width: 46px; height: 46px;
          border-radius: 50%;
          background: var(--clay); color: var(--paper);
          display: grid; place-items: center;
          box-shadow: 0 10px 28px -10px rgba(116,192,67,.45), 0 0 0 1px rgba(14,30,54,.04);
          opacity: 0; pointer-events: none;
          transform: translateY(12px) scale(0.92);
          transition: opacity .25s ease, transform .25s ease, background .2s, box-shadow .2s;
        }
        .back-to-top.show { opacity: 1; pointer-events: auto; transform: translateY(0) scale(1); }
        .back-to-top:hover { background: var(--ink); box-shadow: 0 10px 28px -10px rgba(14,30,54,.5); }
        .back-to-top svg { width: 18px; height: 18px; }
        @media (max-width: 880px) {
          .back-to-top { bottom: 88px; right: 14px; width: 42px; height: 42px; }
        }
        @media (prefers-reduced-motion: reduce) {
          .back-to-top { transition: opacity .15s; transform: none !important; }
        }
      `}</style>
      <svg viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round" strokeLinejoin="round">
        <path d="M8 13V3M4 7l4-4 4 4"/>
      </svg>
    </button>
  );
};

window.Quiz = Quiz;
window.StickyBar = StickyBar;
window.QuizSection = QuizSection;
window.BackToTop = BackToTop;
