/* SocialProof — 3 modules portés de melgeek.com (Tian 2026-07-07) :
   · TechReviews    — section « Tech Review » (vidéos créateurs YouTube, vignettes auto-hébergées, clic → YouTube nouvel onglet)
   · ReviewsSection — avis clients vérifiés Loox, layout desktop SYNCHRONISÉ sur melgeek.com (Tian 2026-07-07) :
                      en-tête centré (note + distribution) + grille masonry de cartes photo compactes + clic → fiche détail.
                      Mobile : 2 colonnes compactes, fiche plein écran.
   · BoxVisual      — visuel officiel « Dans la boîte »
   Data: window.MG_REVIEWS + window.MG_TECH_VIDEOS (assets/data/reviews-manifest.js)
   Overlay pur : nouvelles <section> autonomes, aucune modification des sections existantes. */

const MG_SOCIAL_BASE = "../../assets/img/social/";
const MG_REV_IMG_BASE = "../../assets/img/social/reviews/";

/* masonry + clamp — injecté une fois (media queries impossibles en style inline) */
(function () {
  if (document.getElementById("mg-rev-style")) return;
  const st = document.createElement("style");
  st.id = "mg-rev-style";
  st.textContent = `
    .mg-rev-masonry { column-count: 2; column-gap: 12px; }
    @media (min-width: 720px)  { .mg-rev-masonry { column-count: 3; } }
    @media (min-width: 1000px) { .mg-rev-masonry { column-count: 4; } }
    @media (min-width: 1240px) { .mg-rev-masonry { column-count: 5; } }
    .mg-rev-card { break-inside: avoid; -webkit-column-break-inside: avoid; page-break-inside: avoid; margin: 0 0 12px; }
    .mg-rev-clamp { display: -webkit-box; -webkit-line-clamp: 5; -webkit-box-orient: vertical; overflow: hidden; }
    .mg-rev-card:hover { border-color: var(--mg-kb-accent, #39d7f7) !important; }
    /* fiche : colonne (photo bandeau haut) en mobile → rangée photo|texte dès 860px.
       height explicite + overflow hidden : height:100% d'une <img> dans un conteneur max-height se résout en taille
       intrinsèque → l'image débordait sur le texte (bug mobile 2026-07-07). */
    @media (min-width: 860px) {
      .mg-rev-modal-body { flex-direction: row !important; }
      .mg-rev-modal-img { height: auto !important; max-width: 52%; flex: 1 1 52% !important; min-height: 340px; }
    }
  `;
  document.head.appendChild(st);
})();

function MgStars({ n, size }) {
  return (
    <span aria-label={n + " étoiles sur 5"} style={{ color: "var(--mg-honey, #ffc93d)", fontSize: size || "1em", letterSpacing: "0.08em", whiteSpace: "nowrap" }}>
      {"★".repeat(n)}
      <span style={{ opacity: 0.28 }}>{"★".repeat(5 - n)}</span>
    </span>
  );
}

/* ── Ancre de note dans la BuyBox (Tian 2026-07-07) : ★ 4,9 · N avis, clic → scroll vers #avis en bas de page
   (même pattern que la ligne d'étoiles Loox sous le titre produit sur melgeek.com). Passé via BuyBox ratingSlot. ── */
function RatingAnchor({ product = "centauri", target = "avis" }) {
  const data = (window.MG_REVIEWS || {})[product];
  if (!data) return null;
  const go = (e) => {
    e.preventDefault();
    const el = document.getElementById(target);
    if (el) el.scrollIntoView({ behavior: "smooth", block: "start" });
  };
  return (
    <a href={"#" + target} onClick={go}
      aria-label={"Voir les " + data.count + " avis clients — note " + data.avg + " sur 5"}
      title="Voir les avis clients"
      style={{ display: "inline-flex", alignItems: "center", gap: "8px", textDecoration: "none", color: "inherit", width: "fit-content", cursor: "pointer" }}>
      <MgStars n={5} size="13px" />
      <span style={{ font: "600 12.5px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.04em", color: "var(--mg-ink-500, var(--mg-fg-muted))" }}>
        <b style={{ color: "var(--mg-ink-900, var(--mg-fg))" }}>{data.avg}</b> · {data.count} avis <span aria-hidden="true" style={{ color: "var(--mg-kb-accent, #0a9dbf)" }}>↓</span>
      </span>
    </a>
  );
}

