const {
  HexGrid, SiteNav, SiteFooter, PageShell,
} = window.GS;

const INTERESTS = [
  ['absence-management', 'Absence Management'],
  ['recruitment-systems', 'Recruitment Systems'],
  ['agency-operations', 'Agency Operations'],
  ['specialist-software', 'Specialist Software'],
  ['general', 'Not Sure / General Enquiry'],
];

const EMAIL = 'cam@gsolutions.org.uk';

function ContactForm() {
  const initial = React.useMemo(() => {
    const value = new URLSearchParams(window.location.search).get('interest') || '';
    return INTERESTS.some(([id]) => id === value) ? value : '';
  }, []);
  const [interest, setInterest] = React.useState(initial);
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState(null);
  const [sending, setSending] = React.useState(false);

  async function onSubmit(event) {
    event.preventDefault();
    const form = event.currentTarget;
    const data = new FormData(form);
    const values = {
      name: String(data.get('name') || '').trim(),
      company: String(data.get('company') || '').trim(),
      email: String(data.get('email') || '').trim(),
      phone: String(data.get('phone') || '').trim(),
      interest: String(data.get('interest') || '').trim(),
      details: String(data.get('details') || '').trim(),
      company_website: String(data.get('company_website') || '').trim(),
    };
    const next = {};
    if (!values.name) next.name = 'Enter your full name.';
    if (!values.company) next.company = 'Enter your company name.';
    if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email)) next.email = 'Enter a valid business email.';
    if (!values.interest) next.interest = 'Choose an area of interest.';
    if (values.details.length < 10) next.details = 'Describe the requirement in a sentence or two.';
    setErrors(next);
    if (Object.keys(next).length) {
      setStatus(null);
      const field = form.querySelector(`[name="${Object.keys(next)[0]}"]`);
      if (field) field.focus();
      return;
    }

    setSending(true);
    setStatus(null);
    try {
      const response = await fetch('/api/enquiry', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(values),
      });
      const payload = await response.json().catch(() => ({}));
      if (!response.ok || !payload.ok) {
        if (payload.errors) setErrors(payload.errors);
        setStatus({
          type: 'error',
          text: payload.error || `The enquiry was not sent. Please email ${EMAIL} directly.`,
        });
        return;
      }
      form.reset();
      setInterest(initial);
      setErrors({});
      setStatus({
        type: 'ok',
        text: `Your enquiry has been sent to ${EMAIL}. We will read it and reply to arrange a conversation.`,
      });
    } catch (error) {
      setStatus({
        type: 'error',
        text: `The enquiry was not sent. Please try again, or email ${EMAIL} directly.`,
      });
    } finally {
      setSending(false);
    }
  }

  const field = (name, label, child) => (
    <label className="field" key={name}>
      <span>{label}</span>
      {child}
      {errors[name] ? <span className="field-error" role="alert">{errors[name]}</span> : null}
    </label>
  );

  return (
    <form className="form" onSubmit={onSubmit} noValidate>
      {field('name', 'Full name', (
        <input name="name" type="text" autoComplete="name" aria-invalid={errors.name ? 'true' : 'false'} className={errors.name ? 'input-invalid' : undefined} />
      ))}
      {field('company', 'Company name', (
        <input name="company" type="text" autoComplete="organization" aria-invalid={errors.company ? 'true' : 'false'} className={errors.company ? 'input-invalid' : undefined} />
      ))}
      {field('email', 'Business email', (
        <input name="email" type="email" autoComplete="email" aria-invalid={errors.email ? 'true' : 'false'} className={errors.email ? 'input-invalid' : undefined} />
      ))}
      {field('phone', 'Phone number (optional)', (
        <input name="phone" type="tel" autoComplete="tel" />
      ))}
      {field('interest', 'Area of interest', (
        <select
          name="interest"
          value={interest}
          onChange={(event) => setInterest(event.target.value)}
          aria-invalid={errors.interest ? 'true' : 'false'}
          className={errors.interest ? 'input-invalid' : undefined}
        >
          <option value="">Select an area</option>
          {INTERESTS.map(([id, label]) => <option key={id} value={id}>{label}</option>)}
        </select>
      ))}
      {field('details', 'Description of requirements', (
        <textarea name="details" rows={6} aria-invalid={errors.details ? 'true' : 'false'} className={errors.details ? 'input-invalid' : undefined} />
      ))}
      <div className="hp" aria-hidden="true">
        <label>
          Company website
          <input name="company_website" type="text" tabIndex={-1} autoComplete="off" />
        </label>
      </div>
      <p className="body">
        Send Enquiry emails this form to {EMAIL}. It is not stored on the website.
        A privacy policy will be published separately. Until then, questions about your details can be sent to the same address.
      </p>
      <button className="btn-primary" type="submit" disabled={sending}>
        {sending ? 'Sending…' : 'Send Enquiry'}
      </button>
      {status ? (
        <p className={status.type === 'error' ? 'form-status is-error' : 'form-status'} role={status.type === 'error' ? 'alert' : 'status'}>
          {status.text}
        </p>
      ) : null}
    </form>
  );
}

const links = [
  ['Absence Management', '/absence-management.html'],
  ['Recruitment Systems', '/recruitment-systems.html'],
  ['Agency Operations', '/agency-operations.html'],
  ['Specialist Software', '/specialist-software.html'],
];

function ContactPage() {
  return (
    <PageShell>
      <SiteNav active="Contact" />
      <main id="content">
        <section className="section-hero">
          <div className="hero-glow" aria-hidden="true" />
          <HexGrid opacity={0.04} id="hex-contact" />
          <div className="split relative">
            <div>
              <div className="kicker">Contact</div>
              <h1 className="h1">Tell Us What You Want to Automate.</h1>
              <p className="lede">
                Whether you are looking to deploy Absence Management, improve your existing recruitment systems or commission specialist software, tell us about your requirements.
              </p>
              <ContactForm />
            </div>
            <div className="stack">
              <article className="card">
                <h2 className="h3">What happens next</h2>
                <p>When an enquiry reaches us, we read the requirement and reply to arrange a conversation. Scope, integrations and price are discussed from there. We do not publish a response-time promise.</p>
              </article>
              <article className="card">
                <h2 className="h3">Direct contact</h2>
                <p><a className="text-link" href="mailto:cam@gsolutions.org.uk">cam@gsolutions.org.uk</a></p>
                <p className="mt-8"><a className="text-link" href="tel:+447507064216">+44 75070 64216</a></p>
                <p className="mt-8 dim">124-128 City Road, London EC1V 2NX</p>
              </article>
              <article className="card">
                <h2 className="h3">Or start from a service</h2>
                <ul className="list">
                  {links.map(([label, href]) => (
                    <li key={href}><a className="text-link" href={href}>{label}</a></li>
                  ))}
                </ul>
              </article>
            </div>
          </div>
        </section>
      </main>
      <SiteFooter />
    </PageShell>
  );
}

ReactDOM.createRoot(document.getElementById('root')).render(<ContactPage />);
