'use client';

import { useCallback, useEffect, useState } from 'react';
import { plansApi } from './plans-api';

/**
 * KPI / Tab badge 用的轻量计数:走后端 /plans/counts 单端点(一次 SQL 聚合 5 个 count),
 * 不动主列表 query。任何主列表刷新时,通过 token (`refreshToken`) 触发同步。
 *
 * 历史:早期是前端并行 5 个 pageSize=1 list 请求,列表页刷新会产生 6+ 个 HTTP 请求 +
 * StrictMode dev 双挂翻倍,网络面板看着很吓人。W3 末改为后端聚合。
 */
export interface PlanCounts {
  mine: number;
  mineAssigned: number;
  mineCompleted: number;
  pool: number;
  all: number;
}

const ZERO: PlanCounts = { mine: 0, mineAssigned: 0, mineCompleted: 0, pool: 0, all: 0 };

export function usePlanCounts(refreshToken: number) {
  const [counts, setCounts] = useState<PlanCounts>(ZERO);
  const [loading, setLoading] = useState(false);

  const load = useCallback(async () => {
    setLoading(true);
    try {
      const data = await plansApi.counts();
      setCounts(data);
    } catch {
      // 失败保持上次值,不打断 UI
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void load();
  }, [load, refreshToken]);

  return { counts, loading, reload: load };
}
