// Hooks: Pexels image fetching with cache + intersection observer fade-in

const pexelsCache = new Map();
const pexelsInflight = new Map();

async function fetchPexels(query, perPage = 6) {
  const key = `${query}|${perPage}`;
  if (pexelsCache.has(key)) return pexelsCache.get(key);
  if (pexelsInflight.has(key)) return pexelsInflight.get(key);

  const promise = (async () => {
    try {
      const res = await fetch(
        `https://api.pexels.com/v1/search?query=${encodeURIComponent(query)}&per_page=${perPage}&orientation=portrait`,
        { headers: { Authorization: window.__PEXELS_KEY__ } }
      );
      if (!res.ok) throw new Error('Pexels: ' + res.status);
      const json = await res.json();
      const photos = (json.photos || []).map(p => ({
        src: p.src.large,
        alt: p.alt || query,
        photographer: p.photographer
      }));
      pexelsCache.set(key, photos);
      return photos;
    } catch (err) {
      console.warn('Pexels fetch failed:', err);
      pexelsCache.set(key, []);
      return [];
    }
  })();
  pexelsInflight.set(key, promise);
  return promise;
}

function usePexels(query, perPage = 6) {
  const [photos, setPhotos] = React.useState(() => pexelsCache.get(`${query}|${perPage}`) || null);
  React.useEffect(() => {
    let alive = true;
    fetchPexels(query, perPage).then(p => { if (alive) setPhotos(p); });
    return () => { alive = false; };
  }, [query, perPage]);
  return photos;
}

function usePexelsOne(query) {
  const photos = usePexels(query, 3);
  return photos && photos.length ? photos[0] : null;
}

function useFadeIn() {
  const ref = React.useRef(null);
  React.useEffect(() => {
    const el = ref.current;
    if (!el) return;
    const obs = new IntersectionObserver((entries) => {
      entries.forEach(e => { if (e.isIntersecting) { el.classList.add('in'); obs.unobserve(el); } });
    }, { threshold: 0.12 });
    obs.observe(el);
    return () => obs.disconnect();
  }, []);
  return ref;
}

window.usePexels = usePexels;
window.usePexelsOne = usePexelsOne;
window.useFadeIn = useFadeIn;
window.fetchPexels = fetchPexels;
