// NeoFlow — Pages formulaires dédiées (immo + home)
const { useState: fSt, useEffect: fEff } = React;

const WH_IMMO_REPONDRE_FULL = 'https://n8n.srv1137119.hstgr.cloud/webhook/immo-repondre';
const WH_IMMO_QUESTION_FULL  = 'https://n8n.srv1137119.hstgr.cloud/webhook/immo-question';
const WH_DEMARRER            = 'https://n8n.srv1137119.hstgr.cloud/webhook/demarrer-projet';
const WH_QUESTION            = 'https://n8n.srv1137119.hstgr.cloud/webhook/question';
const CAL_LINK = 'noakim-grelier/appel-decouverte';

/* ── Shell commun des pages formulaire ── */
function FormPageShell({ title, section, back, children }) {
  return (
    <div className="form-page">
      <div className="form-page-header">
        <div className="wrap">
          <button className="legal-back mono" onClick={back}>← Retour</button>
          <div className="mono section-n">{section}</div>
          <h1 className="legal-title">{title}</h1>
        </div>
      </div>
      <div className="form-page-body wrap">{children}</div>
    </div>
  );
}

/* ── Boutons à choix unique ── */
function ChoiceGroup({ options, value, onChange }) {
  return (
    <div className="choice-group">
      {options.map((opt, i) => (
        <button
          key={i}
          type="button"
          className={`choice-btn ${value === opt ? 'is-selected' : ''}`}
          onClick={() => onChange(opt)}
        >
          <span className="choice-letter mono">{String.fromCharCode(65 + i)}</span>
          <span>{opt}</span>
        </button>
      ))}
    </div>
  );
}

/* ── Cases à cocher multi-select ── */
function CheckGroup({ options, value, onChange }) {
  function toggle(opt) {
    onChange(value.includes(opt) ? value.filter(v => v !== opt) : [...value, opt]);
  }
  return (
    <div className="check-group">
      {options.map((opt, i) => (
        <label key={i} className={`check-item ${value.includes(opt) ? 'is-checked' : ''}`}>
          <input type="checkbox" checked={value.includes(opt)} onChange={() => toggle(opt)} />
          <span className="check-box" aria-hidden="true">
            {value.includes(opt) && (
              <svg width="10" height="8" viewBox="0 0 10 8" fill="none">
                <path d="M1 4l3 3 5-6" stroke="currentColor" strokeWidth="1.5" strokeLinecap="round" strokeLinejoin="round"/>
              </svg>
            )}
          </span>
          <span>{opt}</span>
        </label>
      ))}
    </div>
  );
}

/* ── Barre de progression ── */
function ProgressBar({ step, total }) {
  return (
    <div className="form-progress" role="progressbar" aria-valuenow={step + 1} aria-valuemax={total}>
      {Array.from({ length: total }).map((_, i) => (
        <div key={i} className={`form-progress-seg ${i <= step ? 'is-done' : ''}`}></div>
      ))}
    </div>
  );
}

/* =========================================================
   ImmoRepondre — questionnaire customer discovery 4 étapes
   ========================================================= */
