// PhotoGallery — masonry grid + fullscreen lightbox for photo clients

// Extract a clean label from a photo file path
const photoLabel = (src) => {
  const filename = decodeURIComponent(src.split("/").pop()).replace(/\.[^.]+$/, "");
  return filename
    .replace(/ - MATEO ROMERO STUDIO/gi, "")
    .replace(/\s*\(\d+\)\s*$/, "")
    .trim();
};

const PhotoGallery = ({ open, client, onClose }) => {
  const [lightbox, setLightbox] = React.useState(null);
  const [zoom, setZoom] = React.useState(1);
  const [pan, setPan] = React.useState({ x: 0, y: 0 });
  const dragRef = React.useRef(null);
  const imgRef = React.useRef(null);

  // Reset zoom when photo changes
  React.useEffect(() => { setZoom(1); setPan({ x: 0, y: 0 }); }, [lightbox]);

  // Keyboard navigation
  React.useEffect(() => {
    if (!open) { setLightbox(null); return; }
    const onKey = (e) => {
      if (e.key === "Escape") {
        if (zoom > 1) { setZoom(1); setPan({ x: 0, y: 0 }); return; }
        if (lightbox !== null) { setLightbox(null); return; }
        onClose();
      }
      if (lightbox === null) return;
      if (e.key === "ArrowRight" && zoom === 1) setLightbox(i => Math.min(i + 1, client.photos.length - 1));
      if (e.key === "ArrowLeft"  && zoom === 1) setLightbox(i => Math.max(i - 1, 0));
    };
    window.addEventListener("keydown", onKey);
    return () => window.removeEventListener("keydown", onKey);
  }, [open, lightbox, zoom, client]);

  // Scroll-wheel zoom
  const onWheel = (e) => {
    e.preventDefault();
    e.stopPropagation();
    setZoom(z => {
      const next = Math.min(4, Math.max(1, z - e.deltaY * 0.002));
      if (next === 1) setPan({ x: 0, y: 0 });
      return next;
    });
  };

  // Double-click to toggle zoom
  const onDblClick = (e) => {
    e.stopPropagation();
    setZoom(z => {
      if (z > 1) { setPan({ x: 0, y: 0 }); return 1; }
      return 2.5;
    });
  };

  // Drag to pan when zoomed
  const onMouseDown = (e) => {
    if (zoom <= 1) return;
    e.preventDefault();
    const startX = e.clientX - pan.x;
    const startY = e.clientY - pan.y;
    dragRef.current = { startX, startY };
    const onMove = (ev) => {
      if (!dragRef.current) return;
      setPan({ x: ev.clientX - dragRef.current.startX, y: ev.clientY - dragRef.current.startY });
    };
    const onUp = () => { dragRef.current = null; window.removeEventListener("mousemove", onMove); window.removeEventListener("mouseup", onUp); };
    window.addEventListener("mousemove", onMove);
    window.addEventListener("mouseup", onUp);
  };

  // Touch pinch-zoom
  const touchRef = React.useRef(null);
  const onTouchStart = (e) => {
    if (e.touches.length === 2) {
      const dx = e.touches[0].clientX - e.touches[1].clientX;
      const dy = e.touches[0].clientY - e.touches[1].clientY;
      touchRef.current = { dist: Math.hypot(dx, dy), zoom };
    } else if (e.touches.length === 1 && zoom > 1) {
      touchRef.current = { x: e.touches[0].clientX - pan.x, y: e.touches[0].clientY - pan.y, pan: true };
    }
  };
  const onTouchMove = (e) => {
    if (!touchRef.current) return;
    if (e.touches.length === 2 && touchRef.current.dist) {
      e.preventDefault();
      const dx = e.touches[0].clientX - e.touches[1].clientX;
      const dy = e.touches[0].clientY - e.touches[1].clientY;
      const dist = Math.hypot(dx, dy);
      const next = Math.min(4, Math.max(1, touchRef.current.zoom * (dist / touchRef.current.dist)));
      setZoom(next);
      if (next === 1) setPan({ x: 0, y: 0 });
    } else if (e.touches.length === 1 && touchRef.current.pan) {
      setPan({ x: e.touches[0].clientX - touchRef.current.x, y: e.touches[0].clientY - touchRef.current.y });
    }
  };
  const onTouchEnd = () => { touchRef.current = null; };

  React.useEffect(() => {
    document.body.style.overflow = open ? "hidden" : "";
    return () => { document.body.style.overflow = ""; };
  }, [open]);

  if (!open || !client) return null;
  const photos = client.photos || [];
  const isZoomed = zoom > 1;

  return (
    <div className="mr-photo-scrim" onClick={(e) => { if (e.target === e.currentTarget) onClose(); }}>
      <div className="mr-photo-modal">
        <div className="mr-photo-header">
          <div>
            <span className="mr-photo-header-name">{client.name}</span>
            <span className="mr-photo-header-count">{photos.length} photos</span>
          </div>
          <button className="mr-modal-close" onClick={onClose} type="button" aria-label="Close">
            <svg width="18" height="18" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><line x1="18" y1="6" x2="6" y2="18"/><line x1="6" y1="6" x2="18" y2="18"/></svg>
          </button>
        </div>
        <div className="mr-photo-grid">
          {photos.map((src, i) => (
            <div key={i} className="mr-photo-item" onClick={() => setLightbox(i)}>
              <img src={src} alt={photoLabel(src)} loading="lazy" />
              <span className="mr-photo-caption">{photoLabel(src)}</span>
            </div>
          ))}
        </div>
      </div>

      {/* Lightbox */}
      {lightbox !== null && (
        <div
          className={"mr-lightbox" + (isZoomed ? " is-zoomed" : "")}
          onClick={() => { if (!isZoomed) setLightbox(null); }}
          onWheel={onWheel}
          onTouchStart={onTouchStart}
          onTouchMove={onTouchMove}
          onTouchEnd={onTouchEnd}
        >
          {!isZoomed && (
            <button className="mr-lightbox-arrow left" onClick={(e) => { e.stopPropagation(); setLightbox(i => Math.max(i - 1, 0)); }} disabled={lightbox === 0} type="button">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="15 18 9 12 15 6"/></svg>
            </button>
          )}
          <img
            ref={imgRef}
            src={photos[lightbox]}
            alt={photoLabel(photos[lightbox])}
            style={{ transform: `scale(${zoom}) translate(${pan.x / zoom}px, ${pan.y / zoom}px)`, cursor: isZoomed ? "grab" : "zoom-in" }}
            onClick={(e) => e.stopPropagation()}
            onDoubleClick={onDblClick}
            onMouseDown={onMouseDown}
            draggable={false}
          />
          {!isZoomed && (
            <button className="mr-lightbox-arrow right" onClick={(e) => { e.stopPropagation(); setLightbox(i => Math.min(i + 1, photos.length - 1)); }} disabled={lightbox === photos.length - 1} type="button">
              <svg width="24" height="24" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="2" strokeLinecap="round"><polyline points="9 18 15 12 9 6"/></svg>
            </button>
          )}
          <div className="mr-lightbox-footer">
            <span className="mr-lightbox-label">{photoLabel(photos[lightbox])}</span>
            <span className="mr-lightbox-counter">{lightbox + 1} / {photos.length}</span>
          </div>
        </div>
      )}
    </div>
  );
};

Object.assign(window, { PhotoGallery });
