// ConsultationForm.jsx — free-consultation intake. Posts to Supabase via the
// public submit_alex_narayan_lead() RPC. Validation + error display included.
function ConsultationForm() {
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [error, setError] = React.useState('');
  const [form, setForm] = React.useState({ name: '', phone: '', area: 'Personal Injury', msg: '' });

  const set = (k) => (e) => setForm({ ...form, [k]: e.target.value });

  const submit = async (e) => {
    e.preventDefault();
    setError('');
    if (!form.name.trim() || !form.phone.trim()) {
      setError('Name and phone are required.');
      return;
    }
    setSending(true);
    try {
      const res = await fetch(
        `${window.SUPABASE.url}/rest/v1/rpc/${window.SUPABASE.submitLeadFn}`,
        {
          method: 'POST',
          headers: {
            apikey: window.SUPABASE.publishableKey,
            'Content-Type': 'application/json',
            Prefer: 'return=representation',
          },
          body: JSON.stringify({
            p_name: form.name.trim(),
            p_phone: form.phone.trim(),
            p_area: form.area,
            p_message: form.msg.trim(),
          }),
        }
      );
      if (!res.ok) {
        const text = await res.text();
        throw new Error(text || `HTTP ${res.status}`);
      }
      setSent(true);
    } catch (err) {
      console.error('Lead submit failed:', err);
      setError('Something went wrong. Please call us at ' + FIRM.phone + '.');
    } finally {
      setSending(false);
    }
  };

  const labelS = { fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '0.72rem', letterSpacing: '0.08em', textTransform: 'uppercase', color: 'var(--ink-muted)', marginBottom: 7, display: 'block' };
  const inputS = { width: '100%', fontFamily: 'var(--font-sans)', fontSize: '0.98rem', color: 'var(--fg1)',
    background: 'var(--bg-elevated)', border: '1px solid var(--line-strong)', borderRadius: 'var(--radius-sm)', padding: '13px 15px', outline: 'none' };

  return (
    <section id="contact" style={{ background: 'var(--bg-base)', padding: '100px 32px' }}>
      <div style={{ maxWidth: 1060, margin: '0 auto', display: 'grid', gridTemplateColumns: '0.85fr 1fr', gap: 56, alignItems: 'center' }} className="form-grid">
        {/* Left rail */}
        <div>
          <div className="eyebrow" style={{ marginBottom: 14 }}>Free Consultation</div>
          <h2 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: 'clamp(2rem,3.4vw,2.8rem)', color: 'var(--navy-800)', lineHeight: 1.08, marginBottom: 20 }}>
            Talk to Alex about your case — at no cost.
          </h2>
          <p style={{ fontFamily: 'var(--font-sans)', fontSize: '1rem', lineHeight: 1.65, color: 'var(--fg2)', marginBottom: 30 }}>
            Tell us what happened. We respond within one business day, and your consultation is always confidential and free.
          </p>
          {[
            ['phone', FIRM.phone, FIRM.phoneHref],
            ['mail',  FIRM.email, 'mailto:' + FIRM.email],
            ['map-pin', FIRM.address, null],
          ].map(([ic, tx, href]) => (
            <div key={tx} style={{ display: 'flex', alignItems: 'center', gap: 13, marginBottom: 14 }}>
              <span style={{ width: 38, height: 38, borderRadius: 'var(--radius-sm)', background: 'var(--navy-800)', color: 'var(--brass-400)', display: 'flex', alignItems: 'center', justifyContent: 'center' }}>
                <Icon name={ic} size={18} />
              </span>
              {href
                ? <a href={href} style={{ fontFamily: 'var(--font-sans)', fontSize: '0.95rem', fontWeight: 600, color: 'var(--fg1)', textDecoration: 'none' }}>{tx}</a>
                : <span style={{ fontFamily: 'var(--font-sans)', fontSize: '0.95rem', fontWeight: 600, color: 'var(--fg1)' }}>{tx}</span>}
            </div>
          ))}
        </div>

        {/* Form */}
        <div style={{ background: '#fff', border: '1px solid var(--line)', borderTop: '2px solid var(--brass-500)', borderRadius: 'var(--radius-sm)', padding: '36px 32px', boxShadow: 'var(--shadow-md)' }}>
          {sent ? (
            <div style={{ textAlign: 'center', padding: '20px 0' }}>
              <div style={{ width: 60, height: 60, borderRadius: 'var(--radius-pill)', background: 'var(--navy-800)', color: 'var(--brass-400)', display: 'flex', alignItems: 'center', justifyContent: 'center', margin: '0 auto 18px' }}>
                <Icon name="check" size={28} />
              </div>
              <h3 style={{ fontFamily: 'var(--font-display)', fontWeight: 600, fontSize: '1.6rem', color: 'var(--navy-800)', marginBottom: 10 }}>
                Thank you.
              </h3>
              <p style={{ fontFamily: 'var(--font-sans)', fontSize: '1rem', lineHeight: 1.6, color: 'var(--fg2)', maxWidth: 380, margin: '0 auto' }}>
                Your request has reached Alex. We will respond within one business day. If you need help sooner, call <a href={FIRM.phoneHref} style={{ color: 'var(--crimson-600)', fontWeight: 700 }}>{FIRM.phone}</a>.
              </p>
            </div>
          ) : (
            <form onSubmit={submit}>
              <div style={{ marginBottom: 18 }}>
                <label style={labelS}>Your name</label>
                <input style={inputS} value={form.name} onChange={set('name')} required placeholder="Full name" />
              </div>
              <div style={{ marginBottom: 18 }}>
                <label style={labelS}>Phone</label>
                <input style={inputS} value={form.phone} onChange={set('phone')} required type="tel" placeholder="(555) 555-5555" />
              </div>
              <div style={{ marginBottom: 18 }}>
                <label style={labelS}>Practice area</label>
                <select style={inputS} value={form.area} onChange={set('area')}>
                  {PRACTICES.map((p) => <option key={p.slug}>{p.name}</option>)}
                  <option>Other</option>
                </select>
              </div>
              <div style={{ marginBottom: 22 }}>
                <label style={labelS}>What happened?</label>
                <textarea style={{ ...inputS, minHeight: 110, fontFamily: 'var(--font-sans)', resize: 'vertical' }} value={form.msg} onChange={set('msg')} placeholder="Briefly describe your situation." />
              </div>
              {error && (
                <div style={{ background: '#fef2f3', border: '1px solid var(--crimson-400)', color: 'var(--crimson-700)', padding: '10px 14px', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-sans)', fontSize: '0.88rem', marginBottom: 16 }}>
                  {error}
                </div>
              )}
              <button type="submit" disabled={sending} style={{ width: '100%', background: sending ? 'var(--navy-600)' : 'var(--crimson-600)', color: '#fff', padding: '15px 20px', border: 'none', borderRadius: 'var(--radius-sm)', fontFamily: 'var(--font-sans)', fontWeight: 700, fontSize: '0.95rem', letterSpacing: '0.04em', cursor: sending ? 'wait' : 'pointer', transition: 'background var(--dur-fast)' }}>
                {sending ? 'Sending…' : 'Schedule a free consultation'}
              </button>
              <p style={{ fontFamily: 'var(--font-sans)', fontSize: '0.78rem', color: 'var(--ink-muted)', textAlign: 'center', marginTop: 14, lineHeight: 1.5 }}>
                Your information is confidential. Submitting this form does not create an attorney-client relationship.
              </p>
            </form>
          )}
        </div>
      </div>
    </section>
  );
}
