// app/admin.jsx — Panneau admin (réservé Enora & Antoine)
// Accessible via ?admin dans l'URL — affiche paris, anecdotes, photos.

function AdminPanel({ onClose }) {
  const [tab, setTab] = React.useState("bets");
  const [tick, setTick] = React.useState(0);
  const bump = () => setTick(t => t + 1);
  const bets = Store.get("ea-app:bets:submissions", []);
  const anecdotes = Store.get("ea-app:anecdotes", []);
  const photos = Store.get("ea-app:gallery", []);
  const brPosts = (typeof brGetPosts === "function") ? brGetPosts().filter(p => p.statut === "publie") : [];
  const brPrompts = (typeof brGetPrompts === "function") ? brGetPrompts() : [];

  const exportJSON = () => {
    const blob = new Blob([JSON.stringify({ bets, anecdotes, photoCount: photos.length, paparazzi: { prompts: brPrompts, posts: brPosts } }, null, 2)], { type: "application/json" });
    const a = document.createElement("a");
    a.href = URL.createObjectURL(blob);
    a.download = `ea-admin-${new Date().toISOString().slice(0, 10)}.json`;
    a.click();
  };

  return (
    <div style={{ position: "fixed", inset: 0, background: A.white, zIndex: 1000, overflowY: "auto" }}>
      <div style={{ position: "sticky", top: 0, background: A.ink, color: A.white, padding: "16px 20px", display: "flex", justifyContent: "space-between", alignItems: "center", zIndex: 10 }}>
        <div>
          <div style={{ fontFamily: A.mono, fontSize: 10, letterSpacing: 3, color: A.or, textTransform: "uppercase" }}>★ Admin · Enora & Antoine ★</div>
          <div style={{ fontFamily: A.display, fontSize: 22, fontWeight: 700, marginTop: 2 }}>Panneau privé</div>
        </div>
        <button onClick={onClose} style={{ background: "transparent", border: `1px solid ${A.or}`, color: A.or, padding: "8px 14px", fontFamily: A.mono, fontSize: 10, letterSpacing: 2, cursor: "pointer", textTransform: "uppercase" }}>Fermer</button>
      </div>

      <div style={{ display: "flex", gap: 6, padding: "16px 20px", background: A.paper, borderBottom: `1px solid ${A.ruleSoft}` }}>
        {[
          { id: "bets", l: `Paris (${bets.length})` },
          { id: "anec", l: `Anecdotes (${anecdotes.length})` },
          { id: "photos", l: `Photos (${photos.length})` },
          { id: "papa", l: `Paparazzi (${brPosts.length})` },
          { id: "export", l: "⤓ Export" },
        ].map(t => (
          <button key={t.id} onClick={() => t.id === "export" ? exportJSON() : setTab(t.id)} style={{
            padding: "10px 14px", background: tab === t.id ? A.ink : "transparent",
            color: tab === t.id ? A.white : A.ink, border: `1px solid ${A.ruleSoft}`,
            fontFamily: A.mono, fontSize: 10, letterSpacing: 1.5, cursor: "pointer", textTransform: "uppercase", fontWeight: 600,
          }}>{t.l}</button>
        ))}
      </div>

      <div style={{ padding: 20 }}>
        {tab === "bets" && <AdminBets bets={bets}/>}
        {tab === "anec" && <AdminAnecdotes list={anecdotes}/>}
        {tab === "photos" && <AdminPhotos list={photos}/>}
        {tab === "papa" && <AdminPaparazzi posts={brPosts} prompts={brPrompts} onChange={bump}/>}
      </div>
    </div>
  );
}

// ─── Section Paparazzi ───────────────────────────────────────────────────
function AdminPaparazzi({ posts, prompts, onChange }) {
  const [sub, setSub] = React.useState("posts");
  return (
    <div>
      <div style={{ display: "flex", gap: 6, marginBottom: 16 }}>
        {[
          { id: "posts",   l: `Posts (${posts.length})` },
          { id: "prompts", l: `Prompts (${prompts.length})` },
        ].map(t => (
          <button key={t.id} onClick={() => setSub(t.id)} style={{
            padding: "8px 12px", background: sub === t.id ? A.or : "transparent",
            color: sub === t.id ? A.ink : A.inkSoft, border: `1px solid ${A.ruleSoft}`,
            fontFamily: A.mono, fontSize: 9, letterSpacing: 1.5, cursor: "pointer", textTransform: "uppercase", fontWeight: 600,
          }}>{t.l}</button>
        ))}
      </div>
      {sub === "posts"   && <AdminPaparazziPosts posts={posts} prompts={prompts} onChange={onChange}/>}
      {sub === "prompts" && <AdminPaparazziPrompts prompts={prompts} onChange={onChange}/>}
    </div>
  );
}

