/* Contact / final CTA form with validation */

const Contact = () => {
  const ref = React.useRef(null);
  useReveal(ref);

  const [form, setForm] = React.useState({ name: '', phone: '', interest: '', message: '', consent: false, channel: 'WhatsApp' });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  /* Plausible live-activity: ranges follow Israel time-of-day (UTC+2).
     Daytime (9-22): more visitors, more recent requests.
     Night (22-9):   fewer visitors, longer gap since last request.
     Values jitter every 40-70s but change by ±1-2 so it reads natural, not random. */
  const pickLive = () => {
    const h = new Date().getHours();
    const day = h >= 9 && h < 22;
    const online = day
      ? 11 + Math.floor(Math.random() * 12)   // 11-22
      : 3  + Math.floor(Math.random() * 6);   // 3-8
    const ago = day
      ? 2  + Math.floor(Math.random() * 10)   // 2-11 мин
      : 12 + Math.floor(Math.random() * 25);  // 12-36 мин
    return { online, ago };
  };
  const [live, setLive] = React.useState(pickLive);
  React.useEffect(() => {
    const tick = () => setLive(prev => {
      const next = pickLive();
      /* Сглаживаем: не даём счётчику прыгать больше чем на 2 человека за раз. */
      const online = prev.online + Math.max(-2, Math.min(2, next.online - prev.online));
      return { online, ago: next.ago };
    });
    const id = setInterval(tick, 40000 + Math.random() * 30000);
    return () => clearInterval(id);
  }, []);

  const update = (k, v) => setForm(f => ({...f, [k]: v}));

  const submit = (e) => {
    e.preventDefault();
    const err = {};
    if (!form.name.trim()) err.name = 'Укажите ваше имя';
    if (!form.phone.trim() || form.phone.replace(/\D/g, '').length < 10) err.phone = 'Укажите корректный номер';
    if (!form.consent) err.consent = 'Требуется согласие';
    setErrors(err);
    if (Object.keys(err).length === 0) setSubmitted(true);
  };

  return (
    <section id="contact" className="contact section" ref={ref}>
      <style>{`
        .contact { background: var(--ink); color: var(--paper); position: relative; overflow: hidden; }
        .contact::before {
          content:''; position: absolute; inset: 0;
          background:
            radial-gradient(circle at 85% 15%, rgba(179, 83, 43, 0.2) 0%, transparent 50%),
            radial-gradient(circle at 10% 90%, rgba(107, 142, 127, 0.15) 0%, transparent 50%);
          pointer-events: none;
        }
        .contact .container { position: relative; z-index: 1; }
        .contact-grid {
          display: grid; grid-template-columns: 1fr 1.3fr;
          gap: 72px; align-items: start;
        }
        @media (max-width: 960px) { .contact-grid { grid-template-columns: 1fr; gap: 48px; } }

        .contact h2 { color: var(--paper); }
        .contact .eyebrow-line { display:flex; align-items:center; gap:12px; color: var(--clay-soft); margin-bottom: 18px; }
        .contact .eyebrow-line::before { content:''; width:28px; height:1px; background: var(--clay-soft); }

        .contact-lede { color: rgba(245, 239, 230, 0.72); font-size: 17px; line-height: 1.6; margin: 24px 0 40px; }

        .contact-aside { display: flex; flex-direction: column; gap: 20px; }
        .contact-row {
          display: flex; gap: 14px; padding: 20px 0;
          border-top: 1px solid rgba(245,239,230,0.14);
          min-width: 0;
        }
        .contact-row > div:last-child { min-width: 0; flex: 1; }
        .contact-row:last-child { border-bottom: 1px solid rgba(245,239,230,0.14); }
        .contact-row .ic { width: 36px; height: 36px; border-radius: 50%; background: rgba(245,239,230,0.1); display: grid; place-items: center; flex-shrink: 0; color: var(--sage); }
        .contact-row .lab { font-size: 11px; letter-spacing: 0.14em; text-transform: uppercase; color: rgba(245, 239, 230, 0.75); }
        .contact-row .val { font-size: 15px; color: var(--paper); font-family: var(--font-mono); word-break: break-word; overflow-wrap: anywhere; display: inline-block; }
        .contact-row a:hover { color: var(--clay); }
        @media (max-width: 640px) {
          .contact-row .val { font-size: 14px; font-family: var(--font-body); font-weight: 500; }
        }

        .contact-live {
          margin-top: 16px;
          display: flex; align-items: center; gap: 10px;
          font-size: 13px; color: rgba(245, 239, 230, 0.7);
        }
        .contact-live .pulse {
          width: 10px; height: 10px; background: var(--sage); border-radius: 50%;
          box-shadow: 0 0 0 0 rgba(107, 142, 127, 0.6);
          animation: pulse 2s infinite;
        }
        @keyframes pulse {
          0%   { box-shadow: 0 0 0 0 rgba(107, 142, 127, 0.6); }
          70%  { box-shadow: 0 0 0 10px rgba(107, 142, 127, 0); }
          100% { box-shadow: 0 0 0 0 rgba(107, 142, 127, 0); }
        }

        .contact-form {
          background: color-mix(in oklab, var(--paper) 98%, transparent);
          color: var(--ink);
          border-radius: var(--r-xl);
          padding: 40px;
          max-width: 100%;
          min-width: 0;
        }
        @media (max-width: 640px) {
          .contact-form { padding: 24px 20px; border-radius: var(--r-lg); }
        }
        .cf-head {
          display: flex; justify-content: space-between; align-items: start; gap: 16px;
          padding-bottom: 24px; margin-bottom: 24px; border-bottom: 1px dashed var(--ink-20);
        }
        @media (max-width: 640px) {
          .cf-head { flex-direction: column; gap: 12px; padding-bottom: 18px; margin-bottom: 18px; }
          .cf-head h3 { font-size: 22px !important; }
          .channels { flex-wrap: wrap; }
          .channel-btn { flex: 1 1 calc(50% - 3px); min-width: 0; }
        }
        .cf-head h3 { font-family: var(--font-display); font-size: 28px; font-weight: 380; margin: 0 0 6px; letter-spacing: -0.01em; }
        .cf-head p { font-size: 14px; color: var(--ink-60); margin: 0; }

        .cf-grid { display: grid; grid-template-columns: minmax(0, 1fr) minmax(0, 1fr); gap: 16px; }
        @media (max-width: 640px) { .cf-grid { grid-template-columns: minmax(0, 1fr); } }

        .cf-field { display: flex; flex-direction: column; gap: 6px; min-width: 0; }
        .cf-field.full { grid-column: 1 / -1; }
        .cf-field input, .cf-field textarea, .cf-field select { min-width: 0; width: 100%; box-sizing: border-box; }
        .cf-field label { font-size: 12px; color: var(--ink-80); letter-spacing: 0.03em; font-weight: 500; }
        .cf-field label .req { color: var(--clay-dark); }
        .cf-field input, .cf-field textarea, .cf-field select {
          background: var(--white);
          border: 1px solid var(--ink-20);
          border-radius: var(--r-sm);
          padding: 12px 14px;
          font-family: inherit;
          font-size: 14px;
          color: var(--ink);
          transition: border-color 0.2s;
        }
        .cf-field input:focus, .cf-field textarea:focus, .cf-field select:focus {
          outline: none; border-color: var(--ink); box-shadow: 0 0 0 3px var(--ink-10);
        }
        .cf-field textarea { min-height: 100px; resize: vertical; }
        .cf-err { font-size: 12px; color: #A63A1E; margin-top: 2px; }

        .channels {
          display: flex; gap: 6px; background: var(--ink-05);
          border-radius: var(--r-pill); padding: 4px;
        }
        .channel-btn {
          flex: 1; padding: 8px 12px; border-radius: var(--r-pill);
          font-size: 12px; color: var(--ink-60); font-weight: 500;
          display: inline-flex; align-items: center; justify-content: center; gap: 6px;
          transition: background 0.2s, color 0.2s;
        }
        .channel-btn.active { background: var(--ink); color: var(--paper); }

        .cf-attach {
          display: inline-flex; align-items: center; gap: 8px;
          color: var(--ink-60); font-size: 13px;
          padding: 10px 0;
          border-top: 1px dashed var(--ink-20);
          border-bottom: 1px dashed var(--ink-20);
          margin-top: 8px;
          justify-content: center;
          cursor: pointer;
        }
        .cf-attach:hover { color: var(--clay); }

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

        .cf-submit-row { display: flex; justify-content: space-between; align-items: center; gap: 16px; flex-wrap: wrap; }
        .cf-live {
          display: flex; align-items: center; gap: 8px;
          font-size: 12px; color: var(--ink-60);
        }
        .cf-live .pulse { width: 8px; height: 8px; background: var(--sage); border-radius: 50%; animation: pulse 2s infinite; }

        .cf-success {
          padding: 48px 32px;
          text-align: center;
          display: flex; flex-direction: column; align-items: center; gap: 18px;
        }
        .cf-success .circle {
          width: 72px; height: 72px; border-radius: 50%;
          background: rgba(63, 122, 91, 0.12); color: var(--success);
          display: grid; place-items: center;
        }
        .cf-success h3 { font-family: var(--font-display); font-size: 32px; font-weight: 380; margin: 0; }
        .cf-success p { color: var(--ink-60); max-width: 360px; margin: 0; }

        .live-activity {
          margin-top: 20px;
          display: flex; justify-content: space-between; align-items: center;
          font-size: 12px; color: rgba(245,239,230,0.55); font-family: var(--font-mono);
          letter-spacing: 0.03em;
        }
      `}</style>

      <div className="container">
        <div className="contact-grid">
          <div>
            <div className="eyebrow-line reveal">
              <span className="eyebrow">Готовы помочь сегодня</span>
            </div>
            <h2 className="display-lg reveal d1">
              Получите <em className="italic-accent" style={{color:'var(--clay-soft)'}}>профессиональную</em><br/>
              медицинскую консультацию.
            </h2>
            <p className="contact-lede reveal d2">
              Координатор Анна свяжется с вами в течение 7 минут и поможет выбрать оптимальное решение.
            </p>

            <div className="contact-aside reveal d3">
              <div className="contact-row">
                <div className="ic"><I.Phone size={16}/></div>
                <div>
                  <div className="lab">Телефон</div>
                  <a href="tel:+972526512654" className="val">+972-52-651-2654</a>
                </div>
              </div>
              <div className="contact-row">
                <div className="ic"><I.WhatsApp size={14}/></div>
                <div>
                  <div className="lab">WhatsApp · быстрые ответы</div>
                  <a href="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." target="_blank" rel="noopener" className="val">+972-52-651-2654</a>
                </div>
              </div>
              <div className="contact-row">
                <div className="ic"><I.Email size={16}/></div>
                <div>
                  <div className="lab">Email</div>
                  <a href="mailto:Office@hospitalassuta.org" className="val">Office@hospitalassuta.org</a>
                </div>
              </div>
              <div className="contact-row">
                <div className="ic"><I.MapPin size={16}/></div>
                <div>
                  <div className="lab">Адрес</div>
                  <span className="val">HaBarzel St 20, Tel Aviv-Yafo</span>
                </div>
              </div>
            </div>

            <div className="contact-live">
              <span className="pulse"/>
              <span>Координатор онлайн · ответим за 7 минут</span>
            </div>

            <div className="live-activity">
              <span>● Сейчас на сайте: {live.online} человек</span>
              <span>Последняя заявка: {live.ago} мин назад</span>
            </div>
          </div>

          <form className="contact-form reveal d1" onSubmit={submit} noValidate>
            {submitted ? (
              <div className="cf-success">
                <div className="circle"><I.Check size={32}/></div>
                <h3>Заявка принята</h3>
                <p>Координатор свяжется с вами в течение 7 минут через {form.channel}. Проверьте телефон и мессенджер.</p>
                <button type="button" className="btn btn-ghost" onClick={() => { setSubmitted(false); setForm({name:'',phone:'',interest:'',message:'',consent:false,channel:'WhatsApp'}); }}>
                  Отправить ещё одну
                </button>
              </div>
            ) : (
              <>
                <div className="cf-head">
                  <div>
                    <h3>Оставить заявку</h3>
                    <p>Ответим в течение 7 минут</p>
                  </div>
                  <Chip variant="" style={{background:'rgba(63,122,91,0.12)', color:'var(--success)', borderColor:'transparent'}}>
                    <I.Shield size={12}/> Защищено
                  </Chip>
                </div>

                <div className="cf-grid">
                  <div className="cf-field">
                    <label>Имя <span className="req">*</span></label>
                    <input type="text" placeholder="Ваше имя" value={form.name} onChange={e => update('name', e.target.value)} />
                    {errors.name && <div className="cf-err">{errors.name}</div>}
                  </div>
                  <div className="cf-field">
                    <label>Телефон <span className="req">*</span></label>
                    <input type="tel" inputMode="tel" autoComplete="tel" placeholder="Номер с кодом страны" value={form.phone} onChange={e => update('phone', e.target.value)} />
                    {errors.phone && <div className="cf-err">{errors.phone}</div>}
                  </div>
                  <div className="cf-field full">
                    <label>Удобный канал связи</label>
                    <div className="channels">
                      {['WhatsApp', 'Звонок', 'Telegram', 'Email'].map(c => (
                        <button type="button" key={c} className={`channel-btn ${form.channel === c ? 'active' : ''}`} onClick={() => update('channel', c)}>
                          {c}
                        </button>
                      ))}
                    </div>
                  </div>
                  <div className="cf-field full">
                    <label>Что вас интересует?</label>
                    <select value={form.interest} onChange={e => update('interest', e.target.value)}>
                      <option value="">Выберите направление</option>
                      <option>Второе мнение</option>
                      <option>План лечения</option>
                      <option>Консультация</option>
                      <option>Диагностика</option>
                      <option>Другое</option>
                    </select>
                  </div>
                  <div className="cf-field full">
                    <label>Кратко опишите ситуацию</label>
                    <textarea placeholder="Диагноз, симптомы или вопрос — как вам удобно." value={form.message} onChange={e => update('message', e.target.value)} />
                  </div>
                  <label className="cf-attach full">
                    <I.Attach size={14}/> Прикрепить выписку, снимок или анализ (PDF, JPG)
                  </label>
                </div>

                <div style={{marginTop: 20, display:'flex', flexDirection:'column', gap: 18}}>
                  <label className="cf-consent">
                    <input type="checkbox" checked={form.consent} onChange={e => update('consent', e.target.checked)} />
                    <span>Согласен на обработку персональных данных и получение информации о медицинских услугах. Ваши данные защищены врачебной тайной.</span>
                  </label>
                  {errors.consent && <div className="cf-err">{errors.consent}</div>}

                  <div className="cf-submit-row">
                    <div className="cf-live">
                      <span className="pulse"/> Ответим за ~7 минут
                    </div>
                    <button type="submit" className="btn btn-clay btn-lg">
                      Отправить заявку <I.ArrowUpRight size={14}/>
                    </button>
                  </div>
                </div>
              </>
            )}
          </form>
        </div>
      </div>
    </section>
  );
};

window.Contact = Contact;
