import { useState, useEffect, useCallback } from 'react';
import { fetchFeatureCardCounts, incrementFeatureCardClick } from '../utils/featureCardClicks';

/**
 * @param {string} section FEATURE_CARD_SECTION.*
 * @param {boolean} [enabled=true] 为 false 时不请求统计（如未登录页不拉取）
 */
export function useFeatureCardClickStats(section, enabled = true) {
  const [counts, setCounts] = useState({});

  useEffect(() => {
    if (!section || enabled === false) return undefined;
    let cancelled = false;
    fetchFeatureCardCounts(section).then((c) => {
      if (!cancelled) setCounts(c || {});
    });
    return () => {
      cancelled = true;
    };
  }, [section, enabled]);

  const bump = useCallback(
    (itemId) => {
      if (!itemId || !section || enabled === false) return;
      setCounts((prev) => {
        const cur = Number(prev[itemId]) || 0;
        return { ...prev, [itemId]: cur + 1 };
      });
      incrementFeatureCardClick(section, itemId).then((serverCount) => {
        if (serverCount != null) {
          setCounts((prev) => ({ ...prev, [itemId]: serverCount }));
        }
      });
    },
    [section, enabled],
  );

  return { counts, bump };
}
