function CTA() {
  const [tags, setTags] = React.useState(new Set(['Демо']));
  const [industry, setIndustry] = React.useState(null);
  const [status, setStatus] = React.useState('idle'); // idle | sending | success | error

  const toggle = (t) => setTags(prev => {
    const n = new Set(prev);
    n.has(t) ? n.delete(t) : n.add(t);
    return n;
  });

  const REQUEST_TAGS = ['Демо', 'Покупка', 'Своя интеграция', 'Консультация'];
  const INDUSTRY_TAGS = ['Банк', 'FMCG', 'Приложение', 'SaaS', 'Ритейл', 'HoReCa', 'Телеком', 'Другое'];

  // Telegram-бот @skolkbot — получатель chat_id 1086907431.
  // ⚠ Токен в клиенте: вариант временный, по решению владельца.
  // Долгосрочно — перенести на Cloudflare Worker (см. /worker/telegram-proxy.js).
  const TG_BOT_TOKEN = '8285852131:AAE7oa3SiAlp7kveZrDOqbH2cNEufAmRg_I';
  const TG_CHAT_ID   = '1086907431';

  const escapeHtml = (s) => String(s || '')
    .replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;');

  const handleSubmit = async (e) => {
    e.preventDefault();
    const fd = new FormData(e.target);

    // honeypot — заявку от бота молча игнорим, но показываем «успех»
    if (fd.get('hp')) {
      setStatus('success');
      e.target.reset();
      return;
    }

    const interest = Array.from(tags).join(', ') || '—';
    const text = [
      '<b>📩 Новая заявка — главная</b>',
      '',
      `<b>Имя:</b> ${escapeHtml(fd.get('name'))}`,
      `<b>Компания:</b> ${escapeHtml(fd.get('company') || '—')}`,
      `<b>Контакт:</b> ${escapeHtml(fd.get('contact'))}`,
      '',
      `<b>Что интересует:</b> ${escapeHtml(interest)}`,
      `<b>Отрасль:</b> ${escapeHtml(industry || '—')}`,
      '',
      `<b>Кратко о задаче:</b>\n${escapeHtml(fd.get('brief') || '—')}`,
      '',
      `<i>Страница: ${escapeHtml(location.href)}</i>`,
    ].join('\n');

    setStatus('sending');
    try {
      const r = await fetch(`https://api.telegram.org/bot${TG_BOT_TOKEN}/sendMessage`, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          chat_id: TG_CHAT_ID, text, parse_mode: 'HTML', disable_web_page_preview: true,
        }),
      });
      const data = await r.json();
      if (!data.ok) throw new Error(data.description || 'send_failed');
      setStatus('success');
      e.target.reset();
    } catch (err) {
      console.error('[cta] telegram send failed', err);
      setStatus('error');
    }
  };

  return (
    <section id="contact" style={{ padding: '140px 0', background: 'var(--bg)', color: 'var(--ink)' }}>
      <style>{`
        @media (max-width: 860px) {
          #contact img.cta-yuly-avatar {
            width: 48px !important;
            height: 48px !important;
          }
        }
        @media (max-width: 420px) {
          #contact img.cta-yuly-avatar {
            width: 38px !important;
            height: 38px !important;
          }
        }
      `}</style>
      <div className="container">
        <h2 className="display" style={{
          fontSize: 72, lineHeight: 1.08, fontWeight: 700,
          letterSpacing: '-0.035em', color: 'var(--ink)',
          maxWidth: 1100,
        }}>
          Попробовать, приобрести или просто спросить можно в{' '}
          <a
            href="https://t.me/geosibik"
            target="_blank" rel="noopener"
            style={{
              color: 'var(--accent)',
              textDecoration: 'underline',
              textDecorationThickness: '4px',
              textUnderlineOffset: '6px',
              whiteSpace: 'nowrap',
            }}
          >
            <svg viewBox="0 0 24 24" fill="currentColor" style={{
              display: 'inline-block', width: '1em', height: '1em',
              verticalAlign: '-0.14em', marginRight: '0.12em',
            }}>
              <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>
            телеграм
          </a>{' '}
          {' '}у{' '}
          <span style={{ whiteSpace: 'nowrap', display: 'inline-flex', alignItems: 'center', gap: 14, verticalAlign: 'middle' }}>
            Юли
            <img
              src="uploads/yuly.webp"
              alt=""
              loading="lazy"
              decoding="async"
              className="cta-yuly-avatar"
              style={{
                display: 'block', width: 86, height: 86, borderRadius: '50%',
                objectFit: 'cover',
                border: '2px solid rgba(13,13,18,0.10)',
                boxShadow: '0 6px 24px -8px rgba(122,96,255,0.45)',
              }}
            />
          </span>{' '}
          или оставив заявку
        </h2>

        <form
          onSubmit={handleSubmit}
          style={{
            marginTop: 64,
            display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16,
          }}
        >
          {/* honeypot — невидимое поле для ботов */}
          <input type="text" name="hp" tabIndex={-1} autoComplete="off" aria-hidden="true"
            style={{ position: 'absolute', left: -9999, width: 1, height: 1, opacity: 0, pointerEvents: 'none' }} />
          {/* left column: text inputs — stretch to match right card height */}
          <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
            <Input name="name" placeholder="Ваше имя" required style={{ flex: 1 }} />
            <Input name="company" placeholder="Я из компании" style={{ flex: 1 }} />
            <Input name="contact" placeholder="Контакт для связи" required style={{ flex: 1 }} />
          </div>

          {/* right column: brief + tags */}
          <div style={{
            background: 'var(--bg-soft)',
            border: '1px solid var(--line)',
            borderRadius: 22,
            padding: '20px 22px',
            display: 'flex', flexDirection: 'column', gap: 18,
          }}>
            <textarea
              name="brief"
              placeholder="Кратко о задаче"
              rows={2}
              style={{
                width: '100%', resize: 'none',
                background: 'transparent', border: 'none', outline: 'none',
                color: 'var(--ink)', fontFamily: 'inherit', fontSize: 16,
                padding: '4px 0',
              }}
            />

            <div>
              <div style={{
                fontSize: 13, color: 'var(--muted)', marginBottom: 10,
              }}>Что интересует</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {REQUEST_TAGS.map(t => {
                  const on = tags.has(t);
                  return (
                    <button
                      key={t}
                      type="button"
                      onClick={() => toggle(t)}
                      style={{
                        padding: '7px 14px', borderRadius: 999,
                        fontSize: 13.5, fontWeight: 500,
                        background: on ? 'var(--accent)' : 'var(--card)',
                        color: on ? '#fff' : 'var(--ink-2)',
                        border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line)'),
                        cursor: 'pointer',
                        transition: 'all 0.18s',
                      }}
                    >{t}</button>
                  );
                })}
              </div>
            </div>

            <div>
              <div style={{
                fontSize: 13, color: 'var(--muted)', marginBottom: 10,
              }}>Откуда вы</div>
              <div style={{ display: 'flex', flexWrap: 'wrap', gap: 8 }}>
                {INDUSTRY_TAGS.map(t => {
                  const on = industry === t;
                  return (
                    <button
                      key={t}
                      type="button"
                      onClick={() => setIndustry(on ? null : t)}
                      style={{
                        padding: '7px 14px', borderRadius: 999,
                        fontSize: 13.5, fontWeight: 500,
                        background: on ? 'var(--accent)' : 'var(--card)',
                        color: on ? '#fff' : 'var(--ink-2)',
                        border: '1px solid ' + (on ? 'var(--accent)' : 'var(--line)'),
                        cursor: 'pointer',
                        transition: 'all 0.18s',
                      }}
                    >{t}</button>
                  );
                })}
              </div>
            </div>
          </div>

          <label className="cta-consent" style={{
            gridColumn: '1 / -1',
            display: 'flex', alignItems: 'flex-start', gap: 10,
            fontSize: 13, color: 'var(--muted)', marginTop: 8,
            cursor: 'pointer',
          }}>
            <input type="checkbox" defaultChecked className="cta-consent-input" />
            <span className="cta-consent-box" aria-hidden="true">
              <svg viewBox="0 0 14 14" width="11" height="11"><path d="M3 7.5 L6 10 L11 4" stroke="#fff" strokeWidth="2" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
            </span>
            <span>
              Нажимая кнопку, я даю согласие на{' '}
              <a href="#" style={{ color: 'var(--ink-2)', textDecoration: 'underline' }}>обработку персональных данных</a>{' '}
              и соглашаюсь с условиями{' '}
              <a href="#" style={{ color: 'var(--ink-2)', textDecoration: 'underline' }}>политики конфиденциальности</a>.
            </span>
            <style>{`
              .cta-consent { flex-wrap: nowrap !important; }
              .cta-consent > span:last-of-type { flex: 1; min-width: 0; }
              .cta-consent-input {
                position: absolute; opacity: 0; pointer-events: none;
                width: 0; height: 0;
              }
              .cta-consent-box {
                flex-shrink: 0;
                display: inline-flex; align-items: center; justify-content: center;
                width: 18px; height: 18px; min-width: 18px; min-height: 18px;
                border-radius: 4px;
                background: var(--card);
                border: 1.5px solid var(--line);
                margin-top: 1px;
                transition: all 0.15s;
              }
              .cta-consent-input:checked + .cta-consent-box {
                background: var(--accent);
                border-color: var(--accent);
              }
              .cta-consent-box svg { opacity: 0; transition: opacity 0.15s; }
              .cta-consent-input:checked + .cta-consent-box svg { opacity: 1; }
            `}</style>
          </label>

          <button
            type="submit"
            disabled={status === 'sending' || status === 'success'}
            style={{
              gridColumn: '1 / -1',
              marginTop: 8,
              padding: '26px 32px',
              borderRadius: 999,
              background: 'linear-gradient(90deg, #7768F3, #B997FF)',
              color: '#fff',
              fontSize: 18, fontWeight: 700, fontFamily: 'inherit',
              cursor: status === 'sending' ? 'wait' : 'pointer', border: 'none',
              transition: 'transform 0.15s, filter 0.15s, opacity 0.15s',
              opacity: (status === 'sending' || status === 'success') ? 0.7 : 1,
              boxShadow: 'inset 2px 2px 9px rgba(255,255,255,0.13), 0 14px 40px -16px rgba(119,104,243,0.6)',
              display: 'flex', alignItems: 'center', justifyContent: 'center', gap: 10,
            }}
            onMouseDown={(e) => e.currentTarget.style.transform = 'scale(0.99)'}
            onMouseUp={(e) => e.currentTarget.style.transform = 'scale(1)'}
            onMouseLeave={(e) => e.currentTarget.style.transform = 'scale(1)'}
          >
            {status === 'sending' ? 'Отправляем…' : status === 'success' ? 'Отправлено' : 'Отправить'}
            {status !== 'sending' && status !== 'success' && (
              <svg width="14" height="14" viewBox="0 0 14 14"><path d="M3 7 L11 7 M7.5 3 L11 7 L7.5 11" stroke="currentColor" strokeWidth="1.8" fill="none" strokeLinecap="round" strokeLinejoin="round" /></svg>
            )}
          </button>

          {(status === 'success' || status === 'error') && (
            <div style={{
              gridColumn: '1 / -1',
              marginTop: 12, padding: '14px 18px', borderRadius: 14,
              textAlign: 'center', fontSize: 14.5, fontWeight: 500,
              background: status === 'success' ? 'rgba(31,122,76,0.08)' : 'rgba(184,50,74,0.08)',
              border: '1px solid ' + (status === 'success' ? 'rgba(31,122,76,0.25)' : 'rgba(184,50,74,0.28)'),
              color: status === 'success' ? 'var(--pos)' : 'var(--neg)',
            }}>
              {status === 'success'
                ? 'Спасибо! Заявка отправлена — свяжемся с вами в ближайшее время.'
                : 'Не удалось отправить — напишите нам в телеграм @geosibik'}
            </div>
          )}
        </form>
      </div>
    </section>
  );
}

function Input(props) {
  return (
    <input
      {...props}
      style={{
        background: 'var(--bg-soft)',
        border: '1px solid var(--line)',
        borderRadius: 22,
        padding: '20px 24px',
        color: 'var(--ink)',
        fontFamily: 'inherit',
        fontSize: 16,
        outline: 'none',
        width: '100%',
        ...props.style,
      }}
    />
  );
}

window.CTA = CTA;
