// admin-app/rsvp.jsx — Liste RSVP filtrable

function RsvpPage({ data, onReload }) {
  const [filter, setFilter] = React.useState("all");
  const [search, setSearch] = React.useState("");

  if (!data) return null;
  const invites = data.invites || [];
  const tables = data.tables || [];
  const gites = data.gites || [];

  // Index lookup
  const tableById = Object.fromEntries(tables.map(t => [t.id, t]));
  const giteById = Object.fromEntries(gites.map(g => [g.id, g]));

  // Filtres
  const filtered = invites.filter(inv => {
    if (filter === "oui" && inv.rsvp_statut !== "oui") return false;
    if (filter === "non" && inv.rsvp_statut !== "non") return false;
    if (filter === "wait" && inv.rsvp_statut && inv.rsvp_statut !== "en_attente") return false;
    if (filter === "wait" && !inv.rsvp_statut) {/*ok*/}
    if (filter === "cote_e" && !(inv.cote || "").toLowerCase().startsWith("e")) return false;
    if (filter === "cote_a" && !(inv.cote || "").toLowerCase().startsWith("a")) return false;
    if (filter === "no_table" && (!!inv.table_id || inv.rsvp_statut !== "oui")) return false;
    if (filter === "no_gite" && (!!inv.gite_id || inv.rsvp_statut !== "oui")) return false;
    if (filter === "regime" && (!inv.regime || inv.regime === "omni") && !inv.allergies) return false;
    if (search.trim()) {
      const hay = `${inv.prenom} ${inv.nom} ${inv.cote} ${inv.categorie}`;
      if (!fuzzyMatch(search, hay)) return false;
    }
    return true;
  });

  const counts = {
    all: invites.length,
    oui: invites.filter(i => i.rsvp_statut === "oui").length,
    non: invites.filter(i => i.rsvp_statut === "non").length,
    wait: invites.filter(i => !i.rsvp_statut || i.rsvp_statut === "en_attente").length,
    cote_e: invites.filter(i => (i.cote || "").toLowerCase().startsWith("e")).length,
    cote_a: invites.filter(i => (i.cote || "").toLowerCase().startsWith("a")).length,
    no_table: invites.filter(i => i.rsvp_statut === "oui" && !i.table_id).length,
    no_gite: invites.filter(i => i.rsvp_statut === "oui" && !i.gite_id).length,
    regime: invites.filter(i => i.rsvp_statut === "oui" && ((i.regime && i.regime !== "omni") || i.allergies)).length,
  };

  const filters = [
    { id: "all",     label: "Tous" },
    { id: "oui",     label: "Oui" },
    { id: "non",     label: "Non" },
    { id: "wait",    label: "En attente" },
    { id: "cote_e",  label: "Côté E" },
    { id: "cote_a",  label: "Côté A" },
    { id: "no_table", label: "Sans table" },
    { id: "no_gite", label: "Sans gîte" },
    { id: "regime",  label: "Régime / allergie" },
  ];

  return (
    <AdPage
      eyebrow={`${invites.length} invités`}
      title="Liste RSVP"
      actions={<button className="btn sm" onClick={onReload}>↻ Recharger</button>}
    >
      {/* Recherche + filtres */}
      <div style={{ marginBottom: 14, display: "flex", gap: 12, alignItems: "center", flexWrap: "wrap" }}>
        <input type="text" value={search} onChange={(e) => setSearch(e.target.value)}
          placeholder="Rechercher un prénom, nom, catégorie…"
          style={{ flex: "1 1 240px", padding: "8px 12px" }}/>
        <div style={{ fontFamily: AD.mono, fontSize: 11, color: AD.inkMute }}>
          {filtered.length}/{invites.length}
        </div>
      </div>

      <div style={{ display: "flex", gap: 6, flexWrap: "wrap", marginBottom: 16 }}>
        {filters.map(f => (
          <button key={f.id}
            onClick={() => setFilter(f.id)}
            className="btn sm"
            style={{
              background: filter === f.id ? AD.ink : "transparent",
              color: filter === f.id ? AD.white : AD.inkSoft,
              borderColor: filter === f.id ? AD.ink : AD.ruleSoft,
            }}>
            {f.label} <span style={{ opacity: 0.6, marginLeft: 4 }}>({counts[f.id]})</span>
          </button>
        ))}
      </div>

      {/* Tableau */}
      <div style={{ background: AD.white, border: `1px solid ${AD.ruleSoft}`, overflow: "auto" }}>
        <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 12 }}>
          <thead>
            <tr style={{ background: AD.ink, color: AD.white }}>
              <Th>Nom</Th>
              <Th>Côté</Th>
              <Th>RSVP</Th>
              <Th>+1</Th>
              <Th>Régime</Th>
              <Th>Allergies</Th>
              <Th>Table</Th>
              <Th>Gîte</Th>
              <Th>Arrivée</Th>
              <Th>Réponse</Th>
            </tr>
          </thead>
          <tbody>
            {filtered.length === 0 ? (
              <tr><td colSpan={10} style={{ padding: 28, textAlign: "center", fontFamily: AD.italic, fontStyle: "italic", color: AD.inkMute }}>
                Aucun invité ne correspond à ce filtre.
              </td></tr>
            ) : filtered.map((inv, i) => (
              <RsvpRow key={inv.id} inv={inv} tableById={tableById} giteById={giteById} alt={i % 2 === 0}/>
            ))}
          </tbody>
        </table>
      </div>

      <div style={{ marginTop: 14, fontFamily: AD.italic, fontStyle: "italic", fontSize: 13, color: AD.inkSoft }}>
        Pour modifier email, téléphone, notes : éditez directement dans le Google Sheet (onglet <code>Invites</code>). L'admin se rafraîchit toutes les 30 secondes.
      </div>
    </AdPage>
  );
}

