import { useState, useCallback } from 'react';

export function useCallTool() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const callTool = useCallback(async (toolName: string, args: Record<string, unknown>) => {
    setLoading(true);
    setError(null);
    
    try {
      // @ts-expect-error - mcp global is injected by host
      if (typeof window.mcp !== 'undefined') {
        // @ts-expect-error - mcp global
        const result = await window.mcp.callServerTool({ name: toolName, arguments: args });
        setLoading(false);
        return result;
      } else {
        throw new Error('MCP not available');
      }
    } catch (err) {
      const errorMessage = err instanceof Error ? err.message : String(err);
      setError(errorMessage);
      setLoading(false);
      throw err;
    }
  }, []);

  return { callTool, loading, error };
}
