// Silk and Blow — shared form helpers for the Cloudflare Pages Functions.
// postLead(endpoint, payload): '/api/subscribe' or '/api/suite-enquiry'.
// Keeps typed values on failure; returns a friendly message for the UI.
async function postLead(endpoint, payload) {
  let res;
  try {
    res = await fetch(endpoint, {
      method: 'POST',
      headers: { 'Content-Type': 'application/json' },
      body: JSON.stringify(payload),
    });
  } catch (e) {
    throw new Error('We could not reach the salon just now. Please check your connection and try again.');
  }
  let body = null;
  try { body = await res.json(); } catch (e) { /* non-JSON response */ }
  if (!res.ok || !body || body.success !== true) {
    throw new Error((body && body.error) || 'We could not send that just now. Please try again in a moment.');
  }
  return body;
}

// Spam protection shared by both forms: an invisible honeypot input plus the
// timestamp the form rendered (submissions faster than ~2s are treated as bots).
function useFormGuard() {
  const rendered = React.useRef(Date.now());
  const [honeypot, setHoneypot] = React.useState('');
  const guard = () => ({ company: honeypot, renderedAt: rendered.current });
  const HoneypotField = ({ id }) => (
    <div aria-hidden="true" style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, overflow: 'hidden' }}>
      <label htmlFor={id}>Company</label>
      <input id={id} name="company" type="text" tabIndex="-1" autoComplete="off" value={honeypot} onChange={(e) => setHoneypot(e.target.value)} />
    </div>
  );
  return { guard, HoneypotField };
}

const EMAIL_RE = /^[^\s@]+@[^\s@]+\.[a-z]{2,}$/i;
const validEmail = (v) => EMAIL_RE.test((v || '').trim());
const validPhone = (v) => (v || '').replace(/[^0-9]/g, '').length >= 10;

Object.assign(window, { postLead, useFormGuard, validEmail, validPhone });