function ImmoRepondre({ setRoute }) {
  const [step, setStep] = fSt(0);
  const [sent, setSent] = fSt(false);
  const [loading, setLoading] = fSt(false);
  const [ans, setAns] = fSt({
    taille: '',
    outils_quotidien: [],
    outils_satisfait: '',
    site_web: '',
    tache_temps: '',
    perte_prospects: '',
    fonctionnalites: [],
    manques: '',
    automatiser: '',
    echange: '',
    email: '',
  });

  function set(key, val) { setAns(a => ({ ...a, [key]: val })); }

  const STEPS = 4;

  async function submit() {
    setLoading(true);
    try {
      await fetch(WH_IMMO_REPONDRE_FULL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(ans),
      });
    } catch (_) {}
    if (window.posthog) window.posthog.capture('form_submit', { form: 'immo_repondre_full' });
    setLoading(false);
    setSent(true);
  }

  if (sent) return (
    <FormPageShell title="Merci." section="NeoFlow Immo · Réponses" back={() => setRoute('/immobilier')}>
      <div className="form-sent-screen">
        <p className="form-sent-lead">Chaque réponse compte vraiment.</p>
        <p>Je construis cet outil depuis le terrain, pas depuis une idée en l'air. Si vous avez laissé votre email, je reviendrai vers vous.</p>
        <button className="btn btn-ghost" style={{ marginTop: '32px' }} onClick={() => setRoute('/immobilier')}>
          <span>Retour à NeoFlow Immo</span>
          <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>
        </button>
      </div>
    </FormPageShell>
  );

  return (
    <FormPageShell
      title="Partagez votre quotidien."
      section={`NeoFlow Immo · Étape ${step + 1} / ${STEPS}`}
      back={() => step === 0 ? setRoute('/immobilier') : setStep(s => s - 1)}
    >
      <ProgressBar step={step} total={STEPS} />

      {/* Étape 1 — Votre agence */}
      {step === 0 && (
        <div className="form-step">
          <div className="form-q">
            <span className="form-q-label">Quelle est la taille de votre agence ?</span>
            <ChoiceGroup
              value={ans.taille}
              onChange={v => set('taille', v)}
              options={['Indépendant', '2–5 personnes', '6–15 personnes', '+15 personnes']}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Quels outils utilisez-vous au quotidien dans votre agence ?</span>
            <CheckGroup
              value={ans.outils_quotidien}
              onChange={v => set('outils_quotidien', v)}
              options={[
                'Un logiciel de gestion / CRM immobilier',
                "Un outil de création ou gestion de site web",
                "Des portails d'annonces (SeLoger, LeBonCoin, PAP...)",
                "Des outils de communication (WhatsApp pro, email dédié...)",
                "Aucun outil particulier — tout à la main",
                "Autre",
              ]}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Si vous en utilisez, lesquels — et vous en êtes satisfait ?</span>
            <textarea
              className="fld-textarea"
              rows="3"
              placeholder="Ex. Apimo depuis 3 ans, pas mal mais les relances manquent..."
              value={ans.outils_satisfait}
              onChange={e => set('outils_satisfait', e.target.value)}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Votre site web, ça se passe comment ?</span>
            <ChoiceGroup
              value={ans.site_web}
              onChange={v => set('site_web', v)}
              options={[
                "Je n'ai pas de site, ou il est très basique",
                "Un prestataire gère ça, je ne peux rien modifier moi-même",
                "Je le gère moi-même mais c'est chronophage",
                "Pas de problème de ce côté",
              ]}
            />
          </div>
        </div>
      )}

      {/* Étape 2 — Vos défis */}
      {step === 1 && (
        <div className="form-step">
          <div className="form-q">
            <span className="form-q-label">Quelle tâche vous prend le plus de temps inutilement chaque semaine ?</span>
            <p className="form-q-hint">Ne vous censurez pas — la réponse honnête est la plus utile.</p>
            <textarea
              className="fld-textarea"
              rows="5"
              value={ans.tache_temps}
              onChange={e => set('tache_temps', e.target.value)}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Il vous arrive de perdre des prospects parce que vous n'avez pas eu le temps de les relancer ?</span>
            <ChoiceGroup
              value={ans.perte_prospects}
              onChange={v => set('perte_prospects', v)}
              options={['Oui, souvent', 'Parfois', 'Rarement', 'Pas de problème de ce côté']}
            />
          </div>
        </div>
      )}

      {/* Étape 3 — Ce dont vous avez besoin */}
      {step === 2 && (
        <div className="form-step">
          <div className="form-q">
            <span className="form-q-label">Parmi ces fonctionnalités, lesquelles vous sembleraient les plus utiles ?</span>
            <CheckGroup
              value={ans.fonctionnalites}
              onChange={v => set('fonctionnalites', v)}
              options={[
                'Gestion des dossiers de location',
                'Relances automatiques des prospects',
                'Site vitrine moderne connecté au CRM',
                'Agenda + prise de RDV en ligne',
                'Suivi des mandats avec alertes avant expiration',
                "Tableau de bord KPIs de l'agence",
                "Estimation en ligne boostée par l'IA",
                'Agent IA sur votre site — répond aux visiteurs 24h/24',
                'Centralisation des documents par dossier',
                'CRM avec pipeline visuel',
                'Suivi des transactions',
              ]}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Qu'est-ce que vous n'arrivez pas à faire aujourd'hui faute de temps ou d'outil, mais que vous aimeriez faire ?</span>
            <textarea
              className="fld-textarea"
              rows="3"
              placeholder="Ex. relancer tous mes prospects chaque semaine, avoir un vrai suivi de mes mandats..."
              value={ans.manques}
              onChange={e => set('manques', e.target.value)}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">Si vous pouviez supprimer ou automatiser une seule chose dans votre quotidien, ce serait quoi ?</span>
            <p className="form-q-hint">Une seule — la plus pénible.</p>
            <textarea
              className="fld-textarea"
              rows="3"
              value={ans.automatiser}
              onChange={e => set('automatiser', e.target.value)}
            />
          </div>
        </div>
      )}

      {/* Étape 4 — Contact */}
      {step === 3 && (
        <div className="form-step">
          <div className="form-q">
            <span className="form-q-label">Est-ce que vous seriez partant pour échanger quelques minutes avec moi pour approfondir vos réponses ?</span>
            <ChoiceGroup
              value={ans.echange}
              onChange={v => set('echange', v)}
              options={['Oui, volontiers', 'Peut-être, à voir', 'Non, mais je veux suivre le projet', 'Non merci']}
            />
          </div>
          <div className="form-q">
            <span className="form-q-label">
              Votre email{' '}
              <span className="form-q-opt">(pour vous recontacter ou vous tenir informé)</span>
            </span>
            <input
              className="fld-input"
              type="email"
              placeholder="votre@email.com"
              value={ans.email}
              onChange={e => set('email', e.target.value)}
            />
          </div>
        </div>
      )}

      <div className="form-nav">
        {step < STEPS - 1 ? (
          <button className="btn btn-primary big" type="button" onClick={() => setStep(s => s + 1)}>
            <span>Suivant</span>
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>
          </button>
        ) : (
          <button className="btn btn-primary big" type="button" onClick={submit} disabled={loading}>
            <span>{loading ? 'Envoi…' : 'Envoyer mes réponses'}</span>
            {!loading && <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>}
          </button>
        )}
        {step > 0 && (
          <button className="btn btn-ghost" type="button" onClick={() => setStep(s => s - 1)}>
            <span>Précédent</span>
          </button>
        )}
      </div>
    </FormPageShell>
  );
}