/* ── Tech Review — vidéos créateurs ── */
function TechReviews({ product = "centauri" }) {
  const vids = (window.MG_TECH_VIDEOS || {})[product] || [];
  if (!vids.length) return null;
  const DS = window.MelGeekFrDesignSystem_7cf6d5 || {};
  const Eyebrow = DS.Eyebrow;
  return (
    <section id="tech-review" style={{ background: "var(--mg-void)", color: "var(--mg-dark-fg)", borderTop: "1px solid var(--mg-slate)" }}>
      <div style={{ maxWidth: "var(--mg-maxw)", margin: "0 auto", padding: "var(--mg-space-8) var(--mg-gutter)" }}>
        {Eyebrow ? <Eyebrow bracket style={{ color: "var(--mg-dark-fg-muted)" }}>Tech Review</Eyebrow> : null}
        <h2 className="mg-grad-text" style={{ margin: "var(--mg-space-4) 0 0", fontFamily: "var(--mg-font-display)", fontWeight: 700, fontSize: "var(--mg-step-4)", letterSpacing: "var(--mg-track-display)" }}>
          Testé par les créateurs
        </h2>
        <p style={{ margin: "10px 0 22px", font: "400 14px/1.6 inherit", color: "var(--mg-dark-fg-muted)", maxWidth: "62ch" }}>
          Les mêmes vidéos que met en avant MelGeek : tests indépendants et parties jouées au clavier. Le clic ouvre YouTube dans un nouvel onglet.
        </p>
        <div style={{ display: "grid", gridTemplateColumns: "repeat(auto-fit, minmax(min(250px, 100%), 1fr))", gap: "16px" }}>
          {vids.map((v) => (
            <a key={v.id} href={"https://www.youtube.com/watch?v=" + v.id} target="_blank" rel="noopener noreferrer"
              aria-label={"Regarder sur YouTube : " + v.title + " — " + v.channel}
              style={{ textDecoration: "none", color: "inherit", display: "block" }}>
              <span style={{ position: "relative", display: "block", borderRadius: "12px", overflow: "hidden", border: "1px solid var(--mg-slate)", background: "#000" }}>
                <img src={MG_SOCIAL_BASE + v.thumb} alt={"Vidéo YouTube : " + v.title} loading="lazy"
                  style={{ width: "100%", aspectRatio: "16 / 9", objectFit: "cover", display: "block" }} />
                <span aria-hidden="true" style={{ position: "absolute", inset: 0, display: "flex", alignItems: "center", justifyContent: "center" }}>
                  <span style={{ width: "52px", height: "52px", borderRadius: "50%", background: "rgba(8,9,12,0.72)", border: "1px solid rgba(255,255,255,0.35)",
                    display: "flex", alignItems: "center", justifyContent: "center", backdropFilter: "blur(4px)" }}>
                    <span style={{ display: "block", width: 0, height: 0, borderStyle: "solid", borderWidth: "9px 0 9px 15px",
                      borderColor: "transparent transparent transparent #fff", marginLeft: "4px" }} />
                  </span>
                </span>
                {v.fr ? (
                  <span style={{ position: "absolute", top: "10px", left: "10px", font: "700 10px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.08em",
                    padding: "5px 8px", borderRadius: "999px", background: "rgba(8,9,12,0.75)", color: "#fff", border: "1px solid rgba(255,255,255,0.3)" }}>FR</span>
                ) : null}
              </span>
              <span style={{ display: "block", marginTop: "10px", font: "700 12px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.07em", textTransform: "uppercase", color: "var(--mg-kb-accent, #39d7f7)" }}>
                {v.channel} <span aria-hidden="true">↗</span>
              </span>
              <span style={{ display: "-webkit-box", WebkitLineClamp: 2, WebkitBoxOrient: "vertical", overflow: "hidden",
                marginTop: "6px", font: "500 13.5px/1.45 inherit", color: "var(--mg-dark-fg-muted)" }}>
                {v.title}
              </span>
            </a>
          ))}
        </div>
      </div>
    </section>
  );
}

