import { useState, useEffect, useCallback } from 'react';
import { api } from '@/lib/api';

export interface AuthorSocial {
  icon: string;
  link: string;
  name?: string;
}

export interface AuthorEntry {
  name: string;
  description?: string;
  avatar?: string;
  social?: AuthorSocial[];
}

export type AuthorsMap = Record<string, AuthorEntry>;

interface UseBlogAuthorsReturn {
  authors: AuthorsMap;
  loading: boolean;
  refetch: () => Promise<void>;
}

export function useBlogAuthors(): UseBlogAuthorsReturn {
  const [authors, setAuthors] = useState<AuthorsMap>({});
  const [loading, setLoading] = useState(true);

  const refetch = useCallback(async () => {
    setLoading(true);
    try {
      const res = await api.get<{ authors: AuthorsMap }>('/docs/blog/authors');
      setAuthors(res.data.authors ?? {});
    } catch {
      // If no authors file exists yet, keep empty
      setAuthors({});
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => {
    refetch();
  }, [refetch]);

  return { authors, loading, refetch };
}
