// app/anecdotes.jsx — Concours d'anecdotes : 1 vraie + 1 fausse, thématiques
//
// Onglet de premier niveau dédié (depuis dissociation du Carnet).
// Nom de l'auteur pré-rempli depuis l'identité globale (useGuest).

const ANEC_KEY = "ea-app:anecdotes";

function AnecdotesPage({ embedded = false }) {
  const { identity } = useGuest();
  const [list, setList] = React.useState(() => Store.get(ANEC_KEY, []));
  const [author, setAuthor] = React.useState(() => identity?.name || Store.get(ANEC_KEY + ":author", ""));
  React.useEffect(() => { if (identity?.name && !author) setAuthor(identity.name); }, [identity?.name]);
  const [theme, setTheme] = React.useState(null);
  const [trueA, setTrueA] = React.useState("");
  const [falseA, setFalseA] = React.useState("");
  const [done, setDone] = React.useState(false);

  const submit = () => {
    if (!author.trim() || (!trueA.trim() && !falseA.trim())) return;
    Store.set(ANEC_KEY + ":author", author);
    const entry = {
      author, theme,
      trueAnecdote: trueA.trim(),
      falseAnecdote: falseA.trim(),
      at: new Date().toISOString(),
    };
    const next = [...list, entry];
    setList(next);
    Store.set(ANEC_KEY, next);
    setDone(true);
    setTrueA(""); setFalseA(""); setTheme(null);
  };

  const innerContent = (
    <>
      {!embedded && <AppHeader eyebrow="★ Vrai ou faux ★" title="Concours d'anecdotes" />}
      <div style={{ textAlign: "center", fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: A.inkSoft, marginTop: 8, maxWidth: 540, margin: "8px auto 0", lineHeight: 1.55 }}>
        {identity?.firstName && <span style={{ display: "block", marginBottom: 8, fontFamily: A.mono, fontSize: 10, letterSpacing: 2.5, color: A.rouge, textTransform: "uppercase", fontStyle: "normal" }}>★ À vous {identity.firstName} ★</span>}
        Soumettez <strong style={{ color: A.rouge }}>une anecdote vraie</strong> et <strong style={{ color: A.sage }}>une fausse</strong> sur Enora &amp; Antoine. Le jour J, chaque tablée vote pour démêler le vrai du faux. Les anecdotes restent privées jusqu'au mariage.
      </div>

        {done ? (
          <div style={{ marginTop: 32, background: A.card, padding: "32px 24px", border: `1px solid ${A.ruleSoft}`, textAlign: "center" }}>
            <div style={{ fontFamily: A.display, fontSize: 60, color: A.or, lineHeight: 1 }}>♣</div>
            <div className="display-bold" style={{ fontSize: 30, color: A.ink, marginTop: 12 }}>Anecdote bien reçue</div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 15, color: A.inkSoft, marginTop: 10, lineHeight: 1.55, maxWidth: 400, margin: "10px auto 0" }}>
              On la garde précieusement — vous la retrouverez au repas le 21 août.
            </div>
            <div style={{ marginTop: 22, display: "flex", gap: 10, justifyContent: "center", flexWrap: "wrap" }}>
              <ButtonA primary onClick={() => setDone(false)}>+ Soumettre une autre</ButtonA>
            </div>
          </div>
        ) : (
          <>
            {/* Thématiques */}
            <div style={{ marginTop: 26 }}>
              <div className="eyebrow" style={{ marginBottom: 10 }}>★ 10 thématiques pour vous inspirer ★</div>
              <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 8 }}>
                {APP_DATA.anecdotes_themes.map((t) => (
                  <button key={t.id} onClick={() => setTheme(theme === t.id ? null : t.id)} style={{
                    textAlign: "left", padding: "10px 12px",
                    background: theme === t.id ? A.ink : A.paper,
                    color: theme === t.id ? A.white : A.ink,
                    border: `1px solid ${theme === t.id ? A.ink : A.ruleSoft}`,
                    cursor: "pointer", fontFamily: A.sans, fontSize: 13,
                    display: "flex", alignItems: "center", gap: 8,
                  }}>
                    <span style={{ fontFamily: A.display, fontSize: 14, color: theme === t.id ? A.or : A.or }}>{t.icon}</span>
                    <span style={{ fontWeight: 600 }}>{t.title}</span>
                  </button>
                ))}
              </div>
              {theme && (
                <div style={{ marginTop: 12, padding: "12px 16px", background: A.orPale, borderLeft: `3px solid ${A.or}`, fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, lineHeight: 1.55 }}>
                  <strong style={{ fontStyle: "normal" }}>{APP_DATA.anecdotes_themes.find(t => t.id === theme)?.title} —</strong>{" "}
                  {APP_DATA.anecdotes_themes.find(t => t.id === theme)?.hint}
                </div>
              )}
            </div>

            {/* Form */}
            <div style={{ marginTop: 28, display: "flex", flexDirection: "column", gap: 18 }}>
              <div>
                <label style={{ display: "block", fontFamily: A.bold || A.display, fontWeight: 600, fontSize: 13, color: A.ink, marginBottom: 6 }}>
                  Votre nom
                </label>
                <input type="text" value={author} onChange={(e) => setAuthor(e.target.value)}
                  placeholder="Prénom Nom"
                  style={{
                    width: "100%", padding: "12px 14px", background: A.card,
                    border: `1.5px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 15, color: A.ink, outline: "none",
                  }}/>
              </div>

              <div>
                <label style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: A.display, fontWeight: 600, fontSize: 14, color: A.rouge, marginBottom: 6 }}>
                  <span style={{ fontSize: 18 }}>♥</span> Votre anecdote <strong>vraie</strong>
                </label>
                <textarea value={trueA} onChange={(e) => setTrueA(e.target.value)} rows="3"
                  placeholder="Racontez un souvenir, un moment, une histoire authentique sur Enora et/ou Antoine."
                  style={{
                    width: "100%", padding: "12px 14px", background: A.card,
                    border: `1.5px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 14, color: A.ink, outline: "none",
                    resize: "vertical", minHeight: 90, fontStyle: "italic",
                  }}/>
              </div>

              <div>
                <label style={{ display: "flex", alignItems: "center", gap: 8, fontFamily: A.display, fontWeight: 600, fontSize: 14, color: A.sage, marginBottom: 6 }}>
                  <span style={{ fontSize: 18 }}>♣</span> Votre anecdote <strong>fausse</strong>
                </label>
                <textarea value={falseA} onChange={(e) => setFalseA(e.target.value)} rows="3"
                  placeholder="Inventez une histoire crédible mais totalement fausse. Plus c'est plausible, mieux c'est."
                  style={{
                    width: "100%", padding: "12px 14px", background: A.card,
                    border: `1.5px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 14, color: A.ink, outline: "none",
                    resize: "vertical", minHeight: 90, fontStyle: "italic",
                  }}/>
                <div style={{ marginTop: 6, fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute }}>
                  Astuce : reprenez la structure d'une vraie anecdote en changeant juste le détail clé.
                </div>
              </div>

              <ButtonA primary full onClick={submit}>
                ♣ Soumettre mes anecdotes
              </ButtonA>
              <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.inkMute, textAlign: "center" }}>
                Vos anecdotes restent privées jusqu'au jour J — seuls Enora &amp; Antoine y ont accès avant.
              </div>
            </div>

            {list.length > 0 && (
              <div style={{ marginTop: 28, padding: "14px 18px", background: A.paper, border: `1px solid ${A.ruleSoft}`, fontFamily: A.italic, fontStyle: "italic", fontSize: 13, color: A.inkSoft, textAlign: "center" }}>
                Vous avez déjà soumis {list.length} anecdote{list.length > 1 ? "s" : ""}. Merci !
              </div>
            )}
          </>
        )}
    </>
  );

  if (embedded) return innerContent;
  return (
    <div style={{ position: "relative", overflow: "hidden", minHeight: "100vh" }}>
      <WashBg hue={150} opacity={0.16}/>
      <Page>{innerContent}</Page>
    </div>
  );
}

Object.assign(window, { AnecdotesPage });