/* ── Fiche détail d'un avis (modal, portal → body : ancêtres transform piègent position:fixed) ── */
function ReviewLightbox({ data, index, onClose }) {
  const [idx, setIdx] = React.useState(index);
  const items = data.items;
  const r = items[Math.min(idx, items.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, items.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); };
  }, [items.length, onClose]);
  if (!r) return null;
  /* flèches dans le pied de fiche (les flèches latérales absolues chevauchaient le texte) */
  const navBtn = (disabled) => ({
    width: "34px", height: "34px", borderRadius: "50%", border: "1px solid var(--mg-border, #ddd)",
    background: "transparent", color: disabled ? "var(--mg-ink-300, #ccc)" : "var(--mg-ink-700, #333)",
    fontSize: "15px", cursor: disabled ? "default" : "pointer", flex: "0 0 auto",
  });
  return ReactDOM.createPortal(
    <div role="dialog" aria-modal="true" aria-label={"Avis de " + r.author} onClick={onClose}
      style={{ position: "fixed", inset: 0, zIndex: 9999, background: "rgba(5,6,10,0.9)", backdropFilter: "blur(10px)",
        display: "flex", alignItems: "center", justifyContent: "center", padding: "clamp(8px, 2.5vw, 32px)" }}>
      <div onClick={(e) => e.stopPropagation()} className="mg-rev-modal-body"
        style={{ position: "relative", display: "flex", flexDirection: "column", width: "min(960px, 100%)", maxHeight: "92vh",
          borderRadius: "16px", overflow: "hidden", background: "var(--mg-paper, #fff)", color: "var(--mg-ink-700, #222)",
          boxShadow: "0 24px 80px rgba(0,0,0,0.55)" }}>
        {r.img ? (
          <div className="mg-rev-modal-img" style={{ background: "#0b0c10", overflow: "hidden", height: "clamp(200px, 38vh, 420px)", flex: "0 0 auto" }}>
            <img src={MG_REV_IMG_BASE + r.img} alt={"Photo client — avis de " + r.author}
              style={{ width: "100%", height: "100%", objectFit: "contain", display: "block" }} />
          </div>
        ) : null}
        <div style={{ padding: "clamp(18px, 3vw, 28px)", overflowY: "auto", flex: 1, minWidth: 0, background: "var(--mg-paper, #fff)", position: "relative" }}>
          <div style={{ display: "flex", flexWrap: "wrap", alignItems: "center", gap: "8px 12px" }}>
            <b style={{ fontFamily: "var(--mg-font-display)", fontSize: "var(--mg-step-1)", color: "var(--mg-ink-900, #111)" }}>{r.author}</b>
            <span style={{ display: "inline-flex", alignItems: "center", gap: "4px", padding: "4px 9px", borderRadius: "999px",
              border: "1px solid var(--mg-border, #ddd)", font: "600 11px/1 var(--mg-font-mono, monospace)", color: "var(--mg-ink-700, #333)" }}>
              <span style={{ color: "var(--mg-kb-accent, #0a9dbf)" }}>✓</span> Achat vérifié
            </span>
            <span style={{ font: "500 12px/1 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, #999)" }}>{r.date}</span>
          </div>
          <div style={{ margin: "10px 0 12px" }}><MgStars n={r.stars} size="15px" /></div>
          <p style={{ margin: 0, font: "400 15px/1.7 inherit", color: "var(--mg-ink-700, #222)" }}>
            « {r.fr} »{r.excerpt ? <span style={{ color: "var(--mg-ink-400, #999)", fontSize: "12px" }}> (extrait)</span> : null}
          </p>
          {r.azerty ? (
            <p style={{ margin: "10px 0 0", font: "600 12.5px/1.5 var(--mg-font-mono, monospace)", color: "var(--mg-kb-accent, #0a9dbf)" }}>
              → C'est exactement notre mission : la version AZERTY arrive avec MelGeek France.
            </p>
          ) : null}
          {r.lang === "fr" ? (
            <p style={{ margin: "14px 0 0", font: "500 11.5px/1.5 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, #999)" }}>
              Avis rédigé en français (original).
            </p>
          ) : (
            <details style={{ marginTop: "14px" }}>
              <summary style={{ cursor: "pointer", font: "600 11.5px/1.5 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, #999)" }}>
                Texte original (anglais)
              </summary>
              <p style={{ margin: "8px 0 0", font: "400 12.5px/1.6 inherit", color: "var(--mg-ink-500, #777)" }}>{r.orig}</p>
            </details>
          )}
          <div style={{ display: "flex", flexWrap: "wrap", gap: "8px 18px", alignItems: "center", justifyContent: "space-between", marginTop: "18px", paddingTop: "14px", borderTop: "1px solid var(--mg-border, #eee)" }}>
            <span style={{ display: "inline-flex", alignItems: "center", gap: "10px" }}>
              <button type="button" aria-label="Avis précédent" disabled={idx === 0}
                onClick={() => setIdx(i => Math.max(i - 1, 0))} style={navBtn(idx === 0)}>←</button>
              <button type="button" aria-label="Avis suivant" disabled={idx >= items.length - 1}
                onClick={() => setIdx(i => Math.min(i + 1, items.length - 1))} style={navBtn(idx >= items.length - 1)}>→</button>
              <span style={{ font: "500 11px/1.4 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, #999)" }}>
                Avis {idx + 1}/{items.length} · collecté via Loox sur melgeek.com
              </span>
            </span>
            <a href={data.url} target="_blank" rel="noopener noreferrer"
              style={{ font: "700 12px/1 var(--mg-font-mono, monospace)", color: "var(--mg-kb-accent, #0a9dbf)", textDecoration: "none" }}>
              Voir sur melgeek.com ↗
            </a>
          </div>
        </div>
        <button type="button" aria-label="Fermer" onClick={onClose}
          style={{ position: "absolute", top: "10px", right: "10px", width: "36px", height: "36px", borderRadius: "50%",
            border: "1px solid rgba(255,255,255,0.3)", background: "rgba(10,11,16,0.6)", color: "#fff", fontSize: "15px", cursor: "pointer", zIndex: 2 }}>✕</button>
      </div>
    </div>,
    document.body
  );
}

