/* MAKE MEDIA — sections : BestWork, ShowcaseGrid, LatestWork, BTS, Clients, À propos, Contact */
const { useState: useS, useEffect: useE, useRef: useR, useMemo: useM } = React;

/* ---------- Meilleures photos ---------- */
function useBwColumns() {
  const compute = () => {
    if (typeof window === "undefined") return 3;
    const w = window.innerWidth;
    if (w < 640) return 1;
    if (w < 900) return 2;
    return Math.max(3, Math.min(6, Math.round(w / 300)));
  };
  const [cols, setCols] = useS(compute);
  useE(() => {
    const onResize = () => setCols(compute());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return cols;
}

function BestWork() {
  const { BEST_WORK } = window.MM_DATA;
  const [active, setActive] = useS(-1);
  const cur = active >= 0 ? BEST_WORK[active] : null;
  const cols = useBwColumns();

  // Distribution en round-robin (item i -> colonne i % cols) pour que l'ordre du
  // tableau corresponde à l'ordre de lecture rangée par rangée à l'écran.
  const columns = Array.from({ length: cols }, () => []);
  BEST_WORK.forEach((item, idx) => columns[idx % cols].push({ item, idx }));

  useE(() => {
    const onKey = (e) => {
      if (active < 0) return;
      if (e.key === "Escape") setActive(-1);
      if (e.key === "ArrowRight") setActive((i) => (i + 1) % BEST_WORK.length);
      if (e.key === "ArrowLeft") setActive((i) => (i - 1 + BEST_WORK.length) % BEST_WORK.length);
    };
    window.addEventListener("keydown", onKey);
    document.body.style.overflow = active >= 0 ? "hidden" : "";
    return () => window.removeEventListener("keydown", onKey);
  }, [active, BEST_WORK.length]);

  return (
    <section className="section bw" id="travaux" data-screen-label="Meilleures photos">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Sélection</Reveal>
            <Reveal><h2 className="h-section">Notre travail</h2></Reveal>
          </div>
          <Reveal as="p" className="body" delay={120} style={{ maxWidth: "34ch" }}>
            Un aperçu direct : quelques images qui résument le mieux ce qu'on fait sur le terrain.
          </Reveal>
        </div>
      </div>

      <div className="bw-grid">
        {columns.map((colItems, ci) => (
          <div className="bw-col" key={ci}>
            {colItems.map(({ item, idx }) => (
              <Reveal
                as="div" key={item.id} className="bw-item" delay={(idx % 4) * 70}
                onClick={() => setActive(idx)} role="button" tabIndex={0} aria-label={item.cap}
                onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setActive(idx); } }}
              >
                {item.src ?
                  <img src={item.src} alt={item.cap} className="bw-item__img" loading="lazy" style={{ aspectRatio: item.ratio }} /> :
                  <Placeholder label={item.cap} style={{ aspectRatio: item.ratio }} />}
              </Reveal>
            ))}
          </div>
        ))}
      </div>

      <div className={`lightbox lightbox--photo ${active >= 0 ? "open" : ""}`} onClick={(e) => { if (e.target === e.currentTarget) setActive(-1); }}>
        {cur && (
          <React.Fragment>
            <button className="lightbox__close" aria-label="Fermer" onClick={() => setActive(-1)}>✕</button>
            <button className="lightbox__nav prev" aria-label="Précédent" onClick={() => setActive((x) => (x - 1 + BEST_WORK.length) % BEST_WORK.length)}>←</button>
            <button className="lightbox__nav next" aria-label="Suivant" onClick={() => setActive((x) => (x + 1) % BEST_WORK.length)}>→</button>
            <div className="lightbox__inner">
              <div className="lightbox__media">
                {cur.src ?
                  <img src={cur.src} alt={cur.cap} /> :
                  <Placeholder label={cur.cap} dark style={{ aspectRatio: cur.ratio }} />}
              </div>
              <div className="lightbox__bar" style={{ justifyContent: "flex-end" }}>
                <span className="lb-counter">{String(active + 1).padStart(2, "0")} / {String(BEST_WORK.length).padStart(2, "0")}</span>
              </div>
            </div>
          </React.Fragment>
        )}
      </div>
    </section>
  );
}

/* ---------- Grille dynamique expertises ----------
   Adapté de dynamic-frame-layout : survoler une case agrandit toute sa
   ligne ET toute sa colonne (effet "croix"), pas juste la case elle-même. */
const SC_COLS = 4;
const SC_ROWS = 2;
const SC_HOVER_FR = 6;

function scRowCol(idx) {
  return { row: Math.floor(idx / SC_COLS), col: idx % SC_COLS };
}

