// admin-app/regimes.jsx — Récap traiteur (régimes + allergies)
//
// Layout UX (option HANDOFF 3) :
// - Encart stats horizontal : cards par régime (count + %)
// - Tableau déroulant groupé par régime, avec liste des invités + leurs allergies
// - Section séparée pour les Enfants (menu enfant)
// - Bouton "⤓ Exporter CSV"

const REGIME_DEFS = [
  { id: "omni",       label: "Omnivore",   short: "Omni",   color: "ink" },
  { id: "vege",       label: "Végétarien", short: "Végé",   color: "sage" },
  { id: "vegan",      label: "Végan",      short: "Végan",  color: "sage" },
  { id: "sansgluten", label: "Sans gluten",short: "SG",     color: "or" },
  { id: "pesce",      label: "Pescetarien",short: "Pesce",  color: "or" },
  { id: "autre",      label: "Autre",      short: "Autre",  color: "rouge" },
];

function regimeColor(id) {
  const r = REGIME_DEFS.find(x => x.id === id);
  return r?.color || "mute";
}
function regimeLabel(id) {
  const r = REGIME_DEFS.find(x => x.id === id);
  return r?.label || id || "—";
}

function RegimesPage({ data, onReload }) {
  const invites = data.invites || [];
  const tables  = data.tables  || [];

  // Périmètre : RSVP = oui uniquement
  const yes = invites.filter(i => i.rsvp_statut === "oui");

  // Sépare enfants vs adultes
  const adultes = yes.filter(i => i.categorie !== "Enfant");
  const enfants = yes.filter(i => i.categorie === "Enfant");

  // Comptage par régime (adultes)
  const counts = {};
  REGIME_DEFS.forEach(r => { counts[r.id] = []; });
  counts.__nonrenseigne__ = [];
  adultes.forEach(inv => {
    const r = inv.regime || "omni";
    if (counts[r]) counts[r].push(inv);
    else counts.__nonrenseigne__.push(inv);
  });

  // Total allergies
  const allergiesCount = adultes.filter(i => i.allergies && i.allergies.trim()).length;

  // État déplié : par défaut tout fermé sauf "autre" (qui mérite attention)
  const [openId, setOpenId] = React.useState("autre");

  const tableNom = (tid) => tables.find(t => t.id === tid)?.nom || "";

  const exportCsv = () => {
    const headers = ["prenom", "nom", "categorie", "cote", "regime", "allergies", "table"];
    const escape = (v) => `"${String(v ?? "").replace(/"/g, '""')}"`;
    const rows = [headers.join(",")];
    yes.forEach(inv => {
      rows.push([
        inv.prenom || "",
        inv.nom || "",
        inv.categorie || "",
        inv.cote || "",
        regimeLabel(inv.regime || "omni"),
        inv.allergies || "",
        tableNom(inv.table_id) || inv.table_id || "",
      ].map(escape).join(","));
    });
    const csv = rows.join("\n");
    const blob = new Blob(["\uFEFF" + csv], { type: "text/csv;charset=utf-8" });
    const url = URL.createObjectURL(blob);
    const a = document.createElement("a");
    a.href = url;
    a.download = `mariage-EA-regimes-${new Date().toISOString().slice(0,10)}.csv`;
    a.click();
    setTimeout(() => URL.revokeObjectURL(url), 1000);
  };

  return (
    <AdPage
      eyebrow={`${yes.length} invités confirmés · ${enfants.length} enfants`}
      title="Régimes & allergies"
      actions={
        <>
          <button className="btn sm" onClick={onReload}>↻ Recharger</button>
          <button className="btn gold sm" onClick={exportCsv}>⤓ Exporter CSV</button>
        </>
      }
    >
      {/* Encart stats horizontal */}
      <div style={{ display: "grid", gridTemplateColumns: `repeat(${REGIME_DEFS.length + 1}, 1fr)`, gap: 10, marginBottom: 22 }}>
        {REGIME_DEFS.map(r => {
          const c = counts[r.id] || [];
          const pct = adultes.length > 0 ? Math.round((c.length / adultes.length) * 100) : 0;
          const isAlert = (r.id === "autre" || r.id === "vegan" || r.id === "sansgluten") && c.length > 0;
          return (
            <RegimeStatCard key={r.id} regime={r} count={c.length} pct={pct} alert={isAlert}
              onClick={() => setOpenId(openId === r.id ? null : r.id)}
              open={openId === r.id}/>
          );
        })}
        {/* Card allergies (transverse) */}
        <RegimeStatCard
          regime={{ id: "allergies", label: "Avec allergies", short: "Aller.", color: "rouge" }}
          count={allergiesCount}
          pct={adultes.length > 0 ? Math.round((allergiesCount / adultes.length) * 100) : 0}
          alert={allergiesCount > 0}
          onClick={() => setOpenId(openId === "allergies" ? null : "allergies")}
          open={openId === "allergies"}
        />
      </div>

      {counts.__nonrenseigne__.length > 0 && (
        <div style={{ marginBottom: 16, padding: "10px 14px", background: AD.orPale, borderLeft: `3px solid ${AD.or}`, fontFamily: AD.italic, fontStyle: "italic", fontSize: 13, color: AD.orDeep }}>
          ⚠ {counts.__nonrenseigne__.length} invité{counts.__nonrenseigne__.length > 1 ? "s" : ""} sans régime renseigné (champ vide ou non rempli).
          <button className="btn sm" style={{ marginLeft: 12 }} onClick={() => setOpenId("__nonrenseigne__")}>Voir</button>
        </div>
      )}

      {/* Tableau déroulant : section pour le régime ouvert */}
      {openId === "allergies" ? (
        <AllergiesSection invites={adultes.filter(i => i.allergies && i.allergies.trim())} tableNom={tableNom}/>
      ) : openId === "__nonrenseigne__" ? (
        <RegimeSection title="Sans régime renseigné" invites={counts.__nonrenseigne__} tableNom={tableNom}/>
      ) : openId ? (
        <RegimeSection
          title={regimeLabel(openId)}
          invites={counts[openId] || []}
          tableNom={tableNom}
        />
      ) : (
        <div style={{ padding: "30px 20px", textAlign: "center", fontFamily: AD.italic, fontStyle: "italic", fontSize: 14, color: AD.inkMute, background: AD.white, border: `1px dashed ${AD.ruleSoft}` }}>
          Cliquez sur une carte ci-dessus pour voir les invités concernés.
        </div>
      )}

      {/* Section enfants — séparée */}
      {enfants.length > 0 && (
        <div style={{ marginTop: 30 }}>
          <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between", marginBottom: 10 }}>
            <div className="eyebrow">★ Menu enfant</div>
            <div style={{ fontFamily: AD.italic, fontStyle: "italic", fontSize: 12, color: AD.inkMute }}>
              {enfants.length} enfant{enfants.length > 1 ? "s" : ""} confirmé{enfants.length > 1 ? "s" : ""}
            </div>
          </div>
          <RegimeSection
            title="Enfants — menu spécifique"
            invites={enfants}
            tableNom={tableNom}
            isChildren
          />
        </div>
      )}
    </AdPage>
  );
}

