// ============================================================
// RECRUTEMENT PROFESSEURS — /professeurs
// Candidature enseignant → POST /api/lead (type_demandeur: "prof") → CRM Supabase.
// Page autonome : styles embarqués, aucune dépendance à premium.css (en refonte).
// ============================================================

const { useState: useProfS, useEffect: useProfE } = React;

const PR_FILIERES = [
  { label: "Prépa scientifique", items: ["MPSI", "PCSI", "PTSI", "MP2I", "MP", "PC", "PSI", "PT", "BCPST", "TSI"] },
  { label: "Prépa commerciale", items: ["ECG maths appro", "ECG maths appli", "ECS", "ECE", "ECT", "Prépa D1/D2"] },
  { label: "Prépa littéraire", items: ["Hypokhâgne / Khâgne A-L", "Khâgne B-L", "Chartes"] },
  { label: "Autre parcours", items: ["Université", "Médecine (PASS / LAS)", "IUT / BUT", "Admission parallèle (AST)", "Autre"] },
];

// Année d'intégration de l'école : de l'an prochain à dix ans en arrière.
const PR_ANNEES = (() => {
  const y = new Date().getFullYear();
  const out = [];
  for (let a = y + 1; a >= y - 10; a--) out.push(String(a));
  return out;
})();

const PR_MATIERES = [
  "Mathématiques", "Physique-Chimie", "SI", "Informatique / NSI", "SVT",
  "Économie (ECG / ESH)", "Géopolitique", "Français / Philosophie",
  "Culture générale", "Anglais", "Espagnol", "Autre",
];

const PR_ATOUTS = [
  {
    titre: "Des élèves qui visent haut",
    texte: "Terminales qui préparent une CPGE, étudiants de prépa et de licence. Des profils motivés, avec un objectif clair.",
  },
  {
    titre: "Une rémunération à la hauteur",
    texte: "Le tarif reflète ton parcours et ton niveau d'exigence. Il se discute avec toi, jamais imposé par une grille anonyme.",
  },
  {
    titre: "Tu gardes la main",
    texte: "Tes matières, tes niveaux, tes créneaux, ton volume horaire. On te propose des élèves, tu acceptes ou non.",
  },
];

