/* Contact — the single conversion. Mock form: client-side validation + success
   state. Backend (HubSpot upsert + Resend notification to sales@) is a dev
   handoff — noted in-page and in the README. */
function ContactPage() {
  const empty = { first: '', last: '', title: '', org: '', email: '', phone: '', interests: [], message: '' };
  const [form, setForm] = React.useState(empty);
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [sending, setSending] = React.useState(false);
  const [serverError, setServerError] = React.useState('');

  const set = (k) => (e) => setForm((f) => ({ ...f, [k]: e.target.value }));
  const toggleInterest = (v) => setForm((f) => ({
    ...f,
    interests: f.interests.includes(v) ? f.interests.filter((x) => x !== v) : [...f.interests, v],
  }));

  /* Field order drives which invalid field gets focus, so the user is taken to the
     first problem rather than the last one the validator happened to write. */
  const fieldOrder = ['first', 'last', 'org', 'title', 'phone', 'email', 'interest'];

  const validate = () => {
    const err = {};
    if (!form.first.trim()) err.first = 'Please enter your first name.';
    if (!form.last.trim()) err.last = 'Please enter your last name.';
    if (!form.org.trim()) err.org = 'Please enter your Tribe or organization.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(form.email)) err.email = 'Please enter a valid email.';
    if (!form.interests.length) err.interest = 'Please choose at least one program.';
    return err;
  };

  const onSubmit = async (e) => {
    e.preventDefault();
    setServerError('');
    const err = validate();
    setErrors(err);
    if (Object.keys(err).length) {
      // Every required field sits above the button, so a silent failure reads as a
      // dead button. Say so at the button, and move focus to the first problem.
      setServerError('Please complete the highlighted fields above.');
      const firstBad = fieldOrder.find((k) => err[k]);
      try { document.getElementById('fr-' + firstBad).focus({ preventScroll: false }); } catch (_) {}
      return;
    }
    setSending(true);
    try {
      // POST to the Vercel serverless function (api/contact.js):
      // HubSpot upsert by email + Resend notification to sales@facerockinc.com.
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          ...form,
          name: (form.first + ' ' + form.last).trim(),
          firstname: form.first.trim(),
          lastname: form.last.trim(),
          interest: form.interests.map((v) => (interests.find(([s]) => s === v) || [v, v])[1]).join('; '),
          // HubSpot's tracking cookie. Passing it lets HubSpot stitch this person's
          // prior anonymous browsing to the contact record, and track them by name
          // on every future visit.
          hutk: (document.cookie.match(/(?:^|;\s*)hubspotutk=([^;]+)/) || [])[1] || '',
          pageUri: window.location.href,
          pageName: document.title,
        }),
      });
      if (res.ok) {
        try {
          if (window.FRTrack) {
            window.FRTrack.identify(form.email);
            window.FRTrack.event('contact_form_submit', { interest: form.interests.join('; ') });
          }
        } catch (_) {}
        setSent(true);
        try { window.scrollTo({ top: 0, behavior: 'smooth' }); } catch (_) {}
      } else if (res.status === 404) {
        // No backend present (static preview) — show success for the demo.
        setSent(true);
      } else {
        let msg = 'Something went wrong. Please email info@facerockinc.com.';
        try {
          const j = await res.json();
          if (j && j.errors) {
            setErrors(j.errors);
            // Never return silently: if a server error key has no matching field,
            // nothing would render and the button would look dead.
            const orphan = Object.keys(j.errors).filter((k) => !fieldOrder.includes(k));
            setServerError(orphan.length
              ? Object.values(j.errors).join(' ')
              : 'Please complete the highlighted fields above.');
            const firstBad = fieldOrder.find((k) => j.errors[k]);
            if (firstBad) { try { document.getElementById('fr-' + firstBad).focus(); } catch (_) {} }
            return;
          }
          if (j && j.error) msg = j.error;
        } catch (_) {}
        setServerError(msg);
      }
    } catch (_) {
      // Network error / no server (static preview) — demo success.
      setSent(true);
    } finally {
      setSending(false);
    }
  };

  /* Built from the canonical service list so the options never drift from Services. */
  const interests = [
    ...window.FR.services.map((s) => [s.slug, s.name]),
    ['unsure', 'Not sure yet'],
  ];

  return (
    <main>
      <section className="detail-hero page-banner">
        <img className="banner-img banner-legacy" src="assets/photos/face-rock-legacy-hero.jpg" alt="Face Rock rising from the surf, backlit by the afternoon sun" />
        <div className="banner-scrim banner-scrim-legacy"></div>
        <div className="wrap measure">
          <h1 style={{ color: 'var(--fr-off-white)' }}>Start a conversation.</h1>
          <p className="lead" style={{ marginTop: 20, color: 'rgba(240,237,228,.82)' }}>
            Tell us where your program stands. We'll reply with how we can help.<br />No pressure, no obligation.
          </p>
        </div>
        <div className="banner-ground"></div>
      </section>

      <section className="section-sm">
        <div className="wrap" style={{ maxWidth: 760 }}>
          <div>
            {sent ? (
              <div className="form-success">
                <h3>Thank you. Your message is on its way.</h3>
                <p style={{ margin: 0, color: 'var(--text-body)' }}>
                  A member of the Face Rock team will be in touch. For anything time-sensitive, reach us at info@facerockinc.com or 503-799-6824.
                </p>
                <button className="btn btn-ghost" style={{ marginTop: 16 }} onClick={() => { setForm(empty); setErrors({}); setSent(false); }}>
                  Send another message
                </button>
              </div>
            ) : (
              <form className="form-grid" onSubmit={onSubmit} noValidate>
                <div className="field">
                  <label>First name <span className="req">*</span></label>
                  <input id="fr-first" className={errors.first ? 'invalid' : ''} value={form.first} onChange={set('first')} placeholder="First name" />
                  {errors.first && <span className="err">{errors.first}</span>}
                </div>
                <div className="field">
                  <label>Last name <span className="req">*</span></label>
                  <input id="fr-last" className={errors.last ? 'invalid' : ''} value={form.last} onChange={set('last')} placeholder="Last name" />
                  {errors.last && <span className="err">{errors.last}</span>}
                </div>
                <div className="field">
                  <label>Tribe or organization <span className="req">*</span></label>
                  <input id="fr-org" className={errors.org ? 'invalid' : ''} value={form.org} onChange={set('org')} placeholder="Tribe or organization" />
                  {errors.org && <span className="err">{errors.org}</span>}
                </div>
                <div className="field">
                  <label>Title</label>
                  <input value={form.title} onChange={set('title')} placeholder="Your role" />
                </div>
                <div className="field">
                  <label>Phone</label>
                  <input type="tel" value={form.phone} onChange={set('phone')} placeholder="Optional" />
                </div>
                <div className="field">
                  <label>Email <span className="req">*</span></label>
                  <input id="fr-email" className={errors.email ? 'invalid' : ''} type="email" value={form.email} onChange={set('email')} placeholder="you@example.com" />
                  {errors.email && <span className="err">{errors.email}</span>}
                </div>
                <div className="field full">
                  <label>Program interest <span className="req">*</span><span className="field-hint">Select all that apply.</span></label>
                  <div className="checkgrid">
                    {interests.map(([v, l], i) => (
                      <label className="checkopt" key={v}>
                        <input id={i === 0 ? 'fr-interest' : undefined} type="checkbox" checked={form.interests.includes(v)} onChange={() => toggleInterest(v)} />
                        <span>{l}</span>
                      </label>
                    ))}
                  </div>
                  {errors.interest && <span className="err">{errors.interest}</span>}
                </div>
                <div className="field full">
                  <label>Message</label>
                  <textarea value={form.message} onChange={set('message')} placeholder="Optional — tell us a little about your program and where it stands." />
                </div>
                {serverError && (
                  <div className="field full">
                    <div style={{ background: 'rgba(193,99,74,.07)', border: '1px solid rgba(193,99,74,.35)', borderLeft: '4px solid var(--brand-accent)', borderRadius: 'var(--radius-md)', padding: '12px 16px', fontSize: 14, color: 'var(--brand-deep)' }}>{serverError}</div>
                  </div>
                )}
                <div className="field full">
                  <button type="submit" className="btn btn-primary" style={{ alignSelf: 'start' }} disabled={sending}>{sending ? 'Sending…' : 'Send message'}</button>
                </div>
                <div className="field full form-alt">
                  <p>
                    Or contact us direct at <a href="mailto:info@facerockinc.com">info@facerockinc.com</a> or <a href="tel:+15037996824">503-799-6824</a>.
                  </p>
                </div>
              </form>
            )}
          </div>
        </div>
      </section>
    </main>
  );
}
window.ContactPage = ContactPage;
