/* Page /audit-gratuit — formulaire qualifiant en plusieurs étapes (nom,
 * email, téléphone, entreprise, taille équipe, outils, pain point, budget,
 * timeline). Soumet à /api/form avec form_source: "audit". */

const { useState } = React;
const { Logo, ArrowUpRight, ThemeToggle, FooterMin } = window.BMShared;

const TOOLS = [
  'Sales Navigator', 'LinkedIn Sales Nav',
  'Make', 'Zapier', 'n8n',
  'HubSpot', 'Pipedrive', 'Salesforce',
  'Notion', 'Airtable', 'Google Sheets',
  'Gmail', 'Outlook',
  'Stripe', 'QuickBooks',
  'Slack', 'Calendly',
  'ChatGPT', 'Claude', 'Gemini',
  'Aucun pour l\'instant',
];

const TEAM_SIZES = [
  { value: '1', label: 'Solo' },
  { value: '2-5', label: '2 à 5' },
  { value: '6-10', label: '6 à 10' },
  { value: '11-20', label: '11 à 20' },
  { value: '20+', label: 'Plus de 20' },
];

const BUDGETS = [
  { value: '0-500', label: 'Moins de 500€/mois' },
  { value: '500-1500', label: '500 à 1500€/mois' },
  { value: '1500-3000', label: '1500 à 3000€/mois' },
  { value: '3000+', label: 'Plus de 3000€/mois' },
  { value: 'unsure', label: 'Pas encore sûr' },
];

const TIMELINES = [
  { value: 'asap', label: 'Dès maintenant' },
  { value: '1m', label: 'Dans le mois' },
  { value: '3m', label: "Dans 3 mois" },
  { value: '6m', label: 'Dans 6 mois ou plus' },
];

const AuditNav = () => {
  const [open, setOpen] = useState(false);
  return (
    <>
      <nav className="nav" id="nav">
        <a href="/" className="nav-logo" aria-label="Boom Maker"><Logo /></a>
        <div className="nav-links">
          <div className="nav-dropdown">
            <button type="button" className="nav-dropdown-trigger" aria-haspopup="true">
              Expertises <span className="nav-dropdown-caret">▾</span>
            </button>
            <div className="nav-dropdown-menu" role="menu">
              <a href="/expertises">3 piliers</a>
              <a href="/#process">Process</a>
              <a href="/partners">Partenaires</a>
            </div>
          </div>
          <a href="/#prix">Tarifs</a>
          <a href="/news">News</a>
          <div className="nav-dropdown">
            <button type="button" className="nav-dropdown-trigger" aria-haspopup="true">
              À propos <span className="nav-dropdown-caret">▾</span>
            </button>
            <div className="nav-dropdown-menu" role="menu">
              <a href="/a-propos">BoomMaker</a>
              <a href="/#faq">FAQ</a>
            </div>
          </div>
          <a href="/contact">Contact</a>
        </div>
        <ThemeToggle />
        <a href="/audit-gratuit" className="btn btn-glow nav-cta-desktop">Audit gratuit <ArrowUpRight /></a>
        <button className="nav-burger" aria-label="Menu" aria-expanded={open}
                onClick={() => setOpen((o) => !o)}>
          <span /><span /><span />
        </button>
      </nav>
      <div className={`nav-mobile ${open ? 'open' : ''}`} onClick={() => setOpen(false)}>
        <span className="nav-mobile-group">/ Expertises</span>
        <a href="/expertises">3 piliers</a>
        <a href="/#process">Process</a>
        <a href="/partners">Partenaires</a>
        <a href="/#prix">Tarifs</a>
        <a href="/news">News</a>
        <span className="nav-mobile-group">/ À propos</span>
        <a href="/a-propos">BoomMaker</a>
        <a href="/#faq">FAQ</a>
        <a href="/contact">Contact</a>
        <a href="/audit-gratuit" className="btn btn-glow">Audit gratuit <ArrowUpRight /></a>
      </div>
    </>
  );
};

