// SuggestPlant.jsx — page « Suggérer une plante » (réservée aux connectés).
//
// L'utilisateur propose une plante par son nom latin (+ note optionnelle). La
// suggestion part en file d'attente (POST /api/me?action=suggest) ; l'admin la
// traite ensuite manuellement. Sous le formulaire : « Mes suggestions » avec
// leur statut (GET /api/me?view=suggestions).

function SuggestPlant({ setRoute }) {
  const auth = window.useAuth ? window.useAuth() : { user: null, loading: false };
  const isMobile = useMobile();

  const [latin, setLatin] = React.useState("");
  const [note, setNote] = React.useState("");
  const [submitting, setSubmitting] = React.useState(false);
  const [error, setError] = React.useState(null);
  const [success, setSuccess] = React.useState(null);
  const [mine, setMine] = React.useState(null);

  const loadMine = React.useCallback(() => {
    (window.authedFetch || fetch)("/api/me?view=suggestions", { cache: "no-store" })
      .then((r) => (r.ok ? r.json() : Promise.reject(r)))
      .then((d) => setMine(d.suggestions || []))
      .catch(() => setMine([]));
  }, []);

  React.useEffect(() => {
    if (auth.user) loadMine();
  }, [auth.user, loadMine]);

  // ── Guard : connexion requise ──────────────────────────────────────────
  if (!auth.loading && !auth.user) {
    return (
      <main className="page-enter">
        <section style={{ padding: "120px 0", textAlign: "center" }}>
          <div style={{ maxWidth: 560, margin: "0 auto", padding: "0 20px" }}>
            <div className="kicker" style={{ marginBottom: 18, color: "var(--moss-deep)" }}>Connexion requise</div>
            <h1 className="h-display" style={{ fontSize: "clamp(38px, 7vw, 60px)", lineHeight: 1, margin: "0 0 24px" }}>
              Proposez une plante.
            </h1>
            <p style={{ fontFamily: "var(--serif)", fontSize: 18, lineHeight: 1.55, color: "var(--ink-soft)", margin: "0 0 28px" }}>
              Pour suggérer l'ajout d'une plante au recueil, connectez-vous d'abord à votre compte.
            </p>
            <div style={{ display: "flex", gap: 12, justifyContent: "center", alignItems: "center", flexWrap: "wrap" }}>
              {window.UserBadge && <window.UserBadge />}
              <button className="btn btn-ghost" onClick={() => setRoute("home")}>Retour à l'accueil</button>
            </div>
          </div>
        </section>
      </main>
    );
  }

  const submit = async (e) => {
    if (e) e.preventDefault();
    setError(null);
    setSuccess(null);
    const value = latin.trim();
    if (!value) { setError("Indiquez le nom latin de la plante."); return; }
    setSubmitting(true);
    try {
      const res = await (window.authedFetch || fetch)("/api/me?action=suggest", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ latin: value, note: note.trim() || undefined }),
      });
      const json = await res.json().catch(() => ({}));
      if (!res.ok) throw new Error(json.error || "Erreur lors de l'envoi.");
      setSuccess("Merci ! Votre suggestion a été transmise. Elle sera examinée par l'administrateur.");
      setLatin("");
      setNote("");
      loadMine();
    } catch (err) {
      setError(err.message || "Erreur lors de l'envoi.");
    } finally {
      setSubmitting(false);
    }
  };

  const pad = isMobile ? "0 20px" : "0 40px";

  return (
    <main className="page-enter">
      <section style={{ maxWidth: 680, margin: isMobile ? "40px auto 0" : "72px auto 0", padding: pad }}>
        <div className="kicker" style={{ marginBottom: 16, color: "var(--moss-deep)" }}>
          Contribuer · Suggestion
        </div>
        <h1 className="h-display" style={{ fontSize: isMobile ? 40 : 60, lineHeight: 1.02, margin: "0 0 18px" }}>
          Suggérer une <span className="h-italic">plante</span>.
        </h1>
        <p style={{ fontFamily: "var(--serif)", fontSize: isMobile ? 17 : 19, lineHeight: 1.6, color: "var(--ink-soft)", margin: "0 0 32px" }}>
          Une plante manque au recueil ? Indiquez son nom latin : votre proposition rejoint la file
          d'attente, et l'administrateur en rédigera la fiche.
        </p>

        <form onSubmit={submit} style={{ display: "grid", gap: 16, marginBottom: 40 }}>
          <label style={{ display: "grid", gap: 6 }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
              Nom latin *
            </span>
            <input
              type="text"
              value={latin}
              onChange={(e) => setLatin(e.target.value)}
              placeholder="ex. Salvia officinalis"
              autoFocus
              style={inputStyle}
            />
          </label>

          <label style={{ display: "grid", gap: 6 }}>
            <span style={{ fontFamily: "var(--mono)", fontSize: 11, letterSpacing: ".12em", textTransform: "uppercase", color: "var(--ink-mute)" }}>
              Note (optionnel)
            </span>
            <textarea
              value={note}
              onChange={(e) => setNote(e.target.value)}
              placeholder="Pourquoi cette plante ? Où l'avez-vous vue ? (facultatif)"
              rows={3}
              maxLength={500}
              style={{ ...inputStyle, resize: "vertical", lineHeight: 1.5 }}
            />
          </label>

          {error && (
            <p style={{ color: "#b42318", fontFamily: "var(--mono)", fontSize: 12, margin: 0 }}>{error}</p>
          )}
          {success && (
            <p style={{ color: "var(--moss-deep)", fontFamily: "var(--serif)", fontSize: 15, margin: 0 }}>{success}</p>
          )}

          <div>
            <button type="submit" className="btn btn-solid" disabled={submitting}>
              {submitting ? "Envoi…" : "Envoyer ma suggestion"}
            </button>
          </div>
        </form>

        {/* Mes suggestions */}
        {mine && mine.length > 0 && (
          <div>
            <div className="kicker" style={{ marginBottom: 14, color: "var(--ink-mute)" }}>
              Mes suggestions
            </div>
            <div style={{ display: "grid", gap: 8 }}>
              {mine.map((s) => (
                <div key={s.id} style={{
                  display: "flex", alignItems: "center", justifyContent: "space-between", gap: 12,
                  padding: "10px 14px", borderRadius: 10,
                  border: "1px solid var(--line)", background: "var(--paper-2)",
                }}>
                  <span>
                    <span className="h-italic" style={{ fontSize: 16, color: "var(--ink)" }}>{s.latin}</span>
                    {s.note && (
                      <span style={{ fontFamily: "var(--serif)", fontSize: 13, color: "var(--ink-soft)", marginLeft: 8 }}>
                        — {s.note}
                      </span>
                    )}
                  </span>
                  <StatusPill status={s.status} />
                </div>
              ))}
            </div>
          </div>
        )}
      </section>
    </main>
  );
}

const inputStyle = {
  fontFamily: "var(--serif)", fontSize: 16, padding: "11px 14px",
  borderRadius: 10, border: "1px solid var(--line)", background: "var(--paper)",
  color: "var(--ink)", width: "100%", boxSizing: "border-box",
};

function StatusPill({ status }) {
  const map = {
    pending: { label: "en attente", color: "var(--ink-mute)", border: "var(--line)" },
    done: { label: "traitée", color: "var(--moss-deep)", border: "var(--moss-deep)" },
    rejected: { label: "écartée", color: "#b42318", border: "rgba(180,35,24,0.4)" },
  };
  const s = map[status] || map.pending;
  return (
    <span style={{
      fontFamily: "var(--mono)", fontSize: 10, letterSpacing: ".08em", textTransform: "uppercase",
      color: s.color, border: `1px solid ${s.border}`, borderRadius: 100, padding: "3px 10px", whiteSpace: "nowrap",
    }}>
      {s.label}
    </span>
  );
}

Object.assign(window, { SuggestPlant });
