// ─────────────────────────────────────────────────────────────
// Mezoo — Page Contact
// Real form: typed validation, inline errors, segmented project-type
// picker, range slider for budget, animated success state on submit.
// ─────────────────────────────────────────────────────────────

function ContactPage() {
  useReveal();
  const [form, setForm] = React.useState({
    company: '', name: '', email: '', phone: '',
    role: '', type: 'web',
    budget: 50,
    timeline: 'q3',
    brief: '',
    _gotcha: '', // honeypot — bots fill it, humans don't
  });
  const [touched, setTouched] = React.useState({});
  const [submitting, setSubmitting] = React.useState(false);
  const [submitted, setSubmitted] = React.useState(null); // { refId } | null
  const [serverError, setServerError] = React.useState(null);

  const update = (k, v) => setForm((f) => ({ ...f, [k]: v }));
  const blur = (k) => setTouched((t) => ({ ...t, [k]: true }));

  const errors = {
    company: !form.company.trim() ? 'Précisez votre structure' : null,
    name: !form.name.trim() ? 'Votre nom complet' : null,
    email: !/^\S+@\S+\.\S+$/.test(form.email) ? 'Adresse e-mail valide' : null,
    brief: form.brief.trim().length < 20 ? 'Décrivez votre besoin en ≥ 20 caractères' : null,
  };
  const isValid = Object.values(errors).every((e) => !e);

  const onSubmit = async (e) => {
    e.preventDefault();
    setTouched({ company: true, name: true, email: true, brief: true });
    if (!isValid) return;
    setServerError(null);
    setSubmitting(true);

    // POST to the deployed Resend handler. If the endpoint is unreachable
    // (file://, offline) OR doesn't return JSON (static preview where the
    // server falls back to serving the HTML page itself for unknown paths),
    // gracefully drop into a local success state so the demo flow still works.
    const demoFallback = () => {
      setSubmitted({ refId: 'DEMO-' + Date.now().toString(36).toUpperCase().slice(-6), demo: true });
    };

    try {
      const r = await fetch('/api/contact', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(form),
      });

      // If the response isn't JSON, there's no backend deployed at this
      // origin — serve the demo success screen instead of showing a parse
      // error to the user.
      const ct = r.headers.get('content-type') || '';
      if (!ct.includes('json')) { demoFallback(); return; }

      const json = await r.json().catch(() => null);
      if (!json) { demoFallback(); return; }

      if (!r.ok || !json.ok) {
        // 4xx: server-side validation. 5xx: generic.
        throw new Error(json.error || `Erreur ${r.status}`);
      }
      setSubmitted({ refId: json.refId });
    } catch (err) {
      // Network unreachable (file://, CORS pre-flight failure, offline)
      // counts as demo too.
      if (err instanceof TypeError) { demoFallback(); return; }
      setServerError(err.message || 'Erreur inattendue.');
    } finally {
      setSubmitting(false);
    }
  };

  const projectTypes = [
    { id: 'web', label: 'Site web', sub: 'Vitrine · institutionnel' },
    { id: 'ecom', label: 'E-commerce', sub: 'Catalogue · paiement' },
    { id: 'saas', label: 'Application SaaS', sub: 'Outil métier · sur-mesure' },
    { id: 'mobile', label: 'Application mobile', sub: 'iOS · Android' },
    { id: 'audit', label: 'Audit / conseil', sub: '5 jours, sans engagement' },
  ];

  const timelines = [
    { id: 'urgent', label: 'Urgent', sub: '< 1 mois' },
    { id: 'q3', label: 'Standard', sub: '1 à 3 mois' },
    { id: 'q4', label: 'Souple', sub: '3 à 6 mois' },
    { id: 'open', label: 'Sans contrainte', sub: 'À étudier ensemble' },
  ];

  if (submitted) return <ContactSuccess form={form} refId={submitted.refId} demo={submitted.demo} />;

  return (
    <main className="mz-page">
      <section style={{ paddingBlock: 'var(--s-7)', borderBottom: '1px solid var(--hairline)' }}>
        <div className="mz-container-wide">
          <Reveal>
            <Eyebrow>§ Rendez-vous — réponse sous 24h ouvrées</Eyebrow>
          </Reveal>
          <Reveal delay={80} as="h1" className="mz-display-xl"
            style={{ marginTop: 'var(--s-5)', maxWidth: '16ch' }}>
            Parlons de votre <Em>outil numérique</Em>.
          </Reveal>
          <Reveal delay={160} className="mz-lead"
            style={{ marginTop: 'var(--s-5)', maxWidth: '58ch' }}>
            Un seul interlocuteur senior, pas de filtre commercial.
            Entretien de 30 minutes — vous décrivez le contexte,
            on vous dit honnêtement ce qu'on en pense.
          </Reveal>
        </div>
      </section>

      <section style={{ paddingBlock: 'var(--s-8)' }}>
        <div className="mz-container-wide" style={{ display: 'grid', gridTemplateColumns: '1.6fr 1fr', gap: 'var(--s-8)', alignItems: 'flex-start' }}>

          {/* Form */}
          <form onSubmit={onSubmit} noValidate style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-6)' }}>

            {/* Honeypot field — hidden from humans, irresistible for bots */}
            <div aria-hidden="true" style={{ position: 'absolute', left: '-10000px', top: 'auto', width: 1, height: 1, overflow: 'hidden' }}>
              <label>Ne pas remplir <input type="text" tabIndex="-1" autoComplete="off" value={form._gotcha}
                onChange={(e) => update('_gotcha', e.target.value)} /></label>
            </div>

            {/* I — Identité */}
            <Reveal as="fieldset" style={{ border: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
              <FieldHeader roman="I." label="Vous" sub="Pour pouvoir vous rappeler." />
              <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 'var(--s-3)' }}>
                <FormField label="Entreprise *" value={form.company} onChange={(v) => update('company', v)}
                  onBlur={() => blur('company')} error={touched.company && errors.company} placeholder="Hortis SA" />
                <FormField label="Fonction" value={form.role} onChange={(v) => update('role', v)}
                  placeholder="Directrice des opérations" />
                <FormField label="Nom complet *" value={form.name} onChange={(v) => update('name', v)}
                  onBlur={() => blur('name')} error={touched.name && errors.name} placeholder="Christine Vasseur" />
                <FormField label="E-mail *" type="email" value={form.email} onChange={(v) => update('email', v)}
                  onBlur={() => blur('email')} error={touched.email && errors.email} placeholder="vasseur@hortis.fr" />
                <FormField label="Téléphone" type="tel" value={form.phone} onChange={(v) => update('phone', v)}
                  placeholder="+33 6 12 34 56 78" />
              </div>
            </Reveal>

            {/* II — Projet */}
            <Reveal as="fieldset" delay={80} style={{ border: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
              <FieldHeader roman="II." label="Le projet" sub="Pour qu'on arrive préparé." />

              <SegmentedSelect label="Nature du projet"
                options={projectTypes} value={form.type} onChange={(v) => update('type', v)} />

              <SegmentedSelect label="Échéance souhaitée"
                options={timelines} value={form.timeline} onChange={(v) => update('timeline', v)} />

              <BudgetSlider value={form.budget} onChange={(v) => update('budget', v)} />
            </Reveal>

            {/* III — Brief */}
            <Reveal as="fieldset" delay={160} style={{ border: 'none', padding: 0, margin: 0, display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
              <FieldHeader roman="III." label="Le contexte" sub="Trois lignes suffisent — on creusera." />
              <FormField label="Brief *" multiline rows={5}
                value={form.brief} onChange={(v) => update('brief', v)} onBlur={() => blur('brief')}
                error={touched.brief && errors.brief}
                placeholder="Nous opérons cinq sites locaux mal connectés. Le score Lighthouse moyen est de 54, on perd des commandes la nuit. Idéalement on garde nos marques régionales mais on consolide la plateforme." />
              <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.08em' }}>
                ↳ {form.brief.length} caractères
              </span>
            </Reveal>

            <Reveal delay={220} style={{ display: 'flex', flexDirection: 'column', gap: 'var(--s-3)', paddingTop: 'var(--s-4)', borderTop: '1px solid var(--hairline-strong)' }}>
              {serverError && (
                <div role="alert" style={{
                  padding: '12px 16px', border: '1px solid var(--signal-err)',
                  background: 'rgba(140,31,31,0.06)', color: 'var(--signal-err)',
                  fontSize: 13, fontFamily: 'var(--font-mono)', letterSpacing: '0.04em',
                }}>
                  ↳ {serverError} — vous pouvez aussi nous écrire à hello@mezoo.studio.
                </div>
              )}
              <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', flexWrap: 'wrap', gap: 'var(--s-3)' }}>
                <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.06em' }}>
                  ↳ vos données restent confidentielles · chiffrées · europe
                </span>
                <button type="submit" className="mz-btn mz-btn-primary"
                  disabled={submitting || (!isValid && Object.keys(touched).length > 0)}
                  style={(submitting || (!isValid && Object.keys(touched).length > 0)) ? { opacity: 0.6, cursor: 'not-allowed' } : null}>
                  {submitting ? (
                    <>
                      <svg width="13" height="13" viewBox="0 0 16 16" fill="none" stroke="currentColor" strokeWidth="1.6">
                        <circle cx="8" cy="8" r="6" opacity="0.25" />
                        <path d="M14 8a6 6 0 0 0-6-6" strokeLinecap="round">
                          <animateTransform attributeName="transform" type="rotate" from="0 8 8" to="360 8 8" dur="0.8s" repeatCount="indefinite" />
                        </path>
                      </svg>
                      Envoi en cours…
                    </>
                  ) : (
                    <>
                      Envoyer la demande
                      <svg width="13" height="13" viewBox="0 0 12 12" fill="none" stroke="currentColor" strokeWidth="1.4"><path d="M2 6h8M6 2l4 4-4 4" /></svg>
                    </>
                  )}
                </button>
              </div>
            </Reveal>
          </form>

          {/* Sidebar — process & guarantees */}
          <aside style={{ position: 'sticky', top: 100, display: 'flex', flexDirection: 'column', gap: 'var(--s-4)' }}>
            <Reveal delay={100}>
              <SpecCard title="Ce qui se passe ensuite" status="Process · 02 semaines">
                <ol style={{ margin: 0, padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
                  {[
                    ['01', '24h ouvrées', 'On lit votre brief, un senior vous propose 3 créneaux.'],
                    ['02', 'Entretien · 30 min', 'On vous écoute, on regarde votre site en direct.'],
                    ['03', '48h après', 'Note écrite de 4 pages · ce qu\'on ferait, à quel prix.'],
                    ['04', 'Si fit', 'Audit à 5 jours, sans engagement. Sinon, on s\'arrête là.'],
                  ].map(([n, t, d]) => (
                    <li key={n} style={{ display: 'grid', gridTemplateColumns: 'auto 1fr', gap: 14, alignItems: 'flex-start' }}>
                      <span className="mz-mono" style={{
                        color: 'var(--accent)', letterSpacing: '0.04em',
                        paddingTop: 2, fontWeight: 500,
                      }}>{n}</span>
                      <div>
                        <div style={{ fontSize: 14, fontWeight: 500 }}>{t}</div>
                        <div style={{ fontSize: 13, color: 'var(--fg-muted)', marginTop: 2, lineHeight: 1.45 }}>{d}</div>
                      </div>
                    </li>
                  ))}
                </ol>
              </SpecCard>
            </Reveal>

            <Reveal delay={200} as="div" style={{ border: '1px solid var(--hairline-strong)', padding: 'var(--s-4)', display: 'flex', flexDirection: 'column', gap: 'var(--s-2)' }}>
              <Eyebrow line={false}>Trois engagements</Eyebrow>
              <ul style={{ margin: 'var(--s-3) 0 0', padding: 0, listStyle: 'none', display: 'flex', flexDirection: 'column', gap: 10 }}>
                {[
                  'Aucune réponse type, aucun bot.',
                  'Pas de devis avant le diagnostic.',
                  'Vos données ne quittent pas notre serveur.',
                ].map((t) => (
                  <li key={t} style={{ display: 'flex', alignItems: 'flex-start', gap: 12, fontSize: 14 }}>
                    <span style={{ width: 5, height: 5, background: 'var(--accent)', marginTop: 8, flexShrink: 0 }} />
                    {t}
                  </li>
                ))}
              </ul>
            </Reveal>

            <Reveal delay={300} as="div" style={{ border: '1px dashed var(--hairline-strong)', padding: 'var(--s-4)' }}>
              <Eyebrow line={false}>Vous préférez parler ?</Eyebrow>
              <div style={{ marginTop: 'var(--s-3)', display: 'flex', flexDirection: 'column', gap: 8 }}>
                <a href="tel:+33184804196" className="mz-link" style={{ fontSize: 16 }}>+33 1 84 80 41 96</a>
                <a href="mailto:hello@mezoo.studio" className="mz-link" style={{ fontSize: 14, color: 'var(--fg-muted)' }}>hello@mezoo.studio</a>
                <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.06em', marginTop: 6 }}>
                  ↳ lun – ven · 09h – 19h CET
                </span>
              </div>
            </Reveal>
          </aside>
        </div>
      </section>
    </main>
  );
}

// ── Form sub-components ─────────────────────────────────────────

function FieldHeader({ roman, label, sub }) {
  return (
    <div style={{ display: 'flex', alignItems: 'baseline', gap: 14, paddingBottom: 'var(--s-3)', borderBottom: '1px solid var(--hairline)' }}>
      <span className="mz-italic" style={{ fontSize: 32, lineHeight: 1 }}>{roman}</span>
      <span style={{ fontSize: 22, fontFamily: 'var(--font-display)', fontWeight: 500, letterSpacing: '-0.02em' }}>{label}</span>
      <span className="mz-mono" style={{ marginLeft: 'auto', color: 'var(--fg-subtle)', letterSpacing: '0.08em', textTransform: 'uppercase' }}>↳ {sub}</span>
    </div>
  );
}

function FormField({ label, value, onChange, onBlur, error, placeholder, type = 'text', multiline = false, rows = 4 }) {
  const Tag = multiline ? 'textarea' : 'input';
  return (
    <label style={{ display: 'flex', flexDirection: 'column', gap: 6 }}>
      <span className="mz-mono" style={{ color: error ? 'var(--signal-err)' : 'var(--fg-subtle)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
        {label}
      </span>
      <Tag className={`mz-field ${error ? 'mz-field-error' : ''}`}
        type={multiline ? undefined : type}
        rows={multiline ? rows : undefined}
        value={value}
        onChange={(e) => onChange(e.target.value)}
        onBlur={onBlur}
        placeholder={placeholder} />
      {error && (
        <span style={{ fontSize: 12, color: 'var(--signal-err)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em' }}>
          {error}
        </span>
      )}
    </label>
  );
}

function SegmentedSelect({ label, options, value, onChange }) {
  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 8 }}>
      <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>{label}</span>
      <div style={{ display: 'grid', gridTemplateColumns: `repeat(${options.length}, 1fr)`, gap: 0, border: '1px solid var(--hairline)' }}>
        {options.map((opt, i) => {
          const active = value === opt.id;
          return (
            <button key={opt.id} type="button" onClick={() => onChange(opt.id)}
              style={{
                padding: '14px 12px', textAlign: 'left',
                background: active ? 'var(--fg)' : 'var(--surface)',
                color: active ? 'var(--bg)' : 'var(--fg)',
                borderRight: i < options.length - 1 ? '1px solid var(--hairline)' : 'none',
                display: 'flex', flexDirection: 'column', gap: 4,
                cursor: 'pointer',
                transition: 'background var(--dur-base) var(--ease-out), color var(--dur-base) var(--ease-out)',
              }}>
              <span style={{ display: 'flex', alignItems: 'center', gap: 8, fontSize: 14, fontWeight: 500 }}>
                <span style={{
                  width: 8, height: 8,
                  background: active ? 'var(--accent)' : 'var(--hairline-strong)',
                  transition: 'background var(--dur-base) var(--ease-out)',
                }} />
                {opt.label}
              </span>
              <span style={{ fontSize: 11, color: active ? 'rgba(241,237,230,0.7)' : 'var(--fg-subtle)', fontFamily: 'var(--font-mono)', letterSpacing: '0.04em', textTransform: 'uppercase' }}>
                {opt.sub}
              </span>
            </button>
          );
        })}
      </div>
    </div>
  );
}

function BudgetSlider({ value, onChange }) {
  // value 0..100 maps to budget brackets
  const brackets = [
    { max: 15, label: '< 15 k€', sub: 'Pas notre standard — on vous orientera' },
    { max: 40, label: '15 – 40 k€', sub: 'Site vitrine / refonte simple' },
    { max: 80, label: '40 – 80 k€', sub: 'E-commerce / outil de production' },
    { max: 150, label: '80 – 150 k€', sub: 'Plateforme métier complète' },
    { max: 999, label: '> 150 k€', sub: 'Programme pluriannuel — sur-mesure' },
  ];
  const current = brackets.find((b) => value <= b.max) || brackets[brackets.length - 1];

  return (
    <div style={{ display: 'flex', flexDirection: 'column', gap: 14 }}>
      <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'baseline' }}>
        <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.1em', textTransform: 'uppercase' }}>
          Enveloppe budgétaire indicative
        </span>
        <span style={{ fontFamily: 'var(--font-display)', fontSize: 22, fontWeight: 500, letterSpacing: '-0.02em' }}>{current.label}</span>
      </div>

      <div style={{ position: 'relative' }}>
        <input type="range" min="0" max="100" value={value}
          onChange={(e) => onChange(Number(e.target.value))}
          style={{
            width: '100%', appearance: 'none', WebkitAppearance: 'none',
            background: 'transparent', height: 28,
          }} />
        <style>{`
          input[type=range]::-webkit-slider-runnable-track {
            height: 2px; background: var(--hairline-strong); border-radius: 0;
          }
          input[type=range]::-webkit-slider-thumb {
            -webkit-appearance: none; appearance: none;
            width: 14px; height: 28px; background: var(--accent);
            border-radius: 1px; margin-top: -13px; cursor: pointer;
            transition: transform var(--dur-fast) var(--ease-out);
          }
          input[type=range]::-webkit-slider-thumb:active { transform: scaleY(0.9); }
          input[type=range]::-moz-range-track {
            height: 2px; background: var(--hairline-strong);
          }
          input[type=range]::-moz-range-thumb {
            width: 14px; height: 28px; background: var(--accent);
            border-radius: 1px; border: none; cursor: pointer;
          }
        `}</style>
      </div>

      <span className="mz-mono" style={{ color: 'var(--fg-subtle)', letterSpacing: '0.08em' }}>
        ↳ {current.sub}
      </span>
    </div>
  );
}

function ContactSuccess({ form, refId, demo }) {
  const { go } = useRouter();
  return (
    <main className="mz-page" style={{ paddingBlock: 'var(--s-9)' }}>
      <div className="mz-container-wide" style={{ maxWidth: 820, marginInline: 'auto', textAlign: 'left' }}>
        <Eyebrow>↳ Demande reçue · réf. {refId}</Eyebrow>
        <h1 className="mz-display-xl" style={{ marginTop: 'var(--s-5)', maxWidth: '14ch' }}>
          Merci, <Em>{form.name.split(' ')[0] || 'à vous'}</Em>.
        </h1>
        <p className="mz-lead" style={{ marginTop: 'var(--s-5)', maxWidth: '54ch' }}>
          {demo
            ? <>Mode démonstration : aucun e-mail n'a été envoyé. En production, vous recevriez
               une confirmation à <Em>{form.email}</Em> sous 24 heures ouvrées.</>
            : <>Votre demande est arrivée. Un e-mail de confirmation vient de partir vers
               <Em> {form.email}</Em>. Un associé senior vous écrit personnellement
               sous <Em>24 heures ouvrées</Em> avec trois créneaux de 30 minutes.</>}
        </p>

        <div style={{ marginTop: 'var(--s-7)', border: '1px solid var(--hairline-strong)', padding: 'var(--s-5)', display: 'flex', flexDirection: 'column', gap: 'var(--s-3)' }}>
          <Eyebrow line={false}>Récapitulatif</Eyebrow>
          <SpecRow k="ENTREPRISE" v={form.company || '—'} />
          <SpecRow k="CONTACT" v={`${form.name} · ${form.email}`} />
          <SpecRow k="PROJET" v={({ web: 'Site web', ecom: 'E-commerce', saas: 'SaaS', mobile: 'Mobile', audit: 'Audit' })[form.type]} />
          <SpecRow k="ÉCHÉANCE" v={({ urgent: '< 1 mois', q3: '1 à 3 mois', q4: '3 à 6 mois', open: 'Sans contrainte' })[form.timeline]} />
        </div>

        <div style={{ marginTop: 'var(--s-6)', display: 'flex', gap: 12, flexWrap: 'wrap' }}>
          <button onClick={() => go('home')} className="mz-btn mz-btn-primary">
            Retour à l'atelier
          </button>
          <button onClick={() => go('case')} className="mz-btn mz-btn-ghost">
            Lire la pièce 47 en attendant
          </button>
        </div>
      </div>
    </main>
  );
}

Object.assign(window, { ContactPage });