function Th({ children }) {
  return <th style={{ textAlign: "left", padding: "8px 10px", fontFamily: AD.mono, fontSize: 9, letterSpacing: 1, textTransform: "uppercase", fontWeight: 600 }}>{children}</th>;
}

function Td({ children, mono = false, style = {} }) {
  return <td style={{ padding: "8px 10px", borderBottom: `1px solid ${AD.ruleSoft}`, fontFamily: mono ? AD.mono : AD.sans, fontSize: mono ? 11 : 12, ...style }}>{children}</td>;
}

function RsvpRow({ inv, tableById, giteById, alt }) {
  const t = inv.table_id ? tableById[inv.table_id] : null;
  const g = inv.gite_id ? giteById[inv.gite_id] : null;
  const isPlus1 = inv.categorie === "+1";

  let statutBadge;
  if (inv.rsvp_statut === "oui") statutBadge = <AdPill color="sage" small>Oui</AdPill>;
  else if (inv.rsvp_statut === "non") statutBadge = <AdPill color="rouge" small>Non</AdPill>;
  else statutBadge = <AdPill color="mute" small>Attente</AdPill>;

  return (
    <tr style={{ background: alt ? AD.paper : AD.white }}>
      <Td style={{ fontWeight: 600 }}>
        {isPlus1 && <span style={{ color: AD.or, fontFamily: AD.mono, fontSize: 9, marginRight: 4 }}>+1</span>}
        {inv.prenom} {inv.nom || ""}
      </Td>
      <Td>
        <span style={{ fontFamily: AD.mono, fontSize: 10, color: AD.inkSoft }}>
          {inv.cote || "—"} {inv.categorie && `· ${inv.categorie}`}
        </span>
      </Td>
      <Td>{statutBadge}</Td>
      <Td>{inv.plus_one_nom ? <span style={{ color: AD.or }}>+1 {inv.plus_one_nom}</span> : "—"}</Td>
      <Td>
        {inv.regime && inv.regime !== "omni"
          ? <AdPill color="or" small>{inv.regime}</AdPill>
          : <span style={{ color: AD.inkMute }}>—</span>}
      </Td>
      <Td>
        {inv.allergies
          ? <span style={{ color: AD.rougeDeep, fontStyle: "italic", fontFamily: AD.italic }}>{inv.allergies}</span>
          : <span style={{ color: AD.inkMute }}>—</span>}
      </Td>
      <Td mono>{t ? t.nom : <span style={{ color: AD.inkMute }}>—</span>}</Td>
      <Td mono>{g ? g.nom : <span style={{ color: AD.inkMute }}>—</span>}</Td>
      <Td mono>{inv.arrivee || <span style={{ color: AD.inkMute }}>—</span>}</Td>
      <Td mono><span style={{ color: AD.inkMute }}>{inv.rsvp_at ? new Date(inv.rsvp_at).toLocaleDateString("fr-FR") : "—"}</span></Td>
    </tr>
  );
}

Object.assign(window, { RsvpPage });
