// Object 1 — Lead section + register-interest form + brochure modal.

function Lead({ t, onSubmit, onBrochure, onViewing }) {
  const [form, setForm] = React.useState({
    first: '', last: '', email: '', phone: '',
    interest: '', market: '', consent: false,
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);

  function update(k, v) { setForm(f => ({ ...f, [k]: v })); setErrors(e => ({ ...e, [k]: null })); }

  function validate() {
    const e = {};
    if (!form.first.trim()) e.first = '✕';
    if (!form.last.trim()) e.last = '✕';
    if (!/^\S+@\S+\.\S+$/.test(form.email)) e.email = '✕';
    if (!/^[\+0-9\s\-()]{7,}$/.test(form.phone)) e.phone = '✕';
    if (!form.interest) e.interest = '✕';
    if (!form.market) e.market = '✕';
    if (!form.consent) e.consent = '✕';
    return e;
  }

  function handleSubmit(ev) {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length === 0) {
      setSubmitted(true);
      onSubmit && onSubmit(form);
    }
  }

  const ctaActions = [
    () => document.getElementById('register-form')?.scrollIntoView({ behavior: 'smooth', block: 'center' }),
    () => onBrochure(),
    () => onViewing(),
    () => window.open('https://wa.me/971523810148', '_blank'),
  ];

  return (
    <section id="enquire" className="section" data-screen-label="Enquire">
      <div className="wrap">
        <SectionHead plate={t.lead.plate} title={t.lead.title} />
        <div className="lead">
          <div className="lead-side">
            <div className="cta-stack">
              {t.lead.ctas.map((c, i) => (
                <button className="cta-row" key={i} onClick={ctaActions[i]} type="button">
                  <div className="ct-l">
                    <strong>{c.name}</strong>
                    <span>{c.sub}</span>
                  </div>
                  <div className="ct-r">
                    <span style={{ marginInlineEnd: 12 }}>{c.tag}</span>
                    <svg width="18" height="10" viewBox="0 0 18 10" fill="none" aria-hidden="true">
                      <path d="M13 1L17 5L13 9M1 5H17" stroke="currentColor" strokeWidth="1"/>
                    </svg>
                  </div>
                </button>
              ))}
            </div>
          </div>

          <div id="register-form">
            {!submitted ? (
              <form className="form-card" onSubmit={handleSubmit} noValidate>
                <h3 className="h3">{t.lead.formTitle}</h3>
                <p className="sub">{t.lead.formSub}</p>
                <div className="form-grid">
                  <div className="field-row">
                    <div className={`field ${errors.first ? 'err' : ''}`}>
                      <label>{t.lead.first}</label>
                      <input value={form.first} onChange={e => update('first', e.target.value)} />
                    </div>
                    <div className={`field ${errors.last ? 'err' : ''}`}>
                      <label>{t.lead.last}</label>
                      <input value={form.last} onChange={e => update('last', e.target.value)} />
                    </div>
                  </div>
                  <div className={`field ${errors.email ? 'err' : ''}`}>
                    <label>{t.lead.email}</label>
                    <input type="email" value={form.email} onChange={e => update('email', e.target.value)} />
                  </div>
                  <div className={`field ${errors.phone ? 'err' : ''}`}>
                    <label>{t.lead.phone}</label>
                    <input type="tel" value={form.phone} onChange={e => update('phone', e.target.value)} placeholder="+971 …" />
                  </div>
                  <div className={`field ${errors.interest ? 'err' : ''}`}>
                    <label>{t.lead.interest}</label>
                    <select value={form.interest} onChange={e => update('interest', e.target.value)}>
                      <option value="">—</option>
                      {t.lead.interestOpts.map((o, i) => <option key={i} value={o}>{o}</option>)}
                    </select>
                  </div>
                  <div className={`field ${errors.market ? 'err' : ''}`}>
                    <label>{t.lead.market}</label>
                    <select value={form.market} onChange={e => update('market', e.target.value)}>
                      <option value="">—</option>
                      {t.lead.marketOpts.map((o, i) => <option key={i} value={o}>{o}</option>)}
                    </select>
                  </div>
                  <label className={`consent ${errors.consent ? 'err' : ''}`}>
                    <input type="checkbox" checked={form.consent} onChange={e => update('consent', e.target.checked)} />
                    <span>{t.lead.consent}</span>
                  </label>
                  <button className="btn" type="submit" style={{ marginTop: 8 }}>
                    {t.lead.submit} <span className="arrow">→</span>
                  </button>
                </div>
              </form>
            ) : (
              <div className="form-success">
                <div className="check">
                  <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
                    <path d="M1 6L8 13L21 1" stroke="currentColor" strokeWidth="1.5"/>
                  </svg>
                </div>
                <h3 className="h3">{t.lead.successTitle}</h3>
                <p className="body body-muted">{t.lead.successBody}</p>
                <p className="small">project=w1nner · locale={t.dir === 'rtl' ? 'ar' : 'en'} · src=microsite</p>
              </div>
            )}
          </div>
        </div>
      </div>
    </section>
  );
}

