/* global React, PageHeader, FadeUp */

const MONTH_NAMES = [
  "Janvier",
  "Février",
  "Mars",
  "Avril",
  "Mai",
  "Juin",
  "Juillet",
  "Août",
  "Septembre",
  "Octobre",
  "Novembre",
  "Décembre",
];
const DOW_LABELS = ["Lun", "Mar", "Mer", "Jeu", "Ven", "Sam", "Dim"];

// JS Date.getDay(): 0=Dim, 1=Lun ... 6=Sam → on veut Lun=0
function dowMonStart(d) {
  return (d.getDay() + 6) % 7;
}

const TYPE_COLORS = {
  concours_interne: "red",
  match_externe: "navy",
  federal: "gold",
  jeunesse_sport: "green",
  festif: "gold",
  entrainement: "gray",
};
const TYPE_LABELS = {
  concours_interne: "Concours interne",
  match_externe: "Match externe",
  federal: "Tir fédéral",
  jeunesse_sport: "Jeunesse+Sport",
  festif: "Festif",
  entrainement: "Entraînement",
};

function catColor(c) {
  return (
    {
      red: "var(--red)",
      gold: "var(--accent)",
      navy: "var(--navy)",
      green: "var(--green)",
      gray: "var(--gray-2)",
    }[c] || "var(--gray)"
  );
}

