// Contact form — posts JSON to the /api/contact Pages Function.
// Registers window.ContactForm; rendered inside the #book section by FinalCTA.
//
// Design notes (within the fixed contract):
//  - Token-driven only, so it reads correctly in both dark and light themes.
//  - A self-contained <style> block adds the entrance + signal-check flourish
//    for the success state and a subtle field stagger. All motion is gated
//    behind prefers-reduced-motion so it degrades to a clean static layout.
//  - Success state is elevated: an animated cyan check, an Instrument-Serif
//    italic accent line, and the "replies in 24h" cadence echoed from FinalCTA.

// One-time scoped style injection (component owns its motion; field CSS untouched).
const CONTACT_STYLES = `
  .cf-form { animation: cf-rise 600ms var(--ease-out) both; }
  .cf-field { animation: cf-rise 520ms var(--ease-out) both; }
  .cf-success { animation: cf-pop 560ms var(--ease-out) both; }
  .cf-check-ring {
    stroke-dasharray: 151; stroke-dashoffset: 151;
    animation: cf-draw 560ms var(--ease-out) 80ms forwards;
  }
  .cf-check-mark {
    stroke-dasharray: 36; stroke-dashoffset: 36;
    animation: cf-draw 380ms var(--ease-out) 440ms forwards;
  }
  .cf-check-halo { animation: cf-halo 900ms var(--ease-out) 300ms both; }
  .cf-btn-spinner {
    width: 14px; height: 14px; border-radius: 50%;
    border: 2px solid color-mix(in srgb, var(--on-signal) 35%, transparent);
    border-top-color: var(--on-signal);
    animation: cf-spin 700ms linear infinite;
    display: inline-block;
  }
  @keyframes cf-rise { from { opacity: 0; transform: translateY(10px); } to { opacity: 1; transform: none; } }
  @keyframes cf-pop { from { opacity: 0; transform: translateY(8px) scale(0.985); } to { opacity: 1; transform: none; } }
  @keyframes cf-draw { to { stroke-dashoffset: 0; } }
  @keyframes cf-halo { 0% { transform: scale(0.5); opacity: 0.55; } 100% { transform: scale(2.1); opacity: 0; } }
  @keyframes cf-spin { to { transform: rotate(360deg); } }
  @media (prefers-reduced-motion: reduce) {
    .cf-form, .cf-field, .cf-success { animation: none; }
    .cf-check-ring, .cf-check-mark { stroke-dashoffset: 0; animation: none; }
    .cf-check-halo { display: none; }
    .cf-btn-spinner { animation: none; }
  }
`;

function ContactStyleOnce() {
  React.useEffect(() => {
    if (document.getElementById('cf-styles')) return;
    const el = document.createElement('style');
    el.id = 'cf-styles';
    el.textContent = CONTACT_STYLES;
    document.head.appendChild(el);
  }, []);
  return null;
}

function ContactField({ label, required, error, index, children }) {
  return (
    <label className="field cf-field" style={{ animationDelay: `${80 + index * 70}ms` }}>
      <span className="field-label">
        {label}{required ? <span className="req">*</span> : null}
      </span>
      {children}
      {error ? <span className="field-msg" role="alert">{error}</span> : null}
    </label>
  );
}