const PR_CSS = `
.pr-page { background: #FDFCF8; color: #0F1B2D; font-family: Inter, -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; min-height: 100vh; }
.pr-wrap { max-width: 1060px; margin: 0 auto; padding: 0 24px; }

.pr-top { border-bottom: 1px solid #ECE7DA; background: #fff; }
.pr-top .pr-wrap { display: flex; align-items: center; justify-content: space-between; height: 74px; }
.pr-top img { height: 34px; width: auto; display: block; }
.pr-top span { font-size: 12px; letter-spacing: 0.2em; text-transform: uppercase; font-weight: 700; color: #8A7433; }

.pr-hero { position: relative; overflow: hidden; padding: 68px 0 60px;
  background: radial-gradient(120% 150% at 50% -20%, #1B3A6B 0%, #10203A 55%, #0B1526 100%); color: #FDFCF8; }
.pr-hero::before { content: ""; position: absolute; inset: 0; pointer-events: none;
  background: radial-gradient(closest-side, rgba(201,164,77,0.16), transparent 70%) 15% 8% / 44% 60% no-repeat,
              radial-gradient(closest-side, rgba(123,179,232,0.12), transparent 70%) 90% 95% / 50% 65% no-repeat; }
.pr-glyphs { position: absolute; inset: 0; overflow: hidden; pointer-events: none; }
.pr-glyphs span { position: absolute; font-family: "Instrument Serif", Georgia, serif; font-style: italic;
  color: rgba(201,164,77,0.07); line-height: 1; user-select: none; }
.pr-hero .pr-wrap { position: relative; z-index: 1; }
.pr-tag { display: inline-flex; align-items: center; gap: 9px; padding: 8px 20px; border-radius: 999px;
  background: rgba(201,164,77,0.12); border: 1px solid rgba(201,164,77,0.42);
  font-size: 11.5px; font-weight: 700; letter-spacing: 0.18em; text-transform: uppercase; color: #E8D9AE; }
.pr-tag i { width: 7px; height: 7px; border-radius: 50%; background: #C9A44D; }
.pr-h1 { font-family: "Instrument Serif", Georgia, serif; font-weight: 400; font-size: clamp(31px, 5.2vw, 50px);
  line-height: 1.09; letter-spacing: -0.015em; margin: 22px 0 0; max-width: 15ch; text-wrap: balance; }
.pr-h1 em { font-style: italic; color: #E8D9AE; }
.pr-lead { margin: 20px 0 0; max-width: 58ch; font-size: clamp(15px, 2vw, 17px); line-height: 1.65; color: rgba(253,252,248,0.76); }

.pr-atouts { display: grid; grid-template-columns: repeat(3, 1fr); gap: 18px; margin: 40px 0 0; }
.pr-atout { background: rgba(253,252,248,0.055); border: 1px solid rgba(253,252,248,0.13); border-radius: 15px; padding: 20px 20px 22px; }
.pr-atout h3 { font-size: 15.5px; font-weight: 700; margin: 0 0 7px; }
.pr-atout p { margin: 0; font-size: 13.5px; line-height: 1.6; color: rgba(253,252,248,0.68); }

.pr-form-section { padding: 56px 0 84px; }
.pr-form { max-width: 620px; margin: 0 auto; }
.pr-form-head { text-align: center; margin-bottom: 32px; }
.pr-eyebrow { font-size: 11.5px; letter-spacing: 0.24em; text-transform: uppercase; font-weight: 700; color: #8A7433; }
.pr-h2 { font-family: "Instrument Serif", Georgia, serif; font-weight: 400; font-size: clamp(26px, 4vw, 36px);
  line-height: 1.15; margin: 12px 0 0; color: #0F1B2D; }
.pr-h2 em { font-style: italic; color: #8A7433; }
.pr-note { margin: 12px 0 0; font-size: 14.5px; color: #5F6A7D; line-height: 1.6; }

.pr-block { background: #fff; border: 1px solid #ECE7DA; border-radius: 16px; padding: 26px 26px 28px; }
.pr-grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; }
.pr-field { display: flex; flex-direction: column; gap: 7px; margin-bottom: 15px; }
.pr-field:last-child { margin-bottom: 0; }
.pr-field label { font-size: 13.5px; font-weight: 600; color: #33425A; }
.pr-field label .opt { font-weight: 400; color: #8A99B3; }
.pr-field input, .pr-field select {
  font-family: inherit; font-size: 15px; color: #0F1B2D; background: #FDFCF8;
  border: 1px solid #DFD9C9; border-radius: 10px; padding: 11px 13px; width: 100%;
  transition: border-color .18s, box-shadow .18s;
}
.pr-field input:focus, .pr-field select:focus {
  outline: none; border-color: #C9A44D; box-shadow: 0 0 0 3px rgba(201,164,77,0.16);
}
.pr-field.err input, .pr-field.err select { border-color: #D4574E; }
.pr-err { font-size: 12.5px; color: #C0392B; }

.pr-chips { display: flex; flex-wrap: wrap; gap: 8px; }
.pr-chip { font-family: inherit; font-size: 13.5px; padding: 8px 15px; border-radius: 999px; cursor: pointer;
  background: #FDFCF8; border: 1px solid #DFD9C9; color: #33425A; transition: all .18s; }
.pr-chip:hover { border-color: #C9A44D; }
.pr-chip.on { background: #0F1B2D; border-color: #0F1B2D; color: #FDFCF8; font-weight: 600; }
.pr-field.err .pr-chips { padding: 4px; border-radius: 10px; outline: 1px solid #D4574E; }

.pr-submit { width: 100%; margin-top: 20px; padding: 16px 24px; border: none; border-radius: 12px; cursor: pointer;
  font-family: inherit; font-size: 16px; font-weight: 700; color: #0F1B2D;
  background: linear-gradient(135deg, #E8CE8E 0%, #C9A44D 100%);
  box-shadow: 0 6px 22px rgba(201,164,77,0.32); transition: transform .18s, box-shadow .18s; }
.pr-submit:hover:not(:disabled) { transform: translateY(-1px); box-shadow: 0 9px 28px rgba(201,164,77,0.42); }
.pr-submit:disabled { opacity: 0.6; cursor: default; }
.pr-legal { margin: 14px 0 0; font-size: 12.5px; color: #8A99B3; text-align: center; line-height: 1.55; }
.pr-fail { margin: 14px 0 0; padding: 12px 15px; border-radius: 10px; background: #FDECEA; border: 1px solid #F5C6C2;
  color: #922B21; font-size: 14px; line-height: 1.5; }

.pr-done { max-width: 620px; margin: 0 auto; text-align: center; padding: 72px 0 96px; }
.pr-done-ico { width: 68px; height: 68px; margin: 0 auto 26px; border-radius: 50%;
  background: rgba(201,164,77,0.14); border: 1px solid rgba(201,164,77,0.45);
  display: flex; align-items: center; justify-content: center; color: #8A7433; }
.pr-done h2 { font-family: "Instrument Serif", Georgia, serif; font-weight: 400; font-size: clamp(28px, 4.4vw, 40px);
  line-height: 1.14; margin: 0; }
.pr-done h2 em { font-style: italic; color: #8A7433; }
.pr-done p { margin: 18px 0 0; font-size: 16px; line-height: 1.65; color: #5F6A7D; }

@media (max-width: 860px) {
  .pr-hero { padding: 48px 0 44px; }
  .pr-atouts { grid-template-columns: 1fr; gap: 12px; margin-top: 30px; }
  .pr-grid2 { grid-template-columns: 1fr; gap: 0; }
  .pr-glyphs span { display: none; }
  .pr-form-section { padding: 40px 0 60px; }
  .pr-block { padding: 20px 18px 22px; }
  .pr-top .pr-wrap { height: 62px; }
  .pr-top span { display: none; }
}
@media (prefers-reduced-motion: reduce) {
  .pr-submit { transition: none; }
  .pr-submit:hover:not(:disabled) { transform: none; }
}
`;

