// Plazify · Supply landing — reusable lead MODAL (supply defaults) + cross-promo (→/reviews) + shared footer.
// Same component contract & visuals as the approved /reviews page; only supply-specific content/defaults differ.
const { useState: useStateL, useEffect: useEffectL, useRef: useRefL } = React;

function Field({ label, children, error }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 7 }}>
      <span style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 600, fontSize: 14, color: '#202023' }}>{label}</span>
      {children}
      {error ? <span style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 500, fontSize: 12, lineHeight: 1.4, color: '#D14343' }}>{error}</span> : null}
    </label>
  );
}
const inputStyle = {
  fontFamily: 'var(--plz-font-ui)', fontSize: 15, color: '#202023', padding: '13px 14px',
  borderRadius: 8, border: '1px solid #D5D7DB', background: '#fff', outline: 'none', width: '100%',
};
const selectStyle = {
  ...inputStyle, appearance: 'none', cursor: 'pointer',
  background: '#fff url("data:image/svg+xml,%3Csvg xmlns=\'http://www.w3.org/2000/svg\' width=\'16\' height=\'16\' fill=\'none\' stroke=\'%235C5C62\' stroke-width=\'2\'%3E%3Cpath d=\'M4 6l4 4 4-4\'/%3E%3C/svg%3E") no-repeat right 14px center',
};

// One reusable modal, two intents. Submit copy + hidden lead_intent change with intent.
const LEAD_INTENTS = {
  demo:  { submit: 'Запросить демо',          leadIntent: 'Запросить демо / консультация' },
  trial: { submit: 'Получить тестовый доступ', leadIntent: 'Попробовать 7 дней бесплатно' },
};
// Supply default module per brief: «Прогноз спроса и поставки»
const SUPPLY_MODULE = 'Прогноз спроса и поставки';
// --- Lead form helpers: RU phone mask + field validation (no React state, no deps) ---
// Keep digits only, normalise Russian numbers to 11 digits starting with 7 (8… → 7…).
function normalizePhoneDigits(value) {
  var digits = String(value || '').replace(/\D/g, '');
  if (!digits) return '';
  if (digits[0] === '8') digits = '7' + digits.slice(1);
  if (digits[0] !== '7') digits = '7' + digits;
  return digits.slice(0, 11);
}
// Render digits as +7 (000) 000-00-00 while the user types or pastes.
function formatRuPhone(value) {
  var digits = normalizePhoneDigits(value);
  if (!digits) return '';
  var body = digits.slice(1);
  var result = '+7';
  if (body.length > 0) result += ' (' + body.slice(0, 3);
  if (body.length >= 3) result += ')';
  if (body.length > 3) result += ' ' + body.slice(3, 6);
  if (body.length > 6) result += '-' + body.slice(6, 8);
  if (body.length > 8) result += '-' + body.slice(8, 10);
  return result;
}
// Format in place on the uncontrolled input — no React state, no re-render.
function handlePhoneInput(e) {
  e.currentTarget.value = formatRuPhone(e.currentTarget.value);
}
function validateLeadName(value) {
  var v = String(value || '').trim();
  if (!v) return 'Укажите имя';
  if (v.length < 2) return 'Имя должно быть не короче 2 символов';
  return '';
}
function validateLeadContact(value) {
  var digits = normalizePhoneDigits(value);
  if (!digits) return 'Укажите номер телефона';
  if (digits.length < 11) return 'Укажите номер полностью';
  if (digits[0] !== '7') return 'Номер должен начинаться с +7';
  return '';
}
function validateLeadEmail(value) {
  var v = String(value || '').trim();
  if (!v) return '';
  if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(v)) return 'Введите корректный email';
  return '';
}

