/*
 * Shared portfolio gallery — a clean, reliable responsive grid with tap-to-enlarge
 * lightbox. Replaces the old auto-scrolling marquees (which glitched on mobile
 * because cell widths weren't known until images loaded, breaking the loop).
 * Used by portraits, maternity, and headshots/branding pages (Boise + Las Vegas).
 */
function PortfolioGrid({ images, subhead, label, galleryAria }) {
  const GOLD = "#C9A84C";
  const INK = "#1A1A1A";
  const WHITE = "#FFFFFF";
  const BEIGE = "#F6F2EE";
  const GREY = "#5a5550";

  const [lb, setLb] = React.useState(null);

  const closeLb = () => setLb(null);
  const prev = () => setLb((n) => (n === null ? n : (n - 1 + images.length) % images.length));
  const next = () => setLb((n) => (n === null ? n : (n + 1) % images.length));

  React.useEffect(() => {
    if (lb === null) return;
    document.body.style.overflow = "hidden";
    const onKey = (e) => {
      if (e.key === "Escape") closeLb();
      else if (e.key === "ArrowLeft") prev();
      else if (e.key === "ArrowRight") next();
    };
    window.addEventListener("keydown", onKey);
    return () => {
      window.removeEventListener("keydown", onKey);
      document.body.style.overflow = "";
    };
  }, [lb]);

  const cellStyle = {
    border: `1px solid ${GOLD}`, overflow: "hidden", background: INK, cursor: "pointer",
    aspectRatio: "2 / 3",
  };

  return (
    <section data-screen-label={label} className="pg-section" style={{
      background: BEIGE, padding: "120px 0 130px",
      borderTop: `1px solid rgba(201,168,76,0.25)`, borderBottom: `1px solid rgba(201,168,76,0.25)`,
    }}
      itemScope itemType="https://schema.org/ImageGallery"
    >
      <style>{`
        .pg-grid { grid-template-columns: repeat(4, 1fr); gap: 18px; }
        @media (max-width: 900px) {
          .pg-grid { grid-template-columns: repeat(3, 1fr) !important; gap: 14px !important; }
        }
        @media (max-width: 640px) {
          .pg-section { padding: 80px 0 88px !important; }
          .pg-grid { grid-template-columns: repeat(2, 1fr) !important; gap: 10px !important; padding: 0 16px !important; }
        }
      `}</style>

      <div style={{ maxWidth: 1280, margin: "0 auto 64px", padding: "0 48px", textAlign: "center" }}>
        <div style={{ display: "inline-flex", alignItems: "center", gap: 16, marginBottom: 28 }}>
          <span style={{ width: 36, height: 1, background: GOLD, display: "inline-block" }} />
          <span style={{
            fontFamily: "Poppins, sans-serif", fontWeight: 300, fontSize: 11,
            letterSpacing: "0.32em", textTransform: "uppercase", color: GOLD,
          }}>The Work</span>
          <span style={{ width: 36, height: 1, background: GOLD, display: "inline-block" }} />
        </div>
        <h2 style={{
          fontFamily: "Gloock, serif", fontWeight: 400, color: INK,
          fontSize: "clamp(34px, 4.8vw, 60px)", lineHeight: 1.08,
          letterSpacing: "-0.005em", margin: "0 0 18px 0", textWrap: "balance",
        }}>
          A look at the studio's <em style={{ fontStyle: "italic", color: GOLD }}>portfolio</em>.
        </h2>
        <p style={{
          fontFamily: "Gloock, serif", fontStyle: "italic",
          fontSize: 16, color: GREY, margin: 0,
        }}>
          {subhead}
        </p>
      </div>

      <div className="pg-grid" aria-label={galleryAria} style={{
        maxWidth: 1320, margin: "0 auto", padding: "0 48px", display: "grid",
      }}>
        {images.map((img, i) => (
          <div key={i} style={cellStyle}
            onClick={() => setLb(i)}
            onKeyDown={(e) => { if (e.key === "Enter" || e.key === " ") { e.preventDefault(); setLb(i); } }}
            role="button" tabIndex={0} aria-label={`Enlarge: ${img.alt}`}
            itemProp="associatedMedia" itemScope itemType="https://schema.org/ImageObject"
          >
            <img
              itemProp="contentUrl"
              src={img.src}
              alt={img.alt}
              loading={i < 4 ? "eager" : "lazy"}
              onError={(e) => {
                const el = e.currentTarget;
                if (!el.dataset.retried) {
                  el.dataset.retried = "1";
                  el.src = img.src + (img.src.includes("?") ? "&" : "?") + "r=" + Date.now();
                  return;
                }
                el.style.display = "none";
              }}
              style={{ display: "block", width: "100%", height: "100%", objectFit: "cover", objectPosition: "center" }}
            />
          </div>
        ))}
      </div>

      {lb !== null && (
        <div onClick={closeLb} role="dialog" aria-modal="true" aria-label="Portfolio image viewer" style={{
          position: "fixed", inset: 0, zIndex: 200, background: "rgba(10,9,7,0.94)",
          display: "flex", alignItems: "center", justifyContent: "center", padding: 40,
        }}>
          <button onClick={closeLb} aria-label="Close" style={{
            position: "absolute", top: 22, right: 26, background: "transparent", border: "none",
            color: WHITE, fontSize: 34, lineHeight: 1, cursor: "pointer", opacity: 0.85,
          }}>×</button>
          <button onClick={(e) => { e.stopPropagation(); prev(); }} aria-label="Previous image" style={{
            position: "absolute", left: 16, top: "50%", transform: "translateY(-50%)",
            background: "transparent", border: "none", color: WHITE, fontSize: 48,
            lineHeight: 1, cursor: "pointer", opacity: 0.85, padding: 12,
          }}>‹</button>
          <img src={images[lb].src} alt={images[lb].alt} onClick={(e) => e.stopPropagation()} style={{
            maxWidth: "90vw", maxHeight: "84vh", objectFit: "contain", boxShadow: "0 24px 70px rgba(0,0,0,0.55)",
          }}/>
          <button onClick={(e) => { e.stopPropagation(); next(); }} aria-label="Next image" style={{
            position: "absolute", right: 16, top: "50%", transform: "translateY(-50%)",
            background: "transparent", border: "none", color: WHITE, fontSize: 48,
            lineHeight: 1, cursor: "pointer", opacity: 0.85, padding: 12,
          }}>›</button>
          <div style={{
            position: "absolute", bottom: 24, left: "50%", transform: "translateX(-50%)",
            fontFamily: "Poppins, sans-serif", fontWeight: 300, fontSize: 11,
            letterSpacing: "0.3em", textTransform: "uppercase", color: "rgba(255,255,255,0.7)",
          }}>{lb + 1} / {images.length}</div>
        </div>
      )}
    </section>
  );
}

Object.assign(window, { PortfolioGrid });