function ContactForm() {
  const [values, setValues] = React.useState({
    name: '', email: '', website: '', message: '', contact_reason: '',
  });
  const [errors, setErrors] = React.useState({});
  const [status, setStatus] = React.useState('idle'); // idle | submitting | success | error
  const successRef = React.useRef(null);

  // Move focus to the confirmation when the form unmounts into the success
  // state, so keyboard/screen-reader users aren't dropped to the top of <body>.
  React.useEffect(() => {
    if (status === 'success' && successRef.current) successRef.current.focus();
  }, [status]);

  const set = (key) => (e) => {
    const val = e.target.value;
    setValues((v) => ({ ...v, [key]: val }));
    // Clear a field's error as soon as the user starts correcting it.
    setErrors((prev) => (prev[key] ? { ...prev, [key]: undefined } : prev));
  };

  const validate = () => {
    const e = {};
    if (!values.name.trim()) e.name = 'Name is required.';
    if (!values.email.trim()) e.email = 'Email is required.';
    else if (!/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(values.email.trim())) e.email = 'Enter a valid email.';
    if (!values.message.trim()) e.message = 'Message is required.';
    return e;
  };

  const onSubmit = async (ev) => {
    ev.preventDefault();
    const e = validate();
    setErrors(e);
    if (Object.keys(e).length > 0) return;
    setStatus('submitting');
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'content-type': 'application/json' },
        body: JSON.stringify(values),
      });
      const data = await res.json().catch(() => ({}));
      if (res.ok && data.ok) { setStatus('success'); return; }
      if (data.errors) setErrors((prev) => ({ ...prev, ...data.errors }));
      setStatus('error');
    } catch (err) {
      setStatus('error');
    }
  };

  if (status === 'success') {
    return (
      <React.Fragment>
        <ContactStyleOnce />
        <div ref={successRef} tabIndex={-1} className="cf-success" role="status" aria-live="polite" style={{
          maxWidth: 520, margin: '0 auto', padding: '36px 28px', textAlign: 'center',
          border: '1px solid color-mix(in srgb, var(--signal) 35%, transparent)',
          borderRadius: 16, background: 'color-mix(in srgb, var(--signal) 8%, transparent)',
          outline: 'none',
        }}>
          {/* Signal-cyan check that draws itself in, with a single expanding halo */}
          <div style={{ position: 'relative', width: 56, height: 56, margin: '0 auto 20px' }}>
            <span aria-hidden="true" className="cf-check-halo" style={{
              position: 'absolute', inset: 0, borderRadius: '50%',
              border: '1.5px solid var(--signal)',
            }} />
            <svg width="56" height="56" viewBox="0 0 56 56" fill="none" aria-hidden="true"
              style={{ position: 'relative', display: 'block' }}>
              <circle className="cf-check-ring" cx="28" cy="28" r="24"
                stroke="var(--signal)" strokeWidth="2" fill="none" strokeLinecap="round"
                transform="rotate(-90 28 28)" />
              <path className="cf-check-mark" d="M18 28.5 L25 35.5 L38.5 21"
                stroke="var(--signal)" strokeWidth="2.5" fill="none"
                strokeLinecap="round" strokeLinejoin="round" />
            </svg>
          </div>

          <div className="upper-mono" style={{ color: 'var(--signal)', marginBottom: 12 }}>
            Message sent
          </div>
          <p className="t-lede" style={{ margin: '0 auto', maxWidth: '34ch' }}>
            Thanks — your message is in. We'll{' '}
            <span className="t-italic" style={{ color: 'var(--signal)' }}>reply within 24h</span>,
            usually from a founder.
          </p>
        </div>
      </React.Fragment>
    );
  }

  return (
    <React.Fragment>
      <ContactStyleOnce />
      <form onSubmit={onSubmit} noValidate className="cf-form" style={{
        maxWidth: 520, margin: '0 auto', display: 'flex', flexDirection: 'column', gap: 18,
      }}>
        {/* Honeypot — keep out of the tab order and off-screen */}
        <input
          className="field-hp" type="text" name="contact_reason" tabIndex={-1}
          autoComplete="off" aria-hidden="true"
          value={values.contact_reason} onChange={set('contact_reason')}
        />

        <ContactField label="Name" required error={errors.name} index={0}>
          <input className="field-input" type="text" name="name" autoComplete="name"
            placeholder="Your name" value={values.name} onChange={set('name')}
            aria-invalid={errors.name ? 'true' : 'false'} />
        </ContactField>

        <ContactField label="Work email" required error={errors.email} index={1}>
          <input className="field-input" type="email" name="email" autoComplete="email"
            placeholder="you@company.com" value={values.email} onChange={set('email')}
            aria-invalid={errors.email ? 'true' : 'false'} />
        </ContactField>

        <ContactField label="Website" error={errors.website} index={2}>
          <input className="field-input" type="text" name="website" autoComplete="url"
            placeholder="yourcompany.com" value={values.website} onChange={set('website')}
            aria-invalid={errors.website ? 'true' : 'false'} />
        </ContactField>

        <ContactField label="Message" required error={errors.message} index={3}>
          <textarea className="field-textarea" name="message"
            placeholder="A customer you wish you had ten more of…"
            value={values.message} onChange={set('message')}
            aria-invalid={errors.message ? 'true' : 'false'} />
        </ContactField>

        {status === 'error' ? (
          <p className="field-msg" role="alert">
            Something went wrong. Email us at{' '}
            <a href="mailto:hello@betterpipe.ai" style={{ color: 'var(--signal)' }}>hello@betterpipe.ai</a>.
          </p>
        ) : null}

        <button type="submit" className="btn btn-primary" disabled={status === 'submitting'}
          aria-busy={status === 'submitting' ? 'true' : 'false'}
          style={{ padding: '16px 24px', fontSize: 14, width: '100%', justifyContent: 'center' }}>
          {status === 'submitting' ? (
            <React.Fragment>
              <span className="cf-btn-spinner" aria-hidden="true" />
              Sending…
            </React.Fragment>
          ) : (
            <React.Fragment>
              Book a demo
              <ArrowRight />
            </React.Fragment>
          )}
        </button>
      </form>
    </React.Fragment>
  );
}

window.ContactForm = ContactForm;
