// modal.jsx - multi-step invite request form
const { useState: useMS, useEffect: useME, useRef: useMR } = React;

function Field({ label, children, required, error, hint }) {
  return (
    <label style={{ display: 'block' }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline', marginBottom: 7 }}>
        <span style={{ fontSize: 13, fontWeight: 600, color: 'var(--ink)' }}>{label}{required && <span style={{ color: 'var(--gold)' }}> *</span>}</span>
        {error ? <span style={{ fontSize: 11.5, color: 'oklch(0.62 0.18 25)', fontWeight: 600 }}>{error}</span>
               : hint ? <span style={{ fontSize: 11.5, color: 'var(--ink-faint)' }}>{hint}</span> : null}
      </div>
      {children}
    </label>
  );
}

const inputStyle = (err) => ({
  width: '100%', fontFamily: 'inherit', fontSize: 15, color: 'var(--ink)',
  background: 'var(--bg)', border: `1px solid ${err ? 'oklch(0.65 0.16 25)' : 'var(--line-strong)'}`,
  borderRadius: 11, padding: '12px 14px', outline: 'none', transition: 'border-color .2s, box-shadow .2s',
});

const TextInput = React.forwardRef(({ value, onChange, err, ...rest }, ref) => {
  return <input ref={ref} value={value} onChange={onChange} style={inputStyle(err)}
    onFocus={e => { e.target.style.borderColor = 'var(--gold)'; e.target.style.boxShadow = '0 0 0 3px var(--gold-soft)'; }}
    onBlur={e => { e.target.style.borderColor = err ? 'oklch(0.65 0.16 25)' : 'var(--line-strong)'; e.target.style.boxShadow = 'none'; }}
    {...rest} />;
});

const SOCIALS = [['instagram', 'Instagram', '@handle'], ['facebook', 'Facebook', 'facebook.com/…'], ['tiktok', 'TikTok', '@handle'], ['youtube', 'YouTube', 'youtube.com/@…'], ['linkedin', 'LinkedIn', 'linkedin.com/in/…'], ['x', 'X (Twitter)', '@handle']];
const HEARD = ['ChatGPT', 'Google', 'Socials', 'Friend', 'Other'];

function InviteModal() {
  const [open, setOpen] = useMS(false);
  const [step, setStep] = useMS(0); // 0,1 form ; 2 success
  const [f, setF] = useMS({ name: '', agency: '', email: '', phone: '', website: '', volume: '', country: '', socials: {}, heard: '', heardOther: '' });
  const [errs, setErrs] = useMS({});
  const [loading, setLoading] = useMS(false);
  const firstRef = useMR(null);

  useME(() => {
    const h = (e) => { setF(p => ({ ...p, website: e.detail?.website || p.website })); setStep(0); setErrs({}); setOpen(true); };
    window.addEventListener('open-invite', h);
    return () => window.removeEventListener('open-invite', h);
  }, []);

  useME(() => {
    document.body.style.overflow = open ? 'hidden' : '';
    if (open) setTimeout(() => firstRef.current && firstRef.current.focus(), 320);
    const esc = (e) => { if (e.key === 'Escape') setOpen(false); };
    window.addEventListener('keydown', esc);
    return () => window.removeEventListener('keydown', esc);
  }, [open]);

  const set = (k, v) => { setF(p => ({ ...p, [k]: v })); if (errs[k]) setErrs(p => ({ ...p, [k]: undefined })); };
  const setVolume = (v) => set('volume', v.replace(/[^0-9]/g, ''));
  const setSocial = (k, v) => setF(p => ({ ...p, socials: { ...p.socials, [k]: v } }));

  const validateStep0 = () => {
    const e = {};
    if (!f.name.trim()) e.name = 'Required';
    if (!f.agency.trim()) e.agency = 'Required';
    if (!f.email.trim()) e.email = 'Required';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(f.email.trim())) e.email = 'Enter a valid email';
    if (!f.phone.trim()) e.phone = 'Required';
    if (!f.website.trim()) e.website = 'Required';
    if (!f.volume.trim()) e.volume = 'Required';
    if (!f.country.trim()) e.country = 'Required';
    setErrs(e);
    return Object.keys(e).length === 0;
  };
  const validateStep1 = () => {
    const e = {};
    if (!f.heard) e.heard = 'Please choose one';
    setErrs(e);
    return Object.keys(e).length === 0;
  };

  const next = () => { if (validateStep0()) setStep(1); };
  const submit = async () => {
    if (!validateStep1()) return;
    setLoading(true);
    try {
      const res = await fetch('https://my.realtymarketing.app/api/invite-request', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(f),
      });
      const data = await res.json();
      if (data.success) {
        setStep(2);
      } else {
        setErrs(p => ({ ...p, submit: data.error || 'Failed to submit' }));
      }
    } catch (err) {
      setErrs(p => ({ ...p, submit: 'Network error. Please try again.' }));
    } finally {
      setLoading(false);
    }
  };

  const close = () => setOpen(false);

  if (!open) return null;

  const progress = step === 0 ? 50 : 100;

  return (
    <div onMouseDown={close} style={{
      position: 'fixed', inset: 0, zIndex: 1000, display: 'flex', alignItems: 'center', justifyContent: 'center',
      padding: 20, background: 'oklch(0.15 0.02 263 / 0.55)', backdropFilter: 'blur(6px)', WebkitBackdropFilter: 'blur(6px)',
      animation: 'fade .25s ease',
    }}>
      <div onMouseDown={e => e.stopPropagation()} className="card" role="dialog" aria-modal="true" style={{
        width: '100%', maxWidth: 560, maxHeight: '92vh', overflowY: 'auto', borderRadius: 22, position: 'relative',
        boxShadow: 'var(--shadow-lg)', animation: 'pop .32s cubic-bezier(.2,.8,.3,1)',
      }}>
        {/* header */}
        <div style={{ position: 'sticky', top: 0, background: 'var(--card)', borderBottom: '1px solid var(--line)', borderRadius: '22px 22px 0 0', padding: '22px 26px 0', zIndex: 2 }}>
          <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'flex-start' }}>
            <div>
              <Logo size={18} />
              <h3 className="serif" style={{ fontSize: 27, marginTop: 10 }}>
                {step === 2 ? 'You\u2019re on the list' : 'Request your invite code'}
              </h3>
            </div>
            <button onClick={close} aria-label="Close" style={{ background: 'var(--bg-2)', border: '1px solid var(--line)', borderRadius: 9, width: 34, height: 34, cursor: 'pointer', color: 'var(--ink-soft)', fontSize: 18, lineHeight: 1, display: 'flex', alignItems: 'center', justifyContent: 'center' }}>×</button>
          </div>
          {step < 2 && (
            <div style={{ marginTop: 16, marginBottom: 0 }}>
              <div style={{ display: 'flex', justifyContent: 'space-between', fontSize: 12, color: 'var(--ink-faint)', marginBottom: 7, fontWeight: 600 }}>
                <span style={{ color: 'var(--gold)' }}>Step {step + 1} of 2 · {step === 0 ? 'About you' : 'Your presence'}</span>
              </div>
              <div style={{ height: 4, background: 'var(--line)', borderRadius: 99, overflow: 'hidden', marginBottom: 4 }}>
                <div style={{ height: '100%', width: progress + '%', background: 'var(--gold)', borderRadius: 99, transition: 'width .4s cubic-bezier(.3,.7,.3,1)' }} />
              </div>
            </div>
          )}
        </div>

        <div style={{ padding: '24px 26px 28px' }}>
          {step === 0 && (
            <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 16 }}>
              <div style={{ gridColumn: '1 / -1' }}>
                <Field label="Full name" required error={errs.name}>
                  <TextInput ref={firstRef} value={f.name} err={errs.name} onChange={e => set('name', e.target.value)} placeholder="Jordan Avery" />
                </Field>
              </div>
              <div style={{ gridColumn: '1 / -1' }}>
                <Field label="Agency / brokerage name" required error={errs.agency}>
                  <TextInput value={f.agency} err={errs.agency} onChange={e => set('agency', e.target.value)} placeholder="Avery & Co. Realty" />
                </Field>
              </div>
              <Field label="Email" required error={errs.email}>
                <TextInput type="email" value={f.email} err={errs.email} onChange={e => set('email', e.target.value)} placeholder="you@agency.com" />
              </Field>
              <Field label="Phone" required error={errs.phone}>
                <TextInput type="tel" value={f.phone} err={errs.phone} onChange={e => set('phone', e.target.value)} placeholder="+1 (555) 000-0000" />
              </Field>
              <div style={{ gridColumn: '1 / -1' }}>
                <Field label="Website" required error={errs.website} hint="We import listings from here">
                  <TextInput value={f.website} err={errs.website} onChange={e => set('website', e.target.value)} placeholder="yourrealestate.com" />
                </Field>
              </div>
              <div style={{ gridColumn: '1 / -1' }}>
                <Field label="Monthly listings volume" required error={errs.volume} hint="Approx. number of listings / month">
                  <TextInput value={f.volume} err={errs.volume} onChange={e => setVolume(e.target.value)} inputMode="numeric" placeholder="e.g. 25" />
                </Field>
              </div>
              <div style={{ gridColumn: '1 / -1' }}>
                <Field label="Country" required error={errs.country}>
                  <TextInput value={f.country} err={errs.country} onChange={e => set('country', e.target.value)} placeholder="e.g. United States, Canada, Australia" />
                </Field>
              </div>
            </div>
          )}

          {step === 1 && (
            <div>
              <div style={{ marginBottom: 22 }}>
                <div style={{ fontSize: 13, fontWeight: 600, marginBottom: 4 }}>Social media links <span style={{ color: 'var(--ink-faint)', fontWeight: 500 }}>· optional</span></div>
                <p style={{ fontSize: 12.5, color: 'var(--ink-faint)', marginBottom: 14 }}>Add any you&rsquo;d like us to know about.</p>
                <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }} className="social-grid">
                  {SOCIALS.map(([k, label, ph]) => (
                    <div key={k} style={{ display: 'flex', alignItems: 'center', gap: 9, background: 'var(--bg)', border: '1px solid var(--line-strong)', borderRadius: 11, padding: '0 12px' }}>
                      <span style={{ color: 'var(--ink-soft)', flexShrink: 0 }}><Brand name={k} size={18} /></span>
                      <input value={f.socials[k] || ''} onChange={e => setSocial(k, e.target.value)} placeholder={label}
                        style={{ border: 'none', outline: 'none', background: 'transparent', fontFamily: 'inherit', fontSize: 14, color: 'var(--ink)', padding: '11px 0', width: '100%', minWidth: 0 }} />
                    </div>
                  ))}
                </div>
              </div>
              <Field label="How did you hear about us?" required error={errs.heard}>
                <div style={{ display: 'flex', flexWrap: 'wrap', gap: 9, marginTop: 2 }}>
                  {HEARD.map(h => {
                    const active = f.heard === h;
                    return (
                      <button key={h} onClick={() => set('heard', h)} type="button" style={{
                        fontFamily: 'inherit', fontSize: 14, fontWeight: 600, cursor: 'pointer',
                        padding: '10px 18px', borderRadius: 99,
                        border: `1px solid ${active ? 'var(--gold)' : 'var(--line-strong)'}`,
                        background: active ? 'var(--gold-soft)' : 'var(--bg)',
                        color: active ? 'var(--gold)' : 'var(--ink-soft)', transition: 'all .18s',
                      }}>{h}</button>
                    );
                  })}
                </div>
              </Field>
              {f.heard === 'Other' && (
                <div style={{ marginTop: 14 }}>
                  <TextInput value={f.heardOther} onChange={e => set('heardOther', e.target.value)} placeholder="Tell us where…" />
                </div>
              )}
            </div>
          )}

          {step === 2 && (
            <div style={{ textAlign: 'center', padding: '12px 0 8px' }}>
              <div style={{ width: 76, height: 76, borderRadius: 99, background: 'var(--gold-soft)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 22px', color: 'var(--gold)' }}>
                <Icon name="check" size={38} stroke={2} />
              </div>
              <p style={{ color: 'var(--ink-soft)', fontSize: 16.5, lineHeight: 1.6, maxWidth: 400, margin: '0 auto 28px' }}>
                Your request was received &amp; our team will reach out to you shortly.
              </p>
              <button className="btn btn-primary btn-lg" onClick={close}>Done</button>
            </div>
          )}
        </div>

        {/* footer actions */}
        {step < 2 && (
          <div style={{ position: 'sticky', bottom: 0, background: 'var(--card)', borderTop: '1px solid var(--line)', borderRadius: '0 0 22px 22px', padding: '16px 26px', display: 'flex', justifyContent: 'space-between', alignItems: 'center', gap: 12 }}>
            {step === 0
              ? <span style={{ fontSize: 12.5, color: 'var(--ink-faint)' }}>Free · No credit card</span>
              : <button className="btn btn-ghost btn-sm" onClick={() => { setErrs({}); setStep(0); }}>Back</button>}
            {errs.submit && step === 1 && (
              <div style={{ flex: 1, background: '#fee', border: '1px solid #fcc', borderRadius: 8, padding: '10px 14px', color: '#c33', fontSize: 13 }}>
                {errs.submit}
              </div>
            )}
            {step === 0
              ? <button className="btn btn-primary" onClick={next}>Continue <Icon name="arrow" size={17} /></button>
              : <button className="btn btn-gold" onClick={submit} disabled={loading}>
                  {loading ? 'Submitting...' : 'Submit request'} <Icon name="check" size={17} />
                </button>}
          </div>
        )}
      </div>
      <style>{`
        @keyframes fade{ from{opacity:0} to{opacity:1} }
        @keyframes pop{ from{opacity:0; transform: translateY(16px) scale(.98)} to{opacity:1; transform:none} }
        @media (max-width: 480px){ .social-grid{ grid-template-columns: 1fr !important; } }
      `}</style>
    </div>
  );
}

Object.assign(window, { InviteModal });