function LeadModal() {
  const [open, setOpen] = useStateL(false);
  const [show, setShow] = useStateL(false);
  const [intent, setIntent] = useStateL('trial');
  const [source, setSource] = useStateL('');
  const [sent, setSent] = useStateL(false);
  const [submitting, setSubmitting] = useStateL(false);
  const [error, setError] = useStateL(false);
  const [fieldErrors, setFieldErrors] = useStateL({});
  const closeTimer = useRefL(null);
  // Validate a single field on blur — only field-error state changes, inputs stay uncontrolled.
  const onBlurName = (e) => setFieldErrors((p) => ({ ...p, name: validateLeadName(e.target.value) }));
  const onBlurContact = (e) => setFieldErrors((p) => ({ ...p, contact: validateLeadContact(e.target.value) }));
  const onBlurEmail = (e) => setFieldErrors((p) => ({ ...p, email: validateLeadEmail(e.target.value) }));

  function close() {
    setShow(false);
    clearTimeout(closeTimer.current);
    closeTimer.current = setTimeout(() => setOpen(false), 220);
  }

  useEffectL(() => {
    function onOpen(e) {
      const it = (e.detail && e.detail.intent) === 'demo' ? 'demo' : 'trial';
      setIntent(it);
      setSource((e.detail && e.detail.source) || '');
      setSent(false);
      setSubmitting(false);
      setError(false);
      setFieldErrors({});
      setOpen(true);
    }
    window.addEventListener('plz-open-lead', onOpen);
    return () => window.removeEventListener('plz-open-lead', onOpen);
  }, []);

  useEffectL(() => {
    if (!open) return;
    const raf = requestAnimationFrame(() => setShow(true));
    const prevOverflow = document.body.style.overflow;
    document.body.style.overflow = 'hidden';
    function onKey(e) { if (e.key === 'Escape') close(); }
    window.addEventListener('keydown', onKey);
    return () => {
      cancelAnimationFrame(raf);
      document.body.style.overflow = prevOverflow;
      window.removeEventListener('keydown', onKey);
    };
  }, [open]);

  // Real submission: read uncontrolled fields via FormData, validate, then POST the lead
  // to /api/lead, which delivers it to Telegram (see api/lead.js).
  // Success is shown ONLY after the API confirms delivery.
  async function onSubmit(e) {
    e.preventDefault();
    if (submitting) return;
    const form = e.currentTarget;
    const fd = new FormData(form);
    const name = String(fd.get('name') || '').trim();
    const contact = String(fd.get('contact') || '').trim();
    const email = String(fd.get('email') || '').trim();
    const comment = String(fd.get('comment') || '').trim();
    const contactPref = String(fd.get('contactPref') || '');
    const topic = String(fd.get('topic') || '');
    const hp = String(fd.get('hp') || '');

    // Validate name, contact (phone) and optional email. Block submit on the first error.
    const errs = {
      name: validateLeadName(name),
      contact: validateLeadContact(contact),
      email: validateLeadEmail(email),
    };
    const firstInvalid = ['name', 'contact', 'email'].find((k) => errs[k]);
    if (firstInvalid) {
      setError(false);
      setFieldErrors(errs);
      const el = form.elements[firstInvalid];
      if (el && typeof el.focus === 'function') el.focus();
      return;
    }

    setFieldErrors({});
    setError(false);
    setSubmitting(true);
    const payload = {
      name: name,
      contact: contact,
      company: '',
      comment: comment,
      contactPref: contactPref,
      email: email,
      topic: topic,
      module: 'supply',
      intent: intent === 'demo' ? 'demo' : 'try',
      ctaSource: source || 'unknown',
      sourcePage: document.title,
      sourcePath: window.location.pathname,
      hp: hp,
    };
    try {
      const res = await fetch('/api/lead', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => null);
      if (res.ok && json && json.ok) {
        // Track the conversion only after Telegram confirmed delivery.
        track('lead_submit', {
          topic: topic, source: 'supply',
          module: SUPPLY_MODULE,
          intent,
          cta_source: source,
          lead_intent: LEAD_INTENTS[intent].leadIntent,
          contact_pref: contactPref,
        });
        setSent(true);
      } else {
        setError(true);
        setSubmitting(false);
      }
    } catch (err) {
      setError(true);
      setSubmitting(false);
    }
  }

  if (!open) return null;
  const cfg = LEAD_INTENTS[intent];

  return (
    <div
      onClick={close}
      style={{
        position: 'fixed', inset: 0, zIndex: 1000,
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        padding: 20, overflowY: 'auto',
        background: 'rgba(10,10,10,.55)',
        backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
        opacity: show ? 1 : 0, transition: 'opacity .22s ease',
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        role="dialog" aria-modal="true" aria-label="Заявка"
        className="lead-modal-card"
        style={{
          position: 'relative', background: '#fff', borderRadius: 40,
          boxShadow: 'var(--plz-shadow-card)', overflow: 'hidden',
          display: 'grid', width: '100%', maxWidth: 980, margin: 'auto',
          transform: show ? 'translateY(0) scale(1)' : 'translateY(8px) scale(.98)',
          opacity: show ? 1 : 0,
          transition: 'opacity .22s ease, transform .22s ease',
        }}
      >
        <button onClick={close} aria-label="Закрыть" style={{
          position: 'absolute', top: 16, right: 16, zIndex: 3,
          width: 40, height: 40, borderRadius: '50%', border: 'none', cursor: 'pointer',
          background: 'rgba(32,32,35,.06)', color: '#202023',
          display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
          transition: 'background .15s ease',
        }} onMouseEnter={(e) => e.currentTarget.style.background = 'rgba(32,32,35,.12)'}
           onMouseLeave={(e) => e.currentTarget.style.background = 'rgba(32,32,35,.06)'}>
          <svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.4" strokeLinecap="round"><path d="M6 6l12 12M18 6L6 18" /></svg>
        </button>

        {/* left — pitch (hidden on mobile) */}
        <div className="lead-modal-left" style={{ background: '#0A0A0A', padding: '52px 48px', position: 'relative', overflow: 'hidden' }}>
          <div style={{ position: 'absolute', bottom: -80, left: -40, width: 320, height: 280, background: 'radial-gradient(circle, rgba(94,62,229,.4), transparent 70%)', filter: 'blur(34px)' }} />
          <div style={{ position: 'relative' }}>
            <Eyebrow dark>Заявка</Eyebrow>
            <h2 className="plz-h2 sec-h2" style={{ color: '#fff', margin: '20px 0 16px', fontSize: 34 }}>Подключим прогноз спроса и поставки</h2>
            <p style={{ margin: '0 0 28px', fontFamily: 'var(--plz-font-head)', fontSize: 17, lineHeight: 1.55, color: 'rgba(255,255,255,.66)' }}>
              Оставьте контакты — покажем модуль на ваших данных, поможем настроить прогноз спроса,
              контроль остатков и расчёт поставок по складам.
            </p>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              {['7 дней бесплатно, без привязки карты', 'Официальное API Wildberries', 'Резидент Сколково · ООО «Система Координат»'].map((t, i) => (
                <div key={i} style={{ display: 'flex', alignItems: 'center', gap: 12 }}>
                  <span style={{ width: 24, height: 24, borderRadius: '50%', background: '#5E3EE5', display: 'inline-flex', alignItems: 'center', justifyContent: 'center', flex: '0 0 auto' }}>
                    <MIcon name="check" size={14} color="#fff" stroke={2.6} />
                  </span>
                  <span style={{ fontFamily: 'var(--plz-font-head)', fontSize: 16, color: '#fff' }}>{t}</span>
                </div>
              ))}
            </div>
          </div>
        </div>

        {/* right — form */}
        <div style={{ padding: '52px 48px' }}>
          {sent ? (
            <div style={{ height: '100%', minHeight: 360, display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center', textAlign: 'center', gap: 16 }}>
              <span style={{ width: 64, height: 64, borderRadius: '50%', background: '#E4F7F0', display: 'inline-flex', alignItems: 'center', justifyContent: 'center' }}>
                <MIcon name="check" size={30} color="#40856C" stroke={2.4} />
              </span>
              <h3 className="plz-h3" style={{ margin: 0, fontSize: 26 }}>Заявка отправлена</h3>
              <p className="plz-body" style={{ margin: 0, maxWidth: 360 }}>Свяжемся с вами в ближайшее время. А пока можете запустить тест — 7 дней бесплатно.</p>
            </div>
          ) : (
            <form onSubmit={onSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 18 }}>
              {/* hidden intent / module fields — prepared for analytics / lead routing */}
              <input type="hidden" name="intent" value={intent} />
              <input type="hidden" name="cta_source" value={source} />
              <input type="hidden" name="lead_intent" value={cfg.leadIntent} />
              <input type="hidden" name="module" value={SUPPLY_MODULE} />
              {/* honeypot — visually hidden anti-spam field; real users never see or fill it */}
              <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
                <label>Не заполняйте это поле
                  <input type="text" name="hp" tabIndex={-1} autoComplete="off" defaultValue="" />
                </label>
              </div>
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }} className="lead-2col">
                <Field label="Имя" error={fieldErrors.name}><input name="name" style={inputStyle} defaultValue="" placeholder="Как к вам обращаться" onBlur={onBlurName} /></Field>
                <Field label="Телефон или Telegram" error={fieldErrors.contact}><input name="contact" type="tel" inputMode="tel" autoComplete="tel" style={inputStyle} defaultValue="" placeholder="+7 (000) 000-00-00" onInput={handlePhoneInput} onBlur={onBlurContact} /></Field>
              </div>
              <Field label="Как вам удобнее, чтобы мы с вами связались?">
                <select name="contactPref" style={selectStyle} defaultValue="Звонок">
                  {['Звонок', 'Сообщение в Telegram', 'Сообщение в WhatsApp'].map(o => <option key={o}>{o}</option>)}
                </select>
              </Field>
              <Field label="Email" error={fieldErrors.email}><input name="email" type="email" style={inputStyle} defaultValue="" placeholder="you@company.ru" onBlur={onBlurEmail} /></Field>
              <Field label="Что хотите подключить?">
                <select name="topic" style={selectStyle} defaultValue={SUPPLY_MODULE}>
                  {['Прогноз спроса и поставки', 'Контроль остатков и OOS', 'Расчёт и сборка поставок', 'Вся платформа Plazify'].map(o => <option key={o}>{o}</option>)}
                </select>
              </Field>
              <Field label="Комментарий"><textarea name="comment" style={{ ...inputStyle, resize: 'vertical', minHeight: 92 }} defaultValue="" placeholder="Сколько кабинетов и складов, какие задачи, что важно настроить" /></Field>
              {error && (
                <p style={{ margin: 0, fontFamily: 'var(--plz-font-head)', fontSize: 13, lineHeight: 1.5, color: '#D14343', textAlign: 'center' }}>
                  Не удалось отправить заявку. Попробуйте еще раз или напишите нам на support@plazify.ru.
                </p>
              )}
              <MBtn variant="primary" icon="arrowRight" type="submit" full disabled={submitting}>{submitting ? 'Отправляем...' : cfg.submit}</MBtn>
              <p style={{ margin: 0, fontFamily: 'var(--plz-font-head)', fontSize: 13, lineHeight: 1.5, color: '#95959E', textAlign: 'center' }}>
                Нажимая кнопку, вы соглашаетесь с обработкой персональных данных.
              </p>
            </form>
          )}
        </div>
      </div>
    </div>
  );
}

// Cross-promo on /supply promotes the Reviews module → /reviews
function CrossPromo() {
  return (
    <Section id="crosspromo" style={{ paddingTop: 160 }}>
      <a href="/reviews/" onClick={() => track('cross_promo_click', { to: '/reviews/' })} style={{ textDecoration: 'none', display: 'block' }}>
        <div style={{ background: '#E0E4FF', borderRadius: 40, padding: '72px 64px', display: 'grid', gridTemplateColumns: '1fr auto', gap: 48, alignItems: 'center' }} className="cross-grid">
          <div>
            <span style={{ fontFamily: 'var(--plz-font-head)', fontWeight: 600, fontSize: 14, color: '#5E3EE5' }}>Другие инструменты платформы</span>
            <h2 className="plz-h2 sec-h2" style={{ margin: '16px 0 18px', fontSize: 36, color: '#1A1043' }}>Автоответы и аналитика отзывов Wildberries</h2>
            <p className="cross-body" style={{ fontFamily: 'var(--plz-font-head)', fontSize: 18, lineHeight: 1.5, color: '#4a4470', margin: '0 0 36px', maxWidth: 640 }}>
              Настраиваемый AI-ассистент для отзывов, контроль публикации и аналитика по каждой SKU.
              Второй модуль Plazify — под той же HITL-философией.
            </p>
            <span className="cross-cta" style={{ display: 'inline-flex', alignItems: 'center', gap: 10, background: '#5E3EE5', color: '#fff', borderRadius: 12, padding: '15px 26px', fontFamily: 'var(--plz-font-head)', fontWeight: 700, fontSize: 16 }}>
              Подробнее о модуле <MIcon name="arrowRight" size={18} color="#fff" />
            </span>
          </div>
          <img src={window.__resources.aiBubble} width="170" height="170" alt="" loading="lazy" decoding="async" className="cross-3d" style={{ filter: 'drop-shadow(0 24px 40px rgba(77,42,223,.28))' }} />
        </div>
      </a>
    </Section>
  );
}

// Shared footer — identical to the approved /reviews footer (single-domain routing).
const FOOT_COL1 = [
  { label: 'Личный кабинет', href: 'https://app.plazify.ru' },
  { label: 'О компании', href: '/about/' },
  { label: 'Контакты', href: '/about/#contacts' },
];
const FOOT_COL2 = [
  { label: 'Логистика', href: '/supply/' },      // this page
  { label: 'Автоответы', href: '/reviews/' },    // reviews module
  { label: 'FAQ', href: '#faq' },                // anchors to FAQ section on this page
];
// TODO(legal): replace # anchors with real legal document URLs before launch
const FOOT_COL3 = [
  { label: 'Политика конфиденциальности', href: '/privacy-policy/' },
  { label: 'Пользовательское соглашение', href: '/user-agreement/' },
  { label: 'Согласие на обработку файлов Cookies', href: '/cookies/' },
  { label: 'Согласие на обработку персональных данных', href: '/personal-data-consent/' },
];

function FootLink({ label, href, muted }) {
  return (
    <a href={href} onClick={() => track('footer_link', { to: href })} className={'foot-link' + (muted ? ' foot-link-muted' : '')} style={{
      textDecoration: 'none', fontFamily: 'var(--plz-font-head)',
      fontWeight: muted ? 400 : 700, fontSize: muted ? 14 : 16,
      lineHeight: muted ? '20px' : '24px',
      color: muted ? '#E4E6EB' : '#fff', transition: 'opacity .15s ease', opacity: 1,
    }} onMouseEnter={e => e.currentTarget.style.opacity = .7} onMouseLeave={e => e.currentTarget.style.opacity = 1}>{label}</a>
  );
}

function Footer() {
  return (
    <section className="foot-section" style={{ padding: '128px 20px 40px' }}>
      <footer className="foot-box" style={{ background: '#0A0A0A', borderRadius: 40, padding: '48px 56px', maxWidth: 1760, margin: '0 auto' }}>
        <div className="foot-main" style={{ display: 'flex', gap: 40, alignItems: 'flex-start', maxWidth: 1360, margin: '0 auto' }}>
          <div className="foot-left" style={{ flex: '1 1 auto', minWidth: 0 }}>
            <div style={{ display: 'flex', alignItems: 'center', gap: 12, marginBottom: 36 }}>
              <img src={window.__resources.mark} width="36" height="36" alt="" loading="lazy" decoding="async" />
              <span className="plz-wordmark" style={{ fontSize: 22 }}>Plazify</span>
            </div>
            <div className="foot-cols" style={{ display: 'flex', gap: 40 }}>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: '0 0 auto', minWidth: 150 }}>
                {FOOT_COL1.map(l => <FootLink key={l.label} {...l} />)}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: '0 0 auto', minWidth: 120 }}>
                {FOOT_COL2.map(l => <FootLink key={l.label} {...l} />)}
              </div>
              <div style={{ display: 'flex', flexDirection: 'column', gap: 8, flex: '0 0 auto' }}>
                {FOOT_COL3.map(l => <FootLink key={l.label} {...l} muted />)}
              </div>
            </div>
          </div>

          <aside className="foot-info" style={{
            flex: '0 0 460px', background: '#202023', borderRadius: 28, padding: 20,
            display: 'flex', flexDirection: 'column', gap: 16,
          }}>
            <div style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
              <h3 style={{ margin: 0, fontFamily: 'var(--plz-font-head)', fontWeight: 700, fontSize: 16, lineHeight: '24px', color: '#fff' }}>
                Plazify — платформа для селлеров, разработанная ООО «Система Координат»
              </h3>
              <div className="foot-reqs" style={{ display: 'flex', flexDirection: 'column', gap: 4, fontFamily: 'var(--plz-font-head)', fontSize: 14, lineHeight: '20px', color: 'rgba(255,255,255,.78)' }}>
                <span>ИНН: 6200003169, КПП: 773101001, ОГРН: 1246200001850</span>
                <span>г. Москва, ИЦ «Сколково», Большой бульвар 42 стр. 1</span>
                <span>
                  <a href="mailto:support@plazify.ru" onClick={() => track('footer_link', { to: 'email' })} style={{ color: 'inherit', textDecoration: 'none' }}>support@plazify.ru</a>
                  {', '}
                  <a href="tel:+74951466615" onClick={() => track('footer_link', { to: 'phone' })} style={{ color: 'inherit', textDecoration: 'none' }}>+7 (495) 146-66-15</a>
                </span>
              </div>
            </div>
            <img src={window.__resources.skolkovoUchastnik} alt="Участник проекта «Сколково»" width="143" height="42" loading="lazy" decoding="async" style={{ width: 143, height: 'auto', aspectRatio: '702 / 206', objectFit: 'contain', opacity: 0.6, display: 'block' }} />
          </aside>
        </div>
      </footer>
    </section>
  );
}
Object.assign(window, { LeadModal, CrossPromo, Footer });
