// ─────────────────────────────────────────────────────────────────────────────
// WORLDLINESS — Contact / Lead Capture Form
// Saves to Supabase `leads` table on submit.
// Supabase client is shared via window.getSB() from supabase-client.jsx
// See SUPABASE_SETUP.sql for table schema and RLS policies.
// ─────────────────────────────────────────────────────────────────────────────

function formatPhoneInput(value) {
  const digits = value.replace(/\D/g, '').slice(0, 10);
  if (digits.length <= 3) return digits;
  if (digits.length <= 6) return `(${digits.slice(0, 3)}) ${digits.slice(3)}`;
  return `(${digits.slice(0, 3)}) ${digits.slice(3, 6)}-${digits.slice(6)}`;
}

function isValidNorthAmericanPhone(value) {
  return value.replace(/\D/g, '').length === 10;
}

function FinalCTA() {
  const [sent,    setSent]    = useState(false);
  const [error,   setError]   = useState('');
  const [loading, setLoading] = useState(false);

  const [name,        setName]        = useState('');
  const [phone,       setPhone]       = useState('');
  const [email,       setEmail]       = useState('');
  const [projectType, setProjectType] = useState('');
  const [area,        setArea]        = useState('');
  const [message,     setMessage]     = useState('');

  const hasPlaceholderOfficePhone = /555/.test(window.CONTACT.phone || '') || /555/.test(window.CONTACT.phoneHref || '');

  const submit = async (e) => {
    e.preventDefault();
    setError('');

    const normalizedPhone = formatPhoneInput(phone);
    if (!isValidNorthAmericanPhone(normalizedPhone)) {
      setError('Please enter a valid 10-digit phone number.');
      return;
    }

    setLoading(true);
    try {
      const { error: sbError } = await window.getSB().from('leads').insert({
        name,
        phone: normalizedPhone,
        email,
        project_type: projectType,
        area,
        message,
        source: 'website-contact-form',
      });
      if (sbError) throw new Error(sbError.message);
      setSent(true);
    } catch (ex) {
      console.error('Lead save failed:', ex.message);
      setError('Something went wrong. Please call us directly or try again.');
    } finally {
      setLoading(false);
    }
  };

  return (
    <section className="final" id="contact">
      <div className="container">
        <div className="final-wrap">
          <Reveal>
            <Eyebrow>Start Your Project</Eyebrow>
            <h2>Your home <em style={{fontStyle:'italic', color:'var(--bronze-light)', fontWeight:500}}>deserves</em> to be done right.</h2>
            <p>Tell us about your project. We'll respond within 24 hours with next steps. Site visit within 48 hours — no cost, no commitment.</p>
            <ul className="guarantees">
              <li><Icon name="check" size={18}/> Free on-site consultation within 48 hours</li>
              <li><Icon name="check" size={18}/> Detailed written proposal in 3 business days</li>
              <li><Icon name="check" size={18}/> Fully licensed & WCB insured — Vancouver, BC</li>
              <li><Icon name="check" size={18}/> Single point of contact from start to finish</li>
            </ul>
          </Reveal>

          <Reveal>
            <div className="form-card">
              {sent ? (
                <div className="form-success">
                  <div className="check"><Icon name="check" size={28}/></div>
                  <h3>Request received.</h3>
                  <p>
                    We'll be in touch within 24 hours.
                    {hasPlaceholderOfficePhone ? (
                      <> For urgent inquiries, email <a href={window.CONTACT.emailHref}>{window.CONTACT.email}</a>. </>
                    ) : (
                      <> For urgent inquiries, call <a href={window.CONTACT.phoneHref}>{window.CONTACT.phone}</a>. </>
                    )}
                  </p>
                </div>
              ) : (
                <form onSubmit={submit}>
                  <div className="head">Request a free consultation</div>
                  <div className="sub">We respond within 24 hours.</div>

                  {error && <div className="form-submit-error">{error}</div>}

                  <div className="row two">
                    <div>
                      <label>Full Name</label>
                      <input required type="text" placeholder="Jane Smith" value={name} onChange={e => setName(e.target.value)} />
                    </div>
                    <div>
                      <label>Phone</label>
                      <input
                        required
                        type="tel"
                        inputMode="tel"
                        autoComplete="tel"
                        placeholder="(604) 123-4567"
                        value={phone}
                        onChange={e => setPhone(formatPhoneInput(e.target.value))}
                      />
                    </div>
                  </div>
                  <div className="row">
                    <div>
                      <label>Email</label>
                      <input required type="email" placeholder="you@email.com" value={email} onChange={e => setEmail(e.target.value)} />
                    </div>
                  </div>
                  <div className="row two">
                    <div>
                      <label>Project Type</label>
                      <select required value={projectType} onChange={e => setProjectType(e.target.value)}>
                        <option value="" disabled>Select…</option>
                        {window.SERVICE_OPTIONS.map(o => <option key={o}>{o}</option>)}
                      </select>
                    </div>
                    <div>
                      <label>Area / Neighbourhood</label>
                      <input type="text" placeholder="Burnaby, North Van…" value={area} onChange={e => setArea(e.target.value)} />
                    </div>
                  </div>
                  <div className="row">
                    <div>
                      <label>Tell us about the project</label>
                      <textarea placeholder="Scope, rough timeline, anything else…" value={message} onChange={e => setMessage(e.target.value)} />
                    </div>
                  </div>
                  <button type="submit" className="btn btn-primary" disabled={loading}>
                    {loading ? 'Sending…' : 'Send Request'}
                    {!loading && <Icon name="arrow" size={14} />}
                  </button>
                  <p className="fine">No spam. No pressure.</p>
                </form>
              )}
            </div>
          </Reveal>
        </div>
      </div>
    </section>
  );
}
window.FinalCTA = FinalCTA;
