// lead-modal.jsx — Lead capture modal with form validation + success state

function LeadModal({ lang, onClose }) {
  const c = window.CONTENT[lang].form;
  const levels = window.CONTENT[lang].levels.items;
  const [data, setData] = React.useState({
    parent: '', email: '', phone: '', child: '', age: '', level: '', note: '',
  });
  const [submitted, setSubmitted] = React.useState(false);
  const [errors, setErrors] = React.useState({});

  React.useEffect(() => {
    const k = (e) => { if (e.key === 'Escape') onClose(); };
    document.addEventListener('keydown', k);
    document.body.style.overflow = 'hidden';
    return () => { document.removeEventListener('keydown', k); document.body.style.overflow = ''; };
  }, [onClose]);

  const handleChange = (field, value) => {
    setData(d => ({ ...d, [field]: value }));
    if (errors[field]) setErrors(e => ({ ...e, [field]: null }));
  };

  const submit = (e) => {
    e.preventDefault();
    const err = {};
    if (!data.parent.trim()) err.parent = true;
    if (!/^.+@.+\..+$/.test(data.email)) err.email = true;
    if (data.phone.replace(/\D/g, '').length < 8) err.phone = true;
    if (!data.child.trim()) err.child = true;
    if (Object.keys(err).length) { setErrors(err); return; }
    setSubmitted(true);
  };

  const inputBase = {
    width: '100%',
    padding: '12px 14px',
    background: 'var(--bg-soft)',
    border: '2px solid var(--line)',
    borderRadius: 12,
    fontFamily: 'inherit',
    fontSize: 15,
    color: 'var(--ink)',
    outline: 'none',
  };
  const errStyle = { borderColor: '#FF3030', background: 'rgba(255,48,48,0.06)' };
  const labelStyle = {
    fontSize: 12,
    fontWeight: 700,
    textTransform: 'uppercase',
    letterSpacing: '0.06em',
    color: 'var(--ink-soft)',
    marginBottom: 6,
    display: 'block',
  };

  return (
    <div className="modal-back" onClick={onClose}>
      <div className="modal" onClick={e => e.stopPropagation()}>
        <button onClick={onClose} aria-label={c.close} style={{
          position: 'absolute',
          top: 16, right: 16,
          width: 36, height: 36,
          background: 'var(--bg-soft)',
          border: '2px solid var(--line)',
          borderRadius: '50%',
          display: 'flex', alignItems: 'center', justifyContent: 'center',
          color: 'var(--ink)',
        }}>
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="3" strokeLinecap="round">
            <path d="M 6 6 L 18 18 M 18 6 L 6 18" />
          </svg>
        </button>

        {!submitted ? (
          <>
            <div style={{ marginBottom: 24 }}>
              <div style={{
                display: 'inline-block',
                padding: '4px 12px',
                background: 'var(--coral)',
                color: '#fff',
                borderRadius: 999,
                border: '2px solid var(--line)',
                fontSize: 11,
                fontWeight: 700,
                letterSpacing: '0.08em',
                textTransform: 'uppercase',
                marginBottom: 14,
              }}>
                Future AI Creators
              </div>
              <h3 style={{ fontSize: 28, marginBottom: 8, lineHeight: 1.1 }}>{c.title}</h3>
              <p style={{ color: 'var(--ink-soft)', fontSize: 15 }}>{c.sub}</p>
            </div>

            <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
              <div>
                <label style={labelStyle}>{c.parent}</label>
                <input style={{...inputBase, ...(errors.parent ? errStyle : {})}}
                       value={data.parent} onChange={e => handleChange('parent', e.target.value)} placeholder="Ayşe Yılmaz"/>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                <div>
                  <label style={labelStyle}>{c.email}</label>
                  <input type="email" style={{...inputBase, ...(errors.email ? errStyle : {})}}
                         value={data.email} onChange={e => handleChange('email', e.target.value)} placeholder="ayse@email.com"/>
                </div>
                <div>
                  <label style={labelStyle}>{c.phone}</label>
                  <input style={{...inputBase, ...(errors.phone ? errStyle : {})}}
                         value={data.phone} onChange={e => handleChange('phone', e.target.value)} placeholder="+90 5__ ___ __ __"/>
                </div>
              </div>

              <div style={{ display: 'grid', gridTemplateColumns: '2fr 1fr', gap: 12 }}>
                <div>
                  <label style={labelStyle}>{c.child}</label>
                  <input style={{...inputBase, ...(errors.child ? errStyle : {})}}
                         value={data.child} onChange={e => handleChange('child', e.target.value)} placeholder="Ada"/>
                </div>
                <div>
                  <label style={labelStyle}>{c.age}</label>
                  <input type="number" min="6" max="80" style={inputBase}
                         value={data.age} onChange={e => handleChange('age', e.target.value)} placeholder="9"/>
                </div>
              </div>

              <div>
                <label style={labelStyle}>{c.level}</label>
                <select style={{...inputBase, appearance: 'none', backgroundImage: 'url("data:image/svg+xml;utf8,<svg xmlns=\'http://www.w3.org/2000/svg\' viewBox=\'0 0 24 24\' fill=\'none\' stroke=\'%23221934\' stroke-width=\'2.5\' stroke-linecap=\'round\'><path d=\'M 6 9 L 12 15 L 18 9\'/></svg>")', backgroundRepeat: 'no-repeat', backgroundPosition: 'right 14px center', backgroundSize: '20px', paddingRight: 40 }}
                        value={data.level} onChange={e => handleChange('level', e.target.value)}>
                  <option value="">{lang === 'tr' ? 'Seviye seç…' : 'Pick a level…'}</option>
                  {levels.map((l, i) => (
                    <option key={i} value={l.name}>{l.name} · {l.age}</option>
                  ))}
                </select>
              </div>

              <div>
                <label style={labelStyle}>{c.note}</label>
                <textarea rows="3" style={{...inputBase, resize: 'vertical', minHeight: 64, fontFamily: 'inherit'}}
                          value={data.note} onChange={e => handleChange('note', e.target.value)}
                          placeholder={lang === 'tr' ? 'Çocuğunuz hakkında bilmemizi istediğiniz bir şey…' : 'Anything we should know about your child…'}/>
              </div>

              <button type="submit" className="btn" style={{
                marginTop: 6,
                fontSize: 16,
                padding: '15px 24px',
                width: '100%',
                justifyContent: 'center',
              }}>
                {c.submit}
                <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round">
                  <path d="M5 12 H 19 M 13 6 L 19 12 L 13 18"/>
                </svg>
              </button>

              <p style={{
                fontSize: 11.5,
                color: 'var(--ink-soft)',
                textAlign: 'center',
                lineHeight: 1.5,
                marginTop: 4,
              }}>{c.privacy}</p>
            </form>
          </>
        ) : (
          <SuccessState lang={lang} onClose={onClose} c={c} />
        )}
      </div>
    </div>
  );
}