function scTrackSizes(count, hoveredIndex) {
  if (hoveredIndex === null) return `repeat(${count}, 4fr)`;
  const rest = (count * 4 - SC_HOVER_FR) / (count - 1);
  return Array.from({ length: count }, (_, i) => (i === hoveredIndex ? `${SC_HOVER_FR}fr` : `${rest}fr`)).join(" ");
}

function ShowcaseCell({ item, active, dimmed, onActivate, onDeactivate }) {
  const videoRef = useR(null);

  useE(() => {
    const v = videoRef.current;
    if (!v) return;
    if (active) v.play().catch(() => {}); else v.pause();
  }, [active]);

  const handleActivate = (e) => {
    if (item.id !== "location") { active ? onDeactivate() : onActivate(); return; }
    window.location.href = "location.html";
  };

  return (
    <div
      className={`showcase-cell ${active ? "is-active" : ""} ${dimmed ? "is-dim" : ""}`}
      onMouseEnter={onActivate} onMouseLeave={onDeactivate}
      onClick={handleActivate}
      role="button" tabIndex={0} aria-label={item.id === "location" ? "Aller à la location de matériel" : item.label} aria-pressed={active}
      onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); handleActivate(e); } }}
    >
      <div className="showcase-cell__media">
        {item.video ?
          <video ref={videoRef} src={item.video} muted loop playsInline /> :
          item.image ?
          <img src={item.image} alt="" loading="lazy" /> :
          <Placeholder label="" video dark />}
      </div>
      <span className="showcase-cell__label">{item.label}</span>
    </div>
  );
}

function ShowcaseGrid() {
  const { SHOWCASE } = window.MM_DATA;
  const [hoveredIdx, setHoveredIdx] = useS(null);
  const pos = hoveredIdx !== null ? scRowCol(hoveredIdx) : null;

  return (
    <section className="section showcase" id="expertises" data-screen-label="Expertises">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Nos services</Reveal>
            <Reveal><h2 className="h-section">Nos terrains de jeu</h2></Reveal>
          </div>
        </div>
      </div>

      <Reveal
        as="div" className="showcase-grid"
        style={{
          gridTemplateRows: scTrackSizes(SC_ROWS, pos ? pos.row : null),
          gridTemplateColumns: scTrackSizes(SC_COLS, pos ? pos.col : null),
        }}
      >
        {SHOWCASE.map((s, i) => (
          <ShowcaseCell
            key={s.id} item={s}
            active={hoveredIdx === i} dimmed={hoveredIdx !== null && hoveredIdx !== i}
            onActivate={() => setHoveredIdx(i)} onDeactivate={() => setHoveredIdx(null)}
          />
        ))}
      </Reveal>
    </section>
  );
}

/* ---------- Nos dernières réalisations (façon post Instagram) ---------- */
const IG_ICONS = {
  heart: "M20.84 4.61a5.5 5.5 0 0 0-7.78 0L12 5.67l-1.06-1.06a5.5 5.5 0 1 0-7.78 7.78l1.06 1.06L12 21.23l7.78-7.78 1.06-1.06a5.5 5.5 0 0 0 0-7.78z",
  comment: "M21 11.5a8.38 8.38 0 0 1-.9 3.8 8.5 8.5 0 0 1-7.6 4.7 8.38 8.38 0 0 1-3.8-.9L3 21l1.9-5.7a8.38 8.38 0 0 1-.9-3.8 8.5 8.5 0 0 1 4.7-7.6 8.38 8.38 0 0 1 3.8-.9h.5a8.48 8.48 0 0 1 8 8v.5z",
  share: "M22 2 11 13 M22 2 15 22 11 13 2 9 22 2z",
};

function IgIcon({ name }) {
  return (
    <svg viewBox="0 0 24 24" width="18" height="18" fill="none" stroke="currentColor" strokeWidth="1.8" strokeLinecap="round" strokeLinejoin="round" aria-hidden="true">
      <path d={IG_ICONS[name]} />
    </svg>);

}

function LatestWork() {
  const { INSTAGRAM } = window.MM_DATA;
  return (
    <section className="section latest" data-screen-label="Dernières réalisations">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Portfolio</Reveal>
            <Reveal><h2 className="h-section">Nos dernières réalisations</h2></Reveal>
          </div>
          <Reveal as="a" className="btn btn--ghost" href="https://www.instagram.com/make_media.fr/" target="_blank" rel="noopener">Voir notre Instagram <span className="arr">→</span></Reveal>
        </div>

        <div className="ig-grid">
          {INSTAGRAM.map((item, i) => (
            <Reveal as="a" key={item.id} className="ig-card" delay={(i % 4) * 70} href={item.url} target="_blank" rel="noopener" aria-label="Voir la publication sur Instagram">
              <div className="ig-card__head">
                <span className="ig-avatar" aria-hidden="true"></span>
                <span className="ig-handle">{item.handle}</span>
                <span className="ig-dots" aria-hidden="true">•••</span>
              </div>
              <div className="ig-card__media">
                <img src={item.src} alt="" loading="lazy" />
              </div>
              <div className="ig-card__actions">
                <IgIcon name="heart" /><IgIcon name="comment" /><IgIcon name="share" />
              </div>
            </Reveal>
          ))}
        </div>
      </div>
    </section>);

}

