/* Contact form — fully functional mock */

const ROLES = [
  "Investor",
  "Property Operator",
  "Strategic Partner",
  "Pilot Customer",
  "Other",
];

function ContactForm() {
  const [values, setValues] = React.useState({
    firstName: "", lastName: "", email: "", org: "", role: "", message: "",
  });
  const [errors, setErrors] = React.useState({});
  const [submitted, setSubmitted] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);
  const [serverError, setServerError] = React.useState(null);

  function setV(k, v) {
    setValues((s) => ({ ...s, [k]: v }));
    if (errors[k]) setErrors((e) => ({ ...e, [k]: null }));
    if (serverError) setServerError(null);
  }

  function validate() {
    const er = {};
    if (!values.firstName.trim()) er.firstName = "Required";
    if (!values.lastName.trim()) er.lastName = "Required";
    if (!values.email.trim()) er.email = "Required";
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) er.email = "Invalid email";
    if (!values.org.trim()) er.org = "Required";
    if (!values.role) er.role = "Select one";
    return er;
  }

  async function onSubmit(e) {
    e.preventDefault();
    const er = validate();
    if (Object.keys(er).length) { setErrors(er); return; }
    setSubmitting(true);
    setServerError(null);

    try {
      const resp = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values),
      });
      const data = await resp.json().catch(() => ({}));
      if (!resp.ok || !data.ok) {
        throw new Error(data.error || 'Send failed');
      }
      setSubmitted(true);
    } catch (err) {
      setServerError(err.message || 'Something went wrong. Please try again.');
    } finally {
      setSubmitting(false);
    }
  }

  if (submitted) {
    return (
      <form className="form" onSubmit={(e) => e.preventDefault()}>
        <span className="br tl"></span><span className="br tr"></span>
        <span className="br bl"></span><span className="br br_"></span>
        <div className="form__success">
          <div className="check">
            <span className="ms" style={{ color: '#fff', fontSize: 28 }}>check</span>
          </div>
          <h3>Message sent<span className="bode-stop"></span></h3>
          <p>Thank you, {values.firstName}. Your enquiry has landed with the BODE team — we'll be in touch within two working days.</p>
          <div style={{ fontFamily: 'var(--font-mono)', fontSize: 11, letterSpacing: '0.14em', textTransform: 'uppercase', color: 'var(--color-coral)' }}>
            REF · {Math.random().toString(36).slice(2, 8).toUpperCase()}
          </div>
        </div>
      </form>
    );
  }

  return (
    <form className="form" onSubmit={onSubmit} noValidate>
      <span className="br tl"></span><span className="br tr"></span>
      <span className="br bl"></span><span className="br br_"></span>

      <div className={`field ${errors.firstName ? 'error' : ''}`}>
        <label>First Name <span className="req">*</span></label>
        <input value={values.firstName} onChange={e => setV('firstName', e.target.value)} />
        <div className="field__error">{errors.firstName || ''}</div>
      </div>
      <div className={`field ${errors.lastName ? 'error' : ''}`}>
        <label>Last Name <span className="req">*</span></label>
        <input value={values.lastName} onChange={e => setV('lastName', e.target.value)} />
        <div className="field__error">{errors.lastName || ''}</div>
      </div>
      <div className={`field ${errors.email ? 'error' : ''}`}>
        <label>Work Email <span className="req">*</span></label>
        <input type="email" value={values.email} onChange={e => setV('email', e.target.value)} />
        <div className="field__error">{errors.email || ''}</div>
      </div>
      <div className={`field ${errors.org ? 'error' : ''}`}>
        <label>Organisation <span className="req">*</span></label>
        <input value={values.org} onChange={e => setV('org', e.target.value)} />
        <div className="field__error">{errors.org || ''}</div>
      </div>

      <div className={`field field--full ${errors.role ? 'error' : ''}`}>
        <label>I am interested as a… <span className="req">*</span></label>
        <div className="role-options">
          {ROLES.map(r => (
            <button type="button" key={r}
              className={`opt ${values.role === r ? 'is-active' : ''}`} data-magnetic
              onClick={() => setV('role', r)}>{r}</button>
          ))}
        </div>
        <div className="field__error">{errors.role || ''}</div>
      </div>

      <div className="field field--full">
        <label>Message <span style={{ color: 'var(--text-tertiary)' }}>(optional)</span></label>
        <textarea value={values.message} onChange={e => setV('message', e.target.value)} placeholder="Tell us a little about your context."></textarea>
        <div className="field__error"></div>
      </div>

      <div className="form__submit">
        <div className="form__hint">
          {serverError ? (
            <span style={{ color: 'var(--color-red)' }}>{serverError}</span>
          ) : (
            'All fields marked * required'
          )}
        </div>
        <button type="submit" className="submit-btn" disabled={submitting}>
          <span>{submitting ? 'Sending…' : 'Send Enquiry'}</span>
          <span className="ms arrow">arrow_outward</span>
        </button>
      </div>
    </form>
  );
}

function Contact() {
  return (
    <section id="contact" className="section contact" data-screen-label="06 Contact">
      <div className="container">
        <div className="contact__head">
          <div className="reveal">
            <div className="eyebrow"><span className="num">06</span> <span className="bar"></span> Get in Touch</div>
            <h2 className="contact__title">Join us in<br/>shaping the<br/>future<span className="bode-stop"></span></h2>
          </div>
          <p className="contact__intro reveal">
            Whether you're an investor, a property operator, a strategic partner, or a potential pilot customer, we'd love to hear from you. A full deck and demo are available on request.
          </p>
        </div>
        <div className="reveal"><ContactForm /></div>
      </div>
    </section>
  );
}

window.Contact = Contact;
