/* CommunityGallery — DIY/mods + setups réels de la communauté MelGeek.
   Data: window.MG_COMMUNITY (assets/img/community/manifest.js)
   shape: { c80: { diy:[{src,thumb,w,h}], owners:[...] }, ... }
   Exports: CommunityLightbox (fullscreen), HeroModsChip (hero entry, DIY only), CommunityStrip (PDP section).
   Tian 2026-07-05: hero builds = DIY 图 only (pas de setups) · chip = même 流光 sweep que le hero ·
   titres de section = dégradé display (统一 PDP) · pas de badges MOD/SETUP sur les vignettes. */

const MG_COMM_BASE = "../../assets/img/community/";
const MG_COMM_META = {
  c80:   "Centauri 80",
  c60:   "Centauri 60",
  eva80: "EVA 80",
  eva60: "EVA 60 · Asuka",
  ultra: "MADE68 Ultra",
};
const MG_COMM_ORDER = ["c80", "c60", "eva80", "eva60", "ultra"];

function mgCommPhotos(model, sets) {
  const d = (window.MG_COMMUNITY || {})[model] || {};
  const use = sets || ["diy", "owners"];
  const out = [];
  for (const s of use) {
    for (const p of d[s] || []) out.push({ ...p, kind: s === "diy" ? "mod" : "setup" });
  }
  return out;
}

/* 流光 sweep (échos du comet du hero) — injecté une fois */
(function () {
  if (document.getElementById("mg-comm-style")) return;
  const st = document.createElement("style");
  st.id = "mg-comm-style";
  st.textContent = `
    .mg-comm-chip { position: relative; overflow: hidden; isolation: isolate; }
    .mg-comm-chip::after { content: ""; position: absolute; inset: 0; border-radius: inherit; pointer-events: none;
      background: linear-gradient(115deg, transparent 32%, rgba(var(--mg-accent-rgb, 57,215,247), 0.28) 50%, transparent 68%);
      background-size: 240% 100%; background-repeat: no-repeat; animation: mgChipFlow 3.4s linear infinite; }
    @keyframes mgChipFlow { 0% { background-position: 130% 0; } 100% { background-position: -130% 0; } }
    @media (prefers-reduced-motion: reduce) { .mg-comm-chip::after { animation: none; display: none; } }
  `;
  document.head.appendChild(st);
})();