const AuditPage = () => {
  const [form, setForm] = useState({
    name: '', email: '', phone: '', company: '',
    team_size: '', tools: [], pain_point: '',
    budget: '', timeline: '',
    rgpd: false, _gotcha: '',
  });
  const [status, setStatus] = useState('idle');
  const [error, setError] = useState('');

  const update = (field) => (e) => {
    const value = e.target.type === 'checkbox' ? e.target.checked : e.target.value;
    setForm((f) => ({ ...f, [field]: value }));
  };

  const toggleTool = (tool) => {
    setForm((f) => ({
      ...f,
      tools: f.tools.includes(tool)
        ? f.tools.filter((t) => t !== tool)
        : [...f.tools, tool],
    }));
  };

  const submit = async (e) => {
    e.preventDefault();
    if (status === 'sending') return;
    setStatus('sending');
    setError('');
    try {
      const res = await fetch('/api/form', {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify({ ...form, form_source: 'audit' }),
      });
      const data = await res.json().catch(() => ({}));
      if (!res.ok) {
        setError(data.error || 'Aïe, ça a coincé. Réessaye dans 30 secondes ?');
        setStatus('error');
        return;
      }
      setStatus('success');
    } catch (err) {
      setError('Aïe, ça a coincé. Réessaye dans 30 secondes ?');
      setStatus('error');
    }
  };

  return (
    <div className="audit-page">
      <AuditNav />

      <article className="audit-hero">
        <div className="container">
          <a href="/" className="legal-back">← Retour à l'accueil</a>
          <span className="eyebrow"><span className="pulse" /> 30 minutes · gratuit · sans engagement</span>
          <h1>Audit gratuit de <em>ton workflow.</em></h1>
          <p className="lead">
            Réponds à 7 questions (5 min). Je regarde ce qui peut être automatisé chez toi et je te dis ce qui vaut le coup. <strong>Pas de discours marketing</strong> — juste des chiffres et des recos concrètes.
          </p>
        </div>
      </article>

      <section className="audit-form-section">
        <div className="container audit-grid">
          <div className="audit-why">
            <h3>Pourquoi remplir l'audit avant l'appel ?</h3>
            <ul>
              <li>Je viens à l'appel <strong>déjà préparée</strong> avec une analyse de ton contexte</li>
              <li>On gagne 20 minutes de "présentations" pour aller direct au concret</li>
              <li>Tu reçois un <strong>retour écrit en 24h</strong> avec 3 pistes priorisées par ROI</li>
              <li>Si on n'est pas un fit, je te le dis franchement et je redirige vers la bonne ressource</li>
            </ul>
          </div>

          {status === 'success' ? (
            <div className="audit-form audit-success">
              <div className="success-icon">✓</div>
              <h3>Bien reçu. Merci pour ton temps.</h3>
              <p>Je regarde ton contexte aujourd'hui et je te reviens sous 24h sur <strong>{form.email}</strong> avec mon analyse + 3 pistes concrètes.</p>
              <p style={{ fontSize: 14, color: 'var(--mute)' }}>Pendant ce temps, tu peux <a href="https://calendly.com/julia-boommaker/30min" target="_blank" rel="noopener noreferrer" style={{ color: 'var(--violet-2)' }}>déjà réserver 30 min</a> dans mon agenda — comme ça on se cale tout de suite après ma réponse.</p>
              <a href="/news" className="btn btn-ghost">Lire des articles en attendant <ArrowUpRight /></a>
            </div>
          ) : (
            <form className="audit-form" onSubmit={submit} noValidate>
              <input type="text" name="_gotcha" value={form._gotcha} onChange={update('_gotcha')}
                     className="form-honeypot" tabIndex="-1" autoComplete="off" aria-hidden="true" />

              {/* Étape 1 — Identité */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 01 — Toi</span>
                </div>
                <p className="step-help">Pour qu'on sache à qui on parle.</p>
                <div className="form-row">
                  <label>
                    <span className="form-lbl">Ton nom *</span>
                    <input type="text" required value={form.name} onChange={update('name')}
                           placeholder="Julia Levy" maxLength="100" />
                  </label>
                  <label>
                    <span className="form-lbl">Ton email *</span>
                    <input type="email" required value={form.email} onChange={update('email')}
                           placeholder="julia@tonentreprise.fr" maxLength="200" />
                  </label>
                </div>
                <div className="form-row">
                  <label>
                    <span className="form-lbl">Ton téléphone</span>
                    <input type="tel" value={form.phone} onChange={update('phone')}
                           placeholder="06 12 34 56 78" maxLength="50" />
                  </label>
                  <label>
                    <span className="form-lbl">Ton entreprise *</span>
                    <input type="text" required value={form.company} onChange={update('company')}
                           placeholder="Boom Maker" maxLength="200" />
                  </label>
                </div>
              </div>

              {/* Étape 2 — Taille équipe */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 02 — Ton équipe</span>
                </div>
                <p className="step-help">Combien êtes-vous dans la boîte ?</p>
                <div className="form-checkbox-group">
                  {TEAM_SIZES.map((opt) => (
                    <label key={opt.value} className={form.team_size === opt.value ? 'checked' : ''}>
                      <input type="radio" name="team_size" value={opt.value}
                             checked={form.team_size === opt.value}
                             onChange={update('team_size')}
                             style={{ accentColor: 'var(--violet)' }} />
                      <span>{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Étape 3 — Outils actuels */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 03 — Tes outils actuels</span>
                </div>
                <p className="step-help">Coche ce que tu utilises (plusieurs réponses possibles).</p>
                <div className="form-checkbox-group">
                  {TOOLS.map((tool) => (
                    <label key={tool} className={form.tools.includes(tool) ? 'checked' : ''}>
                      <input type="checkbox" checked={form.tools.includes(tool)}
                             onChange={() => toggleTool(tool)} />
                      <span>{tool}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Étape 4 — Pain point */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 04 — Ton problème principal</span>
                </div>
                <p className="step-help">Qu'est-ce qui te fait perdre le plus de temps aujourd'hui ?</p>
                <label className="form-full">
                  <textarea required rows="4" value={form.pain_point} onChange={update('pain_point')}
                            placeholder="Ex: 'Je passe 6h/semaine à relancer mes prospects à la main' / 'Mon CRM n'est jamais à jour' / 'Mes factures partent avec 3 semaines de retard'…"
                            maxLength="2000" />
                </label>
              </div>

              {/* Étape 5 — Budget */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 05 — Ton budget</span>
                </div>
                <p className="step-help">Pour qu'on ne te propose pas une Ferrari si tu cherches une Twingo.</p>
                <div className="form-checkbox-group">
                  {BUDGETS.map((opt) => (
                    <label key={opt.value} className={form.budget === opt.value ? 'checked' : ''}>
                      <input type="radio" name="budget" value={opt.value}
                             checked={form.budget === opt.value}
                             onChange={update('budget')}
                             style={{ accentColor: 'var(--violet)' }} />
                      <span>{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* Étape 6 — Timeline */}
              <div className="audit-form-step">
                <div className="step-meta">
                  <span className="step-num">/ 06 — Quand veux-tu démarrer ?</span>
                </div>
                <div className="form-checkbox-group">
                  {TIMELINES.map((opt) => (
                    <label key={opt.value} className={form.timeline === opt.value ? 'checked' : ''}>
                      <input type="radio" name="timeline" value={opt.value}
                             checked={form.timeline === opt.value}
                             onChange={update('timeline')}
                             style={{ accentColor: 'var(--violet)' }} />
                      <span>{opt.label}</span>
                    </label>
                  ))}
                </div>
              </div>

              {/* RGPD */}
              <label className="form-checkbox">
                <input type="checkbox" required checked={form.rgpd} onChange={update('rgpd')} />
                <span>J'accepte que mes données soient traitées conformément à la <a href="/politique-de-confidentialite" target="_blank">politique de confidentialité</a>. Je peux retirer mon consentement à tout moment en envoyant un email à julia@boommaker.io.</span>
              </label>

              {status === 'error' && (
                <div className="form-error" role="alert">{error}</div>
              )}

              <button type="submit" className="btn btn-glow form-submit" disabled={status === 'sending'}>
                {status === 'sending' ? 'Envoi…' : 'Recevoir mon audit'} <ArrowUpRight />
              </button>
              <span className="form-hint">Retour écrit sous 24h · sans engagement · zéro pitch</span>
            </form>
          )}
        </div>
      </section>

      <FooterMin />
    </div>
  );
};

ReactDOM.createRoot(document.getElementById('root')).render(<AuditPage />);