function ProfRecrutementLanding() {
  const [v, setV] = useProfS({
    prenom: "", nom: "", email: "", tel: "",
    ecole: "", filiere: "", prepa: "", annee: "", matieres: [],
  });
  const [errors, setErrors] = useProfS({});
  const [sending, setSending] = useProfS(false);
  const [sent, setSent] = useProfS(false);
  const [failure, setFailure] = useProfS("");

  useProfE(() => {
    document.title = "Devenir professeur — Cours Edgar";
    try {
      const p = new URLSearchParams(window.location.search);
      ["utm_source", "utm_medium", "utm_campaign"].forEach((k) => {
        const val = p.get(k);
        if (val) sessionStorage.setItem("ce_" + k, val);
      });
    } catch (_) {}
  }, []);

  const set = (k, val) => {
    setV((prev) => Object.assign({}, prev, { [k]: val }));
    setErrors((prev) => {
      if (!prev[k]) return prev;
      const next = Object.assign({}, prev);
      delete next[k];
      return next;
    });
  };

  const toggleMatiere = (m) => {
    setV((prev) => {
      const list = prev.matieres || [];
      const next = list.indexOf(m) >= 0 ? list.filter((x) => x !== m) : list.concat([m]);
      return Object.assign({}, prev, { matieres: next });
    });
    setErrors((prev) => {
      if (!prev.matieres) return prev;
      const next = Object.assign({}, prev);
      delete next.matieres;
      return next;
    });
  };

  const submit = async (ev) => {
    ev.preventDefault();
    const e = {};
    if (!v.prenom.trim()) e.prenom = "Prénom requis";
    if (!v.nom.trim()) e.nom = "Nom requis";
    if (!/^[^@\s]+@[^@\s]+\.[^@\s]+$/.test(v.email.trim())) e.email = "Adresse e-mail invalide";
    if (v.tel.replace(/[^\d]/g, "").length < 9) e.tel = "Numéro de téléphone invalide";
    if (!v.ecole.trim()) e.ecole = "École requise";
    if (!v.filiere) e.filiere = "Filière requise";
    if (!v.annee) e.annee = "Année requise";
    if (v.matieres.length === 0) e.matieres = "Sélectionne au moins une matière";
    setErrors(e);
    if (Object.keys(e).length > 0) {
      const first = document.querySelector(".pr-field.err");
      if (first) first.scrollIntoView({ behavior: "smooth", block: "center" });
      return;
    }

    setSending(true);
    setFailure("");
    const get = (k) => { try { return sessionStorage.getItem("ce_" + k) || null; } catch (_) { return null; } };
    const payload = {
      type_demandeur: "prof",
      source: "recrutement_prof",
      email: v.email.trim(),
      tel: v.tel.trim(),
      prenomEnfant: v.prenom.trim(),
      nom_parent: v.nom.trim(),
      prof_ecole: v.ecole.trim(),
      prof_annee: v.annee,
      filiere_universite: v.filiere,
      prof_prepa: v.prepa.trim() || null,
      prof_matieres_enseignees: v.matieres,
      utm_source: get("utm_source"),
      utm_medium: get("utm_medium"),
      utm_campaign: get("utm_campaign"),
    };
    try {
      const res = await fetch("/api/lead", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify(payload),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok || json.ok === false) {
        throw new Error((json && (json.error || (json.errors && json.errors.join(", ")))) || "Envoi impossible");
      }
      setSent(true);
      window.scrollTo({ top: 0, behavior: "smooth" });
    } catch (err) {
      setFailure("L'envoi n'a pas abouti. Réessaie dans un instant — ou écris-nous à contact@cours-edgar.fr.");
    } finally {
      setSending(false);
    }
  };

  const Header = (
    <header className="pr-top">
      <div className="pr-wrap">
        <img src="/assets/logo-cours-edgar.png" alt="Cours Edgar" />
        <span>Recrutement · Professeurs</span>
      </div>
    </header>
  );

  if (sent) {
    return (
      <div className="pr-page">
        <style>{PR_CSS}</style>
        {Header}
        <div className="pr-wrap">
          <div className="pr-done">
            <div className="pr-done-ico">
              <svg viewBox="0 0 24 24" width="30" height="30" fill="none" stroke="currentColor" strokeWidth="1.6" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
                <path d="M4 12.5l5 5L20 6.5" />
              </svg>
            </div>
            <h2>Candidature <em>bien reçue.</em></h2>
            <p>
              Merci {v.prenom.trim()}. Nous étudions chaque profil individuellement et revenons vers toi
              sous quelques jours, à l'adresse {v.email.trim()}.
            </p>
            <p style={{ fontSize: "14.5px" }}>
              Une question d'ici là&nbsp;? Écris-nous à contact@cours-edgar.fr.
            </p>
          </div>
        </div>
      </div>
    );
  }

  return (
    <div className="pr-page">
      <style>{PR_CSS}</style>
      {Header}

      <section className="pr-hero">
        <div className="pr-glyphs" aria-hidden="true">
          <span style={{ fontSize: "300px", left: "-55px", top: "-70px" }}>∀</span>
          <span style={{ fontSize: "250px", right: "30px", bottom: "-65px" }}>Σ</span>
        </div>
        <div className="pr-wrap">
          <div className="pr-tag"><i />Nous recrutons</div>
          <h1 className="pr-h1">Enseigne à celles et ceux qui <em>visent les meilleures écoles.</em></h1>
          <p className="pr-lead">
            Cours Edgar réunit des étudiants et diplômés des grandes écoles pour accompagner des élèves
            exigeants, du lycée à la prépa. Si tu as réussi ce parcours et que tu sais l'expliquer,
            cette page est faite pour toi.
          </p>
          <div className="pr-atouts">
            {PR_ATOUTS.map((a, i) => (
              <article key={i} className="pr-atout">
                <h3>{a.titre}</h3>
                <p>{a.texte}</p>
              </article>
            ))}
          </div>
        </div>
      </section>

      <section className="pr-form-section">
        <div className="pr-wrap">
          <div className="pr-form">
            <div className="pr-form-head">
              <div className="pr-eyebrow">Candidature</div>
              <h2 className="pr-h2">Parle-nous de <em>ton parcours.</em></h2>
              <p className="pr-note">Deux minutes suffisent. On te recontacte pour la suite.</p>
            </div>

            <form onSubmit={submit} noValidate>
              <div className="pr-block">
                <div className="pr-grid2">
                  <div className={`pr-field ${errors.prenom ? "err" : ""}`}>
                    <label htmlFor="pr-prenom">Prénom</label>
                    <input id="pr-prenom" type="text" value={v.prenom} onChange={(e) => set("prenom", e.target.value)} autoComplete="given-name" />
                    {errors.prenom && <span className="pr-err">{errors.prenom}</span>}
                  </div>
                  <div className={`pr-field ${errors.nom ? "err" : ""}`}>
                    <label htmlFor="pr-nom">Nom</label>
                    <input id="pr-nom" type="text" value={v.nom} onChange={(e) => set("nom", e.target.value)} autoComplete="family-name" />
                    {errors.nom && <span className="pr-err">{errors.nom}</span>}
                  </div>
                </div>

                <div className={`pr-field ${errors.ecole ? "err" : ""}`}>
                  <label htmlFor="pr-ecole">École</label>
                  <input id="pr-ecole" type="text" value={v.ecole} onChange={(e) => set("ecole", e.target.value)} placeholder="HEC Paris, Polytechnique, ENS…" />
                  {errors.ecole && <span className="pr-err">{errors.ecole}</span>}
                </div>

                <div className="pr-grid2">
                  <div className={`pr-field ${errors.filiere ? "err" : ""}`}>
                    <label htmlFor="pr-filiere">Filière d'origine</label>
                    <select id="pr-filiere" value={v.filiere} onChange={(e) => set("filiere", e.target.value)}>
                      <option value="">Choisir…</option>
                      {PR_FILIERES.map((g) => (
                        <optgroup key={g.label} label={g.label}>
                          {g.items.map((it) => <option key={it} value={it}>{it}</option>)}
                        </optgroup>
                      ))}
                    </select>
                    {errors.filiere && <span className="pr-err">{errors.filiere}</span>}
                  </div>
                  <div className={`pr-field ${errors.annee ? "err" : ""}`}>
                    <label htmlFor="pr-annee">Année d'intégration</label>
                    <select id="pr-annee" value={v.annee} onChange={(e) => set("annee", e.target.value)}>
                      <option value="">Choisir…</option>
                      {PR_ANNEES.map((a) => <option key={a} value={a}>{a}</option>)}
                    </select>
                    {errors.annee && <span className="pr-err">{errors.annee}</span>}
                  </div>
                </div>

                <div className="pr-field">
                  <label htmlFor="pr-prepa">Prépa d'origine <span className="opt">· si concerné</span></label>
                  <input id="pr-prepa" type="text" value={v.prepa} onChange={(e) => set("prepa", e.target.value)} placeholder="Louis-le-Grand, Sainte-Geneviève…" />
                </div>

                <div className={`pr-field ${errors.matieres ? "err" : ""}`}>
                  <label>Matières que tu souhaites enseigner <span className="opt">· plusieurs choix possibles</span></label>
                  <div className="pr-chips">
                    {PR_MATIERES.map((m) => (
                      <button key={m} type="button" className={`pr-chip ${v.matieres.indexOf(m) >= 0 ? "on" : ""}`}
                        onClick={() => toggleMatiere(m)} aria-pressed={v.matieres.indexOf(m) >= 0}>{m}</button>
                    ))}
                  </div>
                  {errors.matieres && <span className="pr-err">{errors.matieres}</span>}
                </div>

                <div className="pr-grid2">
                  <div className={`pr-field ${errors.email ? "err" : ""}`}>
                    <label htmlFor="pr-email">Adresse e-mail</label>
                    <input id="pr-email" type="email" value={v.email} onChange={(e) => set("email", e.target.value)} autoComplete="email" placeholder="prenom.nom@exemple.fr" />
                    {errors.email && <span className="pr-err">{errors.email}</span>}
                  </div>
                  <div className={`pr-field ${errors.tel ? "err" : ""}`}>
                    <label htmlFor="pr-tel">Téléphone</label>
                    <input id="pr-tel" type="tel" value={v.tel} onChange={(e) => set("tel", e.target.value)} autoComplete="tel" placeholder="06 12 34 56 78" />
                    {errors.tel && <span className="pr-err">{errors.tel}</span>}
                  </div>
                </div>

                <button className="pr-submit" type="submit" disabled={sending}>
                  {sending ? "Envoi en cours…" : "Envoyer ma candidature"}
                </button>
                {failure && <div className="pr-fail">{failure}</div>}
              </div>

            </form>
          </div>
        </div>
      </section>
    </div>
  );
}