function CommunityLightbox({ initialModel = "c80", initialIndex = 0, onClose, sets = null, base = MG_COMM_BASE }) {
  const [model, setModel] = React.useState(initialModel);
  const [idx, setIdx] = React.useState(initialIndex);
  const touch = React.useRef(null);
  const photos = mgCommPhotos(model, sets);
  const cur = photos[Math.min(idx, photos.length - 1)];

  React.useEffect(() => {
    const prev = document.body.style.overflow;
    document.body.style.overflow = "hidden";
    const onKey = (e) => {
      if (e.key === "Escape") onClose();
      if (e.key === "ArrowRight") setIdx(i => Math.min(i + 1, photos.length - 1));
      if (e.key === "ArrowLeft") setIdx(i => Math.max(i - 1, 0));
    };
    window.addEventListener("keydown", onKey);
    return () => { document.body.style.overflow = prev; window.removeEventListener("keydown", onKey); };
  }, [photos.length, onClose]);

  const swap = (m) => { setModel(m); setIdx(0); };
  if (!cur) return null;
  // portal → body : le hero a des ancêtres transform/filter qui piègent position:fixed (containing block)
  return ReactDOM.createPortal(
    <div role="dialog" aria-modal="true" aria-label="Builds de la communauté"
      onClick={onClose}
      style={{ position: "fixed", inset: 0, zIndex: 9999, background: "rgba(5,6,10,0.94)", backdropFilter: "blur(10px)",
        display: "flex", flexDirection: "column", padding: "clamp(10px, 2vw, 28px)" }}>
      {/* header: tabs + close */}
      <div onClick={(e) => e.stopPropagation()} style={{ display: "flex", alignItems: "center", gap: "8px", flexWrap: "wrap", paddingBottom: "10px" }}>
        {MG_COMM_ORDER.filter(m => mgCommPhotos(m, sets).length).map(m => (
          <button key={m} type="button" onClick={() => swap(m)}
            style={{ font: "600 12px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.06em", textTransform: "uppercase",
              padding: "9px 14px", borderRadius: "999px", cursor: "pointer",
              color: m === model ? "#0b0c10" : "rgba(255,255,255,0.82)",
              background: m === model ? "var(--mg-honey, #ffc93d)" : "rgba(255,255,255,0.07)",
              border: "1px solid " + (m === model ? "var(--mg-honey, #ffc93d)" : "rgba(255,255,255,0.18)") }}>
            {MG_COMM_META[m]}
          </button>
        ))}
        <button type="button" onClick={onClose} aria-label="Fermer"
          style={{ marginLeft: "auto", font: "600 13px/1 var(--mg-font-mono, monospace)", color: "rgba(255,255,255,0.85)",
            padding: "9px 14px", borderRadius: "999px", cursor: "pointer", background: "rgba(255,255,255,0.07)",
            border: "1px solid rgba(255,255,255,0.18)" }}>
          ✕ Fermer
        </button>
      </div>
      {/* main image */}
      <div onClick={(e) => e.stopPropagation()} style={{ flex: 1, minHeight: 0, position: "relative", display: "flex", alignItems: "center", justifyContent: "center" }}
        onTouchStart={(e) => { touch.current = e.touches[0].clientX; }}
        onTouchEnd={(e) => {
          if (touch.current == null) return;
          const dx = e.changedTouches[0].clientX - touch.current;
          if (dx < -40) setIdx(i => Math.min(i + 1, photos.length - 1));
          if (dx > 40) setIdx(i => Math.max(i - 1, 0));
          touch.current = null;
        }}>
        <img key={model + idx} src={base + cur.src} alt={MG_COMM_META[model] + " — build communauté " + (idx + 1)}
          style={{ maxWidth: "100%", maxHeight: "100%", objectFit: "contain", borderRadius: "10px",
            boxShadow: "0 24px 80px rgba(0,0,0,0.55)" }} />
        {idx > 0 && (
          <button type="button" aria-label="Précédent" onClick={() => setIdx(i => i - 1)}
            style={{ position: "absolute", left: "6px", top: "50%", transform: "translateY(-50%)", width: "44px", height: "44px",
              borderRadius: "50%", border: "1px solid rgba(255,255,255,0.25)", background: "rgba(10,11,16,0.65)",
              color: "#fff", fontSize: "18px", cursor: "pointer" }}>←</button>
        )}
        {idx < photos.length - 1 && (
          <button type="button" aria-label="Suivant" onClick={() => setIdx(i => i + 1)}
            style={{ position: "absolute", right: "6px", top: "50%", transform: "translateY(-50%)", width: "44px", height: "44px",
              borderRadius: "50%", border: "1px solid rgba(255,255,255,0.25)", background: "rgba(10,11,16,0.65)",
              color: "#fff", fontSize: "18px", cursor: "pointer" }}>→</button>
        )}
      </div>
      {/* footer: caption + thumb rail */}
      <div onClick={(e) => e.stopPropagation()} style={{ paddingTop: "10px" }}>
        <p style={{ margin: "0 0 8px", font: "500 12px/1.5 var(--mg-font-mono, monospace)", color: "rgba(255,255,255,0.6)", letterSpacing: "0.04em" }}>
          Keycaps, molette, badge : tout se change. Photos réelles de la communauté MelGeek — {idx + 1}/{photos.length}
        </p>
        <div style={{ display: "flex", gap: "8px", overflowX: "auto", paddingBottom: "4px", WebkitOverflowScrolling: "touch" }}>
          {photos.map((p, i) => (
            <button key={i} type="button" onClick={() => setIdx(i)} aria-label={"Photo " + (i + 1)}
              style={{ flex: "0 0 auto", width: "62px", height: "62px", padding: 0, borderRadius: "8px", overflow: "hidden",
                cursor: "pointer", background: "transparent",
                border: i === idx ? "2px solid var(--mg-honey, #ffc93d)" : "1px solid rgba(255,255,255,0.2)",
                opacity: i === idx ? 1 : 0.65 }}>
              <img src={base + p.thumb} alt="" loading="lazy" style={{ width: "100%", height: "100%", objectFit: "cover", display: "block" }} />
            </button>
          ))}
        </div>
      </div>
    </div>,
    document.body
  );
}

/* Hero entry — thumb-stack chip following the active board. DIY builds only (Tian).
   Accepte board id du hero (RK_BOARDS) ou model key direct. */
