import React, { useEffect, useRef, useCallback } from 'react';
import './MasonryGrid.css';

/* ─────────────────────────────────────────────
   Utility
───────────────────────────────────────────── */
function getPhotoLabel(photo) {
  if (photo.label) return photo.label;
  if (photo.name) {
    const base = photo.name.replace(/\.[^.]+$/, '');
    return base.replace(/[_-]/g, ' ');
  }
  return '';
}

/* ─────────────────────────────────────────────
   MasonryGrid — CSS columns + infinite scroll
───────────────────────────────────────────── */
export default function MasonryGrid({
  photos,
  onSelectPhoto,
  onLoadMore,
  hasNext,
  isLoadingMore,
  regionAccent,
}) {
  const sentinelRef = useRef(null);
  const itemRefs = useRef([]);

  /* infinite scroll sentinel */
  useEffect(() => {
    const sentinel = sentinelRef.current;
    if (!sentinel || !hasNext) return;

    const io = new IntersectionObserver(
      ([entry]) => {
        if (entry.isIntersecting && !isLoadingMore && onLoadMore) {
          onLoadMore();
        }
      },
      { rootMargin: '300px' },
    );
    io.observe(sentinel);
    return () => io.disconnect();
  }, [hasNext, isLoadingMore, onLoadMore]);

  /* scroll-reveal */
  useEffect(() => {
    const nodes = itemRefs.current.filter(Boolean);
    if (!nodes.length) return;

    const io = new IntersectionObserver(
      (entries) => {
        entries.forEach((entry) => {
          if (entry.isIntersecting) {
            entry.target.classList.add('masonry-item--revealed');
            io.unobserve(entry.target);
          }
        });
      },
      { rootMargin: '120px', threshold: 0.05 },
    );

    nodes.forEach((n) => io.observe(n));
    return () => io.disconnect();
  }, [photos]);

  const setItemRef = useCallback((el, idx) => {
    itemRefs.current[idx] = el;
  }, []);

  return (
    <div className="masonry-grid" style={{ '--region-accent': regionAccent }}>
      {photos.map((photo, idx) => {
        const label = getPhotoLabel(photo);
        return (
          <div
            key={photo.id || photo.src || idx}
            className="masonry-item"
            ref={(el) => setItemRef(el, idx)}
            onClick={() => onSelectPhoto && onSelectPhoto(photo, idx)}
          >
            <img
              className="masonry-item__img"
              src={photo.thumb || photo.src}
              alt={label}
              loading={idx < 8 ? 'eager' : 'lazy'}
              draggable={false}
            />
            {label && (
              <div className="masonry-item__overlay">
                <span className="masonry-item__label">{label}</span>
              </div>
            )}
          </div>
        );
      })}

      {/* sentinel for infinite scroll */}
      {hasNext && <div ref={sentinelRef} className="masonry-sentinel" />}

      {/* loading indicator */}
      {isLoadingMore && (
        <div className="masonry-loading">
          <span className="masonry-dot" />
          <span className="masonry-dot" />
          <span className="masonry-dot" />
        </div>
      )}

      {/* end message */}
      {!hasNext && photos.length > 0 && (
        <p className="masonry-end">— {photos.length} frames developed —</p>
      )}
    </div>
  );
}