function BrochureModal({ t, open, onClose }) {
  const [email, setEmail] = React.useState('');
  const [done, setDone] = React.useState(false);
  const [err, setErr] = React.useState('');

  React.useEffect(() => {
    if (!open) { setEmail(''); setDone(false); setErr(''); }
  }, [open]);

  if (!open) return null;

  function submit(e) {
    e.preventDefault();
    if (!/^\S+@\S+\.\S+$/.test(email)) { setErr(t.dir === 'rtl' ? 'يرجى إدخال بريد صحيح' : 'Please enter a valid email'); return; }
    setDone(true);
  }

  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor"/></svg>
        </button>
        {!done ? (
          <>
            <h3 className="h3">{t.brochure.title}</h3>
            <p className="sub">{t.brochure.sub}</p>
            <form className="form-grid" onSubmit={submit}>
              <div className={`field ${err ? 'err' : ''}`}>
                <label>{t.lead.email}</label>
                <input type="email" value={email} onChange={e => { setEmail(e.target.value); setErr(''); }} autoFocus />
                {err && <div className="err-msg">{err}</div>}
              </div>
              <button className="btn" type="submit">{t.brochure.submit} <span className="arrow">→</span></button>
            </form>
          </>
        ) : (
          <div style={{ display: 'grid', gap: 12, padding: '24px 0' }}>
            <div className="check" style={{ width: 56, height: 56, border: '1px solid var(--ink)', borderRadius: '50%', display: 'grid', placeItems: 'center' }}>
              <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
                <path d="M1 6L8 13L21 1" stroke="currentColor" strokeWidth="1.5"/>
              </svg>
            </div>
            <h3 className="h3">{t.lead.successTitle}</h3>
            <p className="body body-muted">{t.dir === 'rtl' ? 'يتم إرسال الكتيب إلى بريدك خلال دقائق.' : 'The brochure will arrive in your inbox within a few minutes.'}</p>
          </div>
        )}
      </div>
    </div>
  );
}

function ViewingModal({ t, open, onClose }) {
  const [form, setForm] = React.useState({ name: '', email: '', when: '' });
  const [done, setDone] = React.useState(false);
  React.useEffect(() => { if (!open) { setForm({ name: '', email: '', when: '' }); setDone(false); } }, [open]);
  if (!open) return null;
  function submit(e) { e.preventDefault(); setDone(true); }
  return (
    <div className="modal-bg" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button className="close" onClick={onClose} aria-label="Close">
          <svg width="14" height="14" viewBox="0 0 14 14"><path d="M1 1L13 13M13 1L1 13" stroke="currentColor"/></svg>
        </button>
        {!done ? (
          <>
            <h3 className="h3">{t.dir === 'rtl' ? 'احجز معاينةً خاصة' : 'Book a private viewing'}</h3>
            <p className="sub">{t.dir === 'rtl' ? 'صالة العرض في وسط مدينة دبي. عند الطلب.' : 'Sales gallery, Downtown Dubai. By appointment.'}</p>
            <form className="form-grid" onSubmit={submit}>
              <div className="field">
                <label>{t.lead.first} / {t.lead.last}</label>
                <input value={form.name} onChange={e => setForm(f => ({...f, name: e.target.value}))} required />
              </div>
              <div className="field">
                <label>{t.lead.email}</label>
                <input type="email" value={form.email} onChange={e => setForm(f => ({...f, email: e.target.value}))} required />
              </div>
              <div className="field">
                <label>{t.dir === 'rtl' ? 'الموعد المفضّل' : 'Preferred date'}</label>
                <input type="date" value={form.when} onChange={e => setForm(f => ({...f, when: e.target.value}))} required />
              </div>
              <button className="btn" type="submit">{t.dir === 'rtl' ? 'طلب موعد' : 'Request appointment'} <span className="arrow">→</span></button>
            </form>
          </>
        ) : (
          <div style={{ display: 'grid', gap: 12, padding: '24px 0' }}>
            <div className="check" style={{ width: 56, height: 56, border: '1px solid var(--ink)', borderRadius: '50%', display: 'grid', placeItems: 'center' }}>
              <svg width="22" height="14" viewBox="0 0 22 14" fill="none">
                <path d="M1 6L8 13L21 1" stroke="currentColor" strokeWidth="1.5"/>
              </svg>
            </div>
            <h3 className="h3">{t.lead.successTitle}</h3>
            <p className="body body-muted">{t.dir === 'rtl' ? 'سنؤكد الموعد خلال يوم عمل.' : 'We will confirm the appointment within one business day.'}</p>
          </div>
        )}
      </div>
    </div>
  );
}

function WhatsAppFab() {
  return (
    <a className="wa-fab" href="https://wa.me/971523810148" target="_blank" rel="noopener" aria-label="WhatsApp the sales team">
      <svg width="22" height="22" viewBox="0 0 24 24" fill="none">
        <path d="M3 21l1.65-4.5A8 8 0 1 1 7.5 19.35L3 21z" stroke="currentColor" strokeWidth="1.4" strokeLinejoin="round"/>
        <path d="M9 9.5c.5 2 2 3.5 4 4l1-1c.4-.4 1-.5 1.4-.2l.9.5c.4.2.6.7.4 1.1-.5 1-1.6 1.6-2.7 1.4-2.6-.5-4.8-2.7-5.3-5.3-.2-1.1.4-2.2 1.4-2.7.4-.2.9 0 1.1.4l.5.9c.3.5.2 1-.2 1.4l-1 1z" fill="currentColor"/>
      </svg>
    </a>
  );
}

Object.assign(window, { Lead, BrochureModal, ViewingModal, WhatsAppFab });