// asuka60 → c60 : même hardware, l'EVA60 n'a pas encore de photos DIY (Tian 2026-07-06 — bouton DIY avec les images du Centauri 60)
const MG_BOARD_TO_MODEL = { centauri: "c80", centauri60: "c60", eva: "eva80", asuka60: "c60" };
function HeroModsChip({ board, model, base = MG_COMM_BASE }) {
  const [open, setOpen] = React.useState(false);
  const m = model || MG_BOARD_TO_MODEL[board] || board || "c80";
  const photos = mgCommPhotos(m, ["diy"]);
  if (!photos.length) return null;
  return (
    <React.Fragment>
      <button type="button" onClick={() => setOpen(true)} className="mg-comm-chip"
        aria-label={"Voir les builds de la communauté — " + MG_COMM_META[m]}
        style={{ display: "inline-flex", alignItems: "center", gap: "10px", padding: "9px 16px 9px 10px",
          borderRadius: "999px", cursor: "pointer", background: "rgba(255,255,255,0.05)",
          border: "1px solid var(--mg-slate, rgba(255,255,255,0.2))",
          font: "600 12.5px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.04em",
          color: "var(--mg-dark-fg, #f4f5f7)" }}>
        <span style={{ display: "inline-flex" }}>
          {photos.slice(0, 3).map((p, i) => (
            <img key={i} src={base + p.thumb} alt="" loading="lazy"
              style={{ width: "26px", height: "26px", borderRadius: "50%", objectFit: "cover", display: "block",
                border: "2px solid #14161d", marginLeft: i ? "-9px" : 0 }} />
          ))}
        </span>
        100 % personnalisable · voir les builds customisés →
      </button>
      {open && <CommunityLightbox initialModel={m} sets={["diy"]} onClose={() => setOpen(false)} base={base} />}
    </React.Fragment>
  );
}

/* PDP section — horizontal strip of community photos, opens the lightbox.
   models: 1+ model keys merged in order (eva.html passe ["eva80","eva60"]).
   Titre = dégradé display (même langage que les sections PDP). */
function CommunityStrip({ model = "c80", models = null, title = "Entre les mains de la communauté", titleColor = null, base = MG_COMM_BASE }) {
  const [openAt, setOpenAt] = React.useState(null); // {model, index} | null
  const list = models || [model];
  const photos = list.flatMap(m => mgCommPhotos(m).map((p, i) => ({ ...p, _m: m, _i: i })));
  if (!photos.length) return null;
  const DS = window.MelGeekFrDesignSystem_7cf6d5 || {};
  const Eyebrow = DS.Eyebrow;
  // titleColor (ex. "#fff" sur la page EVA, Tian 2026-07-06) remplace le dégradé par une couleur pleine
  const titleFx = titleColor
    ? { color: titleColor }
    : { background: "var(--mg-kb-grad-text)", WebkitBackgroundClip: "text", backgroundClip: "text",
        WebkitTextFillColor: "transparent", color: "transparent" };
  return (
    // hérite le thème de la page (pages blanches: data-mg-theme remappe --mg-void → blanc; texte = currentColor)
    <section style={{ borderTop: "1px solid var(--mg-slate)" }}>
      <div style={{ maxWidth: "var(--mg-maxw)", margin: "0 auto", padding: "var(--mg-space-7, 64px) var(--mg-gutter, 20px)" }}>
        {Eyebrow ? <Eyebrow>Communauté</Eyebrow> : (
          <p style={{ margin: "0 0 6px", font: "700 11px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.14em",
            textTransform: "uppercase", color: "var(--mg-honey, #ffc93d)" }}>Communauté</p>
        )}
        <div style={{ margin: "var(--mg-space-3, 12px) 0 6px" }}>
          <h2 className={titleColor ? undefined : "mg-grad-text"} style={{ display: "inline-block", margin: 0, fontFamily: "var(--mg-font-display)",
            fontWeight: 700, fontSize: "var(--mg-step-4)", letterSpacing: "var(--mg-track-display)", ...titleFx }}>{title}</h2>
        </div>
        <p style={{ margin: "0 0 18px", font: "400 14px/1.6 inherit", color: "inherit", opacity: 0.68, maxWidth: "60ch" }}>
          Keycaps, molette, badge : tout se change. Builds &amp; setups réels partagés par la communauté MelGeek.
        </p>
        <div style={{ display: "flex", gap: "12px", overflowX: "auto", paddingBottom: "8px", WebkitOverflowScrolling: "touch", scrollSnapType: "x proximity" }}>
          {photos.map((p, i) => (
            <button key={i} type="button" onClick={() => setOpenAt({ model: p._m, index: p._i })} aria-label={"Agrandir la photo " + (i + 1)}
              style={{ flex: "0 0 auto", width: "min(240px, 58vw)", padding: 0, borderRadius: "12px", overflow: "hidden",
                cursor: "zoom-in", background: "var(--mg-surface, #14161d)", border: "1px solid var(--mg-slate)",
                position: "relative", scrollSnapAlign: "start" }}>
              <img src={base + p.thumb} alt={MG_COMM_META[p._m] + " communauté " + (i + 1)} loading="lazy"
                style={{ width: "100%", aspectRatio: "4 / 3", objectFit: "cover", display: "block" }} />
            </button>
          ))}
        </div>
      </div>
      {openAt && <CommunityLightbox initialModel={openAt.model} initialIndex={openAt.index} onClose={() => setOpenAt(null)} base={base} />}
    </section>
  );
}

window.CommunityLightbox = CommunityLightbox;
window.HeroModsChip = HeroModsChip;
window.CommunityStrip = CommunityStrip;