function SuccessState({ lang, onClose, c }) {
  return (
    <div style={{ textAlign: 'center', padding: '12px 8px' }}>
      <div style={{
        width: 80, height: 80,
        background: 'var(--leaf)',
        border: '2.5px solid var(--line)',
        borderRadius: '50%',
        margin: '0 auto 24px',
        display: 'flex', alignItems: 'center', justifyContent: 'center',
        boxShadow: '0 6px 0 var(--line)',
        animation: 'pop .35s cubic-bezier(.2,.9,.3,1.6)',
      }}>
        <svg viewBox="0 0 32 32" width="40" height="40" fill="none" stroke="#fff" strokeWidth="4.5" strokeLinecap="round" strokeLinejoin="round">
          <path d="M 6 17 L 13 24 L 26 9"/>
        </svg>
      </div>
      <h3 style={{ fontSize: 32, marginBottom: 12 }}>{c.success}</h3>
      <p style={{ color: 'var(--ink-soft)', fontSize: 16, marginBottom: 28, maxWidth: 380, margin: '0 auto 28px' }}>
        {c.successBody}
      </p>
      <div style={{ display: 'flex', gap: 12, justifyContent: 'center', flexWrap: 'wrap' }}>
        <a href="#" className="btn">
          {lang === 'tr' ? 'Veli Kılavuzu İndir' : 'Download Parent Guide'}
          <svg viewBox="0 0 24 24" width="16" height="16" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round">
            <path d="M 12 3 V 16 M 6 11 L 12 17 L 18 11 M 4 21 H 20"/>
          </svg>
        </a>
        <button onClick={onClose} className="btn btn-ghost">{c.close}</button>
      </div>
    </div>
  );
}

Object.assign(window, { LeadModal });