/* =========================================================
   ImmoAppelPage — prise de RDV via Cal.com (iframe)
   ========================================================= */
function ImmoAppelPage({ setRoute }) {
  return (
    <FormPageShell title="Réserver un appel." section="NeoFlow Immo · Prise de RDV" back={() => setRoute('/immobilier')}>
      <p className="form-q-hint" style={{ marginBottom: '32px', fontSize: '15px', opacity: 0.65 }}>
        Un appel découverte de 30 minutes — sans engagement. Choisissez le créneau qui vous convient.
      </p>
      <div className="cal-container">
        <iframe
          src={`https://cal.com/${CAL_LINK}?embed=true&layout=month_view&theme=light`}
          style={{ width: '100%', height: '680px', border: 'none', borderRadius: '8px' }}
          title="Réserver un appel découverte"
          loading="lazy"
        />
      </div>
    </FormPageShell>
  );
}

/* =========================================================
   ImmoQuestionPage — question simple (page dédiée)
   ========================================================= */
function ImmoQuestionPage({ setRoute }) {
  const [sent, setSent] = fSt(false);
  const [loading, setLoading] = fSt(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    const data = Object.fromEntries(new FormData(e.target));
    try {
      await fetch(WH_IMMO_QUESTION_FULL, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
    } catch (_) {}
    if (window.posthog) window.posthog.capture('form_submit', { form: 'immo_question_page' });
    setLoading(false);
    setSent(true);
  }

  return (
    <FormPageShell title="Posez votre question." section="NeoFlow Immo · Contact" back={() => setRoute('/immobilier')}>
      {sent ? (
        <div className="form-sent-screen">
          <p className="form-sent-lead">Message envoyé.</p>
          <p>On répond sous 24h.</p>
          <button className="btn btn-ghost" style={{ marginTop: '32px' }} onClick={() => setRoute('/immobilier')}>
            <span>Retour à NeoFlow Immo</span>
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>
          </button>
        </div>
      ) : (
        <form className="form" style={{ maxWidth: '560px' }} onSubmit={handleSubmit}>
          <div className="form-row">
            <label className="field"><span>Prénom</span><input name="prenom" type="text" required /></label>
            <label className="field"><span>Nom</span><input name="nom" type="text" required /></label>
          </div>
          <label className="field"><span>Email</span><input name="email" type="email" required /></label>
          <label className="field"><span>Message</span><textarea name="message" rows="5" required></textarea></label>
          <button type="submit" className="btn btn-primary big" disabled={loading}>
            <span>{loading ? 'Envoi…' : 'Envoyer'}</span>
            {!loading && <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>}
          </button>
        </form>
      )}
    </FormPageShell>
  );
}

/* =========================================================
   DemarrerPage — formulaire "démarrer un projet" (page home)
   ========================================================= */
function DemarrerPage({ setRoute }) {
  const [sent, setSent] = fSt(false);
  const [loading, setLoading] = fSt(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    const data = Object.fromEntries(new FormData(e.target));
    try {
      await fetch(WH_DEMARRER, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
    } catch (_) {}
    if (window.posthog) window.posthog.capture('form_submit', { form: 'demarrer_projet' });
    setLoading(false);
    setSent(true);
  }

  return (
    <FormPageShell title="Démarrer un projet." section="NeoFlow Agency · Contact" back={() => setRoute('/')}>
      {sent ? (
        <div className="form-sent-screen">
          <p className="form-sent-lead">Merci — on vous revient sous 24h.</p>
          <p>On a bien reçu votre demande et on reviendra vers vous rapidement avec une proposition concrète.</p>
          <button className="btn btn-ghost" style={{ marginTop: '32px' }} onClick={() => setRoute('/')}>
            <span>Retour à l'accueil</span>
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>
          </button>
        </div>
      ) : (
        <form className="form" style={{ maxWidth: '640px' }} onSubmit={handleSubmit}>
          <div className="form-q" style={{ marginBottom: '0' }}>
            <span className="form-q-label">Qui êtes-vous ?</span>
          </div>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <label className="field"><span>Prénom</span><input name="prenom" type="text" required /></label>
            <label className="field"><span>Nom</span><input name="nom" type="text" required /></label>
          </div>
          <label className="field"><span>Entreprise / Structure <em style={{ fontStyle:'normal', opacity:0.55, fontSize:'12px' }}>(optionnel)</em></span><input name="entreprise" type="text" /></label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <label className="field"><span>Email</span><input name="email" type="email" required /></label>
            <label className="field"><span>Téléphone <em style={{ fontStyle:'normal', opacity:0.55, fontSize:'12px' }}>(optionnel)</em></span><input name="telephone" type="tel" /></label>
          </div>
          <label className="field"><span>Secteur d'activité</span><input name="secteur" type="text" placeholder="Ex. cabinet d'avocats, restauration, e-commerce…" /></label>
          <label className="field">
            <span>Parlez-nous de votre projet</span>
            <textarea name="projet" rows="5" required placeholder="Qu'est-ce que vous cherchez à accomplir ? Quel problème résoudre ?"></textarea>
          </label>
          <label className="field"><span>Outils actuellement utilisés</span><input name="outils" type="text" placeholder="Ex. Excel, Gmail, un CRM…" /></label>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <label className="field"><span>Budget approximatif <em style={{ fontStyle:'normal', opacity:0.55, fontSize:'12px' }}>(optionnel)</em></span><input name="budget" type="text" placeholder="Ex. 2 000 €, pas encore défini…" /></label>
            <label className="field"><span>Délai souhaité <em style={{ fontStyle:'normal', opacity:0.55, fontSize:'12px' }}>(optionnel)</em></span><input name="delai" type="text" placeholder="Ex. dans 3 mois, dès que possible…" /></label>
          </div>
          <button type="submit" className="btn btn-primary big" disabled={loading}>
            <span>{loading ? 'Envoi…' : 'Envoyer ma demande'}</span>
            {!loading && <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>}
          </button>
        </form>
      )}
    </FormPageShell>
  );
}

/* =========================================================
   QuestionPage — formulaire "poser une question" (page home)
   ========================================================= */
function QuestionPage({ setRoute }) {
  const [sent, setSent] = fSt(false);
  const [loading, setLoading] = fSt(false);

  async function handleSubmit(e) {
    e.preventDefault();
    setLoading(true);
    const data = Object.fromEntries(new FormData(e.target));
    try {
      await fetch(WH_QUESTION, {
        method: 'POST',
        headers: { 'Content-Type': 'application/json' },
        body: JSON.stringify(data),
      });
    } catch (_) {}
    if (window.posthog) window.posthog.capture('form_submit', { form: 'question' });
    setLoading(false);
    setSent(true);
  }

  return (
    <FormPageShell title="Posez votre question." section="NeoFlow Agency · Contact" back={() => setRoute('/')}>
      {sent ? (
        <div className="form-sent-screen">
          <p className="form-sent-lead">Message envoyé.</p>
          <p>On répond sous 24h.</p>
          <button className="btn btn-ghost" style={{ marginTop: '32px' }} onClick={() => setRoute('/')}>
            <span>Retour à l'accueil</span>
            <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>
          </button>
        </div>
      ) : (
        <form className="form" style={{ maxWidth: '560px' }} onSubmit={handleSubmit}>
          <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: '12px' }}>
            <label className="field"><span>Prénom</span><input name="prenom" type="text" required /></label>
            <label className="field"><span>Nom</span><input name="nom" type="text" required /></label>
          </div>
          <label className="field"><span>Email</span><input name="email" type="email" required /></label>
          <label className="field"><span>Message</span><textarea name="message" rows="5" required placeholder="Votre question…"></textarea></label>
          <button type="submit" className="btn btn-primary big" disabled={loading}>
            <span>{loading ? 'Envoi…' : 'Envoyer'}</span>
            {!loading && <svg width="14" height="10" viewBox="0 0 14 10" fill="none"><path d="M1 5h12m0 0L9 1m4 4L9 9" stroke="currentColor" strokeWidth="1.4"/></svg>}
          </button>
        </form>
      )}
    </FormPageShell>
  );
}

Object.assign(window, { ImmoRepondre, ImmoAppelPage, ImmoQuestionPage, DemarrerPage, QuestionPage });
