import { useEffect, useRef, useState } from 'react';

type Photo = { id: number; file_path?: string; thumbnail_path?: string; created_at?: string };

export function usePollGalleryDelta(slug: string) {
  const [photos, setPhotos] = useState<Photo[]>([]);
  const [loading, setLoading] = useState(true);
  const [newCount, setNewCount] = useState(0);
  const latestAt = useRef<string | null>(null);
  const timer = useRef<number | null>(null);

  async function fetchDelta() {
    const qs = latestAt.current ? `?since=${encodeURIComponent(latestAt.current)}` : '';
    const res = await fetch(`/api/v1/events/${encodeURIComponent(slug)}/photos${qs}`, {
      headers: { 'Cache-Control': 'no-store' },
    });
    if (res.status === 304) return;
    const json = await res.json();
    if (Array.isArray(json.data)) {
      const added = json.data.length;
      const merged = latestAt.current ? [...json.data, ...photos] : json.data;
      if (added > 0 && latestAt.current) setNewCount((c) => c + added);
      setPhotos(merged);
    }
    if (json.latest_photo_at) latestAt.current = json.latest_photo_at;
    setLoading(false);
  }

  useEffect(() => {
    setLoading(true);
    latestAt.current = null;
    setPhotos([]);
    fetchDelta();
    timer.current = window.setInterval(fetchDelta, 30_000);
    return () => {
      if (timer.current) window.clearInterval(timer.current);
    };
  }, [slug]);

  function acknowledgeNew() { setNewCount(0); }
  return { loading, photos, newCount, acknowledgeNew };
}
