/* Contact — secure intake form. Posts JSON to /api/contact (Vercel serverless
 * function). Validation runs client-side for UX and again on the server for
 * trust. The hidden `website` field is a honeypot: bots fill every input
 * they see, so any submission that arrives with it populated is dropped
 * server-side. We never echo user input back into the page (XSS guard).
 *
 * Field limits mirror the server caps to give immediate feedback. If the
 * server rejects with a validation error we surface a generic message —
 * specific reasons stay server-side so probing for reflection oracles
 * doesn't pay off. */
const CONTACT_LIMITS = {
  name:    { min: 1,  max: 200 },
  email:   { min: 5,  max: 254 },
  company: { min: 0,  max: 200 },
  role:    { min: 0,  max: 100 },
  message: { min: 10, max: 5000 },
};

const SUBJECT_OPTIONS = [
  'General enquiry',
  'Demo request',
  'Press / research',
  'Partnership',
  'Methodology question',
  'Something else',
];

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[^\s@]{2,}$/;

const Contact = ({ setRoute }) => {
  const [form, setForm] = React.useState({
    name: '', email: '', company: '', role: '',
    subject: SUBJECT_OPTIONS[0], message: '',
    website: '',
  });
  const [touched, setTouched] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | sending | sent | error
  const [errorMsg, setErrorMsg] = React.useState('');

  const set = (k) => (e) => setForm(f => ({ ...f, [k]: e.target.value }));
  const blur = (k) => () => setTouched(t => ({ ...t, [k]: true }));

  const errors = React.useMemo(() => {
    const e = {};
    const n = form.name.trim();
    if (n.length < CONTACT_LIMITS.name.min) e.name = 'Name is required';
    else if (n.length > CONTACT_LIMITS.name.max) e.name = 'Name is too long';

    const em = form.email.trim();
    if (em.length < CONTACT_LIMITS.email.min) e.email = 'Email is required';
    else if (em.length > CONTACT_LIMITS.email.max) e.email = 'Email is too long';
    else if (!EMAIL_RE.test(em)) e.email = 'Enter a valid email';

    if (form.company.length > CONTACT_LIMITS.company.max) e.company = 'Company is too long';
    if (form.role.length    > CONTACT_LIMITS.role.max)    e.role    = 'Role is too long';

    const m = form.message.trim();
    if (m.length < CONTACT_LIMITS.message.min) e.message = `Message must be at least ${CONTACT_LIMITS.message.min} characters`;
    else if (m.length > CONTACT_LIMITS.message.max) e.message = 'Message is too long';
    return e;
  }, [form]);

  const showErr = (k) => touched[k] && errors[k];
  const isInvalid = Object.keys(errors).length > 0;

  const submit = async (e) => {
    e.preventDefault();
    setTouched({ name:true, email:true, company:true, role:true, message:true });
    if (isInvalid) return;
    if (form.website) {
      // Honeypot tripped — pretend success, drop on the floor.
      setStatus('sent');
      return;
    }
    setStatus('sending');
    setErrorMsg('');
    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({
          name:    form.name.trim(),
          email:   form.email.trim(),
          company: form.company.trim(),
          role:    form.role.trim(),
          subject: form.subject,
          message: form.message.trim(),
          website: form.website,
        }),
      });
      if (r.ok) {
        setStatus('sent');
      } else if (r.status === 429) {
        setStatus('error');
        setErrorMsg('Too many requests — please wait a moment and try again.');
      } else if (r.status === 400) {
        setStatus('error');
        setErrorMsg('We couldn\u2019t accept that submission. Please review the fields and try again.');
      } else {
        setStatus('error');
        setErrorMsg('Something went wrong on our end. Please try again shortly.');
      }
    } catch (_) {
      setStatus('error');
      setErrorMsg('Network error — check your connection and try again.');
    }
  };

  const reset = () => {
    setForm({ name:'', email:'', company:'', role:'', subject: SUBJECT_OPTIONS[0], message:'', website:'' });
    setTouched({});
    setStatus('idle');
    setErrorMsg('');
  };

  if (status === 'sent') {
    return (
      <section className="section first contact-section">
        <div className="site-wrap">
          <EyebrowRow label="Contact"/>
          <Reveal>
            <h1 style={{fontSize:56,lineHeight:'62px',fontWeight:600,letterSpacing:'-0.025em',maxWidth:780}}>
              Thank you. <span className="serif-moment" style={{fontSize:56,lineHeight:'62px'}}>Your note is on its way.</span>
            </h1>
            <p className="lede" style={{marginTop:24,maxWidth:560}}>
              We read every message and reply within a few working days. If your enquiry is time-sensitive, mention that in your follow-up.
            </p>
            <div style={{marginTop:40,display:'flex',gap:12,flexWrap:'wrap'}}>
              <button className="btn btn-primary btn-lg" onClick={()=>setRoute({page:'home'})}>
                Back to overview
              </button>
              <button className="btn btn-ghost btn-lg" onClick={reset}>
                Send another message
              </button>
            </div>
          </Reveal>
        </div>
      </section>
    );
  }

  return (
    <section className="section first contact-section">
      <div className="site-wrap">
        <EyebrowRow label="Contact"/>
        <h1 style={{fontSize:56,lineHeight:'62px',fontWeight:600,letterSpacing:'-0.025em',maxWidth:820}}>
          Tell us what you&rsquo;re looking for.<br/>
          <span className="serif-moment" style={{fontSize:56,lineHeight:'62px'}}>We&rsquo;ll write back with substance.</span>
        </h1>
        <p className="lede" style={{marginTop:24,maxWidth:640}}>
          Kestrel is still growing — we welcome your thoughts, feedback, and questions.
        </p>
        <p style={{marginTop:12,maxWidth:560,fontSize:14,lineHeight:'22px',color:'var(--ink-2)'}}>
          Use this form for demo requests, methodology questions, partnership conversations, or anything else.
          Replies typically land within a few working days.
        </p>

        <Reveal delay={60}>
          <form className="contact-form" onSubmit={submit} noValidate style={{
            marginTop:48, display:'grid', gridTemplateColumns:'1fr 1fr', gap:20,
            maxWidth:780,
          }}>
            <Field label="Name" required error={showErr('name') && errors.name}>
              <input
                type="text"
                value={form.name}
                onChange={set('name')}
                onBlur={blur('name')}
                maxLength={CONTACT_LIMITS.name.max}
                autoComplete="name"
                required
                aria-invalid={!!showErr('name')}
                className="contact-input"
              />
            </Field>

            <Field label="Email" required error={showErr('email') && errors.email}>
              <input
                type="email"
                value={form.email}
                onChange={set('email')}
                onBlur={blur('email')}
                maxLength={CONTACT_LIMITS.email.max}
                autoComplete="email"
                inputMode="email"
                required
                aria-invalid={!!showErr('email')}
                className="contact-input"
              />
            </Field>

            <Field label="Company" error={showErr('company') && errors.company}>
              <input
                type="text"
                value={form.company}
                onChange={set('company')}
                onBlur={blur('company')}
                maxLength={CONTACT_LIMITS.company.max}
                autoComplete="organization"
                className="contact-input"
              />
            </Field>

            <Field label="Role" error={showErr('role') && errors.role}>
              <input
                type="text"
                value={form.role}
                onChange={set('role')}
                onBlur={blur('role')}
                maxLength={CONTACT_LIMITS.role.max}
                autoComplete="organization-title"
                className="contact-input"
              />
            </Field>

            <Field label="Subject" full>
              <select
                value={form.subject}
                onChange={set('subject')}
                className="contact-input">
                {SUBJECT_OPTIONS.map(s => <option key={s} value={s}>{s}</option>)}
              </select>
            </Field>

            <Field label="Message" required full
                   help={`${form.message.length} / ${CONTACT_LIMITS.message.max}`}
                   error={showErr('message') && errors.message}>
              <textarea
                value={form.message}
                onChange={set('message')}
                onBlur={blur('message')}
                maxLength={CONTACT_LIMITS.message.max}
                rows={7}
                required
                aria-invalid={!!showErr('message')}
                className="contact-input contact-textarea"
                placeholder="What would you like to discuss?"
              />
            </Field>

            {/* Honeypot — visually hidden, off the tab order. Real users never
                see or fill this; bots that auto-fill every input will trip it
                and the server will silently drop the submission. */}
            <div aria-hidden="true" className="contact-honeypot">
              <label>Website (leave blank)
                <input
                  type="text"
                  tabIndex={-1}
                  autoComplete="off"
                  value={form.website}
                  onChange={set('website')}
                />
              </label>
            </div>

            <div className="contact-actions" style={{gridColumn:'1 / -1', display:'flex', flexDirection:'column', gap:14, marginTop:8}}>
              {status === 'error' && (
                <div role="alert" style={{
                  padding:'12px 16px', borderRadius:10,
                  border:'1px solid #C97070', background:'#FBEDED',
                  color:'#7A2E2E', fontSize:13, lineHeight:'20px',
                }}>
                  {errorMsg || 'Could not send the message. Please try again.'}
                </div>
              )}
              <div style={{display:'flex', gap:14, alignItems:'center', flexWrap:'wrap'}}>
                <button
                  type="submit"
                  className="btn btn-primary btn-lg"
                  disabled={status === 'sending'}>
                  {status === 'sending' ? 'Sending…' : <>Send message <Icon name="arrow-right" size={16} style={{marginLeft:4}} className="arrow"/></>}
                </button>
                <span style={{fontSize:12, color:'var(--ink-3)', maxWidth:380, lineHeight:'18px'}}>
                  By sending you agree we may store your message and reply by email. We never share contact details.
                </span>
              </div>
            </div>
          </form>
        </Reveal>
      </div>
    </section>
  );
};

const Field = ({ label, required, full, help, error, children }) => (
  <div className={`contact-field ${full ? 'is-full' : ''}`} style={full ? {gridColumn:'1 / -1'} : undefined}>
    <div className="contact-field-head">
      <label className="contact-label">
        {label}{required && <span aria-hidden="true" style={{color:'var(--moss-deep)',marginLeft:4}}>*</span>}
      </label>
      {help && <span className="contact-help">{help}</span>}
    </div>
    {children}
    {error && <div className="contact-error" role="alert">{error}</div>}
  </div>
);

window.Contact = Contact;
