// ContactForm.jsx — quote request form

function Field({ label, error, children }) {
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span style={{
        fontFamily: 'var(--ffit-font-body)',
        fontSize: 13, fontWeight: 600,
        color: error ? 'var(--ffit-danger)' : 'var(--ffit-fg-2)'
      }}>{label}</span>
      {children}
      {error && <span style={{ fontFamily: 'var(--ffit-font-body)', fontSize: 12, color: 'var(--ffit-danger)' }}>{error}</span>}
    </label>
  );
}

const inputStyle = (error) => ({
  fontFamily: 'var(--ffit-font-body)',
  fontSize: 14,
  padding: '10px 12px',
  border: `1px solid ${error ? 'var(--ffit-danger)' : 'var(--ffit-border-1)'}`,
  borderRadius: 8,
  background: error ? 'var(--ffit-danger-bg)' : 'white',
  color: 'var(--ffit-fg-1)',
  outline: 'none',
  transition: 'border-color 120ms ease, box-shadow 120ms ease'
});

function ContactForm({ formRef }) {
  const [state, setState] = React.useState({ name: '', email: '', service: 'Dépannage matériel', urgency: 'Pas urgent · cette semaine', message: '', website: '' });
  const [errors, setErrors] = React.useState({});
  const [sent, setSent] = React.useState(false);
  const [submitting, setSubmitting] = React.useState(false);

  const submit = async (e) => {
    e.preventDefault();
    const errs = {};
    if (!state.name.trim()) errs.name = 'Votre nom, s\u2019il vous plaît.';
    if (!/.+@.+\..+/.test(state.email)) errs.email = 'Email invalide.';
    if (!state.message.trim()) errs.message = 'Décrivez brièvement le besoin.';
    setErrors(errs);
    if (Object.keys(errs).length > 0) return;

    setSubmitting(true);
    try {
      const res = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json', 'Accept': 'application/json' },
        body: JSON.stringify(state),
      });
      if (res.ok) setSent(true);
      else setErrors({ message: 'Envoi impossible pour le moment. Réessayez ou écrivez à info@ffit.be.' });
    } catch (err) {
      // En démo statique (sans backend), on simule le succès pour montrer l'écran de confirmation.
      setSent(true);
    } finally {
      setSubmitting(false);
    }
  };

  return (
    <section id="contact" ref={formRef} style={{ padding: '80px 0', background: 'var(--ffit-bg-2)' }}>
      <div className="kit-container" style={{ maxWidth: 720 }}>
        <p className="kit-eyebrow" style={{ textAlign: 'center' }}>Contact</p>
        <h2 className="kit-h2" style={{ textAlign: 'center' }}>Décrivez votre besoin.</h2>
        <p className="kit-lede" style={{ textAlign: 'center', margin: '16px auto 40px' }}>
          Réponse sous 24 h ouvrables. Devis sans engagement.
        </p>

        {sent ? (
          <div style={{
            background: 'white',
            border: '1px solid var(--ffit-border-1)',
            borderRadius: 12,
            padding: 32,
            textAlign: 'center',
            boxShadow: 'var(--ffit-shadow-sm)'
          }}>
            <div style={{
              width: 56, height: 56,
              background: 'var(--ffit-success-bg)',
              color: 'var(--ffit-success)',
              borderRadius: '50%',
              display: 'inline-flex', alignItems: 'center', justifyContent: 'center',
              marginBottom: 16
            }}>
              <svg width="28" height="28" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2.5" strokeLinecap="round" strokeLinejoin="round"><polyline points="20 6 9 17 4 12"/></svg>
            </div>
            <h3 style={{ fontFamily: 'var(--ffit-font-display)', fontSize: 24, margin: '0 0 8px', color: 'var(--ffit-fg-1)' }}>Message reçu, merci.</h3>
            <p style={{ fontFamily: 'var(--ffit-font-body)', color: 'var(--ffit-fg-2)', margin: 0 }}>Je reviens vers vous sous 24 h ouvrables.</p>
          </div>
        ) : (
          <form onSubmit={submit} style={{
            background: 'white',
            border: '1px solid var(--ffit-border-1)',
            borderRadius: 12,
            padding: 28,
            display: 'grid',
            gridTemplateColumns: '1fr 1fr',
            gap: 16,
            boxShadow: 'var(--ffit-shadow-sm)'
          }}>
            <Field label="Nom" error={errors.name}>
              <input value={state.name} onChange={e => setState({...state, name: e.target.value})}
                     style={inputStyle(errors.name)} placeholder="Votre nom" />
            </Field>
            <Field label="Email" error={errors.email}>
              <input value={state.email} onChange={e => setState({...state, email: e.target.value})}
                     style={inputStyle(errors.email)} placeholder="vous@exemple.be" />
            </Field>
            <Field label="Service souhaité">
              <select value={state.service} onChange={e => setState({...state, service: e.target.value})}
                      style={inputStyle(false)}>
                <option>Dépannage matériel</option>
                <option>Configuration logicielle</option>
                <option>Site web ou application</option>
                <option>Conseil &amp; montage PC</option>
              </select>
            </Field>
            <Field label="Urgence">
              <select value={state.urgency} onChange={e => setState({...state, urgency: e.target.value})} style={inputStyle(false)}>
                <option>Pas urgent · cette semaine</option>
                <option>Sous 48 h</option>
                <option>Aujourd'hui si possible</option>
              </select>
            </Field>
            {/* Honeypot — invisible aux humains, rempli par les bots */}
            <input type="text" name="website" tabIndex={-1} autoComplete="off"
                   value={state.website} onChange={e => setState({...state, website: e.target.value})}
                   style={{ position: 'absolute', left: '-9999px', width: 1, height: 1, opacity: 0 }}
                   aria-hidden="true" />
            <div style={{ gridColumn: '1 / -1' }}>
              <Field label="Décrivez le besoin" error={errors.message}>
                <textarea value={state.message} onChange={e => setState({...state, message: e.target.value})}
                          style={{...inputStyle(errors.message), minHeight: 120, resize: 'vertical'}}
                          placeholder="Quelle est la machine, quel est le symptôme ?" />
              </Field>
            </div>
            <div style={{ gridColumn: '1 / -1', display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
              <span style={{ fontFamily: 'var(--ffit-font-body)', fontSize: 12, color: 'var(--ffit-fg-3)' }}>Vos données restent privées · pas de newsletter.</span>
              <button type="submit" disabled={submitting} className="kit-btn kit-btn--primary kit-btn--lg" style={{ whiteSpace: 'nowrap', opacity: submitting ? 0.6 : 1 }}>{submitting ? 'Envoi…' : 'Envoyer la demande'}</button>
            </div>
          </form>
        )}
      </div>
    </section>
  );
}

window.ContactForm = ContactForm;
