import { useState, useEffect, useCallback } from 'react';
import type { ServerConfig } from '../types';
import { fetchPublicServers } from '../api/central';

export const usePublicServers = (refreshMs: number = 30000) => {
  const [servers, setServers] = useState<ServerConfig[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  const reload = useCallback(async () => {
    try {
      setError(null);
      const list = await fetchPublicServers();
      setServers(
        list.map((s) => ({
          id: s.id,
          name: s.name,
          url: s.url.replace(/\/$/, ''),
          enabled: s.enabled,
        }))
      );
    } catch (e) {
      setError(e instanceof Error ? e.message : '加载失败');
      setServers([]);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    void reload();
    const t = setInterval(() => void reload(), refreshMs);
    return () => clearInterval(t);
  }, [reload, refreshMs]);

  return { servers, loading, error, reload };
};