/* ── Avis clients vérifiés — layout Loox/melgeek.com : en-tête centré + distribution + masonry photo, clic → fiche ── */
function ReviewsSection({ product = "centauri", productLabel = "" }) {
  const data = (window.MG_REVIEWS || {})[product];
  const [openAt, setOpenAt] = React.useState(null);
  if (!data || !data.items || !data.items.length) return null;
  const DS = window.MelGeekFrDesignSystem_7cf6d5 || {};
  const Eyebrow = DS.Eyebrow;
  const dist = data.dist || {};
  return (
    <section id="avis" style={{ background: "var(--mg-paper)", borderTop: "1px solid var(--mg-border)" }}>
      <div style={{ maxWidth: "var(--mg-maxw)", margin: "0 auto", padding: "var(--mg-space-8) var(--mg-gutter)" }}>
        {/* En-tête centré, même construction que le widget Loox de melgeek.com */}
        <div style={{ textAlign: "center", marginBottom: "8px" }}>
          {Eyebrow ? <Eyebrow>Avis vérifiés{productLabel ? " — " + productLabel : ""}</Eyebrow> : null}
        </div>
        <div style={{ display: "flex", flexWrap: "wrap", gap: "18px 46px", alignItems: "center", justifyContent: "center", marginBottom: "8px" }}>
          <div style={{ textAlign: "center" }}>
            <div style={{ display: "flex", alignItems: "center", gap: "10px", justifyContent: "center" }}>
              <span style={{ fontFamily: "var(--mg-font-display)", fontWeight: 700, fontSize: "var(--mg-step-6)", lineHeight: 1, color: "var(--mg-ink-900, var(--mg-fg))" }}>{data.avg}</span>
              <MgStars n={5} size="17px" />
            </div>
            <p style={{ margin: "8px 0 0", font: "600 12.5px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.05em", color: "var(--mg-ink-500, var(--mg-fg-muted))" }}>
              sur 5 · {data.count} avis
            </p>
          </div>
          {data.dist ? (
            <div role="img" aria-label="Répartition des notes" style={{ width: "min(300px, 100%)" }}>
              {[5, 4, 3, 2, 1].map((s) => (
                <div key={s} style={{ display: "flex", alignItems: "center", gap: "8px", margin: "3px 0", opacity: (dist[s] || 0) ? 1 : 0.4 }}>
                  <span style={{ font: "600 11px/1 var(--mg-font-mono, monospace)", color: "var(--mg-ink-500, var(--mg-fg-muted))", width: "22px", textAlign: "right" }}>{s} ★</span>
                  <span style={{ flex: 1, height: "8px", borderRadius: "999px", background: "var(--mg-border, rgba(0,0,0,0.08))", overflow: "hidden" }}>
                    <span style={{ display: "block", height: "100%", width: ((dist[s] || 0) / data.count * 100) + "%", background: "var(--mg-honey, #ffc93d)" }} />
                  </span>
                  <span style={{ font: "500 11px/1 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, var(--mg-fg-muted))", width: "30px" }}>{dist[s] || 0}</span>
                </div>
              ))}
            </div>
          ) : null}
        </div>
        <p style={{ textAlign: "center", margin: "0 0 26px" }}>
          <a href={data.url} target="_blank" rel="noopener noreferrer"
            style={{ font: "700 12.5px/1 var(--mg-font-mono, monospace)", letterSpacing: "0.05em", color: "var(--mg-kb-accent, #0a9dbf)", textDecoration: "none" }}>
            Voir les {data.count} avis sur melgeek.com ↗
          </a>
        </p>

        {/* Grille masonry compacte (photos d'abord) — clic = fiche détail */}
        <div className="mg-rev-masonry">
          {data.items.map((r, i) => (
            <button key={r.id} type="button" onClick={() => setOpenAt(i)} aria-label={"Lire l'avis de " + r.author}
              className="mg-rev-card"
              style={{ display: "block", width: "100%", padding: 0, textAlign: "left", cursor: "pointer",
                borderRadius: "12px", overflow: "hidden", border: "1px solid var(--mg-border)", background: "var(--mg-paper, #fff)", color: "inherit" }}>
              {r.img ? (
                <img src={MG_REV_IMG_BASE + r.img} alt={"Photo client de " + r.author} loading="lazy"
                  style={{ width: "100%", height: "auto", display: "block", background: "#0b0c10" }} />
              ) : null}
              <span style={{ display: "block", padding: "12px 13px 14px" }}>
                <span style={{ display: "flex", alignItems: "center", gap: "6px", marginBottom: "4px" }}>
                  <b style={{ font: "700 12.5px/1.3 var(--mg-font-mono, monospace)", color: "var(--mg-ink-900, var(--mg-fg))",
                    overflow: "hidden", textOverflow: "ellipsis", whiteSpace: "nowrap" }}>{r.author}</b>
                  <span title="Achat vérifié" aria-label="Achat vérifié" style={{ color: "var(--mg-kb-accent, #0a9dbf)", fontSize: "11px", flex: "0 0 auto" }}>✓</span>
                </span>
                <span style={{ display: "block", font: "500 10.5px/1 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, var(--mg-fg-muted))", marginBottom: "6px" }}>{r.date}</span>
                <MgStars n={r.stars} size="11px" />
                <span className="mg-rev-clamp" style={{ margin: "7px 0 0", font: "400 12.5px/1.55 inherit", color: "var(--mg-ink-700, var(--mg-fg))" }}>
                  {r.fr}
                </span>
              </span>
            </button>
          ))}
        </div>

        <p style={{ margin: "18px auto 0", maxWidth: "86ch", textAlign: "center", font: "400 11px/1.55 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, var(--mg-fg-muted))" }}>
          Avis collectés via Loox auprès d'acheteurs vérifiés sur melgeek.com, la boutique internationale MelGeek (mêmes claviers, layout US).
          Traduits de l'anglais sauf mention ; texte original dans la fiche. Note et total constatés le {(window.MG_REVIEWS || {}).updated || "7 juillet 2026"}.
        </p>
      </div>
      {openAt != null && <ReviewLightbox data={data} index={openAt} onClose={() => setOpenAt(null)} />}
    </section>
  );
}

/* ── Visuel officiel « Dans la boîte » — s'insère DANS la section existante, au-dessus de la liste ── */
function BoxVisual({ src, alt, caption }) {
  return (
    <figure style={{ margin: "var(--mg-space-4) 0 0" }}>
      <img src={MG_SOCIAL_BASE + src} alt={alt} loading="lazy"
        style={{ width: "100%", height: "auto", display: "block", borderRadius: "14px", border: "1px solid var(--mg-border)", background: "#08090c" }} />
      {caption ? (
        <figcaption style={{ margin: "8px 0 0", font: "500 11.5px/1.5 var(--mg-font-mono, monospace)", color: "var(--mg-ink-400, var(--mg-fg-muted))" }}>
          {caption}
        </figcaption>
      ) : null}
    </figure>
  );
}

window.TechReviews = TechReviews;
window.ReviewsSection = ReviewsSection;
window.ReviewLightbox = ReviewLightbox;
window.BoxVisual = BoxVisual;
window.MgStars = MgStars;
window.RatingAnchor = RatingAnchor;
