// Lead form (Subscribe + Contact) — mirrors web/src/components/LeadForm.tsx.

function LeadForm({ intent = 'subscribe' }) {
  const [state, setState] = React.useState({ status: 'idle', message: '' });
  const [values, setValues] = React.useState({});

  const fields = intent === 'contact'
    ? [
        { name: 'name', label: 'Name', type: 'text', required: true },
        { name: 'email', label: 'Email', type: 'email', required: true },
        { name: 'organization', label: 'Organization', type: 'text', required: false },
      ]
    : [{ name: 'email', label: 'Email', type: 'email', required: true }];

  function set(name, v) { setValues(prev => ({ ...prev, [name]: v })); }

  async function submit(e) {
    e.preventDefault();
    setState({ status: 'loading', message: 'Sending…' });

    const endpoint = window.SP_FORM_ENDPOINT;
    const payload = { ...values, intent, _subject: `SciPHR ${intent} — ${values.email || ''}` };

    // Fallback: no Formspree endpoint configured → open user's mail client.
    if (!endpoint) {
      const subject = encodeURIComponent(intent === 'subscribe' ? 'Subscribe' : 'Contact');
      const body = encodeURIComponent(
        Object.entries(payload)
          .filter(([k]) => !k.startsWith('_'))
          .map(([k, v]) => `${k}: ${v}`)
          .join('\n')
      );
      window.location.href = `mailto:hello@sciphr.io?subject=${subject}&body=${body}`;
      setState({ status: 'success', message: 'Opened your mail client.' });
      return;
    }

    try {
      const res = await fetch(endpoint, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', Accept: 'application/json' },
        body: JSON.stringify(payload),
      });
      if (!res.ok) throw new Error(`HTTP ${res.status}`);
      setValues({});
      setState({
        status: 'success',
        message: intent === 'subscribe' ? 'Subscribed. Watch your inbox.' : "Message sent. We'll reply soon.",
      });
    } catch (err) {
      setState({
        status: 'error',
        message: 'Send failed. Email hello@sciphr.io.',
      });
    }
  }

  return (
    <form onSubmit={submit} style={{ display: 'flex', flexDirection: 'column', gap: 12 }}>
      {fields.map(f => (
        <label key={f.name} style={labelStyle}>
          {f.label}
          <input
            style={inputStyle}
            type={f.type}
            name={f.name}
            placeholder={f.label.toLowerCase()}
            required={f.required}
            value={values[f.name] || ''}
            onChange={e => set(f.name, e.target.value)}
          />
        </label>
      ))}
      {intent === 'contact' && (
        <label style={labelStyle}>
          Message
          <textarea
            style={{ ...inputStyle, height: 120, padding: '10px 12px', resize: 'vertical' }}
            name="message"
            placeholder="How can we help?"
            required
            value={values.message || ''}
            onChange={e => set('message', e.target.value)}
          />
        </label>
      )}
      <div style={{ display: 'flex', alignItems: 'center', gap: 14 }}>
        <CommandButton
          as="button"
          type="submit"
          variant="solid"
          tone="dark"
          label={intent === 'subscribe' ? 'Subscribe' : 'Send'}
          disabled={state.status === 'loading'}
        />
        <p style={{
          fontFamily: SP_MONO_W, fontSize: 10, color: SP_COL.grayLight,
          letterSpacing: '0.25em', textTransform: 'uppercase', margin: 0,
        }}>
          {state.message}
        </p>
      </div>
    </form>
  );
}

const labelStyle = {
  fontFamily: SP_MONO_W, fontSize: 11, color: SP_COL.grayLight,
  letterSpacing: '0.3em', textTransform: 'uppercase',
  display: 'flex', flexDirection: 'column', gap: 8,
};

const inputStyle = {
  height: 44, width: '100%', background: 'transparent', color: SP_COL.white,
  border: `1px solid ${SP_COL.grayDark}`, borderRadius: 4,
  padding: '0 12px', fontFamily: SP_MONO_W, fontSize: 13,
  letterSpacing: '0.04em', boxSizing: 'border-box', outline: 'none',
};

Object.assign(window, { LeadForm });