// ─── Card statistique pour un régime ─────────────────────────────────
function RegimeStatCard({ regime, count, pct, alert, onClick, open }) {
  const palette = {
    ink:   { bg: AD.paperDeep, fg: AD.ink,       barBg: AD.ink },
    sage:  { bg: AD.sagePale,  fg: AD.sage,      barBg: AD.sage },
    or:    { bg: AD.orPale,    fg: AD.orDeep,    barBg: AD.or },
    rouge: { bg: AD.rougePale, fg: AD.rougeDeep, barBg: AD.rouge },
    mute:  { bg: AD.paperDeep, fg: AD.inkMute,   barBg: AD.inkMute },
  }[regime.color] || { bg: AD.paperDeep, fg: AD.ink, barBg: AD.ink };

  return (
    <button onClick={onClick}
      style={{
        textAlign: "left",
        background: open ? palette.bg : AD.white,
        border: `1px solid ${open ? palette.fg : AD.ruleSoft}`,
        borderLeft: `4px solid ${palette.barBg}`,
        padding: "12px 14px",
        cursor: "pointer",
        transition: "all .15s",
        display: "flex", flexDirection: "column", gap: 6,
        minWidth: 0,
      }}>
      <div style={{ display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
        <span className="display-bold" style={{ fontSize: 28, color: alert ? palette.fg : AD.ink, lineHeight: 1 }}>
          {count}
        </span>
        <span style={{ fontFamily: AD.mono, fontSize: 10, color: palette.fg, letterSpacing: 1, fontWeight: 600 }}>
          {pct}%
        </span>
      </div>
      <div style={{ fontFamily: AD.mono, fontSize: 9, letterSpacing: 1.4, color: palette.fg, textTransform: "uppercase", fontWeight: 600, whiteSpace: "nowrap", overflow: "hidden", textOverflow: "ellipsis" }}>
        {regime.label}
      </div>
      <div style={{ height: 3, background: AD.ruleSoft, position: "relative", overflow: "hidden" }}>
        <div style={{ position: "absolute", left: 0, top: 0, bottom: 0, width: `${pct}%`, background: palette.barBg }}/>
      </div>
    </button>
  );
}

// ─── Section : liste des invités d'un régime ─────────────────────────
function RegimeSection({ title, invites, tableNom, isChildren }) {
  if (invites.length === 0) {
    return (
      <div style={{ padding: "30px 20px", textAlign: "center", fontFamily: AD.italic, fontStyle: "italic", fontSize: 14, color: AD.inkMute, background: AD.white, border: `1px solid ${AD.ruleSoft}` }}>
        Aucun invité dans « {title} ».
      </div>
    );
  }
  return (
    <div style={{ background: AD.white, border: `1px solid ${AD.ruleSoft}`, borderLeft: `4px solid ${isChildren ? AD.or : AD.ink}` }}>
      <div style={{ padding: "10px 16px", borderBottom: `1px solid ${AD.ruleSoft}`, display: "flex", alignItems: "baseline", justifyContent: "space-between" }}>
        <div className="display-bold" style={{ fontSize: 16, color: AD.ink }}>{title}</div>
        <div style={{ fontFamily: AD.mono, fontSize: 10, letterSpacing: 1.2, color: AD.inkMute }}>
          {invites.length} invité{invites.length > 1 ? "s" : ""}
        </div>
      </div>
      <table style={{ width: "100%", borderCollapse: "collapse", fontSize: 13 }}>
        <thead>
          <tr style={{ background: AD.paperDeep }}>
            <th style={thStyle()}>Prénom</th>
            <th style={thStyle()}>Nom</th>
            <th style={thStyle()}>Côté</th>
            <th style={thStyle()}>Cat.</th>
            <th style={thStyle()}>Allergies / précisions</th>
            <th style={thStyle()}>Table</th>
          </tr>
        </thead>
        <tbody>
          {invites.map(inv => {
            const coteColor = (inv.cote || "").toLowerCase().startsWith("e") ? AD.sage : AD.rouge;
            return (
              <tr key={inv.id} style={{ borderTop: `1px solid ${AD.ruleSoft}` }}>
                <td style={tdStyle()}><strong>{inv.prenom}</strong></td>
                <td style={tdStyle()}>{inv.nom || "—"}</td>
                <td style={tdStyle()}>
                  <span style={{ display: "inline-block", padding: "1px 7px", background: coteColor === AD.sage ? AD.sagePale : AD.rougePale, color: coteColor, fontFamily: AD.mono, fontSize: 9, letterSpacing: 1 }}>
                    {(inv.cote || "?").charAt(0).toUpperCase()}
                  </span>
                </td>
                <td style={{ ...tdStyle(), fontFamily: AD.mono, fontSize: 10, color: AD.inkMute, letterSpacing: 0.5 }}>{inv.categorie || "—"}</td>
                <td style={tdStyle()}>
                  {inv.allergies ? (
                    <span style={{ color: AD.rougeDeep, fontWeight: 500 }}>{inv.allergies}</span>
                  ) : <span style={{ color: AD.inkMute }}>—</span>}
                </td>
                <td style={{ ...tdStyle(), fontFamily: AD.mono, fontSize: 11, color: AD.inkSoft }}>
                  {inv.table_id ? tableNom(inv.table_id) || inv.table_id : <span style={{ color: AD.orDeep }}>— sans table —</span>}
                </td>
              </tr>
            );
          })}
        </tbody>
      </table>
    </div>
  );
}

// ─── Section spécifique : tous les invités avec allergies ─────────────
function AllergiesSection({ invites, tableNom }) {
  return <RegimeSection title="Allergies & précisions déclarées" invites={invites} tableNom={tableNom}/>;
}

function thStyle() {
  return {
    padding: "8px 12px", textAlign: "left",
    fontFamily: AD.mono, fontSize: 9, letterSpacing: 1.5, textTransform: "uppercase",
    color: AD.inkSoft, fontWeight: 600,
  };
}
function tdStyle() {
  return { padding: "8px 12px", verticalAlign: "middle" };
}

Object.assign(window, { RegimesPage });