/* ---------- BTS — mood board des coulisses ----------
   Collage libre avec chevauchement réel (comme un vrai moodboard de tirages
   posés/collés), calculé en JS : colonnes en "shortest-first", léger
   décalage horizontal + rotation pseudo-aléatoires par photo. */
function parseRatio(str) {
  const [w, h] = str.split("/").map((n) => parseFloat(n.trim()));
  return w / h;
}

function useIsMobile(breakpoint = 640) {
  const compute = () => typeof window !== "undefined" && window.innerWidth < breakpoint;
  const [isMobile, setIsMobile] = useS(compute);
  useE(() => {
    const onResize = () => setIsMobile(compute());
    window.addEventListener("resize", onResize);
    return () => window.removeEventListener("resize", onResize);
  }, []);
  return isMobile;
}

function useCollageLayout(items, { colWidth = 300, gap = 10, jitter = 30 } = {}) {
  const containerRef = useR(null);
  const [state, setState] = useS({ layout: [], height: 0 });

  useE(() => {
    function compute() {
      const el = containerRef.current;
      const containerWidth = el && el.clientWidth;
      if (!containerWidth) return;
      const cols = Math.max(2, Math.min(5, Math.round(containerWidth / colWidth)));
      const baseWidth = (containerWidth - gap * (cols - 1)) / cols;
      const colHeights = Array(cols).fill(0);

      const layout = items.map((item, i) => {
        let col = 0;
        for (let c = 1; c < cols; c++) if (colHeights[c] < colHeights[col]) col = c;
        const sizeFactor = 0.88 + ((i * 31) % 30) / 100; // 0.88 → 1.17
        const tileWidth = baseWidth * sizeFactor;
        const tileHeight = tileWidth / parseRatio(item.ratio);
        const jx = ((i * 47) % (jitter * 2 + 1)) - jitter;
        const rot = (((i * 53) % 11) - 5) * 0.85;
        const left = col * (baseWidth + gap) + jx;
        const top = colHeights[col];
        colHeights[col] = top + tileHeight + gap - jitter * 0.9;
        return { id: item.id, src: item.src, cap: item.cap, left, top, width: tileWidth, height: tileHeight, rot, z: i };
      });

      setState({ layout, height: Math.max(...colHeights, 0) + jitter });
    }
    compute();
    window.addEventListener("resize", compute);
    return () => window.removeEventListener("resize", compute);
  }, [items]);

  return { containerRef, ...state };
}

const BTS_MOBILE_PREVIEW = 6;

function BTS() {
  const { BTS: BOARD } = window.MM_DATA;
  const isMobile = useIsMobile();
  const [expanded, setExpanded] = useS(false);

  const visible = useM(
    () => (isMobile && !expanded ? BOARD.slice(0, BTS_MOBILE_PREVIEW) : BOARD),
    [isMobile, expanded, BOARD]
  );
  const { containerRef, layout, height } = useCollageLayout(visible);

  return (
    <section className="section bts section--paper" id="bts" data-screen-label="Coulisses">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Coulisses</Reveal>
            <Reveal><h2 className="h-section">Behind the scenes</h2></Reveal>
          </div>
        </div>
      </div>

      <div className="board" ref={containerRef} style={{ height }}>
        {layout.map((t) => (
          <div
            key={t.id} className="board-item"
            style={{ left: t.left, top: t.top, width: t.width, height: t.height, "--rot": `${t.rot}deg`, "--z": t.z }}
          >
            <img src={t.src} alt={t.cap} loading="lazy" />
          </div>
        ))}
      </div>

      {isMobile && !expanded && (
        <div className="board-more">
          <button className="btn btn--ghost" onClick={() => setExpanded(true)}>
            Voir plus de photos <span className="arr">↓</span>
          </button>
        </div>
      )}
    </section>);

}

/* ---------- Clients ---------- */
function Clients() {
  const { CLIENTS } = window.MM_DATA;
  const loop = [...CLIENTS, ...CLIENTS];
  return (
    <section className="section" id="clients" data-screen-label="Clients">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Confiance</Reveal>
            <Reveal><h2 className="h-section"><DecryptedText text="Ils nous ont fait confiance" animateOn="view" sequential speed={28} className="dtxt__revealed" encryptedClassName="dtxt__encrypted" /></h2></Reveal>
          </div>
        </div>
      </div>

      <div className="marquee">
        <div className="marquee__track">
          {loop.map((c, i) =>
          <div className="logo-cell" key={i}><img className="logo-img" src={c} alt="" loading="lazy" aria-hidden={i >= CLIENTS.length} /></div>
          )}
        </div>
      </div>
    </section>);

}