function PageCalendrier({ onNav }) {
  const [data, setData] = React.useState(null);
  const [error, setError] = React.useState(null);
  // Default: current month if 2026 and within range, else May 2026
  const today = new Date();
  const initMonth = today.getFullYear() === 2026 ? today.getMonth() + 1 : 5;
  const [currentMonth, setCurrentMonth] = React.useState(initMonth);
  const [view, setView] = React.useState("mois");
  const [selectedEvent, setSelectedEvent] = React.useState(null);
  const [filters, setFilters] = React.useState({
    disciplines: new Set(),
    types: new Set(),
    org: new Set(),
  });

  React.useEffect(() => {
    fetch("data/calendrier-2026.json")
      .then((r) => r.json())
      .then(setData)
      .catch((e) => setError(e.message));
  }, []);

  if (error)
    return (
      <div className="container-wide" style={{ padding: 64 }}>
        Erreur de chargement : {error}
      </div>
    );
  if (!data)
    return (
      <div className="container-wide" style={{ padding: 64 }}>
        <div className="tag-mono">— Chargement —</div>
      </div>
    );

  const allEvents = data.events;

  // Apply filters
  const matchesFilters = (e) => {
    if (
      filters.disciplines.size &&
      (!e.discipline || !filters.disciplines.has(e.discipline))
    )
      return false;
    if (filters.types.size && !filters.types.has(e.type)) return false;
    if (filters.org.size && !filters.org.has(e.organisateur)) return false;
    return true;
  };
  const filtered = allEvents.filter(matchesFilters);
  const inMonth = filtered.filter((e) => e.mois === currentMonth);

  // Build calendar grid
  const firstDay = new Date(2026, currentMonth - 1, 1);
  const daysInMonth = new Date(2026, currentMonth, 0).getDate();
  const startDow = dowMonStart(firstDay);
  const cells = [];
  for (let i = 0; i < startDow; i++) cells.push(null);
  for (let d = 1; d <= daysInMonth; d++) cells.push(d);
  while (cells.length % 7) cells.push(null);

  const eventsByDay = {};
  inMonth.forEach((e) => {
    if (!eventsByDay[e.jour]) eventsByDay[e.jour] = [];
    eventsByDay[e.jour].push(e);
  });

  const realToday =
    today.getMonth() + 1 === currentMonth && today.getFullYear() === 2026
      ? today.getDate()
      : null;

  const upcoming = filtered
    .filter((e) => {
      const evDate = new Date(2026, e.mois - 1, e.jour);
      return (
        evDate >=
        new Date(today.getFullYear(), today.getMonth(), today.getDate())
      );
    })
    .slice(0, 8);

  const allDisciplines = [
    ...new Set(allEvents.map((e) => e.discipline).filter(Boolean)),
  ].sort();
  const allTypes = [
    "concours_interne",
    "match_externe",
    "federal",
    "jeunesse_sport",
    "festif",
    "entrainement",
  ];
  const allOrgs = [
    ...new Set(allEvents.map((e) => e.organisateur).filter(Boolean)),
  ].sort();

  const toggleSet = (key, value) => {
    setFilters((prev) => {
      const next = new Set(prev[key]);
      next.has(value) ? next.delete(value) : next.add(value);
      return { ...prev, [key]: next };
    });
  };
  const reset = () =>
    setFilters({ disciplines: new Set(), types: new Set(), org: new Set() });
  const totalActiveFilters =
    filters.disciplines.size + filters.types.size + filters.org.size;

  const goToMonth = (delta) =>
    setCurrentMonth((m) => Math.max(1, Math.min(12, m + delta)));

  return (
    <div className="container-wide">
      <PageHeader
        eyebrow="MMXXVI"
        title="Calendrier"
        italic="des tirs"
        subtitle={`Saison 2026 — ${data._meta.count} manifestations sur l'année. Concours internes, matches externes, école Jeunesse+Sport, tir fédéral. Filtrez par discipline, type ou société organisatrice.`}
      />

      <div
        className="cal-layout"
        style={{
          display: "grid",
          gridTemplateColumns: "260px 1fr",
          gap: 48,
          marginTop: 40,
        }}
      >
        {/* SIDEBAR */}
        <aside
          className="hide-mobile"
          style={{ borderRight: "1px solid var(--hairline)", paddingRight: 32 }}
        >
          <FilterBlock
            title={`Disciplines (${filters.disciplines.size || "toutes"})`}
          >
            {allDisciplines.map((d) => (
              <CheckRow
                key={d}
                label={d}
                checked={filters.disciplines.has(d)}
                onClick={() => toggleSet("disciplines", d)}
              />
            ))}
          </FilterBlock>
          <FilterBlock title={`Type (${filters.types.size || "tous"})`}>
            {allTypes.map((t) => (
              <CheckRow
                key={t}
                label={TYPE_LABELS[t]}
                checked={filters.types.has(t)}
                onClick={() => toggleSet("types", t)}
              />
            ))}
          </FilterBlock>
          <FilterBlock title={`Société (${filters.org.size || "toutes"})`}>
            {allOrgs.slice(0, 8).map((o) => (
              <CheckRow
                key={o}
                label={o}
                checked={filters.org.has(o)}
                onClick={() => toggleSet("org", o)}
              />
            ))}
          </FilterBlock>

          <button
            className="btn btn-ghost"
            style={{ width: "100%", justifyContent: "center", marginTop: 12 }}
            onClick={reset}
            disabled={!totalActiveFilters}
          >
            {totalActiveFilters
              ? `Réinitialiser (${totalActiveFilters})`
              : "Aucun filtre actif"}
          </button>

          <div
            style={{
              marginTop: 40,
              padding: 18,
              background: "var(--paper-2)",
              border: "1px solid var(--hairline)",
            }}
          >
            <div
              className="tag-mono"
              style={{ marginBottom: 10, fontSize: 10 }}
            >
              — Stats {MONTH_NAMES[currentMonth - 1]}
            </div>
            <div
              style={{
                fontFamily: "var(--display)",
                fontSize: 32,
                fontStyle: "italic",
                color: "var(--accent-deep)",
                lineHeight: 1,
              }}
            >
              {inMonth.length}
            </div>
            <div style={{ fontSize: 12, color: "var(--gray)", marginTop: 4 }}>
              manifestations ce mois
              {filters.disciplines.size + filters.types.size + filters.org.size
                ? " (filtré)"
                : ""}
            </div>
            <div
              style={{
                fontSize: 11,
                color: "var(--gray)",
                marginTop: 12,
                lineHeight: 1.6,
              }}
            >
              Total année : <strong>{filtered.length}</strong> /{" "}
              {allEvents.length}
            </div>
          </div>
        </aside>

        {/* MAIN */}
        <div>
          <div
            style={{
              display: "flex",
              alignItems: "center",
              justifyContent: "space-between",
              marginBottom: 24,
              flexWrap: "wrap",
              gap: 16,
            }}
          >
            <div style={{ display: "flex", alignItems: "center", gap: 16 }}>
              <button
                className="btn btn-ghost"
                style={{ padding: "10px 14px" }}
                onClick={() => goToMonth(-1)}
                disabled={currentMonth <= 1}
              >
                ←
              </button>
              <h2
                className="cal-month-title"
                style={{
                  fontFamily: "var(--display)",
                  fontSize: 40,
                  fontWeight: 500,
                  margin: 0,
                  letterSpacing: "-0.01em",
                  textAlign: "center",
                }}
              >
                {MONTH_NAMES[currentMonth - 1]}{" "}
                <em style={{ color: "var(--accent-deep)" }}>2026</em>
              </h2>
              <button
                className="btn btn-ghost"
                style={{ padding: "10px 14px" }}
                onClick={() => goToMonth(1)}
                disabled={currentMonth >= 12}
              >
                →
              </button>
            </div>
            <div
              style={{
                display: "flex",
                gap: 4,
                border: "1px solid var(--hairline-strong)",
              }}
            >
              {["mois", "liste"].map((v) => (
                <button
                  key={v}
                  onClick={() => setView(v)}
                  style={{
                    padding: "8px 16px",
                    border: 0,
                    background: view === v ? "var(--ink)" : "transparent",
                    color: view === v ? "var(--paper)" : "var(--ink)",
                    fontFamily: "var(--mono)",
                    fontSize: 11,
                    letterSpacing: "0.12em",
                    textTransform: "uppercase",
                    cursor: "pointer",
                  }}
                >
                  {v}
                </button>
              ))}
            </div>
          </div>

          {/* Quick month nav */}
          <div
            className="cal-quick-nav"
            style={{
              display: "flex",
              gap: 4,
              marginBottom: 20,
              flexWrap: "wrap",
            }}
          >
            {MONTH_NAMES.map((mn, idx) => {
              const m = idx + 1;
              const cnt = filtered.filter((e) => e.mois === m).length;
              const isCur = m === currentMonth;
              return (
                <button
                  key={m}
                  onClick={() => setCurrentMonth(m)}
                  disabled={!cnt}
                  style={{
                    padding: "6px 10px",
                    border:
                      "1px solid " + (isCur ? "var(--ink)" : "var(--hairline)"),
                    background: isCur ? "var(--ink)" : "transparent",
                    color: isCur
                      ? "var(--paper)"
                      : cnt
                        ? "var(--ink)"
                        : "var(--gray-2)",
                    fontFamily: "var(--mono)",
                    fontSize: 10,
                    letterSpacing: "0.08em",
                    cursor: cnt ? "pointer" : "not-allowed",
                    opacity: cnt ? 1 : 0.4,
                    textTransform: "uppercase",
                  }}
                >
                  {mn.slice(0, 3)} <span style={{ opacity: 0.6 }}>· {cnt}</span>
                </button>
              );
            })}
          </div>

          {/* legend */}
          <div
            style={{
              display: "flex",
              gap: 18,
              marginBottom: 16,
              flexWrap: "wrap",
              fontFamily: "var(--mono)",
              fontSize: 10,
              letterSpacing: "0.08em",
              textTransform: "uppercase",
              color: "var(--gray)",
            }}
          >
            {Object.keys(TYPE_LABELS).map((t) => (
              <span
                key={t}
                style={{ display: "inline-flex", gap: 6, alignItems: "center" }}
              >
                <span
                  className="dot"
                  style={{ background: catColor(TYPE_COLORS[t]) }}
                />{" "}
                {TYPE_LABELS[t]}
              </span>
            ))}
          </div>

          {view === "mois" && (
            <div
              className="cal-month-grid-wrap"
              style={{
                border: "1px solid var(--hairline)",
                background: "var(--white)",
              }}
            >
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(7, minmax(0, 1fr))",
                  borderBottom: "1px solid var(--hairline)",
                  background: "var(--ink)",
                  color: "var(--paper-2)",
                }}
              >
                {DOW_LABELS.map((d) => (
                  <div
                    key={d}
                    style={{
                      padding: "12px 14px",
                      fontFamily: "var(--mono)",
                      fontSize: 11,
                      letterSpacing: "0.16em",
                      textTransform: "uppercase",
                    }}
                  >
                    {d}
                  </div>
                ))}
              </div>
              <div
                style={{
                  display: "grid",
                  gridTemplateColumns: "repeat(7, minmax(0, 1fr))",
                }}
              >
                {cells.map((d, i) => {
                  const evs = d ? eventsByDay[d] || [] : [];
                  const isToday = d === realToday;
                  return (
                    <div
                      key={i}
                      style={{
                        minHeight: 110,
                        borderRight:
                          i % 7 < 6 ? "1px solid var(--hairline)" : "none",
                        borderBottom: "1px solid var(--hairline)",
                        padding: 8,
                        background: isToday
                          ? "var(--paper-2)"
                          : d
                            ? "var(--white)"
                            : "rgba(0,0,0,0.02)",
                        position: "relative",
                      }}
                    >
                      {isToday && (
                        <div
                          style={{
                            position: "absolute",
                            top: 0,
                            left: 0,
                            right: 0,
                            height: 2,
                            background: "var(--accent)",
                          }}
                        />
                      )}
                      {d && (
                        <>
                          <div
                            className="mono"
                            style={{
                              fontSize: 12,
                              color: isToday
                                ? "var(--accent-deep)"
                                : "var(--gray)",
                              marginBottom: 6,
                              fontWeight: isToday ? 600 : 400,
                            }}
                          >
                            {String(d).padStart(2, "0")}
                          </div>
                          {evs.slice(0, 3).map((e, j) => (
                            <div
                              key={j}
                              onClick={() => setSelectedEvent(e)}
                              style={{
                                display: "flex",
                                gap: 6,
                                alignItems: "flex-start",
                                fontSize: 10.5,
                                marginBottom: 3,
                                lineHeight: 1.2,
                                paddingLeft: 6,
                                borderLeft:
                                  "2px solid " + catColor(TYPE_COLORS[e.type]),
                                cursor: "pointer",
                                minWidth: 0,
                              }}
                              title={e.titre}
                            >
                              <span
                                className="mono"
                                style={{ color: "var(--gray)", flexShrink: 0 }}
                              >
                                {e.heure_debut || "·"}
                              </span>
                              <span
                                style={{
                                  overflow: "hidden",
                                  textOverflow: "ellipsis",
                                  whiteSpace: "nowrap",
                                  minWidth: 0,
                                  flex: 1,
                                }}
                              >
                                {e.titre}
                              </span>
                            </div>
                          ))}
                          {evs.length > 3 && (
                            <div
                              onClick={() =>
                                setSelectedEvent({ list: evs, day: d })
                              }
                              style={{
                                fontSize: 10,
                                color: "var(--accent-deep)",
                                cursor: "pointer",
                                marginTop: 4,
                                fontFamily: "var(--mono)",
                                textTransform: "uppercase",
                                letterSpacing: "0.08em",
                              }}
                            >
                              +{evs.length - 3} autre
                              {evs.length - 3 > 1 ? "s" : ""}
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  );
                })}
              </div>
            </div>
          )}

          {view === "liste" && (
            <div
              style={{
                border: "1px solid var(--hairline)",
                background: "var(--white)",
              }}
            >
              {inMonth.length === 0 && (
                <div
                  style={{
                    padding: 40,
                    textAlign: "center",
                    color: "var(--gray)",
                  }}
                >
                  Aucune manifestation ce mois avec ces filtres.
                </div>
              )}
              {inMonth.map((e, i) => (
                <div
                  key={e.id}
                  onClick={() => setSelectedEvent(e)}
                  style={{
                    display: "grid",
                    gridTemplateColumns: "90px 1fr auto",
                    gap: 24,
                    padding: "16px 24px",
                    borderBottom:
                      i < inMonth.length - 1
                        ? "1px dashed var(--hairline)"
                        : "none",
                    alignItems: "center",
                    cursor: "pointer",
                  }}
                >
                  <div
                    style={{
                      textAlign: "center",
                      borderRight: "1px solid var(--hairline)",
                      paddingRight: 16,
                    }}
                  >
                    <div
                      style={{
                        fontFamily: "var(--display)",
                        fontSize: 26,
                        fontStyle: "italic",
                        color: "var(--accent-deep)",
                        lineHeight: 1,
                      }}
                    >
                      {String(e.jour).padStart(2, "0")}
                    </div>
                    <div
                      className="tag-mono"
                      style={{ marginTop: 4, fontSize: 9 }}
                    >
                      {e.jour_semaine.slice(0, 3).toUpperCase()}
                    </div>
                  </div>
                  <div>
                    <div
                      style={{
                        display: "flex",
                        gap: 10,
                        alignItems: "center",
                        marginBottom: 4,
                        flexWrap: "wrap",
                      }}
                    >
                      <span
                        className="dot"
                        style={{ background: catColor(TYPE_COLORS[e.type]) }}
                      />
                      <span className="tag-mono" style={{ fontSize: 10 }}>
                        {TYPE_LABELS[e.type]}
                      </span>
                      {e.discipline && (
                        <span
                          className="chip gold"
                          style={{ fontSize: 9, padding: "2px 6px" }}
                        >
                          {e.discipline}
                        </span>
                      )}
                      <span
                        className="mono"
                        style={{ fontSize: 11, color: "var(--gray)" }}
                      >
                        · {e.organisateur}
                      </span>
                    </div>
                    <div
                      style={{
                        fontFamily: "var(--display)",
                        fontSize: 18,
                        fontWeight: 500,
                      }}
                    >
                      {e.titre}
                    </div>
                    <div
                      style={{
                        fontSize: 12,
                        color: "var(--gray)",
                        marginTop: 2,
                      }}
                    >
                      {e.lieu}
                      {e.horaire_label ? " · " + e.horaire_label : ""}
                    </div>
                  </div>
                  <div
                    style={{
                      fontFamily: "var(--mono)",
                      fontSize: 11,
                      color: "var(--accent-deep)",
                    }}
                  >
                    ▸
                  </div>
                </div>
              ))}
            </div>
          )}

          {/* upcoming bar */}
          {view === "mois" && (
            <div style={{ marginTop: 56 }}>
              <div
                style={{
                  display: "flex",
                  justifyContent: "space-between",
                  alignItems: "baseline",
                  marginBottom: 24,
                }}
              >
                <h3
                  style={{
                    fontFamily: "var(--display)",
                    fontStyle: "italic",
                    fontSize: 28,
                    fontWeight: 500,
                    margin: 0,
                  }}
                >
                  Prochains tirs
                </h3>
                <span className="tag-mono">{upcoming.length} à venir</span>
              </div>
              <div
                style={{
                  display: "flex",
                  flexDirection: "column",
                  border: "1px solid var(--hairline)",
                  background: "var(--white)",
                }}
              >
                {upcoming.map((e, i) => (
                  <FadeUp key={e.id} delay={i * 30}>
                    <div
                      onClick={() => setSelectedEvent(e)}
                      style={{
                        display: "grid",
                        gridTemplateColumns: "90px 1fr auto",
                        gap: 24,
                        padding: "16px 24px",
                        borderBottom:
                          i < upcoming.length - 1
                            ? "1px dashed var(--hairline)"
                            : "none",
                        alignItems: "center",
                        cursor: "pointer",
                      }}
                    >
                      <div
                        style={{
                          textAlign: "center",
                          borderRight: "1px solid var(--hairline)",
                          paddingRight: 16,
                        }}
                      >
                        <div
                          style={{
                            fontFamily: "var(--display)",
                            fontSize: 24,
                            fontStyle: "italic",
                            color: "var(--accent-deep)",
                            lineHeight: 1,
                          }}
                        >
                          {String(e.jour).padStart(2, "0")}
                        </div>
                        <div
                          className="tag-mono"
                          style={{ marginTop: 4, fontSize: 9 }}
                        >
                          {MONTH_NAMES[e.mois - 1].slice(0, 3).toUpperCase()}
                        </div>
                      </div>
                      <div>
                        <div
                          style={{
                            display: "flex",
                            gap: 10,
                            alignItems: "center",
                            marginBottom: 4,
                            flexWrap: "wrap",
                          }}
                        >
                          <span
                            className="dot"
                            style={{
                              background: catColor(TYPE_COLORS[e.type]),
                            }}
                          />
                          <span className="tag-mono" style={{ fontSize: 10 }}>
                            {TYPE_LABELS[e.type]}
                          </span>
                          {e.discipline && (
                            <span
                              className="chip gold"
                              style={{ fontSize: 9, padding: "2px 6px" }}
                            >
                              {e.discipline}
                            </span>
                          )}
                        </div>
                        <div
                          style={{
                            fontFamily: "var(--display)",
                            fontSize: 18,
                            fontWeight: 500,
                          }}
                        >
                          {e.titre}
                        </div>
                        <div
                          style={{
                            fontSize: 12,
                            color: "var(--gray)",
                            marginTop: 2,
                          }}
                        >
                          {e.organisateur} ·{" "}
                          {e.horaire_label || "horaire à confirmer"}
                        </div>
                      </div>
                      <button
                        className="btn btn-ghost-gold"
                        style={{ padding: "6px 12px", fontSize: 11 }}
                      >
                        Détails →
                      </button>
                    </div>
                  </FadeUp>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>

      {/* Modal event detail */}
      {selectedEvent && (
        <EventModal
          event={selectedEvent}
          onClose={() => setSelectedEvent(null)}
        />
      )}

      <style>{`
        @media (max-width: 900px) {
          .cal-layout { grid-template-columns: 1fr !important; gap: 24px !important; }
          .cal-layout > div { min-width: 0; }
          .cal-month-grid-wrap { overflow-x: auto; -webkit-overflow-scrolling: touch; }
          .cal-month-grid-wrap > div { min-width: 560px; }
          .cal-quick-nav { overflow-x: auto; flex-wrap: nowrap !important; padding-bottom: 8px; }
          .cal-quick-nav button { flex-shrink: 0; }
          .cal-month-title { font-size: 28px !important; min-width: 0 !important; }
        }
      `}</style>
    </div>
  );
}

function FilterBlock({ title, children }) {
  return (
    <div style={{ marginBottom: 24 }}>
      <div className="tag-mono" style={{ marginBottom: 10, fontSize: 10 }}>
        — {title}
      </div>
      <div style={{ display: "flex", flexDirection: "column", gap: 4 }}>
        {children}
      </div>
    </div>
  );
}
function CheckRow({ label, checked, onClick }) {
  return (
    <div
      onClick={onClick}
      style={{
        display: "flex",
        alignItems: "center",
        gap: 10,
        fontSize: 13,
        cursor: "pointer",
        padding: "3px 0",
      }}
    >
      <span
        style={{
          width: 14,
          height: 14,
          border:
            "1px solid " + (checked ? "var(--ink)" : "var(--hairline-strong)"),
          background: checked ? "var(--ink)" : "transparent",
          display: "inline-flex",
          alignItems: "center",
          justifyContent: "center",
          color: "var(--paper)",
          fontSize: 10,
        }}
      >
        {checked ? "✓" : ""}
      </span>
      <span>{label}</span>
    </div>
  );
}

function EventModal({ event, onClose }) {
  // Multi-event from "+N autres" click
  if (event.list) {
    return (
      <div
        onClick={onClose}
        style={{
          position: "fixed",
          inset: 0,
          background: "rgba(26,26,26,0.6)",
          zIndex: 100,
          display: "flex",
          alignItems: "center",
          justifyContent: "center",
          padding: 20,
          backdropFilter: "blur(2px)",
        }}
      >
        <div
          onClick={(e) => e.stopPropagation()}
          style={{
            background: "var(--paper)",
            maxWidth: 640,
            width: "100%",
            maxHeight: "85vh",
            overflowY: "auto",
            border: "1px solid var(--ink)",
          }}
        >
          <div
            style={{
              padding: "20px 28px",
              borderBottom: "1px solid var(--hairline)",
              display: "flex",
              justifyContent: "space-between",
              alignItems: "center",
            }}
          >
            <h3
              style={{
                fontFamily: "var(--display)",
                fontStyle: "italic",
                fontSize: 28,
                margin: 0,
              }}
            >
              {event.list.length} évènements le{" "}
              {String(event.day).padStart(2, "0")}
            </h3>
            <button
              onClick={onClose}
              style={{
                background: "transparent",
                border: 0,
                fontSize: 22,
                cursor: "pointer",
                color: "var(--ink)",
              }}
            >
              ✕
            </button>
          </div>
          <div>
            {event.list.map((e, i) => (
              <div
                key={i}
                style={{
                  padding: "16px 28px",
                  borderBottom:
                    i < event.list.length - 1
                      ? "1px dashed var(--hairline)"
                      : "none",
                }}
              >
                <div
                  style={{
                    display: "flex",
                    gap: 10,
                    marginBottom: 4,
                    flexWrap: "wrap",
                  }}
                >
                  <span
                    className="dot"
                    style={{ background: catColor(TYPE_COLORS[e.type]) }}
                  />
                  <span className="tag-mono" style={{ fontSize: 10 }}>
                    {e.heure_debut || "·"}
                    {e.heure_fin ? " — " + e.heure_fin : ""}
                  </span>
                  {e.discipline && (
                    <span
                      className="chip gold"
                      style={{ fontSize: 9, padding: "2px 6px" }}
                    >
                      {e.discipline}
                    </span>
                  )}
                </div>
                <div style={{ fontFamily: "var(--display)", fontSize: 18 }}>
                  {e.titre}
                </div>
                <div
                  style={{ fontSize: 12, color: "var(--gray)", marginTop: 2 }}
                >
                  {e.organisateur_label} · {e.lieu}
                </div>
              </div>
            ))}
          </div>
        </div>
      </div>
    );
  }
  return (
    <div
      onClick={onClose}
      style={{
        position: "fixed",
        inset: 0,
        background: "rgba(26,26,26,0.6)",
        zIndex: 100,
        display: "flex",
        alignItems: "center",
        justifyContent: "center",
        padding: 20,
        backdropFilter: "blur(2px)",
      }}
    >
      <div
        onClick={(e) => e.stopPropagation()}
        style={{
          background: "var(--paper)",
          maxWidth: 560,
          width: "100%",
          border: "1px solid var(--ink)",
          position: "relative",
        }}
      >
        <button
          onClick={onClose}
          style={{
            position: "absolute",
            top: 16,
            right: 16,
            background: "transparent",
            border: 0,
            fontSize: 22,
            cursor: "pointer",
            color: "var(--ink)",
            zIndex: 2,
          }}
        >
          ✕
        </button>
        <div style={{ padding: "32px 36px 28px" }}>
          <div className="tag-gold" style={{ marginBottom: 14 }}>
            — {TYPE_LABELS[event.type] || event.type}
          </div>
          <h2
            style={{
              fontFamily: "var(--display)",
              fontSize: 30,
              fontWeight: 500,
              margin: "0 0 18px",
              lineHeight: 1.2,
            }}
          >
            {event.titre}
          </h2>
          <div
            style={{
              display: "flex",
              gap: 10,
              marginBottom: 24,
              flexWrap: "wrap",
            }}
          >
            {event.discipline && (
              <span className="chip gold">{event.discipline}</span>
            )}
            <span className="chip">
              {event.organisateur_label || event.organisateur}
            </span>
          </div>
          <div
            style={{
              borderTop: "1px solid var(--hairline)",
              paddingTop: 20,
              display: "grid",
              gridTemplateColumns: "90px 1fr",
              gap: 12,
              fontSize: 14,
            }}
          >
            <span className="tag-mono">DATE</span>
            <span style={{ fontFamily: "var(--display)", fontSize: 18 }}>
              {event.jour_semaine} {String(event.jour).padStart(2, "0")}{" "}
              {MONTH_NAMES[event.mois - 1]} {event.annee}
            </span>
            <span className="tag-mono">HORAIRE</span>
            <span className="mono">
              {event.horaire_label ||
                (event.heure_debut
                  ? event.heure_debut +
                    (event.heure_fin ? " — " + event.heure_fin : "")
                  : "À confirmer")}
            </span>
            <span className="tag-mono">LIEU</span>
            <span>{event.lieu}</span>
            <span className="tag-mono">SOCIÉTÉ</span>
            <span>{event.organisateur_label || event.organisateur}</span>
          </div>
          <div style={{ marginTop: 28, display: "flex", gap: 12 }}>
            <button
              className="btn btn-primary"
              style={{ flex: 1, justifyContent: "center" }}
            >
              S'inscrire →
            </button>
            <button
              className="btn btn-ghost-gold"
              style={{ justifyContent: "center" }}
            >
              + iCal
            </button>
          </div>
        </div>
      </div>
    </div>
  );
}

window.PageCalendrier = PageCalendrier;
