// Hyper · Lead modal (форма заявки → Telegram)
// Самостоятельный модуль: монтирует себя в отдельный корень и слушает
// глобальное событие. Любая кнопка на любой странице открывает окно вызовом
// window.openLead({ service, source }). Заявка уходит на бэкенд (window.LEAD_ENDPOINT),
// который пересылает её в Telegram-группу. Токен живёт только на сервере.

(function () {
  // ── Куда форма отправляет заявку (серверная функция). Меняется одной строкой,
  //    когда выберем хостинг. По умолчанию — относительный путь /api/lead.
  window.LEAD_ENDPOINT = window.LEAD_ENDPOINT || '/api/lead';

  // ── Номер WhatsApp (для запасной ссылки, если сервер недоступен)
  const WHATSAPP = '79886554717';

  // ── Список услуг в выпадающем меню. Первый пункт — по умолчанию.
  //    Подписи можно менять здесь же — больше нигде править не нужно.
  const SERVICES = [
    { value: 'consult',    label: 'Нужна консультация' },
    { value: 'marketing',  label: 'Маркетинг' },
    { value: 'smm',        label: 'SMM' },
    { value: 'maximum',    label: 'Максимум' },
    { value: 'branding',   label: 'Брендинг и дизайн' },
    { value: 'production', label: 'Продакшн / видео' },
    { value: 'personal',   label: 'Личный бренд' },
    { value: 'ai',         label: 'Решения с ИИ' },
    { value: 'other',      label: 'Другое' },
  ];
  const SERVICE_VALUES = SERVICES.map((s) => s.value);
  const labelOf = (value) => {
    const s = SERVICES.find((x) => x.value === value);
    return s ? s.label : value;
  };

  // ── Раздел кейса → услуга, которая подставится в форму по умолчанию.
  //    Сопоставляем по названию раздела (стабильнее, чем по id).
  const CATEGORY_TO_SERVICE = {
    'SMM и маркетинг': 'smm',
    'Продакшн': 'production',
    'Дизайн': 'branding',
    'Личный бренд': 'personal',
    'Кейсы по ИИ': 'ai',
  };
  window.serviceFromCategory = function (name) {
    return CATEGORY_TO_SERVICE[name] || 'consult';
  };

  // ── Открыть окно из любого места: window.openLead({ service, source })
  window.openLead = function (opts) {
    window.dispatchEvent(new CustomEvent('lead:open', { detail: opts || {} }));
  };

  // ── Отправка заявки на сервер. Используется и окном, и формой в контактах.
  window.sendLead = async function (data) {
    const payload = Object.assign({}, data, {
      page: location.pathname + location.hash,
      url: location.href,
      at: new Date().toISOString(),
    });
    const res = await fetch(window.LEAD_ENDPOINT, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
    if (!res.ok) throw new Error('HTTP ' + res.status);
    return res.json().catch(() => ({}));
  };

  function LeadModal() {
    const [open, setOpen] = React.useState(false);
    const [service, setService] = React.useState('consult');
    const [partner, setPartner] = React.useState(false);
    const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
    const [source, setSource] = React.useState('');
    const nameRef = React.useRef(null);

    const close = React.useCallback(() => setOpen(false), []);

    // Открытие по глобальному событию
    React.useEffect(() => {
      const onOpen = (e) => {
        const d = (e && e.detail) || {};
        setService(SERVICE_VALUES.includes(d.service) ? d.service : 'consult');
        setPartner(false);
        setStatus('idle');
        setSource(d.source || 'Кнопка на сайте');
        setOpen(true);
      };
      window.addEventListener('lead:open', onOpen);
      return () => window.removeEventListener('lead:open', onOpen);
    }, []);

    // Esc + блокировка прокрутки фона + автофокус на имени
    React.useEffect(() => {
      if (!open) return;
      const onKey = (e) => { if (e.key === 'Escape') close(); };
      document.addEventListener('keydown', onKey);
      const prev = document.body.style.overflow;
      document.body.style.overflow = 'hidden';
      const t = setTimeout(() => { if (nameRef.current) nameRef.current.focus(); }, 60);
      return () => {
        document.removeEventListener('keydown', onKey);
        document.body.style.overflow = prev;
        clearTimeout(t);
      };
    }, [open, close]);

    const submit = async (e) => {
      e.preventDefault();
      const f = e.currentTarget;
      const name = f.elements.name.value.trim();
      const phone = f.elements.phone.value.trim();
      if (!name || !phone) return;
      setStatus('sending');
      try {
        await window.sendLead({
          name,
          phone,
          service: labelOf(service),
          partnership: partner,
          source,
        });
        setStatus('sent');
        setTimeout(() => setOpen(false), 2600);
      } catch (err) {
        setStatus('error');
      }
    };

    if (!open) return null;

    const sending = status === 'sending';

    return (
      <div
        className="lead-overlay"
        onMouseDown={(e) => { if (e.target === e.currentTarget) close(); }}
      >
        <div className="lead-modal" role="dialog" aria-modal="true" aria-label="Оставить заявку">
          <button
            type="button"
            className="lead-close"
            onClick={close}
            aria-label="Закрыть"
            data-cursor data-cursor-label="закрыть"
          >×</button>

          {status === 'sent' ? (
            <div className="lead-done">
              <div className="lead-done-mark" aria-hidden="true">✓</div>
              <h3 className="lead-done-title">Заявка принята</h3>
              <p className="lead-done-sub">
                Мы свяжемся с вами в&nbsp;течение
                {' '}<span style={{ color: 'var(--red)' }}>одного часа</span> в&nbsp;рабочее время.
              </p>
            </div>
          ) : (
            <form className="lead-form" onSubmit={submit}>
              <header className="lead-head">
                <span className="lead-stamp">Оставить заявку</span>
                <h3 className="lead-title">
                  Оставьте контакты —<br />
                  <span className="muted">мы&nbsp;перезвоним.</span>
                </h3>
              </header>

              <div className="lead-field">
                <label className="lead-label" htmlFor="lead-name">Имя</label>
                <input
                  id="lead-name" name="name" type="text" required
                  ref={nameRef}
                  placeholder="Как к вам обращаться"
                  data-cursor="text"
                />
              </div>

              <div className="lead-field">
                <label className="lead-label" htmlFor="lead-phone">Телефон</label>
                <input
                  id="lead-phone" name="phone" type="tel" required
                  placeholder="+7 (___) ___-__-__"
                  data-cursor="text"
                />
              </div>

              <div className="lead-field">
                <label className="lead-label" htmlFor="lead-service">Какая услуга вас интересует</label>
                <div className="lead-select-wrap">
                  <select
                    id="lead-service" name="service"
                    value={service}
                    onChange={(e) => setService(e.target.value)}
                    data-cursor
                  >
                    {SERVICES.map((s) => (
                      <option key={s.value} value={s.value}>{s.label}</option>
                    ))}
                  </select>
                  <span className="lead-select-arrow" aria-hidden="true">▾</span>
                </div>
              </div>

              <label className="lead-check" data-cursor data-cursor-label="выбрать">
                <input
                  type="checkbox"
                  checked={partner}
                  onChange={(e) => setPartner(e.target.checked)}
                />
                <span className="lead-check-box" aria-hidden="true"></span>
                <span className="lead-check-text">Меня интересует партнёрство</span>
              </label>

              <button
                type="submit"
                className="btn primary magnetic lead-submit"
                disabled={sending}
                data-cursor data-cursor-label={sending ? 'отправляем' : 'отправить'}
              >
                <span>{sending ? 'Отправляем…' : 'Отправить заявку'}</span>
                <span className="arrow">→</span>
              </button>

              {status === 'error' && (
                <p className="lead-error">
                  Не удалось отправить. Напишите нам напрямую в&nbsp;
                  <a href={'https://wa.me/' + WHATSAPP} target="_blank" rel="noopener">WhatsApp</a>.
                </p>
              )}

              <p className="lead-note">
                Никакого спама — только короткий звонок по&nbsp;делу.
              </p>
            </form>
          )}
        </div>
      </div>
    );
  }

  window.LeadModal = LeadModal;

  // ── Самомонтирование в собственный корень (работает на всех страницах,
  //    не зависит от App конкретной страницы)
  function mount() {
    if (document.getElementById('lead-modal-root')) return;
    const el = document.createElement('div');
    el.id = 'lead-modal-root';
    document.body.appendChild(el);
    ReactDOM.createRoot(el).render(<LeadModal />);
  }
  if (document.body) mount();
  else document.addEventListener('DOMContentLoaded', mount);
})();