/* ---------- À propos de l'entreprise ---------- */
function About() {
  return (
    <section className="section section--soft" id="apropos" data-screen-label="À propos">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Make Media</Reveal>
            <Reveal><h2 className="h-section"><DecryptedText text="À propos de l'entreprise" animateOn="view" sequential speed={22} className="dtxt__revealed" encryptedClassName="dtxt__encrypted" /></h2></Reveal>
          </div>
          <Reveal as="p" className="lede" delay={120} style={{ maxWidth: "40ch" }}>
            Make Media est l'agence de communication digital et de création de contenu du groupe Make Alpes Invest, un groupe grenoblois qui réunit plusieurs activités complémentaires.
          </Reveal>
        </div>

        <div className="about-grid">
        <Reveal as="figure" className="about-portrait">
          <img src="assets/equipe/charlie-hubert-rousseau.jpg" alt="Charlie Hubert Rousseau" loading="lazy" />
          <figcaption><b>Charlie Hubert Rousseau</b><span>Président</span></figcaption>
        </Reveal>
        <div>
        <Reveal as="div" style={{ maxWidth: "62ch" }}>
          <p className="body" style={{ marginBottom: "1.4em" }}>
            Gérée par Charlie Hubert, Make Media est composée d'une équipe jeune, passionnée et créative,
            animée par une volonté commune : évoluer constamment et toujours aller plus loin.
          </p>
          <p className="body" style={{ marginBottom: "1.4em" }}>
            Make Media accompagne les entreprises, marques, établissements et événements dans leur communication digitale.
            Réseaux sociaux, stratégie, création de contenu, photo, vidéo ou encore création graphique : nous construisons
            des univers cohérents et adaptés à chaque projet.
          </p>
          <p className="body">
            L'agence fait également partie du groupe Make Alpes Invest, qui rassemble plusieurs activités complémentaires
            et nous permet de bénéficier d'un environnement tourné vers l'entrepreneuriat, l'événementiel et la création.
          </p>
        </Reveal>

        <Reveal as="div" className="svc-deliv" delay={140} style={{ marginTop: "clamp(32px,5vh,56px)" }}>
          <div className="k">Ce qui nous définit</div>
          <div className="svc-deliv__tags">
            <span>Passion</span>
            <span>Créativité</span>
            <span>Culture digitale</span>
            <span>Groupe Make Alpes Invest</span>
          </div>
        </Reveal>
        </div>
        </div>
      </div>
    </section>);

}

/* ---------- Contact ---------- */

function Contact() {
  return (
    <section className="section" id="contact" data-screen-label="Contact">
      <div className="wrap">
        <div className="section__head">
          <div>
            <Reveal as="div" className="eyebrow">Parlons-en</Reveal>
            <Reveal><h2 className="h-section"><DecryptedText text="Contact" animateOn="view" sequential speed={28} className="dtxt__revealed" encryptedClassName="dtxt__encrypted" /></h2></Reveal>
          </div>
          <Reveal as="p" className="lede" delay={120} style={{ maxWidth: "34ch" }}>
            Un projet, une intuition, un brief à dégrossir ? Écrivez-nous.
          </Reveal>
        </div>

        <div className="contact-simple">
          <Reveal as="div" className="info-block">
            <div className="eyebrow">Email</div>
            <a href="mailto:contact@makemediafrance.com" className="contact-simple__big ulink">contact@makemediafrance.com</a>
          </Reveal>
          <Reveal as="div" className="info-block" delay={90}>
            <div className="eyebrow">Téléphone</div>
            <a href="tel:+33974650734" className="contact-simple__big ulink">09 74 65 07 34</a>
          </Reveal>
          <Reveal as="div" className="info-block" delay={150}>
            <div className="eyebrow">Suivre</div>
            <div className="socials">
              <a href={window.MM_DATA.SOCIALS.instagram} target="_blank" rel="noopener" className="ulink">Instagram</a>
              {window.MM_DATA.SOCIALS.linkedin && <a href={window.MM_DATA.SOCIALS.linkedin} target="_blank" rel="noopener" className="ulink">LinkedIn</a>}
            </div>
          </Reveal>
          <Reveal as="div" delay={210}>
            <a href="mailto:contact@makemediafrance.com" className="btn">Nous contacter <span className="arr">→</span></a>
          </Reveal>
        </div>
      </div>
    </section>);

}

Object.assign(window, { BestWork, ShowcaseGrid, LatestWork, BTS, Clients, About, Contact });