function AdminPaparazziPosts({ posts, prompts, onChange }) {
  if (!posts.length) return <Empty msg="Aucun post Paparazzi pour l'instant."/>;
  const promptById = Object.fromEntries(prompts.map(p => [p.id, p]));
  const remove = (id) => {
    if (!confirm("Retirer ce post du mur ?")) return;
    brRemovePost(id);
    onChange();
  };
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fill, minmax(180px, 1fr))", gap: 14 }}>
      {posts.map((p) => {
        const prompt = promptById[p.prompt_id];
        return (
          <div key={p.id} style={{ background: A.white, border: `1px solid ${A.ruleSoft}`, padding: 8, position: "relative" }}>
            <div style={{
              aspectRatio: "4/5", marginBottom: 8,
              background: p.photo_url
                ? `url(${p.photo_url}) center/cover`
                : `linear-gradient(135deg, ${p.photo_color?.from || "#ddd"}, ${p.photo_color?.to || "#aaa"})`,
            }}/>
            <div style={{ fontFamily: A.mono, fontSize: 8, letterSpacing: 1.5, color: A.orDeep, marginBottom: 2 }}>
              {prompt ? `N° ${prompt.numero}` : "—"} {p.mock && "· MOCK"}
            </div>
            <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 12, color: A.ink, lineHeight: 1.3, marginBottom: 2 }}>
              {p.caption || <span style={{ color: A.inkMute }}>—</span>}
            </div>
            <div style={{ fontFamily: A.sans, fontSize: 11, color: A.inkSoft, marginBottom: 6 }}>
              {p.nom_invite || "Anonyme"} · {new Date(p.publie_le).toLocaleDateString("fr-FR")}
            </div>
            <button onClick={() => remove(p.id)} style={{
              padding: "6px 10px", background: "transparent", color: A.rouge,
              border: `1px solid ${A.rouge}`, fontFamily: A.mono, fontSize: 9, letterSpacing: 1.5,
              cursor: "pointer", textTransform: "uppercase", width: "100%",
            }}>Retirer</button>
          </div>
        );
      })}
    </div>
  );
}

