import { useState, useEffect } from 'react';
import axios from 'axios';
import { useSettingsStore } from '@/stores/settings.store';
import type { GalleryAd } from '@/types/gallery-ads';

/**
 * Fetches active ads targeted to a specific page placement.
 * Returns empty array if gallery ads are disabled or on error.
 */
export function usePageAds(placement: string): GalleryAd[] {
  const [ads, setAds] = useState<GalleryAd[]>([]);
  const { settings } = useSettingsStore();

  useEffect(() => {
    if (!settings?.enableGalleryAds) {
      setAds([]);
      return;
    }

    axios
      .get<GalleryAd[]>('/api/gallery-ads', { params: { placement } })
      .then(({ data }) => setAds(data))
      .catch(() => setAds([]));
  }, [placement, settings?.enableGalleryAds]);

  return ads;
}