function AdminPaparazziPrompts({ prompts, onChange }) {
  const [newQ, setNewQ] = React.useState("");
  const [newSub, setNewSub] = React.useState("");
  const addNow = () => {
    if (!newQ.trim()) return;
    const { start, end } = brGetWeekRange(new Date());
    // S'assure que les autres "actifs" passent en archive si on en publie un nouveau
    prompts.filter(p => p.statut === "actif").forEach(p => brUpdatePrompt(p.id, { statut: "archive", ferme_le: new Date().toISOString() }));
    brAddPrompt({
      id: `manual-${Date.now()}`,
      numero: prompts.length + 1,
      type: "seed",
      question: newQ.trim(),
      sous_texte: newSub.trim(),
      publie_le: start.toISOString(),
      ferme_le:  end.toISOString(),
      statut: "actif",
    });
    setNewQ(""); setNewSub("");
    onChange();
  };
  return (
    <div>
      <div style={{ padding: 14, background: A.paper, border: `1px solid ${A.ruleSoft}`, marginBottom: 16 }}>
        <div style={{ fontFamily: A.mono, fontSize: 9, letterSpacing: 2, color: A.orDeep, marginBottom: 8 }}>✱ NOUVEAU PROMPT (ACTIF CETTE SEMAINE)</div>
        <input value={newQ} onChange={(e) => setNewQ(e.target.value)} placeholder="Question (ex : « Ta tenue choisie »)"
          style={{ width: "100%", padding: "8px 10px", marginBottom: 6, border: `1px solid ${A.ruleSoft}`, fontFamily: A.sans, fontSize: 13, outline: "none" }}/>
        <input value={newSub} onChange={(e) => setNewSub(e.target.value)} placeholder="Sous-texte explicatif (optionnel)"
          style={{ width: "100%", padding: "8px 10px", marginBottom: 8, border: `1px solid ${A.ruleSoft}`, fontFamily: A.italic, fontStyle: "italic", fontSize: 13, outline: "none" }}/>
        <button onClick={addNow} style={{ padding: "8px 14px", background: A.ink, color: A.or, border: "none", fontFamily: A.mono, fontSize: 10, letterSpacing: 2, cursor: "pointer", textTransform: "uppercase" }}>✱ Publier</button>
      </div>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
        <thead>
          <tr style={{ background: A.ink, color: A.white }}>
            <th style={thStyle()}>N°</th>
            <th style={thStyle()}>Question</th>
            <th style={thStyle()}>Type</th>
            <th style={thStyle()}>Fenêtre</th>
            <th style={thStyle()}>Statut</th>
            <th style={thStyle()}></th>
          </tr>
        </thead>
        <tbody>
          {prompts.map(p => (
            <tr key={p.id} style={{ borderBottom: `1px solid ${A.ruleSoft}` }}>
              <td style={tdStyle()}>{p.numero}</td>
              <td style={{ ...tdStyle(), fontFamily: A.italic, fontStyle: "italic", fontSize: 13.5 }}>«{p.question}»</td>
              <td style={{ ...tdStyle(), fontFamily: A.mono, fontSize: 10, textTransform: "uppercase", letterSpacing: 1 }}>{p.type}</td>
              <td style={{ ...tdStyle(), fontFamily: A.mono, fontSize: 10 }}>{brFormatRange(p)}</td>
              <td style={{ ...tdStyle(), color: p.statut === "actif" ? A.rouge : A.inkSoft, fontFamily: A.mono, fontSize: 10, letterSpacing: 1, textTransform: "uppercase" }}>{p.statut}</td>
              <td style={tdStyle()}>
                <button onClick={() => { if (confirm(`Supprimer le prompt « ${p.question} » ?`)) { brDeletePrompt(p.id); onChange(); } }} style={{ padding: "4px 8px", background: "transparent", color: A.rouge, border: `1px solid ${A.rouge}`, fontFamily: A.mono, fontSize: 9, cursor: "pointer" }}>×</button>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function AdminBets({ bets }) {
  if (!bets.length) return <Empty msg="Aucune mise enregistrée."/>;
  return (
    <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12, fontFamily: A.sans }}>
      <thead>
        <tr style={{ background: A.ink, color: A.white }}>
          <th style={thStyle()}>Quand</th>
          <th style={thStyle()}>Nom</th>
          {APP_DATA.bets.map(b => <th key={b.id} style={thStyle()}>{b.q.slice(0, 30)}…</th>)}
        </tr>
      </thead>
      <tbody>
        {bets.map((s, i) => (
          <tr key={i} style={{ borderBottom: `1px solid ${A.ruleSoft}` }}>
            <td style={tdStyle()}>{new Date(s.at).toLocaleString("fr-FR")}</td>
            <td style={{ ...tdStyle(), fontWeight: 600 }}>{s.name || "—"}</td>
            {APP_DATA.bets.map(b => <td key={b.id} style={{ ...tdStyle(), color: A.rouge }}>{s.bets?.[b.id] || "—"}</td>)}
          </tr>
        ))}
      </tbody>
    </table>
  );
}

function AdminAnecdotes({ list }) {
  if (!list.length) return <Empty msg="Aucune anecdote pour l'instant."/>;
  return (
    <div style={{ display: "flex", flexDirection: "column", gap: 12 }}>
      {list.map((a, i) => (
        <div key={i} style={{ background: A.paper, padding: "16px 18px", border: `1px solid ${A.ruleSoft}` }}>
          <div style={{ display: "flex", justifyContent: "space-between", alignItems: "baseline", marginBottom: 8 }}>
            <div style={{ fontFamily: A.display, fontWeight: 700, fontSize: 15, color: A.ink }}>{a.author}</div>
            <div style={{ fontFamily: A.mono, fontSize: 10, color: A.inkMute }}>{new Date(a.at).toLocaleString("fr-FR")}</div>
          </div>
          {a.theme && <div style={{ fontFamily: A.mono, fontSize: 9, color: A.orDeep, letterSpacing: 2, marginBottom: 8, textTransform: "uppercase" }}>Thème · {a.theme}</div>}
          {a.trueAnecdote && (
            <div style={{ marginBottom: 10, padding: "10px 12px", background: A.rougePale, borderLeft: `3px solid ${A.rouge}` }}>
              <div style={{ fontFamily: A.mono, fontSize: 9, color: A.rouge, letterSpacing: 2, marginBottom: 4 }}>♥ VRAIE</div>
              <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, lineHeight: 1.5 }}>{a.trueAnecdote}</div>
            </div>
          )}
          {a.falseAnecdote && (
            <div style={{ padding: "10px 12px", background: A.sageWash, borderLeft: `3px solid ${A.sage}` }}>
              <div style={{ fontFamily: A.mono, fontSize: 9, color: A.sage, letterSpacing: 2, marginBottom: 4 }}>♣ FAUSSE</div>
              <div style={{ fontFamily: A.italic, fontStyle: "italic", fontSize: 14, color: A.ink, lineHeight: 1.5 }}>{a.falseAnecdote}</div>
            </div>
          )}
        </div>
      ))}
    </div>
  );
}

function AdminPhotos({ list }) {
  if (!list.length) return <Empty msg="La galerie est vide."/>;
  return (
    <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(140px, 1fr))", gap: 8 }}>
      {list.map((p, i) => (
        <div key={i} style={{ position: "relative", aspectRatio: "1/1", background: A.paper }}>
          <img src={p.src} alt="" style={{ width: "100%", height: "100%", objectFit: "cover" }}/>
          <div style={{ position: "absolute", bottom: 0, left: 0, right: 0, padding: "6px 8px", background: "linear-gradient(transparent, rgba(0,0,0,0.7))", color: A.white, fontFamily: A.italic, fontStyle: "italic", fontSize: 10 }}>
            {p.author || "Anonyme"}
          </div>
        </div>
      ))}
    </div>
  );
}

function Empty({ msg }) {
  return <div style={{ padding: 40, background: A.paper, textAlign: "center", fontFamily: A.italic, fontStyle: "italic", color: A.inkSoft }}>{msg}</div>;
}

function thStyle() { return { padding: "10px 12px", textAlign: "left", fontFamily: A.mono, fontSize: 10, letterSpacing: 1, textTransform: "uppercase" }; }
function tdStyle() { return { padding: "8px 12px", verticalAlign: "top", maxWidth: 200 }; }

Object.assign(window, { AdminPanel });
